@tmhs/screencast-mcp 0.47.0 → 0.48.1

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 (41) hide show
  1. package/README.md +28 -247
  2. package/assets/fonts/Inter-Bold.ttf +0 -0
  3. package/assets/fonts/Inter-Regular.ttf +0 -0
  4. package/dist/cli.js +189 -34
  5. package/dist/server.js +13 -0
  6. package/dist/setup.js +437 -0
  7. package/dist/tools/assembleHighlights.js +2 -0
  8. package/dist/tools/cutByTranscript.js +3 -3
  9. package/dist/tools/exportPreset.js +2 -0
  10. package/dist/tools/indexRecording.js +37 -15
  11. package/dist/tools/narrate.js +3 -1
  12. package/dist/tools/pipeline.js +23 -11
  13. package/dist/tools/searchRecording.js +9 -3
  14. package/dist/tools/startRecording.js +72 -42
  15. package/dist/tools/stepGuide.js +57 -4
  16. package/dist/tools/titleCard.js +2 -0
  17. package/dist/tools/xfadeTransition.js +2 -0
  18. package/dist/utils/argPaths.js +39 -0
  19. package/dist/utils/audioDevices.js +0 -4
  20. package/dist/utils/captions.js +5 -3
  21. package/dist/utils/events.js +40 -8
  22. package/dist/utils/gpu.js +50 -4
  23. package/dist/utils/lifecycle.js +56 -16
  24. package/dist/utils/media.js +3 -2
  25. package/dist/utils/monitors.js +34 -3
  26. package/dist/utils/narrate.js +12 -3
  27. package/dist/utils/ocr.js +8 -3
  28. package/dist/utils/paths.js +41 -3
  29. package/dist/utils/pause.js +15 -1
  30. package/dist/utils/pipeline.js +5 -1
  31. package/dist/utils/recipes.js +7 -3
  32. package/dist/utils/recorder.js +20 -11
  33. package/dist/utils/recordingIndex.js +54 -8
  34. package/dist/utils/replay.js +20 -2
  35. package/dist/utils/retention.js +4 -1
  36. package/dist/utils/roots.js +1 -1
  37. package/dist/utils/sessions.js +3 -4
  38. package/dist/utils/sheet.js +4 -4
  39. package/dist/utils/stepGuide.js +26 -0
  40. package/dist/utils/transcriptCut.js +20 -5
  41. package/package.json +7 -5
@@ -6,10 +6,11 @@ import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
6
6
  import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
7
7
  import { requireFfmpeg, probeMedia, hasFilter, runCapture, runFfmpeg, scriptLongFilters } from "../utils/ffmpeg.js";
8
8
  import { jobTimeoutMs, runEditJob } from "../utils/jobs.js";
9
- import { planPipeline, probeArgs, MAX_PIPELINE_STEPS } from "../utils/pipeline.js";
9
+ import { planPipeline, probeArgs, sidecarCues, MAX_PIPELINE_STEPS } from "../utils/pipeline.js";
10
10
  import { calloutFonts, prepareCalloutAssets } from "../utils/calloutAssets.js";
11
11
  import { exportAnimation } from "../utils/animExport.js";
12
12
  import { calloutItemSchema, fontFileSchema } from "./callout.js";
13
+ import { assertEditContainer } from "../utils/media.js";
13
14
  import { readClicks, zoomKeyframeSchema } from "./zoom.js";
14
15
  import { redactRegionSchema } from "./redactRegion.js";
15
16
  import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
@@ -110,7 +111,8 @@ const inputSchema = {
110
111
  .enum(RECIPES)
111
112
  .optional()
112
113
  .describe("Polish preset expanded to steps (see dryRun): pr_demo = cut_idle, click zoom, GIF <=10 MB; tutorial = " +
113
- "+ audio, captions, 1080p mp4; social_reel = 9:16, big captions. Given steps replace its same-op step."),
114
+ "+ audio, captions, 1080p mp4; social_reel = 9:16, big captions. Given steps replace its same-op step; " +
115
+ "trim, redact, crop and cursor go first (source pixels and time)."),
114
116
  quality: z.enum(["draft", "standard", "high"]).optional().describe("Encoder preset for an mp4 result (default standard)."),
115
117
  dryRun: z.boolean().optional().describe("Return the plan (ffmpeg command, output size) without running it."),
116
118
  output: z.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),
@@ -162,6 +164,18 @@ export function register(server) {
162
164
  hasAudio,
163
165
  };
164
166
  const timeout = jobTimeoutMs(info.durationSec);
167
+ const last = steps.at(-1);
168
+ if (!last)
169
+ throw new ScreencastError("Provide at least one step.");
170
+ if (last.op !== "export_gif")
171
+ assertEditContainer(args.output);
172
+ const ext = last.op === "export_gif" ? `.${last.format ?? "gif"}` : ".mp4";
173
+ const output = resolveOutput(args.output, subdir("edits"), `pipeline-${stamp()}-${rand()}${ext}`, args.overwrite);
174
+ const transcribes = last.op !== "export_gif" && steps.some((s) => s.op === "burn_subtitles" && s.transcribe);
175
+ const sidecar = output.replace(/\.[^./\\]+$/, "") + ".srt";
176
+ if (transcribes && !args.overwrite && existsSync(sidecar)) {
177
+ throw new ScreencastError(`Output already exists: ${sidecar}. Pass overwrite: true to replace it.`);
178
+ }
165
179
  for (const [i, s] of steps.entries()) {
166
180
  if (s.op !== "burn_subtitles")
167
181
  continue;
@@ -203,11 +217,6 @@ export function register(server) {
203
217
  const freezes = parseFreezes(scan.stderr, total);
204
218
  idle = useAudio ? intersect(freezes, parseSilences(scan.stderr, total)) : freezes;
205
219
  }
206
- const last = steps.at(-1);
207
- if (!last)
208
- throw new ScreencastError("Provide at least one step.");
209
- const ext = last.op === "export_gif" ? `.${last.format ?? "gif"}` : ".mp4";
210
- const output = resolveOutput(args.output, subdir("edits"), `pipeline-${stamp()}-${rand()}${ext}`, args.overwrite);
211
220
  const work = mkdtempSync(join(tmpdir(), "screencast-pipeline-"));
212
221
  try {
213
222
  const assets = {};
@@ -292,8 +301,8 @@ export function register(server) {
292
301
  const cues = existsSync(raw) ? normalizeCues(parseSrt(readFileSync(raw, "utf8"))) : [];
293
302
  subtitles[p.step] = cues.length > 0 ? join(work, `s${p.step}.srt`) : "";
294
303
  if (cues.length > 0) {
295
- transcript = formatSrt(cues);
296
- writeFileSync(subtitles[p.step], transcript);
304
+ transcript = { cues, opsBefore: p.ops.length };
305
+ writeFileSync(subtitles[p.step], formatSrt(cues));
297
306
  }
298
307
  else
299
308
  warnings.push(`Step ${p.step + 1}: no speech was recognised; no captions.`);
@@ -360,8 +369,11 @@ export function register(server) {
360
369
  let subtitlesPath;
361
370
  if (transcript) {
362
371
  try {
363
- subtitlesPath = output.replace(/\.[^./\\]+$/, "") + ".srt";
364
- writeFileSync(subtitlesPath, transcript);
372
+ const cues = sidecarCues(transcript.cues, plan.timeOps, transcript.opsBefore);
373
+ if (cues.length > 0) {
374
+ writeFileSync(sidecar, formatSrt(cues));
375
+ subtitlesPath = sidecar;
376
+ }
365
377
  }
366
378
  catch {
367
379
  subtitlesPath = undefined;
@@ -29,13 +29,19 @@ export function register(server) {
29
29
  }, async (args, extra) => {
30
30
  try {
31
31
  const source = await resolveRecording(args);
32
- const indexPath = findIndex(source.path, subdir("edits"));
32
+ const fingerprint = fingerprintFile(source.path);
33
+ const indexPath = findIndex(source.path, subdir("edits"), fingerprint);
33
34
  const index = indexPath ? readIndex(indexPath) : null;
34
35
  if (!indexPath || !index) {
35
36
  throw new ScreencastError(`No index for ${source.path}.`, "Run index_recording on it first.");
36
37
  }
37
- const stale = !sameFingerprint(index.fingerprint, fingerprintFile(source.path));
38
- const { hits, total } = searchIndex(index, args.query, { regex: args.regex === true, limit: args.limit });
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
+ });
39
45
  const want = Math.min(clampInlineCount(args.images ?? 0), hits.length);
40
46
  let images = [];
41
47
  if (want > 0) {
@@ -13,11 +13,11 @@ import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
13
13
  import { getStore } from "../context.js";
14
14
  import { killPid, serverIdentity } from "../utils/sessions.js";
15
15
  import { mkdirSync, rmSync } from "node:fs";
16
- import { buildDdaInputArgs, ddagrabWorks, encoderArgs, getDxgiOutputs, planDdaSource, resolveEncoder, } from "../utils/gpu.js";
16
+ import { buildDdaInputArgs, ddagrabWorks, encoderArgs, getDxgiOutputs, planDdaSource, resolveEncoder, startWithEncoderFallback, } from "../utils/gpu.js";
17
17
  import { attachExitHandler, captureStartMs, settleCapture, tailLines, watchStderr, } from "../utils/recorder.js";
18
18
  import { DEFAULT_WEBCAM_SIZE, eventClock, partsDir, sessionEnded, webcamOutputPath, webcamPartPath, } from "../utils/pause.js";
19
19
  import { basename, join } from "node:path";
20
- import { MAX_REPLAY_SEC, MIN_REPLAY_SEC, discardReplay, planReplayBuffer, prepareReplayDir, segmentOutputArgs, } from "../utils/replay.js";
20
+ import { MAX_REPLAY_SEC, MIN_REPLAY_SEC, discardReplay, planReplayBuffer, prepareReplayDir, replayEventRotateSec, resetReplaySegments, segmentOutputArgs, } from "../utils/replay.js";
21
21
  import { DEFAULT_KEY_MODE, eventPaths, parseCaptureStart, prepareEventPaths, startEventLogger, stopEventLogger, summarizeEvents, trackFinalizer, writeEventsFile, } from "../utils/events.js";
22
22
  const inputSchema = {
23
23
  target: z
@@ -103,8 +103,17 @@ const inputSchema = {
103
103
  .min(MIN_REPLAY_SEC)
104
104
  .max(MAX_REPLAY_SEC)
105
105
  .optional()
106
- .describe("Instant replay: keep only the last N s (bounded disk) for save_replay. gdigrab only."),
106
+ .describe("Instant replay: keep only the last N s (bounded disk) for save_replay. gdigrab or ddagrab, not wgc."),
107
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
+ }
108
117
  function webcamStart(watch, audio) {
109
118
  const ms = parseCaptureStart(watch.head(), audio ? 2 : 1);
110
119
  return ms !== null ? { webcamStartMs: ms } : {};
@@ -143,7 +152,7 @@ export function register(server) {
143
152
  }
144
153
  }
145
154
  if (args.replayBufferSec !== undefined && backend === "wgc") {
146
- throw new ScreencastError('replayBufferSec is not supported with backend "wgc" yet; use gdigrab.');
155
+ throw new ScreencastError('replayBufferSec is not supported with backend "wgc" yet; use gdigrab or ddagrab.');
147
156
  }
148
157
  const replay = args.replayBufferSec !== undefined ? planReplayBuffer(args.replayBufferSec) : null;
149
158
  const fps = args.fps ?? DEFAULT_FPS;
@@ -165,33 +174,36 @@ export function register(server) {
165
174
  (webcamDevice ? `, with the webcam (${webcamDevice})` : "") +
166
175
  (args.events ? ", logging mouse clicks and typing" : "") +
167
176
  (replay ? ", kept only until save_replay or stop_recording { save: true } writes it out?" : `, saved to ${output}?`), extra.signal);
168
- const pick = await resolveEncoder(args.encoder ?? (backend === "ddagrab" ? "auto" : "x264"), backend === "ddagrab" ? "ddagrab" : "gdigrab", ffmpeg);
169
- if (dda && !pick.gpuFrames && !(await ddagrabWorks(ffmpeg))) {
177
+ let pick = await resolveEncoder(args.encoder ?? (backend === "ddagrab" ? "auto" : "x264"), backend === "ddagrab" ? "ddagrab" : "gdigrab", ffmpeg, undefined, backend === "wgc" ? undefined : frameSize(target, monitors));
178
+ const ddaUsable = async (p) => !dda || p.gpuFrames || (await ddagrabWorks(ffmpeg));
179
+ if (!(await ddaUsable(pick))) {
170
180
  throw new ScreencastError("Desktop Duplication (ddagrab) does not capture on this machine (a remote session, or no D3D11 GPU).", 'Use backend "gdigrab".');
171
181
  }
172
- const hw = pick.encoder !== "x264";
173
- const captureOpts = {
174
- fps,
175
- quality,
176
- monitors,
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;
182
+ const webcamRaw = webcamDevice ? webcamPartPath(output, 0) : undefined;
186
183
  if (webcamRaw)
187
184
  mkdirSync(partsDir(output), { recursive: true });
188
- const captureArgs = buildCaptureArgs(target, {
189
- ...captureOpts,
190
- output,
191
- maxDurationSec,
192
- ...(webcam && webcamRaw ? { webcam: { ...webcam, output: webcamRaw } } : {}),
193
- });
194
- const ffArgs = replay ? segmentOutputArgs(captureArgs, replay) : captureArgs;
185
+ const plan = (p) => {
186
+ const hw = p.encoder !== "x264";
187
+ const captureOpts = {
188
+ fps,
189
+ quality,
190
+ monitors,
191
+ audio,
192
+ drawMouse: !hideCursor,
193
+ ...(dda ? { videoInput: buildDdaInputArgs(dda, fps, { download: !p.gpuFrames, drawMouse: !hideCursor }) } : {}),
194
+ ...(hw ? { videoCodec: encoderArgs(p.encoder, quality, { gpuFrames: p.gpuFrames }) } : {}),
195
+ };
196
+ const webcam = webcamDevice
197
+ ? { device: webcamDevice, ...(hw ? { codec: encoderArgs(p.encoder, quality) } : {}) }
198
+ : undefined;
199
+ const captureArgs = buildCaptureArgs(target, {
200
+ ...captureOpts,
201
+ output,
202
+ maxDurationSec,
203
+ ...(webcam && webcamRaw ? { webcam: { ...webcam, output: webcamRaw } } : {}),
204
+ });
205
+ return { captureOpts, webcam, ffArgs: replay ? segmentOutputArgs(captureArgs, replay) : captureArgs };
206
+ };
195
207
  if (replay)
196
208
  prepareReplayDir(replay);
197
209
  const keyMode = args.keys ?? DEFAULT_KEY_MODE;
@@ -201,21 +213,38 @@ export function register(server) {
201
213
  let frame = args.events
202
214
  ? captureFrame(target, monitors)
203
215
  : null;
204
- const logger = evPaths ? await startEventLogger(evPaths.raw, keyMode) : null;
205
- const spawnedAt = Date.now();
206
- const child = backend === "wgc"
207
- ? spawn(process.execPath, [
208
- fileURLToPath(new URL("../wgcRecorder.js", import.meta.url)),
209
- JSON.stringify({ ffmpeg, hwnd: window.hwnd, fps, encode: [...encoderArgs(pick.encoder, quality), ...captureKeyframeArgs(fps)], output, maxDurationSec, cursor: !hideCursor }),
210
- ], { stdio: ["pipe", "ignore", "pipe"], windowsHide: true })
211
- : spawn(ffmpeg, ffArgs, {
212
- stdio: ["pipe", "ignore", "pipe"],
213
- windowsHide: true,
214
- });
216
+ const logger = evPaths
217
+ ? await startEventLogger(evPaths.raw, keyMode, replay ? { rotateSec: replayEventRotateSec(replay.bufferSec) } : {})
218
+ : null;
215
219
  const id = `rec-${stamp()}-${rand(6)}`;
216
- const watch = watchStderr(child, id);
217
- const settled = await settleCapture(child, watch, backend);
218
- if (settled === "exited") {
220
+ const launch = async (p) => {
221
+ const settings = plan(p);
222
+ const spawnedAt = Date.now();
223
+ const child = backend === "wgc"
224
+ ? spawn(process.execPath, [
225
+ fileURLToPath(new URL("../wgcRecorder.js", import.meta.url)),
226
+ JSON.stringify({ ffmpeg, hwnd: window.hwnd, fps, encode: [...encoderArgs(p.encoder, quality), ...captureKeyframeArgs(fps)], output, maxDurationSec, cursor: !hideCursor }),
227
+ ], { stdio: ["pipe", "ignore", "pipe"], windowsHide: true })
228
+ : spawn(ffmpeg, settings.ffArgs, {
229
+ stdio: ["pipe", "ignore", "pipe"],
230
+ windowsHide: true,
231
+ });
232
+ const watch = watchStderr(child, id);
233
+ const settled = await settleCapture(child, watch, backend);
234
+ return { ...settings, child, watch, spawnedAt, settled };
235
+ };
236
+ const started = await startWithEncoderFallback(pick, launch, {
237
+ why: (r) => tailLines(r.watch, 3),
238
+ canFallback: () => ddaUsable({ encoder: "x264", gpuFrames: false }),
239
+ beforeRetry: () => {
240
+ if (replay)
241
+ resetReplaySegments(replay);
242
+ },
243
+ });
244
+ const { run, failure: retried } = started;
245
+ pick = started.pick;
246
+ const { child, watch, spawnedAt, captureOpts, webcam } = run;
247
+ if (run.settled === "exited") {
219
248
  if (logger)
220
249
  await stopEventLogger(logger);
221
250
  if (evPaths)
@@ -224,7 +253,8 @@ export function register(server) {
224
253
  discardReplay(replay);
225
254
  if (webcamRaw)
226
255
  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)}`);
256
+ throw new ScreencastError(`Recording failed to start (${backend === "wgc" ? "window capture" : "ffmpeg"} exited immediately):\n${tailLines(watch)}` +
257
+ (retried ? `\n(Retried with libx264 after ${retried})` : ""));
228
258
  }
229
259
  const startMs = captureStartMs(watch, backend, spawnedAt);
230
260
  if (backend === "wgc" && frame && window?.client) {
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
2
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, rmdirSync, statSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
@@ -13,9 +13,10 @@ import { ocrStatus } from "../utils/capabilities.js";
13
13
  import { readFrames, scanMatches } from "../utils/ocrScan.js";
14
14
  import { DEFAULT_SECRET_PATTERN } from "../utils/bugReport.js";
15
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";
16
+ import { GUIDE_FILES, HTML_IMAGE_LADDER, HTML_MAX_BYTES, MAX_GUIDE_STEPS, assignSections, base64Bytes, buildHtmlImageArgs, buildGuideHtml, buildGuideMarkdown, buildStepFrameArgs, buildStepShotArgs, caption, guideSteps, htmlImageName, labelAt, nextHtmlRung, shotFilter, } from "../utils/stepGuide.js";
17
17
  import { resolveSource } from "./bugReport.js";
18
18
  const OCR_BATCH = 10;
19
+ const HTML_SAMPLE = 5;
19
20
  const inputSchema = {
20
21
  input: z.string().min(1).optional().describe("Recording path (uses its .events.jsonl)."),
21
22
  sessionId: z.string().min(1).optional().describe("Or a stopped session's id."),
@@ -149,10 +150,62 @@ export function register(server) {
149
150
  written.push(paths.markdown);
150
151
  }
151
152
  if (wantHtml) {
152
- const src = (file) => `data:image/png;base64,${readFileSync(join(imageDir, file)).toString("base64")}`;
153
- writeFileSync(paths.html, buildGuideHtml(data, src));
153
+ const htmlDir = join(work, "html");
154
+ mkdirSync(htmlDir, { recursive: true });
155
+ const files = steps.flatMap((s) => (s.image ? [s.image] : []));
156
+ const src = (file) => `data:image/jpeg;base64,${readFileSync(join(htmlDir, htmlImageName(file))).toString("base64")}`;
157
+ const encode = async (file, rung) => {
158
+ const out = join(htmlDir, htmlImageName(file));
159
+ await runFfmpeg(buildHtmlImageArgs(join(imageDir, file), rung, out), 60_000, { signal: extra.signal });
160
+ return base64Bytes(statSync(out).size);
161
+ };
162
+ const sample = files.length > HTML_SAMPLE ? files.filter((_, k) => k % Math.ceil(files.length / HTML_SAMPLE) === 0) : [];
163
+ let start = 0;
164
+ for (; sample.length > 0 && start < HTML_IMAGE_LADDER.length - 1; start++) {
165
+ let bytes = 0;
166
+ for (const f of sample)
167
+ bytes += await encode(f, HTML_IMAGE_LADDER[start]);
168
+ if ((bytes / sample.length) * files.length <= HTML_MAX_BYTES * 0.9)
169
+ break;
170
+ }
171
+ let page = "";
172
+ for (let r = start; r !== null;) {
173
+ const rung = HTML_IMAGE_LADDER[r];
174
+ let images = 0;
175
+ for (const file of files)
176
+ images += await encode(file, rung);
177
+ page = images <= HTML_MAX_BYTES ? buildGuideHtml(data, src) : "";
178
+ const bytes = page ? Buffer.byteLength(page) : images;
179
+ if (bytes <= HTML_MAX_BYTES)
180
+ break;
181
+ const next = nextHtmlRung(r, bytes);
182
+ if (next === null) {
183
+ page ||= buildGuideHtml(data, src);
184
+ warnings.push(`guide.html is ${(Buffer.byteLength(page) / 1e6).toFixed(1)} MB, over the ${HTML_MAX_BYTES / 1e6} MB budget even with ${rung.width} px JPEGs; ` +
185
+ "use format: md for a guide this long.");
186
+ }
187
+ r = next;
188
+ }
189
+ writeFileSync(paths.html, page);
154
190
  written.push(paths.html);
155
191
  }
192
+ if (args.overwrite) {
193
+ if (!wantHtml)
194
+ rmSync(paths.html, { force: true });
195
+ if (!wantMd) {
196
+ rmSync(paths.markdown, { force: true });
197
+ if (existsSync(paths.images)) {
198
+ for (const f of readdirSync(paths.images))
199
+ if (/^step-\d+\.png$/.test(f))
200
+ rmSync(join(paths.images, f), { force: true });
201
+ try {
202
+ rmdirSync(paths.images);
203
+ }
204
+ catch {
205
+ }
206
+ }
207
+ }
208
+ }
156
209
  if (data.stepsOmitted)
157
210
  warnings.push(`Only the first ${MAX_GUIDE_STEPS} steps were written; ${data.stepsOmitted} more were left out.`);
158
211
  if (stepsNote)
@@ -8,6 +8,7 @@ import { buildTitleCardArgs, DEFAULT_TITLE_DURATION } from "../utils/produce.js"
8
8
  import { resolveTextFont } from "../utils/fonts.js";
9
9
  import { fontFileSchema } from "./callout.js";
10
10
  import { resolveOutput, subdir, stamp, rand, tempPath } from "../utils/paths.js";
11
+ import { assertEditContainer } from "../utils/media.js";
11
12
  const inputSchema = {
12
13
  text: z.string().min(1).describe("Title text. Multiple lines are allowed (use \\n)."),
13
14
  duration: z.number().positive().optional().describe("Card length in seconds (default 3)."),
@@ -33,6 +34,7 @@ export function register(server) {
33
34
  }, async (args, extra) => {
34
35
  try {
35
36
  requireFfmpeg();
37
+ assertEditContainer(args.output);
36
38
  const output = resolveOutput(args.output, subdir("edits"), `title-${stamp()}-${rand()}.mp4`, args.overwrite);
37
39
  const font = resolveTextFont(args.text, { weight: args.bold === false ? "regular" : "bold", fontFile: args.fontFile });
38
40
  const textFile = tempPath(".txt");
@@ -5,6 +5,7 @@ import { OUTPUT_PATH, WRITES_FILE } from "../utils/toolSpec.js";
5
5
  import { requireFfmpeg, probeMedia } from "../utils/ffmpeg.js";
6
6
  import { runEditJob } from "../utils/jobs.js";
7
7
  import { buildXfadeArgs, clipLength, DEFAULT_TRANSITION_DUR } from "../utils/produce.js";
8
+ import { assertEditContainer } from "../utils/media.js";
8
9
  import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
9
10
  const inputSchema = {
10
11
  inputA: z.string().min(1).describe("Outgoing video."),
@@ -36,6 +37,7 @@ export function register(server) {
36
37
  if (!existsSync(f))
37
38
  throw new ScreencastError(`Input file not found: ${f}`);
38
39
  }
40
+ assertEditContainer(args.output);
39
41
  const [a, b] = await Promise.all([probeMedia(args.inputA), probeMedia(args.inputB)]);
40
42
  const durA = clipLength(a);
41
43
  const durB = clipLength(b);
@@ -0,0 +1,39 @@
1
+ import { assertInputAllowed, assertLocalPath } from "./paths.js";
2
+ const INPUT_KEYS = new Set([
3
+ "input", "inputs", "inputA", "inputB", "clips", "a", "b", "image", "overlay",
4
+ "music", "video", "subtitles", "srt", "transcript", "events",
5
+ ]);
6
+ const LOCAL_ONLY_KEYS = new Set(["output", "outputDir", "model", "fontFile"]);
7
+ const KEYWORDS = new Set(["whisper"]);
8
+ function strings(value) {
9
+ if (typeof value === "string")
10
+ return [value];
11
+ if (Array.isArray(value))
12
+ return value.filter((v) => typeof v === "string");
13
+ return [];
14
+ }
15
+ export function assertArgPaths(args) {
16
+ const visit = (node) => {
17
+ if (Array.isArray(node)) {
18
+ node.forEach(visit);
19
+ return;
20
+ }
21
+ if (!node || typeof node !== "object")
22
+ return;
23
+ for (const [key, value] of Object.entries(node)) {
24
+ if (INPUT_KEYS.has(key)) {
25
+ for (const s of strings(value)) {
26
+ if (s.trim().length > 0 && !KEYWORDS.has(s))
27
+ assertInputAllowed(s, `Input "${key}"`);
28
+ }
29
+ }
30
+ else if (LOCAL_ONLY_KEYS.has(key)) {
31
+ for (const s of strings(value))
32
+ assertLocalPath(s, `"${key}"`);
33
+ }
34
+ if (value && typeof value === "object")
35
+ visit(value);
36
+ }
37
+ };
38
+ visit(args);
39
+ }
@@ -94,10 +94,6 @@ async function enumerateDshow() {
94
94
  cachedDevices = parseDshowAudioDevices(res.stderr);
95
95
  cachedVideo = parseDshowVideoDevices(res.stderr);
96
96
  }
97
- export function clearAudioDeviceCache() {
98
- cachedDevices = null;
99
- cachedVideo = null;
100
- }
101
97
  export async function resolveLoopbackDevice(explicit) {
102
98
  const devices = await listDshowAudioDevices();
103
99
  const picked = pickLoopbackDevice(devices, explicit);
@@ -47,7 +47,7 @@ function fmt(sec) {
47
47
  const pad = (n, w = 2) => String(n).padStart(w, "0");
48
48
  return `${pad(h)}:${pad(m)}:${pad(s)},${pad(ms % 1000, 3)}`;
49
49
  }
50
- export function parseSrt(srt) {
50
+ export function parseSrt(srt, opts = {}) {
51
51
  const cues = [];
52
52
  for (const block of srt.replace(/\r\n/g, "\n").split(/\n\s*\n/)) {
53
53
  const lines = block.split("\n").map((l) => l.trim()).filter((l) => l.length > 0);
@@ -61,8 +61,10 @@ export function parseSrt(srt) {
61
61
  if (!sa || !sb)
62
62
  continue;
63
63
  const text = lines.slice(i + 1).join("\n");
64
- if (text)
65
- cues.push({ start: toSec(sa), end: toSec(sb), text });
64
+ if (!text)
65
+ continue;
66
+ const n = opts.index && i > 0 && /^\d+$/.test(lines[i - 1]) ? Number(lines[i - 1]) : undefined;
67
+ cues.push({ start: toSec(sa), end: toSec(sb), text, ...(n !== undefined && { index: n }) });
66
68
  }
67
69
  return cues;
68
70
  }
@@ -178,6 +178,7 @@ public static class ScEvents{
178
178
  [DllImport("user32.dll")] static extern int ToUnicodeEx(uint vk,uint scan,byte[] ks,[Out,MarshalAs(UnmanagedType.LPWStr)] StringBuilder b,int n,uint f,IntPtr hkl);
179
179
  struct LII{public uint cb;public uint t;}
180
180
  static Proc mp,kp;static StreamWriter w;static bool sc;static double lastMove;static int cx,cy;
181
+ static readonly object wl=new object();static string P;public static int Rot;static int lastRot;
181
182
  static HashSet<uint> held=new HashSet<uint>();
182
183
  static readonly object q=new object();static StringBuilder buf=new StringBuilder();
183
184
  static double typeStart=-1,typeLast;static int lastHook=Environment.TickCount;static bool missing;
@@ -193,15 +194,18 @@ public static class ScEvents{
193
194
  static void Typed(){double t=Now();lock(q){if(typeStart<0)typeStart=t;typeLast=t;}}
194
195
  static void EndTyping(bool force){double s,e;lock(q){if(typeStart<0||(!force&&Now()-typeLast<${TYPING_GAP_MS}))return;s=typeStart;e=typeLast;typeStart=-1;}
195
196
  double g=${TYPING_GRAIN_MS};double s2=Math.Floor(s/g)*g,e2=Math.Max(s2+g,Math.Ceiling(e/g)*g);Line(s2,"typing",cx,cy,(e2-s2).ToString("F0",Inv));}
196
- static void Drain(){lock(w){string s;lock(q){s=buf.ToString();buf.Clear();}if(s.Length>0){w.Write(s);w.Flush();}}}
197
- static void Quit(){EndTyping(true);Drain();w.Close();Process.GetCurrentProcess().Kill();}
197
+ static void Drain(){lock(wl){string s;lock(q){s=buf.ToString();buf.Clear();}if(s.Length>0){w.Write(s);w.Flush();}}}
198
+ static void Quit(){EndTyping(true);Drain();lock(wl){w.Close();}Process.GetCurrentProcess().Kill();}
199
+ // Replay buffers (#258): every Rot ms the log becomes path.1 (replacing the one before), so it never holds much more than two periods.
200
+ static void Rotate(){lock(wl){w.Close();try{string old=P+".1";if(File.Exists(old))File.Delete(old);File.Move(P,old);}catch{}w=new StreamWriter(P,true,new UTF8Encoding(false));}}
198
201
  static void Pump(string stop){int tick=0;while(true){Thread.Sleep(250);tick++;
199
202
  EndTyping(false);
200
203
  lock(held){foreach(uint vk in new List<uint>(held)){if(!Down((int)vk))held.Remove(vk);}}
201
204
  LII li=new LII();li.cb=8;if(!missing&&GetLastInputInfo(ref li)&&unchecked((int)li.t-lastHook)>${MISSED_INPUT_MS}){missing=true;Put("miss",cx,cy,"");}
202
205
  if(tick%4==0)Put("hb",0,0,"");
203
206
  if(File.Exists(stop))Quit();
204
- Drain();}}
207
+ Drain();
208
+ if(Rot>0&&unchecked(Environment.TickCount-lastRot)>=Rot){lastRot=Environment.TickCount;Rotate();}}}
205
209
  static IntPtr Mouse(int n,IntPtr wp,IntPtr lp){
206
210
  if(n>=0){Seen();MS s=(MS)Marshal.PtrToStructure(lp,typeof(MS));int m=(int)wp;cx=s.x;cy=s.y;
207
211
  if(m==0x200){double t=Now();if(t-lastMove>=${MOVE_SAMPLE_MS}){lastMove=t;Put("move",s.x,s.y,"");}}
@@ -234,7 +238,7 @@ public static class ScEvents{
234
238
  return CallNextHookEx(IntPtr.Zero,n,wp,lp);}
235
239
  public static void Run(string path,bool shortcuts,int parent){
236
240
  try{SetProcessDpiAwarenessContext(new IntPtr(-4));}catch{}
237
- sc=shortcuts;w=new StreamWriter(path,true,new UTF8Encoding(false));
241
+ sc=shortcuts;P=path;lastRot=Environment.TickCount;w=new StreamWriter(path,true,new UTF8Encoding(false));
238
242
  IntPtr mod=GetModuleHandle(null);mp=Mouse;kp=Key;
239
243
  if(SetWindowsHookEx(14,mp,mod,0)==IntPtr.Zero||SetWindowsHookEx(13,kp,mod,0)==IntPtr.Zero)throw new Exception("SetWindowsHookEx failed: "+Marshal.GetLastWin32Error());
240
244
  var watch=new Thread(()=>{while(true){Thread.Sleep(500);bool gone;try{gone=Process.GetProcessById(parent).HasExited;}catch{gone=true;}if(gone)Quit();}});
@@ -245,12 +249,40 @@ public static class ScEvents{
245
249
  }
246
250
  }
247
251
  "@
252
+ [ScEvents]::Rot=__ROTATE__
248
253
  [ScEvents]::Run([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PATH__')), [bool]__MODE__, __PARENT__)
249
254
  `;
250
- export function buildHookScript(rawPath, mode, parentPid) {
255
+ export function buildHookScript(rawPath, mode, parentPid, rotateSec = 0) {
256
+ const rotateMs = Math.max(0, Math.round(rotateSec * 1000));
251
257
  return PS_HOOK.replace("__PATH__", Buffer.from(rawPath, "utf8").toString("base64"))
252
258
  .replace("__MODE__", mode === "shortcuts" ? "1" : "0")
253
- .replace("__PARENT__", String(parentPid));
259
+ .replace("__PARENT__", String(parentPid))
260
+ .replace("__ROTATE__", String(rotateMs));
261
+ }
262
+ export function rotatedLogPath(rawPath) {
263
+ return `${rawPath}.1`;
264
+ }
265
+ export function rawLinesSince(raw, sinceMs) {
266
+ return raw
267
+ .split(/\r?\n/)
268
+ .filter((line) => {
269
+ const comma = line.indexOf(",");
270
+ const ms = comma > 0 ? Number(line.slice(0, comma)) : NaN;
271
+ return Number.isFinite(ms) && ms >= sinceMs;
272
+ })
273
+ .join("\n");
274
+ }
275
+ export function readRawEventLog(rawPath, sinceMs = -Infinity) {
276
+ const read = (p) => {
277
+ try {
278
+ return existsSync(p) ? readFileSync(p, "utf8") : "";
279
+ }
280
+ catch {
281
+ return "";
282
+ }
283
+ };
284
+ const text = `${read(rotatedLogPath(rawPath))}\n${read(rawPath)}`;
285
+ return sinceMs === -Infinity ? text : rawLinesSince(text, sinceMs);
254
286
  }
255
287
  export function cleanPsError(stderr) {
256
288
  if (!stderr.startsWith("#< CLIXML"))
@@ -265,12 +297,12 @@ export function cleanPsError(stderr) {
265
297
  .trim();
266
298
  }
267
299
  export const LOGGER_READY_TIMEOUT_MS = 20_000;
268
- export async function startEventLogger(rawPath, mode) {
300
+ export async function startEventLogger(rawPath, mode, opts = {}) {
269
301
  if (process.platform !== "win32") {
270
302
  throw new ScreencastError("The input event log is implemented for Windows only.");
271
303
  }
272
304
  rmSync(`${rawPath}.stop`, { force: true });
273
- const encoded = Buffer.from(buildHookScript(rawPath, mode, process.pid), "utf16le").toString("base64");
305
+ const encoded = Buffer.from(buildHookScript(rawPath, mode, process.pid, opts.rotateSec), "utf16le").toString("base64");
274
306
  const child = spawn("powershell", ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], {
275
307
  stdio: ["ignore", "pipe", "pipe"],
276
308
  windowsHide: true,
package/dist/utils/gpu.js CHANGED
@@ -76,19 +76,65 @@ export async function probeHwEncoders(ffmpeg, run = ffmpegRunner(ffmpeg)) {
76
76
  const results = await Promise.all(HW_ENCODERS.map((e) => cachedProbe(ffmpeg, `enc:${e}`, buildEncoderProbeArgs(e), run)));
77
77
  return Object.fromEntries(HW_ENCODERS.map((e, i) => [e, results[i]]));
78
78
  }
79
- export async function resolveEncoder(choice, backend, ffmpeg, run = ffmpegRunner(ffmpeg)) {
79
+ export const HW_MAX_FRAME = {
80
+ nvenc: { width: 4096, height: 4096 },
81
+ qsv: { width: 4096, height: 2304 },
82
+ amf: { width: 4096, height: 2304 },
83
+ };
84
+ export function encoderFits(encoder, frame) {
85
+ const max = HW_MAX_FRAME[encoder];
86
+ return frame.width <= max.width && frame.height <= max.height;
87
+ }
88
+ export async function resolveEncoder(choice, backend, ffmpeg, run = ffmpegRunner(ffmpeg), frame) {
80
89
  if (choice === "x264")
81
90
  return { encoder: "x264", gpuFrames: false };
91
+ const fits = (e) => !frame || encoderFits(e, frame);
92
+ const size = frame ? `${frame.width}x${frame.height}` : "";
93
+ if (choice !== "auto" && !fits(choice)) {
94
+ const max = HW_MAX_FRAME[choice];
95
+ throw new ScreencastError(`The ${choice} encoder (${ENCODER_CODECS[choice]}) cannot encode a ${size} frame (at most ${max.width}x${max.height}).`, 'Use encoder: "x264" (or "auto", which picks libx264 for it), or record a smaller target.');
96
+ }
82
97
  const available = await probeHwEncoders(ffmpeg, run);
83
- const pick = choice === "auto" ? HW_ENCODERS.find((e) => available[e]) : available[choice] ? choice : undefined;
98
+ const pick = choice === "auto" ? HW_ENCODERS.find((e) => available[e] && fits(e)) : available[choice] ? choice : undefined;
84
99
  if (!pick) {
85
- if (choice === "auto")
86
- return { encoder: "x264", gpuFrames: false, note: "No hardware encoder passed a trial encode; using libx264." };
100
+ if (choice === "auto") {
101
+ const working = HW_ENCODERS.filter((e) => available[e]);
102
+ return {
103
+ encoder: "x264",
104
+ gpuFrames: false,
105
+ note: working.length > 0
106
+ ? `The capture is ${size}, larger than the hardware encoders here take (${working
107
+ .map((e) => `${e}: ${HW_MAX_FRAME[e].width}x${HW_MAX_FRAME[e].height}`)
108
+ .join(", ")}); using libx264.`
109
+ : "No hardware encoder passed a trial encode; using libx264.",
110
+ };
111
+ }
87
112
  throw new ScreencastError(`The ${choice} encoder (${ENCODER_CODECS[choice]}) failed a trial encode on this machine.`, 'Use encoder: "auto" (falls back to libx264) or "x264"; doctor lists the encoders that work here.');
88
113
  }
89
114
  const gpuFrames = backend === "ddagrab" && (await cachedProbe(ffmpeg, `dda:${pick}`, buildDdaProbeArgs(pick), run));
90
115
  return { encoder: pick, gpuFrames };
91
116
  }
117
+ export async function startWithEncoderFallback(pick, launch, opts) {
118
+ const first = await launch(pick);
119
+ if (first.settled === "running" || pick.encoder === "x264")
120
+ return { run: first, pick };
121
+ const fallback = { encoder: "x264", gpuFrames: false };
122
+ if (opts.canFallback && !(await opts.canFallback()))
123
+ return { run: first, pick };
124
+ const name = `${pick.encoder} (${ENCODER_CODECS[pick.encoder]})`;
125
+ const why = opts.why(first).trim();
126
+ const failure = `the ${name} encoder exited at start${why ? `:\n${why}` : ""}`;
127
+ opts.beforeRetry?.();
128
+ const run = await launch(fallback);
129
+ if (run.settled === "exited")
130
+ return { run, pick: fallback, failure };
131
+ const last = why.split("\n").at(-1) ?? "";
132
+ return {
133
+ run,
134
+ pick: { ...fallback, note: `The ${name} encoder exited at start; recording with libx264 instead.${last ? ` ffmpeg said: ${last}` : ""}` },
135
+ failure,
136
+ };
137
+ }
92
138
  export function ddagrabWorks(ffmpeg, run = ffmpegRunner(ffmpeg)) {
93
139
  return cachedProbe(ffmpeg, "dda", buildDdaProbeArgs(), run);
94
140
  }