@tmhs/screencast-mcp 0.46.0 → 0.48.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 (55) hide show
  1. package/README.md +127 -303
  2. package/assets/cursor/arrow.png +0 -0
  3. package/assets/fonts/Inter-Bold.ttf +0 -0
  4. package/assets/fonts/Inter-Regular.ttf +0 -0
  5. package/dist/cli.js +515 -0
  6. package/dist/index.js +10 -2
  7. package/dist/server.js +23 -0
  8. package/dist/setup.js +437 -0
  9. package/dist/tools/addMarker.js +6 -2
  10. package/dist/tools/bugReport.js +1 -1
  11. package/dist/tools/chapters.js +1 -1
  12. package/dist/tools/cursor.js +87 -0
  13. package/dist/tools/cutByTranscript.js +3 -3
  14. package/dist/tools/doctor.js +14 -1
  15. package/dist/tools/indexRecording.js +37 -15
  16. package/dist/tools/listVideoDevices.js +26 -0
  17. package/dist/tools/narrate.js +86 -0
  18. package/dist/tools/overlay.js +2 -0
  19. package/dist/tools/pauseRecording.js +44 -0
  20. package/dist/tools/pipeline.js +37 -13
  21. package/dist/tools/readEvents.js +1 -1
  22. package/dist/tools/resumeRecording.js +46 -0
  23. package/dist/tools/reviewRecording.js +1 -1
  24. package/dist/tools/searchRecording.js +9 -3
  25. package/dist/tools/startRecording.js +155 -86
  26. package/dist/tools/stepGuide.js +57 -4
  27. package/dist/tools/stopRecording.js +38 -3
  28. package/dist/utils/argPaths.js +39 -0
  29. package/dist/utils/audioDevices.js +34 -4
  30. package/dist/utils/captions.js +5 -3
  31. package/dist/utils/cursor.js +317 -0
  32. package/dist/utils/events.js +62 -12
  33. package/dist/utils/gpu.js +219 -0
  34. package/dist/utils/lifecycle.js +136 -13
  35. package/dist/utils/media.js +7 -2
  36. package/dist/utils/monitors.js +39 -5
  37. package/dist/utils/narrate.js +233 -0
  38. package/dist/utils/ocr.js +8 -3
  39. package/dist/utils/paths.js +41 -3
  40. package/dist/utils/pause.js +190 -0
  41. package/dist/utils/pipeline.js +29 -2
  42. package/dist/utils/recipes.js +7 -3
  43. package/dist/utils/recorder.js +172 -0
  44. package/dist/utils/recordingIndex.js +55 -9
  45. package/dist/utils/replay.js +20 -2
  46. package/dist/utils/retention.js +4 -1
  47. package/dist/utils/roots.js +1 -1
  48. package/dist/utils/sessions.js +32 -6
  49. package/dist/utils/stepGuide.js +26 -0
  50. package/dist/utils/targets.js +31 -7
  51. package/dist/utils/toolsets.js +8 -3
  52. package/dist/utils/transcriptCut.js +20 -5
  53. package/dist/utils/wgc.js +2 -2
  54. package/dist/wgcRecorder.js +1 -1
  55. package/package.json +5 -1
@@ -0,0 +1,219 @@
1
+ import { ScreencastError } from "./errors.js";
2
+ import { runCapture } from "./ffmpeg.js";
3
+ import { runPowerShell } from "./monitors.js";
4
+ import { QUALITY_PRESETS, resolveQuality } from "./targets.js";
5
+ export const HW_ENCODERS = ["nvenc", "qsv", "amf"];
6
+ export const ENCODER_CODECS = {
7
+ x264: "libx264",
8
+ nvenc: "h264_nvenc",
9
+ qsv: "h264_qsv",
10
+ amf: "h264_amf",
11
+ };
12
+ export const HW_QUALITY = {
13
+ nvenc: { draft: { preset: "p1", q: 30 }, standard: { preset: "p4", q: 25 }, high: { preset: "p6", q: 20 } },
14
+ qsv: { draft: { preset: "veryfast", q: 30 }, standard: { preset: "medium", q: 25 }, high: { preset: "slower", q: 20 } },
15
+ amf: { draft: { preset: "speed", q: 30 }, standard: { preset: "balanced", q: 25 }, high: { preset: "quality", q: 20 } },
16
+ };
17
+ export function encoderArgs(encoder, quality, opts = {}) {
18
+ if (!QUALITY_PRESETS[quality])
19
+ throw new ScreencastError(`Unknown quality preset "${quality}".`);
20
+ if (encoder === "x264")
21
+ return resolveQuality(quality);
22
+ const { preset, q } = HW_QUALITY[encoder][quality];
23
+ const codec = ["-c:v", ENCODER_CODECS[encoder]];
24
+ const rate = encoder === "nvenc"
25
+ ? ["-preset", preset, "-rc", "vbr", "-cq", String(q), "-b:v", "0"]
26
+ : encoder === "qsv"
27
+ ? ["-preset", preset, "-global_quality", String(q)]
28
+ : ["-quality", preset, "-rc", "cqp", "-qp_i", String(q), "-qp_p", String(q)];
29
+ return [...codec, ...rate, ...(opts.gpuFrames ? [] : ["-pix_fmt", "nv12"])];
30
+ }
31
+ export function buildEncoderProbeArgs(encoder) {
32
+ return [
33
+ "-hide_banner", "-v", "error",
34
+ "-f", "lavfi", "-i", "color=c=black:s=256x256:r=30",
35
+ "-frames:v", "3",
36
+ ...encoderArgs(encoder, "draft"),
37
+ "-f", "null", "-",
38
+ ];
39
+ }
40
+ export function buildDdaProbeArgs(encoder) {
41
+ return [
42
+ "-hide_banner", "-v", "error",
43
+ "-f", "lavfi", "-i", `ddagrab=framerate=10${encoder ? "" : ",hwdownload,format=bgra"}`,
44
+ "-frames:v", "2",
45
+ ...(encoder ? encoderArgs(encoder, "draft", { gpuFrames: true }) : []),
46
+ "-f", "null", "-",
47
+ ];
48
+ }
49
+ const PROBE_TIMEOUT_MS = 20_000;
50
+ export function ffmpegRunner(ffmpeg) {
51
+ return async (args) => {
52
+ try {
53
+ const res = await runCapture(ffmpeg, args, PROBE_TIMEOUT_MS, { closeStdin: true });
54
+ return res.code === 0;
55
+ }
56
+ catch {
57
+ return false;
58
+ }
59
+ };
60
+ }
61
+ const probes = new Map();
62
+ function cachedProbe(ffmpeg, key, args, run) {
63
+ const k = `${ffmpeg}\u0000${key}`;
64
+ let p = probes.get(k);
65
+ if (!p) {
66
+ p = run(args);
67
+ probes.set(k, p);
68
+ }
69
+ return p;
70
+ }
71
+ export function clearGpuProbeCache() {
72
+ probes.clear();
73
+ dxgiCache = null;
74
+ }
75
+ export async function probeHwEncoders(ffmpeg, run = ffmpegRunner(ffmpeg)) {
76
+ const results = await Promise.all(HW_ENCODERS.map((e) => cachedProbe(ffmpeg, `enc:${e}`, buildEncoderProbeArgs(e), run)));
77
+ return Object.fromEntries(HW_ENCODERS.map((e, i) => [e, results[i]]));
78
+ }
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) {
89
+ if (choice === "x264")
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
+ }
97
+ const available = await probeHwEncoders(ffmpeg, run);
98
+ const pick = choice === "auto" ? HW_ENCODERS.find((e) => available[e] && fits(e)) : available[choice] ? choice : undefined;
99
+ if (!pick) {
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
+ }
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.');
113
+ }
114
+ const gpuFrames = backend === "ddagrab" && (await cachedProbe(ffmpeg, `dda:${pick}`, buildDdaProbeArgs(pick), run));
115
+ return { encoder: pick, gpuFrames };
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
+ }
138
+ export function ddagrabWorks(ffmpeg, run = ffmpegRunner(ffmpeg)) {
139
+ return cachedProbe(ffmpeg, "dda", buildDdaProbeArgs(), run);
140
+ }
141
+ export function parseDxgiOutputs(stdout) {
142
+ const out = [];
143
+ for (const line of stdout.split(/\r?\n/)) {
144
+ const parts = line.trim().split(",");
145
+ if (parts.length < 7)
146
+ continue;
147
+ const n = parts.slice(0, 6).map(Number);
148
+ if (n.some((v) => !Number.isInteger(v)))
149
+ continue;
150
+ const [adapter = 0, output = 0, x = 0, y = 0, w = 0, h = 0] = n;
151
+ if (w <= 0 || h <= 0)
152
+ continue;
153
+ out.push({ adapter, output, x, y, w, h, name: parts.slice(6).join(",") });
154
+ }
155
+ return out;
156
+ }
157
+ const PS_DXGI = `
158
+ Add-Type -TypeDefinition @"
159
+ using System; using System.Runtime.InteropServices; using System.Text;
160
+ public static class ScDxgi {
161
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
162
+ public struct DESC { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string Name; public int L, T, R, B; public int Attached; public int Rot; public IntPtr Mon; }
163
+ [ComImport, Guid("770aae78-f26f-4dba-a829-253c83d1b387"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
164
+ interface IF1 { void a(); void b(); void c(); void d(); void e(); void f(); void g(); void h(); void i();
165
+ [PreserveSig] int EnumAdapters1(uint i, [MarshalAs(UnmanagedType.Interface)] out IA1 a); }
166
+ [ComImport, Guid("29038f61-3839-4626-91fd-086879011a05"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
167
+ interface IA1 { void a(); void b(); void c(); void d();
168
+ [PreserveSig] int EnumOutputs(uint i, [MarshalAs(UnmanagedType.Interface)] out IO o); }
169
+ [ComImport, Guid("ae02eedb-c735-4690-8d52-5a8dc20213aa"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
170
+ interface IO { void a(); void b(); void c(); void d(); [PreserveSig] int GetDesc(out DESC d); }
171
+ [DllImport("dxgi.dll")] static extern int CreateDXGIFactory1(ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IF1 f);
172
+ public static string List() {
173
+ Guid g = new Guid("770aae78-f26f-4dba-a829-253c83d1b387"); IF1 f;
174
+ if (CreateDXGIFactory1(ref g, out f) != 0) return "";
175
+ StringBuilder sb = new StringBuilder(); IA1 a;
176
+ for (uint ai = 0; f.EnumAdapters1(ai, out a) == 0; ai++) { IO o;
177
+ for (uint oi = 0; a.EnumOutputs(oi, out o) == 0; oi++) { DESC d;
178
+ if (o.GetDesc(out d) == 0) sb.AppendFormat("{0},{1},{2},{3},{4},{5},{6}\\n", ai, oi, d.L, d.T, d.R - d.L, d.B - d.T, d.Name); } }
179
+ return sb.ToString(); } }
180
+ "@
181
+ [ScDxgi]::List()
182
+ `;
183
+ const DXGI_CACHE_MS = 5_000;
184
+ let dxgiCache = null;
185
+ export function getDxgiOutputs() {
186
+ if (dxgiCache && Date.now() - dxgiCache.at < DXGI_CACHE_MS)
187
+ return dxgiCache.outputs;
188
+ const outputs = runPowerShell(PS_DXGI, "DXGI outputs").then(parseDxgiOutputs);
189
+ dxgiCache = { at: Date.now(), outputs };
190
+ outputs.catch(() => {
191
+ dxgiCache = null;
192
+ });
193
+ return outputs;
194
+ }
195
+ const evenDown = (n) => n - (n % 2);
196
+ export function planDdaSource(rect, outputs) {
197
+ const holds = (o) => rect.x >= o.x && rect.y >= o.y && rect.x + rect.w <= o.x + o.w && rect.y + rect.h <= o.y + o.h;
198
+ const host = outputs.find(holds);
199
+ if (!host) {
200
+ throw new ScreencastError(`backend "ddagrab" captures one display, and ${rect.x},${rect.y} ${rect.w}x${rect.h} is not inside a single one.`, 'Use a monitor:<i> target, a region inside one display, or backend "gdigrab".');
201
+ }
202
+ if (host.adapter !== 0) {
203
+ throw new ScreencastError(`That display (${host.name || `adapter ${host.adapter} output ${host.output}`}) is driven by a second GPU, which ddagrab cannot reach.`, 'Use backend "gdigrab" for it.');
204
+ }
205
+ const w = evenDown(rect.w);
206
+ const h = evenDown(rect.h);
207
+ if (w <= 0 || h <= 0)
208
+ throw new ScreencastError("The capture rectangle is too small to record (needs at least 2x2 px).");
209
+ const whole = rect.x === host.x && rect.y === host.y && w === host.w && h === host.h;
210
+ return whole ? { output: host.output } : { output: host.output, crop: { x: rect.x - host.x, y: rect.y - host.y, w, h } };
211
+ }
212
+ export function buildDdaInputArgs(src, fps, opts) {
213
+ const crop = src.crop
214
+ ? `:offset_x=${src.crop.x}:offset_y=${src.crop.y}:video_size=${src.crop.w}x${src.crop.h}`
215
+ : "";
216
+ const mouse = opts.drawMouse === false ? 0 : 1;
217
+ const graph = `ddagrab=output_idx=${src.output}:framerate=${fps}:draw_mouse=${mouse}${crop}${opts.download ? ",hwdownload,format=bgra" : ""}`;
218
+ return ["-f", "lavfi", "-i", graph];
219
+ }
@@ -5,6 +5,8 @@ import { whenFinalized } from "./events.js";
5
5
  import { buildProbeArgs, parseMediaInfo } from "./media.js";
6
6
  import { ScreencastError } from "./errors.js";
7
7
  import { wgcStopFile } from "./wgc.js";
8
+ import { encoderArgs } from "./gpu.js";
9
+ import { clearPausing, endSession, finishSegments, markPausing, pauseBlocker, recordedSec, segmentDurationSec, webcamOutputPath, } from "./pause.js";
8
10
  import { expectedImage, isAlive, isRecorderProcess, killPid, } from "./sessions.js";
9
11
  async function waitForPidExit(pid, ms) {
10
12
  const deadline = Date.now() + ms;
@@ -36,6 +38,116 @@ export async function probeDuration(ffprobe, path) {
36
38
  return null;
37
39
  }
38
40
  }
41
+ async function quitChild(child, pid, gracefulMs) {
42
+ if (!child.stdin || !child.stdin.writable)
43
+ return false;
44
+ child.stdin.write("q\n");
45
+ child.stdin.end();
46
+ const graceful = await waitForExit(child, gracefulMs);
47
+ if (!graceful && pid !== null) {
48
+ killPid(pid);
49
+ await waitForPidExit(pid, 2000);
50
+ await waitForExit(child, 2000);
51
+ }
52
+ return graceful;
53
+ }
54
+ export async function finalParts(record, ffprobe) {
55
+ const seg = record.segments;
56
+ if (!seg)
57
+ return [];
58
+ const parts = [...seg.parts];
59
+ if (seg.current) {
60
+ const probed = await probeDuration(ffprobe, seg.current.path);
61
+ const endMs = record.stoppedAt ? Date.parse(record.stoppedAt) : Date.now();
62
+ const durationSec = segmentDurationSec(seg.current.path, probed, seg.current.startMs, endMs) ?? 0;
63
+ parts.push({ ...seg.current, durationSec });
64
+ }
65
+ return parts;
66
+ }
67
+ export function needsJoin(record) {
68
+ const seg = record.segments;
69
+ return !!seg && (seg.parts.length > 0 || !!record.webcam);
70
+ }
71
+ export async function joinSegments(record, tools) {
72
+ const parts = await finalParts(record, tools.ffprobe);
73
+ const res = await finishSegments(record.outputPath, parts, {
74
+ ffmpeg: tools.ffmpeg,
75
+ webcamOutput: record.webcam ? webcamOutputPath(record.outputPath) : undefined,
76
+ webcamCodec: encoderArgs(record.encoder ?? "x264", record.quality, { gpuFrames: false }),
77
+ });
78
+ return {
79
+ patch: {
80
+ segments: { parts },
81
+ ...(record.webcam ? { webcam: { ...record.webcam, error: res.webcamError } } : {}),
82
+ },
83
+ count: parts.length,
84
+ error: res.error,
85
+ };
86
+ }
87
+ const sessionOps = new WeakMap();
88
+ export function sessionOpInFlight(store, id) {
89
+ return sessionOps.get(store)?.get(id)?.kind ?? null;
90
+ }
91
+ export function withSessionOp(store, id, kind, fn, opts = {}) {
92
+ let ops = sessionOps.get(store);
93
+ if (!ops)
94
+ sessionOps.set(store, (ops = new Map()));
95
+ const running = ops.get(id);
96
+ if (running?.kind === kind)
97
+ return running.promise;
98
+ if (running && !opts.queue) {
99
+ return Promise.reject(new ScreencastError(`Cannot ${kind} ${id}: a ${running.kind} of it is in progress.`, "Retry once it finishes (get_recording shows the session's status)."));
100
+ }
101
+ let start;
102
+ if (running) {
103
+ start = running.promise.then(() => fn(true), () => fn(true));
104
+ }
105
+ else {
106
+ try {
107
+ start = fn(false);
108
+ }
109
+ catch (err) {
110
+ start = Promise.reject(err);
111
+ }
112
+ }
113
+ const map = ops;
114
+ const op = start.finally(() => {
115
+ if (map.get(id)?.promise === op)
116
+ map.delete(id);
117
+ });
118
+ map.set(id, { kind, promise: op });
119
+ return op;
120
+ }
121
+ export function pauseSession(store, record, opts) {
122
+ return withSessionOp(store, record.id, "pause", () => runPause(store, store.get(record.id) ?? record, opts));
123
+ }
124
+ async function runPause(store, record, opts) {
125
+ const child = store.getChild(record.id);
126
+ const blocker = pauseBlocker(record, !!child);
127
+ if (blocker)
128
+ throw new ScreencastError(`Cannot pause ${record.id}: ${blocker}.`);
129
+ markPausing(record.id);
130
+ store.markStopping(record.id);
131
+ try {
132
+ const pausedAt = Date.now();
133
+ const graceful = await quitChild(child, record.pid, opts.gracefulMs ?? 8000);
134
+ store.detachChild(record.id, child);
135
+ const cur = record.segments.current;
136
+ const probed = await opts.probe(cur.path);
137
+ const segmentSec = segmentDurationSec(cur.path, probed, cur.startMs, pausedAt) ?? 0;
138
+ const parts = record.segments.parts;
139
+ const next = segmentSec > 0 ? [...parts, { ...cur, durationSec: segmentSec }] : parts;
140
+ if (segmentSec <= 0 && cur.path !== record.outputPath)
141
+ rmSync(cur.path, { force: true });
142
+ store.markPaused(record.id);
143
+ const updated = store.update(record.id, { status: "paused", pid: null, segments: { parts: next } });
144
+ return { record: updated, recordedSec: recordedSec(next), segmentSec, graceful };
145
+ }
146
+ finally {
147
+ clearPausing(record.id);
148
+ store.clearStopping(record.id);
149
+ }
150
+ }
39
151
  export async function stopAll(store, probe, capMs = 10_000) {
40
152
  const ids = store.activeIds();
41
153
  const stops = ids.map(async (id) => {
@@ -57,17 +169,16 @@ export async function stopAll(store, probe, capMs = 10_000) {
57
169
  clearTimeout(timer);
58
170
  return ids;
59
171
  }
60
- const inFlight = new WeakMap();
61
172
  export function stopSession(store, record, opts) {
62
- let stops = inFlight.get(store);
63
- if (!stops)
64
- inFlight.set(store, (stops = new Map()));
65
- const running = stops.get(record.id);
66
- if (running)
67
- return running;
68
- const stop = runStop(store, record, opts).finally(() => stops.delete(record.id));
69
- stops.set(record.id, stop);
70
- return stop;
173
+ return withSessionOp(store, record.id, "stop", async (waited) => {
174
+ if (!waited)
175
+ return runStop(store, record, opts);
176
+ const cur = store.get(record.id) ?? record;
177
+ if (cur.status !== "recording" && cur.status !== "paused") {
178
+ return { record: cur, graceful: true, durationSec: cur.durationSec ?? null };
179
+ }
180
+ return runStop(store, cur, opts);
181
+ }, { queue: true });
71
182
  }
72
183
  async function runStop(store, record, opts) {
73
184
  store.markStopping(record.id);
@@ -100,8 +211,19 @@ async function runStop(store, record, opts) {
100
211
  }
101
212
  }
102
213
  }
103
- store.detachChild(record.id);
214
+ store.detachChild(record.id, child);
215
+ if (record.status === "paused")
216
+ graceful = true;
217
+ endSession(record.id);
218
+ store.clearPaused(record.id);
104
219
  await whenFinalized(record.id);
220
+ let segments;
221
+ let segmentPatch = {};
222
+ if (needsJoin(record)) {
223
+ const join = await joinSegments(record, requireFfmpeg());
224
+ segmentPatch = join.patch;
225
+ segments = { count: join.count, ...(join.error ? { error: join.error } : {}) };
226
+ }
105
227
  const replay = record.replay
106
228
  ? await finishReplay(record.replay, {
107
229
  save: opts.saveReplay ?? false,
@@ -112,13 +234,14 @@ async function runStop(store, record, opts) {
112
234
  : undefined;
113
235
  const durationSec = await opts.probe(record.outputPath);
114
236
  const updated = store.update(record.id, {
237
+ ...segmentPatch,
115
238
  status: "stopped",
116
239
  stoppedAt: new Date().toISOString(),
117
240
  durationSec: durationSec ?? undefined,
118
241
  endReason: opts.reason,
119
- error: undefined,
242
+ error: segments?.error,
120
243
  });
121
- return { record: updated, graceful, durationSec, ...(replay ? { replay } : {}) };
244
+ return { record: updated, graceful, durationSec, ...(replay ? { replay } : {}), ...(segments ? { segments } : {}) };
122
245
  }
123
246
  finally {
124
247
  if (stopFile)
@@ -360,6 +360,8 @@ export function buildSpeedArgs(input, output, factor, hasAudio, quality = DEFAUL
360
360
  args.push(output);
361
361
  return args;
362
362
  }
363
+ export const CIRCLE_MASK = "crop='min(iw,ih)':'min(iw,ih)',format=yuva420p," +
364
+ "geq=lum='p(X,Y)':cb='p(X,Y)':cr='p(X,Y)':a='if(lte(hypot(X-W/2,Y-H/2),W/2),255,0)'";
363
365
  export function buildOverlayArgs(input, overlay, output, opts, quality = DEFAULT_EDIT_QUALITY) {
364
366
  const x = requireNonNegativeInt(opts.x, "overlay x");
365
367
  const y = requireNonNegativeInt(opts.y, "overlay y");
@@ -376,6 +378,8 @@ export function buildOverlayArgs(input, overlay, output, opts, quality = DEFAULT
376
378
  const sh = opts.scale.height ?? -1;
377
379
  ovl += `,scale=${sw}:${sh}`;
378
380
  }
381
+ if (opts.shape === "circle")
382
+ ovl += `,${CIRCLE_MASK}`;
379
383
  const filter = `${ovl}[ovl];[0:v][ovl]overlay=${x}:${y}${enable}[v]`;
380
384
  const dur = opts.durationSec;
381
385
  return [
@@ -480,8 +484,9 @@ export const BLUR_PASSES = 3;
480
484
  export const MIN_PIXEL_BLOCK = 16;
481
485
  export function blurRadius(r) {
482
486
  const m = Math.min(r.w, r.h);
483
- const lr = Math.min(Math.floor(m / 2), Math.max(MIN_BLUR_RADIUS, Math.min(20, Math.floor(m / 4))));
484
- const cr = Math.min(lr, Math.floor(Math.ceil(m / 2) / 2));
487
+ const maxRadius = (side) => Math.max(0, Math.floor((side - 1) / 2));
488
+ const lr = Math.min(maxRadius(m), Math.max(MIN_BLUR_RADIUS, Math.min(20, Math.floor(m / 4))));
489
+ const cr = Math.min(lr, maxRadius(Math.ceil(m / 2)));
485
490
  return `lr=${lr}:lp=${BLUR_PASSES}:cr=${cr}:cp=${BLUR_PASSES}`;
486
491
  }
487
492
  export function pixelateFilter(r) {
@@ -1,4 +1,8 @@
1
1
  import { execFile } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
2
6
  import { ScreencastError } from "./errors.js";
3
7
  export function parseMonitors(raw) {
4
8
  const arr = Array.isArray(raw) ? raw : raw ? [raw] : [];
@@ -43,18 +47,48 @@ export function psTimeoutMs(fallback, env = process.env) {
43
47
  const override = Number(env[PS_TIMEOUT_ENV]);
44
48
  return Number.isInteger(override) && override > 0 ? override : fallback;
45
49
  }
50
+ export const MAX_COMMAND_LINE_CHARS = 32_767;
51
+ export function payloadPreamble(path) {
52
+ const b64 = Buffer.from(path, "utf8").toString("base64");
53
+ return `$Payload = [IO.File]::ReadAllText([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64}')), [Text.Encoding]::UTF8)\n`;
54
+ }
55
+ export function powerShellArgs(script, payloadPath) {
56
+ const full = PS_UTF8_PREAMBLE + (payloadPath === undefined ? "" : payloadPreamble(payloadPath)) + script;
57
+ return ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(full, "utf16le").toString("base64")];
58
+ }
59
+ export function commandLineLength(file, args) {
60
+ return [file, ...args].reduce((n, a) => n + a.length + 3, 0);
61
+ }
62
+ export async function withPayloadFile(payload, fn) {
63
+ const path = join(tmpdir(), `screencast-ps-${process.pid}-${randomBytes(6).toString("hex")}.json`);
64
+ writeFileSync(path, payload, { encoding: "utf8", mode: 0o600 });
65
+ try {
66
+ return await fn(path);
67
+ }
68
+ finally {
69
+ rmSync(path, { force: true });
70
+ }
71
+ }
46
72
  export function runPowerShell(script, what, opts = {}) {
47
- const encoded = Buffer.from(PS_UTF8_PREAMBLE + script, "utf16le").toString("base64");
73
+ if (opts.payload === undefined)
74
+ return execPowerShell(script, what, opts);
75
+ return withPayloadFile(opts.payload, (path) => execPowerShell(script, what, opts, path));
76
+ }
77
+ function execPowerShell(script, what, opts, payloadPath) {
48
78
  const timeout = opts.timeoutMs ?? psTimeoutMs(PS_TIMEOUT_MS);
49
79
  const file = opts.command?.file ?? "powershell";
50
- const args = opts.command?.args ?? ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded];
80
+ const args = opts.command?.args ?? powerShellArgs(script, payloadPath);
51
81
  return new Promise((resolve, reject) => {
52
- execFile(file, args, { encoding: "utf8", windowsHide: true, maxBuffer: 8 * 1024 * 1024, timeout, killSignal: "SIGKILL" }, (err, stdout, stderr) => {
53
- if (err && err.killed) {
82
+ execFile(file, args, { encoding: "utf8", windowsHide: true, maxBuffer: 8 * 1024 * 1024, timeout, killSignal: "SIGKILL", signal: opts.signal }, (err, stdout, stderr) => {
83
+ if (opts.signal?.aborted) {
84
+ reject(new ScreencastError(`Cancelled while reading ${what}.`));
85
+ }
86
+ else if (err && err.killed) {
54
87
  reject(new ScreencastError(`Timed out reading ${what} after ${timeout / 1000} s (PowerShell did not answer).`, `Retry; if it keeps happening, restart the app being captured or raise ${PS_TIMEOUT_ENV}.`));
55
88
  }
56
89
  else if (err || !stdout) {
57
- reject(new ScreencastError(`Could not enumerate ${what}: ${stderr?.trim() || err?.message || "powershell failed"}`));
90
+ const label = opts.failure ?? `Could not enumerate ${what}`;
91
+ reject(new ScreencastError(`${label}: ${stderr?.trim() || err?.message || "powershell failed"}`));
58
92
  }
59
93
  else {
60
94
  resolve(stdout);