@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
@@ -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
  }
@@ -0,0 +1,317 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { ScreencastError } from "./errors.js";
3
+ import { escapeFilterPath } from "./fonts.js";
4
+ import { MOVE_SAMPLE_MS } from "./events.js";
5
+ import { mapTime, mapWindow } from "./timeline.js";
6
+ import { resolveQuality } from "./targets.js";
7
+ export const CURSOR_SPRITE = { w: 114, h: 168, hotX: 9, hotY: 9, arrowH: 135 };
8
+ export function cursorSpritePath() {
9
+ return fileURLToPath(new URL("../../assets/cursor/arrow.png", import.meta.url));
10
+ }
11
+ export const DEFAULT_SMOOTHING = 0.5;
12
+ export const DEFAULT_HIDE_AFTER_SEC = 2;
13
+ export const DEFAULT_CURSOR_SIZE = 1.5;
14
+ export const RIPPLE_SEC = 0.4;
15
+ const SIM_HZ = 240;
16
+ const PATH_EVERY = 4;
17
+ const SIMPLIFY_PX = 0.35;
18
+ const POSITION_TYPES = new Set(["move", "down", "up", "wheel"]);
19
+ const r3 = (n) => Math.round(n * 1000) / 1000;
20
+ export function springFor(smoothing) {
21
+ const omega = 6 + (1 - smoothing) * 34;
22
+ return { omega, lead: Math.min(2 / omega, 0.2) };
23
+ }
24
+ export function targetPath(samples) {
25
+ const out = [];
26
+ const step = MOVE_SAMPLE_MS / 1000;
27
+ for (const s of samples) {
28
+ const prev = out.at(-1);
29
+ if (prev && s.t - prev.t > step * 2 && (prev.x !== s.x || prev.y !== s.y)) {
30
+ out.push({ t: s.t - step, x: prev.x, y: prev.y });
31
+ }
32
+ if (prev && s.t === prev.t)
33
+ out[out.length - 1] = s;
34
+ else
35
+ out.push(s);
36
+ }
37
+ return out;
38
+ }
39
+ export function pathAt(path, t, from = 0) {
40
+ if (path.length === 0)
41
+ return { x: 0, y: 0, i: 0 };
42
+ let i = Math.max(0, Math.min(from, path.length - 1));
43
+ while (i > 0 && path[i].t > t)
44
+ i--;
45
+ while (i < path.length - 1 && path[i + 1].t <= t)
46
+ i++;
47
+ const a = path[i];
48
+ const b = path[i + 1];
49
+ if (!b || t <= a.t)
50
+ return { x: a.x, y: a.y, i };
51
+ const f = (t - a.t) / (b.t - a.t);
52
+ return { x: a.x + (b.x - a.x) * f, y: a.y + (b.y - a.y) * f, i };
53
+ }
54
+ export function springPath(target, omega, lead, from, to) {
55
+ if (target.length === 0)
56
+ return [];
57
+ const dt = 1 / SIM_HZ;
58
+ let hint = 0;
59
+ const at = (t) => {
60
+ const p = pathAt(target, t + lead, hint);
61
+ hint = p.i;
62
+ return p;
63
+ };
64
+ const start = at(from);
65
+ let x = start.x;
66
+ let y = start.y;
67
+ let vx = 0;
68
+ let vy = 0;
69
+ const out = [{ t: r3(from), x, y }];
70
+ const e = Math.exp(-omega * dt);
71
+ const steps = Math.max(0, Math.ceil((to - from) * SIM_HZ));
72
+ for (let n = 1; n <= steps; n++) {
73
+ const t = Math.min(to, from + n * dt);
74
+ const p = at(t);
75
+ const cx = x - p.x;
76
+ const cy = y - p.y;
77
+ const tx = (vx + omega * cx) * dt;
78
+ const ty = (vy + omega * cy) * dt;
79
+ vx = (vx - omega * tx) * e;
80
+ vy = (vy - omega * ty) * e;
81
+ x = p.x + (cx + tx) * e;
82
+ y = p.y + (cy + ty) * e;
83
+ if (n % PATH_EVERY === 0 || n === steps)
84
+ out.push({ t: r3(t), x, y });
85
+ }
86
+ return out;
87
+ }
88
+ export function simplifyPath(path, tol = SIMPLIFY_PX) {
89
+ if (path.length <= 2)
90
+ return [...path];
91
+ const keep = new Uint8Array(path.length);
92
+ keep[0] = 1;
93
+ keep[path.length - 1] = 1;
94
+ const stack = [[0, path.length - 1]];
95
+ while (stack.length > 0) {
96
+ const [a, b] = stack.pop();
97
+ const A = path[a];
98
+ const B = path[b];
99
+ let worst = -1;
100
+ let at = -1;
101
+ for (let i = a + 1; i < b; i++) {
102
+ const P = path[i];
103
+ const f = B.t > A.t ? (P.t - A.t) / (B.t - A.t) : 0;
104
+ const d = Math.hypot(P.x - (A.x + (B.x - A.x) * f), P.y - (A.y + (B.y - A.y) * f));
105
+ if (d > worst) {
106
+ worst = d;
107
+ at = i;
108
+ }
109
+ }
110
+ if (worst > tol) {
111
+ keep[at] = 1;
112
+ stack.push([a, at], [at, b]);
113
+ }
114
+ }
115
+ return path.filter((_, i) => keep[i] === 1);
116
+ }
117
+ function mergeWindows(ws) {
118
+ const out = [];
119
+ for (const w of [...ws].sort((a, b) => a[0] - b[0])) {
120
+ const last = out.at(-1);
121
+ if (last && w[0] <= last[1])
122
+ last[1] = Math.max(last[1], w[1]);
123
+ else
124
+ out.push([w[0], w[1]]);
125
+ }
126
+ return out;
127
+ }
128
+ export function planCursor(events, opts = {}, endSec = null) {
129
+ const smoothing = opts.smoothing ?? DEFAULT_SMOOTHING;
130
+ if (!(smoothing >= 0 && smoothing <= 1))
131
+ throw new ScreencastError("smoothing must be between 0 and 1.");
132
+ const hideAfter = opts.hideAfterSec ?? DEFAULT_HIDE_AFTER_SEC;
133
+ if (!(hideAfter >= 0))
134
+ throw new ScreencastError("hideAfterSec must be 0 or more.");
135
+ const samples = events
136
+ .filter((e) => POSITION_TYPES.has(e.type) && Number.isFinite(e.t) && e.t >= 0 && Number.isFinite(e.x) && Number.isFinite(e.y))
137
+ .filter((e) => endSec === null || e.t <= endSec)
138
+ .sort((a, b) => a.t - b.t);
139
+ if (samples.length === 0)
140
+ return { path: [], visible: [], clicks: [] };
141
+ const target = targetPath(samples.map((e) => ({ t: e.t, x: e.x, y: e.y })));
142
+ const first = target[0].t;
143
+ const last = target.at(-1).t;
144
+ let path;
145
+ let lead = 0;
146
+ if (smoothing === 0) {
147
+ path = target.map((p) => ({ ...p }));
148
+ if (endSec !== null && endSec > last)
149
+ path.push({ ...target.at(-1), t: endSec });
150
+ }
151
+ else {
152
+ const spring = springFor(smoothing);
153
+ lead = spring.lead;
154
+ const from = Math.max(0, first - lead);
155
+ const to = Math.max(from, endSec ?? last + 8 / spring.omega);
156
+ path = springPath(target, spring.omega, lead, from, to);
157
+ }
158
+ const start = Math.max(0, first - lead);
159
+ const visible = hideAfter === 0
160
+ ? [[start, endSec ?? Infinity]]
161
+ : mergeWindows(samples.map((e) => [Math.max(0, e.t - lead), e.t + hideAfter]));
162
+ const clicks = samples.filter((e) => e.type === "down").map((e) => ({ t: e.t, x: e.x, y: e.y }));
163
+ return {
164
+ path,
165
+ visible: visible.map(([a, b]) => [r3(a), endSec !== null ? Math.min(b, endSec) : b]).filter(([a, b]) => b > a),
166
+ clicks,
167
+ };
168
+ }
169
+ const IDENTITY = { sx: 1, sy: 1, ox: 0, oy: 0 };
170
+ export function transformCursor(plan, ops = [], geo = IDENTITY) {
171
+ const move = (p) => {
172
+ const t = mapTime(p.t, ops);
173
+ return t === null ? null : { t: r3(t), x: p.x * geo.sx + geo.ox, y: p.y * geo.sy + geo.oy };
174
+ };
175
+ const path = [];
176
+ for (const p of plan.path) {
177
+ const m = move(p);
178
+ if (!m)
179
+ continue;
180
+ if (path.length > 0 && path.at(-1).t >= m.t)
181
+ path[path.length - 1] = { ...m, t: path.at(-1).t };
182
+ else
183
+ path.push(m);
184
+ }
185
+ const visible = plan.visible.flatMap(([a, b]) => {
186
+ const w = mapWindow(a, b, ops);
187
+ return w && w[1] - w[0] >= 0.05 ? [[r3(w[0]), Number.isFinite(w[1]) ? r3(w[1]) : w[1]]] : [];
188
+ });
189
+ const clicks = plan.clicks.flatMap((c) => {
190
+ const m = move(c);
191
+ return m ? [m] : [];
192
+ });
193
+ return { path: simplifyPath(path), visible, clicks };
194
+ }
195
+ const num = (n, d = 2) => {
196
+ const v = Number(n.toFixed(d));
197
+ return Object.is(v, -0) ? "0" : String(v);
198
+ };
199
+ export function linearExpr(v0, t0, k) {
200
+ const kk = Number(k.toFixed(3));
201
+ if (kk === 0)
202
+ return num(v0);
203
+ return `${num(v0)}${kk < 0 ? "-" : "+"}(t-${num(t0, 3)})*${num(Math.abs(kk), 3)}`;
204
+ }
205
+ export function cursorLayout(frameH, size = DEFAULT_CURSOR_SIZE) {
206
+ if (!(size >= 0.25 && size <= 8))
207
+ throw new ScreencastError("size must be between 0.25 and 8.");
208
+ const arrowH = Math.max(8, frameH * 0.025 * size);
209
+ const k = arrowH / CURSOR_SPRITE.arrowH;
210
+ const d = Math.max(12, Math.round(arrowH * 2.2));
211
+ return {
212
+ spriteW: Math.max(2, Math.round(CURSOR_SPRITE.w * k)),
213
+ spriteH: Math.max(2, Math.round(CURSOR_SPRITE.h * k)),
214
+ hotX: CURSOR_SPRITE.hotX * k,
215
+ hotY: CURSOR_SPRITE.hotY * k,
216
+ ripples: [0.45, 0.72, 1].map((f) => Math.max(6, Math.round((d * f) / 2) * 2)),
217
+ spotRadius: Math.max(24, Math.round(frameH * 0.12)),
218
+ };
219
+ }
220
+ export function formatCommands(cmds) {
221
+ const byTime = new Map();
222
+ for (const c of [...cmds].sort((a, b) => a.t - b.t)) {
223
+ const key = num(Math.max(0, c.t), 3);
224
+ const list = byTime.get(key) ?? [];
225
+ list.push(c.text);
226
+ byTime.set(key, list);
227
+ }
228
+ return [...byTime.entries()].map(([t, list]) => `${t} ${list.join(", ")};`).join("\n") + "\n";
229
+ }
230
+ function pathCommands(path, target, dx, dy) {
231
+ return path.map((p, i) => {
232
+ const n = path[i + 1];
233
+ const span = n ? n.t - p.t : 0;
234
+ const kx = n && span > 0 ? (n.x - p.x) / span : 0;
235
+ const ky = n && span > 0 ? (n.y - p.y) / span : 0;
236
+ return {
237
+ t: p.t,
238
+ text: `${target} x ${linearExpr(p.x + dx, p.t, kx)}, ${target} y ${linearExpr(p.y + dy, p.t, ky)}`,
239
+ };
240
+ });
241
+ }
242
+ function windowCommands(windows, target) {
243
+ return windows.flatMap(([a, b]) => [
244
+ { t: a, text: `${target} enable 1` },
245
+ ...(Number.isFinite(b) ? [{ t: b, text: `${target} enable 0` }] : []),
246
+ ]);
247
+ }
248
+ export function cursorSteps(plan, style, frame, input, firstInput, tag, sprite, commandsFile) {
249
+ if (plan.path.length === 0)
250
+ throw new ScreencastError("No cursor positions to draw.");
251
+ const L = cursorLayout(frame.height, style.size);
252
+ const { width: W, height: H } = frame;
253
+ const name = (s) => `overlay@${tag}c${s}`;
254
+ const steps = [];
255
+ const cmds = [];
256
+ const p0 = plan.path[0];
257
+ let cur = `[${tag}cm]`;
258
+ steps.push(`${input}sendcmd=f=${escapeFilterPath(commandsFile)}${cur}`);
259
+ const layer = (src, id, dx, dy, windows) => {
260
+ const out = `[${tag}c${id}o]`;
261
+ steps.push(`${cur}${src}${name(id)}=x=${num(p0.x + dx)}:y=${num(p0.y + dy)}:enable=0${out}`);
262
+ cmds.push(...windowCommands(windows, name(id)));
263
+ cur = out;
264
+ };
265
+ if (style.spotlight) {
266
+ const q = 4;
267
+ const mw = Math.ceil((2 * W) / q);
268
+ const mh = Math.ceil((2 * H) / q);
269
+ const r = L.spotRadius / q;
270
+ const feather = r * 0.8;
271
+ const a = `255*0.55*clip((hypot(X-${num(mw / 2)},Y-${num(mh / 2)})-${num(r)})/${num(feather)},0,1)`;
272
+ steps.push(`color=c=black:s=${mw}x${mh}:r=1:d=1,format=rgba,geq=r=0:g=0:b=0:a='${a}',scale=${2 * W}:${2 * H}[${tag}csm]`);
273
+ const cx = L.spriteW * 0.25 - W;
274
+ const cy = L.spriteH * 0.3 - H;
275
+ layer(`[${tag}csm]`, "s", cx, cy, plan.visible);
276
+ cmds.push(...pathCommands(plan.path, name("s"), cx, cy));
277
+ }
278
+ if (style.clicks !== false && plan.clicks.length > 0) {
279
+ const third = RIPPLE_SEC / 3;
280
+ L.ripples.forEach((d, k) => {
281
+ const c = d / 2;
282
+ const th = Math.max(1.5, d * 0.05);
283
+ const dist = `abs(hypot(X-${num(c - 0.5)},Y-${num(c - 0.5)})-${num(c - th - 1)})`;
284
+ const alpha = [0.9, 0.65, 0.4][k];
285
+ const white = `255*lt(${dist},${num(th * 0.45)})`;
286
+ steps.push(`color=c=black:s=${d}x${d}:r=1:d=1,format=rgba,geq=r='${white}':g='${white}':b='${white}':` +
287
+ `a='255*${alpha}*clip(${num(th)}-${dist},0,1)'[${tag}cr${k}]`);
288
+ const windows = plan.clicks.map((p) => [p.t + k * third, p.t + (k + 1) * third]);
289
+ layer(`[${tag}cr${k}]`, `r${k}`, -c, -c, []);
290
+ for (const [i, p] of plan.clicks.entries()) {
291
+ const [a, b] = windows[i];
292
+ const next = windows[i + 1];
293
+ cmds.push({ t: a, text: `${name(`r${k}`)} x ${num(p.x - c)}, ${name(`r${k}`)} y ${num(p.y - c)}, ${name(`r${k}`)} enable 1` });
294
+ if (!next || next[0] >= b)
295
+ cmds.push({ t: b, text: `${name(`r${k}`)} enable 0` });
296
+ }
297
+ });
298
+ }
299
+ steps.push(`[${firstInput}:v]scale=${L.spriteW}:${L.spriteH}:flags=lanczos,format=rgba[${tag}csp]`);
300
+ layer(`[${tag}csp]`, "p", -L.hotX, -L.hotY, plan.visible);
301
+ cmds.push(...pathCommands(plan.path, name("p"), -L.hotX, -L.hotY));
302
+ return { steps, out: cur, extraInputs: ["-i", sprite], commands: formatCommands(cmds) };
303
+ }
304
+ export function buildCursorArgs(input, output, plan, style, frame, sprite, commandsFile, quality = "standard") {
305
+ const { steps, out, extraInputs, commands } = cursorSteps(plan, style, frame, "[0:v]", 1, "", sprite, commandsFile);
306
+ return {
307
+ args: [
308
+ "-y", "-i", input, ...extraInputs,
309
+ "-filter_complex", steps.join(";"),
310
+ "-map", out, "-map", "0:a?",
311
+ ...resolveQuality(quality),
312
+ "-c:a", "copy",
313
+ output,
314
+ ],
315
+ commands,
316
+ };
317
+ }
@@ -4,14 +4,29 @@ import { ScreencastError } from "./errors.js";
4
4
  export const DEFAULT_KEY_MODE = "masked";
5
5
  export const EVENT_TYPES = ["down", "up", "move", "wheel", "key", "typing", "gap"];
6
6
  export const MOVE_SAMPLE_MS = 33;
7
- export function parseCaptureStart(stderr) {
8
- const input = stderr.indexOf("Input #0");
7
+ export function parseCaptureStart(stderr, inputIndex = 0) {
8
+ const input = stderr.indexOf(`Input #${inputIndex},`);
9
9
  if (input < 0)
10
10
  return null;
11
- const m = /start: (\d{9,}\.\d+)/.exec(stderr.slice(input));
11
+ const next = stderr.indexOf("Input #", input + 1);
12
+ const m = /start: (\d{9,}\.\d+)/.exec(stderr.slice(input, next < 0 ? undefined : next));
12
13
  return m ? Math.round(Number(m[1]) * 1000) : null;
13
14
  }
15
+ export function videoTimeSec(epochMs, spans) {
16
+ const first = spans[0];
17
+ if (!first)
18
+ return null;
19
+ if (epochMs < first.startMs)
20
+ return (epochMs - first.startMs) / 1000;
21
+ for (const s of spans) {
22
+ const rel = (epochMs - s.startMs) / 1000;
23
+ if (rel >= 0 && (s.durationSec === undefined || rel <= s.durationSec))
24
+ return s.offsetSec + rel;
25
+ }
26
+ return null;
27
+ }
14
28
  export function convertEvents(raw, opts) {
29
+ const spans = opts.spans && opts.spans.length > 0 ? opts.spans : null;
15
30
  const out = [];
16
31
  const beats = [];
17
32
  let missFrom = null;
@@ -31,7 +46,10 @@ export function convertEvents(raw, opts) {
31
46
  const dy = Number(ys);
32
47
  if (!Number.isFinite(epoch) || !Number.isFinite(dx) || !Number.isFinite(dy))
33
48
  continue;
34
- const t = Math.round(epoch - opts.startMs) / 1000;
49
+ const vt = spans ? videoTimeSec(epoch, spans) : (epoch - opts.startMs) / 1000;
50
+ if (vt === null)
51
+ continue;
52
+ const t = Math.round(vt * 1000) / 1000;
35
53
  if (type === "hb") {
36
54
  beats.push(t);
37
55
  continue;
@@ -160,6 +178,7 @@ public static class ScEvents{
160
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);
161
179
  struct LII{public uint cb;public uint t;}
162
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;
163
182
  static HashSet<uint> held=new HashSet<uint>();
164
183
  static readonly object q=new object();static StringBuilder buf=new StringBuilder();
165
184
  static double typeStart=-1,typeLast;static int lastHook=Environment.TickCount;static bool missing;
@@ -175,15 +194,18 @@ public static class ScEvents{
175
194
  static void Typed(){double t=Now();lock(q){if(typeStart<0)typeStart=t;typeLast=t;}}
176
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;}
177
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));}
178
- static void Drain(){lock(w){string s;lock(q){s=buf.ToString();buf.Clear();}if(s.Length>0){w.Write(s);w.Flush();}}}
179
- 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));}}
180
201
  static void Pump(string stop){int tick=0;while(true){Thread.Sleep(250);tick++;
181
202
  EndTyping(false);
182
203
  lock(held){foreach(uint vk in new List<uint>(held)){if(!Down((int)vk))held.Remove(vk);}}
183
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,"");}
184
205
  if(tick%4==0)Put("hb",0,0,"");
185
206
  if(File.Exists(stop))Quit();
186
- Drain();}}
207
+ Drain();
208
+ if(Rot>0&&unchecked(Environment.TickCount-lastRot)>=Rot){lastRot=Environment.TickCount;Rotate();}}}
187
209
  static IntPtr Mouse(int n,IntPtr wp,IntPtr lp){
188
210
  if(n>=0){Seen();MS s=(MS)Marshal.PtrToStructure(lp,typeof(MS));int m=(int)wp;cx=s.x;cy=s.y;
189
211
  if(m==0x200){double t=Now();if(t-lastMove>=${MOVE_SAMPLE_MS}){lastMove=t;Put("move",s.x,s.y,"");}}
@@ -216,7 +238,7 @@ public static class ScEvents{
216
238
  return CallNextHookEx(IntPtr.Zero,n,wp,lp);}
217
239
  public static void Run(string path,bool shortcuts,int parent){
218
240
  try{SetProcessDpiAwarenessContext(new IntPtr(-4));}catch{}
219
- 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));
220
242
  IntPtr mod=GetModuleHandle(null);mp=Mouse;kp=Key;
221
243
  if(SetWindowsHookEx(14,mp,mod,0)==IntPtr.Zero||SetWindowsHookEx(13,kp,mod,0)==IntPtr.Zero)throw new Exception("SetWindowsHookEx failed: "+Marshal.GetLastWin32Error());
222
244
  var watch=new Thread(()=>{while(true){Thread.Sleep(500);bool gone;try{gone=Process.GetProcessById(parent).HasExited;}catch{gone=true;}if(gone)Quit();}});
@@ -227,12 +249,40 @@ public static class ScEvents{
227
249
  }
228
250
  }
229
251
  "@
252
+ [ScEvents]::Rot=__ROTATE__
230
253
  [ScEvents]::Run([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PATH__')), [bool]__MODE__, __PARENT__)
231
254
  `;
232
- 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));
233
257
  return PS_HOOK.replace("__PATH__", Buffer.from(rawPath, "utf8").toString("base64"))
234
258
  .replace("__MODE__", mode === "shortcuts" ? "1" : "0")
235
- .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);
236
286
  }
237
287
  export function cleanPsError(stderr) {
238
288
  if (!stderr.startsWith("#< CLIXML"))
@@ -247,12 +297,12 @@ export function cleanPsError(stderr) {
247
297
  .trim();
248
298
  }
249
299
  export const LOGGER_READY_TIMEOUT_MS = 20_000;
250
- export async function startEventLogger(rawPath, mode) {
300
+ export async function startEventLogger(rawPath, mode, opts = {}) {
251
301
  if (process.platform !== "win32") {
252
302
  throw new ScreencastError("The input event log is implemented for Windows only.");
253
303
  }
254
304
  rmSync(`${rawPath}.stop`, { force: true });
255
- 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");
256
306
  const child = spawn("powershell", ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], {
257
307
  stdio: ["ignore", "pipe", "pipe"],
258
308
  windowsHide: true,