@tmhs/screencast-mcp 0.45.0 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +138 -82
  2. package/assets/cursor/arrow.png +0 -0
  3. package/dist/cli.js +360 -0
  4. package/dist/index.js +10 -2
  5. package/dist/prompts.js +16 -3
  6. package/dist/server.js +18 -0
  7. package/dist/tools/addMarker.js +6 -2
  8. package/dist/tools/bugReport.js +2 -2
  9. package/dist/tools/chapters.js +1 -1
  10. package/dist/tools/cursor.js +87 -0
  11. package/dist/tools/cutByTranscript.js +86 -0
  12. package/dist/tools/doctor.js +14 -1
  13. package/dist/tools/indexRecording.js +173 -0
  14. package/dist/tools/listVideoDevices.js +26 -0
  15. package/dist/tools/narrate.js +84 -0
  16. package/dist/tools/overlay.js +2 -0
  17. package/dist/tools/pauseRecording.js +44 -0
  18. package/dist/tools/pipeline.js +215 -19
  19. package/dist/tools/readEvents.js +1 -1
  20. package/dist/tools/resumeRecording.js +46 -0
  21. package/dist/tools/reviewRecording.js +1 -1
  22. package/dist/tools/searchRecording.js +73 -0
  23. package/dist/tools/startRecording.js +106 -67
  24. package/dist/tools/stepGuide.js +193 -0
  25. package/dist/tools/stopRecording.js +38 -3
  26. package/dist/tools/transcribe.js +4 -3
  27. package/dist/tools/zoom.js +1 -1
  28. package/dist/utils/audio.js +12 -4
  29. package/dist/utils/audioDevices.js +34 -4
  30. package/dist/utils/bugReport.js +1 -75
  31. package/dist/utils/captions.js +19 -6
  32. package/dist/utils/chapters.js +5 -0
  33. package/dist/utils/cursor.js +317 -0
  34. package/dist/utils/events.js +22 -4
  35. package/dist/utils/gpu.js +173 -0
  36. package/dist/utils/idle.js +10 -3
  37. package/dist/utils/keystrokes.js +2 -17
  38. package/dist/utils/lifecycle.js +85 -2
  39. package/dist/utils/media.js +4 -0
  40. package/dist/utils/monitors.js +5 -2
  41. package/dist/utils/narrate.js +224 -0
  42. package/dist/utils/pause.js +176 -0
  43. package/dist/utils/pipeline.js +154 -14
  44. package/dist/utils/recipes.js +67 -0
  45. package/dist/utils/recorder.js +163 -0
  46. package/dist/utils/recordingIndex.js +266 -0
  47. package/dist/utils/sessions.js +29 -5
  48. package/dist/utils/stepGuide.js +205 -0
  49. package/dist/utils/steps.js +88 -0
  50. package/dist/utils/targets.js +31 -7
  51. package/dist/utils/timeline.js +85 -0
  52. package/dist/utils/toolsets.js +17 -6
  53. package/dist/utils/transcriptCut.js +134 -0
  54. package/dist/utils/wgc.js +2 -2
  55. package/dist/wgcRecorder.js +1 -1
  56. package/package.json +3 -1
@@ -14,6 +14,12 @@ export const NO_LOOPBACK_HINT = "System audio capture needs a virtual-audio loop
14
14
  "virtual-audio-capturer, or VB-CABLE). Then pass its name as `device`, or run " +
15
15
  "list_audio_devices to see what is available. Microphone capture is not supported.";
16
16
  export function parseDshowAudioDevices(stderr) {
17
+ return parseDshowDevices(stderr, "audio");
18
+ }
19
+ export function parseDshowVideoDevices(stderr) {
20
+ return parseDshowDevices(stderr, "video");
21
+ }
22
+ function parseDshowDevices(stderr, kind) {
17
23
  const names = [];
18
24
  let section = null;
19
25
  for (const line of stderr.split(/\r?\n/)) {
@@ -33,7 +39,8 @@ export function parseDshowAudioDevices(stderr) {
33
39
  const inlineAudio = /\(audio\)/i.test(line);
34
40
  const inlineVideo = /\(video\)/i.test(line);
35
41
  const isAudio = inlineAudio || (!inlineVideo && section === "audio");
36
- if (isAudio && quoted[1])
42
+ const isVideo = inlineVideo || (!inlineAudio && section === "video");
43
+ if ((kind === "audio" ? isAudio : isVideo) && quoted[1])
37
44
  names.push(quoted[1]);
38
45
  }
39
46
  return [...new Set(names)];
@@ -50,9 +57,32 @@ const ENUM_FAILED_HINT = "Enumerating DirectShow audio devices timed out or fail
50
57
  "misbehaving audio driver, or no audio device present. Record without system " +
51
58
  "audio, or fix the device, then retry. " + NO_LOOPBACK_HINT;
52
59
  let cachedDevices = null;
60
+ let cachedVideo = null;
53
61
  export async function listDshowAudioDevices(forceRefresh = false) {
54
62
  if (!forceRefresh && cachedDevices)
55
63
  return cachedDevices;
64
+ await enumerateDshow();
65
+ return cachedDevices ?? [];
66
+ }
67
+ export async function listDshowVideoDevices(forceRefresh = false) {
68
+ if (!forceRefresh && cachedVideo)
69
+ return cachedVideo;
70
+ await enumerateDshow();
71
+ return cachedVideo ?? [];
72
+ }
73
+ export async function resolveVideoDevice(explicit) {
74
+ const devices = await listDshowVideoDevices();
75
+ if (explicit && explicit.trim().length > 0) {
76
+ if (devices.includes(explicit))
77
+ return explicit;
78
+ throw new ScreencastError(`Video device "${explicit}" not found. Available dshow video devices: ${devices.join(", ") || "none"}.`);
79
+ }
80
+ const first = devices[0];
81
+ if (!first)
82
+ throw new ScreencastError("No webcam (dshow video device) found.", "Connect a camera, then run list_video_devices.");
83
+ return first;
84
+ }
85
+ async function enumerateDshow() {
56
86
  const { ffmpeg } = requireFfmpeg();
57
87
  let res;
58
88
  try {
@@ -61,12 +91,12 @@ export async function listDshowAudioDevices(forceRefresh = false) {
61
91
  catch (err) {
62
92
  throw new ScreencastError(`Could not enumerate audio devices (${err.message}).`, ENUM_FAILED_HINT);
63
93
  }
64
- const devices = parseDshowAudioDevices(res.stderr);
65
- cachedDevices = devices;
66
- return devices;
94
+ cachedDevices = parseDshowAudioDevices(res.stderr);
95
+ cachedVideo = parseDshowVideoDevices(res.stderr);
67
96
  }
68
97
  export function clearAudioDeviceCache() {
69
98
  cachedDevices = null;
99
+ cachedVideo = null;
70
100
  }
71
101
  export async function resolveLoopbackDevice(explicit) {
72
102
  const devices = await listDshowAudioDevices();
@@ -42,81 +42,7 @@ export function clipWindow(durationSec, opts = {}) {
42
42
  }
43
43
  return { start: r3(start), end: r3(end) };
44
44
  }
45
- const DOUBLE_CLICK_SEC = 0.5;
46
- const DOUBLE_CLICK_PX = 6;
47
- const SCROLL_JOIN_SEC = 1;
48
- const GAP_WHY = {
49
- input_not_seen: "input went to an elevated window or the lock screen, or the hook was removed",
50
- helper_stalled: "the event logger paused",
51
- helper_stopped: "the event logger stopped",
52
- };
53
- function clickText(button, double, e) {
54
- const verb = double ? "double-click" : "click";
55
- const which = button && button !== "left" ? `${button.charAt(0).toUpperCase()}${button.slice(1)} ${verb}` : `${verb.charAt(0).toUpperCase()}${verb.slice(1)}`;
56
- return e.inFrame ? `${which} at (${e.x}, ${e.y})` : `${which} outside the recorded area`;
57
- }
58
- export function reconstructSteps(events) {
59
- const steps = [];
60
- const sorted = [...events].sort((a, b) => a.t - b.t);
61
- let lastDown = null;
62
- let scroll = null;
63
- const scrollText = (axis, notches) => {
64
- const dir = axis === "vertical" ? (notches >= 0 ? "up" : "down") : notches >= 0 ? "right" : "left";
65
- const n = Math.abs(notches);
66
- return `Scroll ${dir} ${n} notch${n === 1 ? "" : "es"}`;
67
- };
68
- for (const e of sorted) {
69
- if (e.type === "move" || e.type === "up")
70
- continue;
71
- if (e.type !== "wheel")
72
- scroll = null;
73
- if (e.type === "down") {
74
- const prev = lastDown;
75
- if (prev &&
76
- prev.e.button === e.button &&
77
- e.t - prev.e.t <= DOUBLE_CLICK_SEC &&
78
- Math.abs(e.x - prev.e.x) <= DOUBLE_CLICK_PX &&
79
- Math.abs(e.y - prev.e.y) <= DOUBLE_CLICK_PX &&
80
- prev.step.action === "click" &&
81
- steps.at(-1) === prev.step) {
82
- prev.step.action = "double_click";
83
- prev.step.text = clickText(e.button, true, prev.e);
84
- lastDown = null;
85
- continue;
86
- }
87
- const step = { t: e.t, action: "click", text: clickText(e.button, false, e), x: e.x, y: e.y };
88
- steps.push(step);
89
- lastDown = { e, step };
90
- continue;
91
- }
92
- lastDown = null;
93
- if (e.type === "wheel") {
94
- const axis = e.axis ?? "vertical";
95
- const delta = e.delta ?? 0;
96
- if (scroll && scroll.axis === axis && e.t - scroll.last <= SCROLL_JOIN_SEC && Math.sign(delta) === Math.sign(scroll.notches)) {
97
- scroll.notches += delta;
98
- scroll.last = e.t;
99
- scroll.step.text = scrollText(axis, scroll.notches);
100
- continue;
101
- }
102
- const step = { t: e.t, action: "scroll", text: scrollText(axis, delta), x: e.x, y: e.y };
103
- steps.push(step);
104
- scroll = { step, axis, notches: delta, last: e.t };
105
- }
106
- else if (e.type === "key") {
107
- steps.push({ t: e.t, action: "shortcut", text: `Press ${e.keys ?? "a shortcut"}` });
108
- }
109
- else if (e.type === "typing") {
110
- const d = e.durationSec ?? 0;
111
- steps.push({ t: e.t, action: "typing", text: `Type${d > 0 ? ` for ${r3(d)} s` : ""} (keys are not logged)` });
112
- }
113
- else if (e.type === "gap") {
114
- const why = GAP_WHY[e.reason ?? "input_not_seen"];
115
- steps.push({ t: e.t, action: "gap", text: `Input may be missing for ${r3(e.durationSec ?? 0)} s (${why})` });
116
- }
117
- }
118
- return steps;
119
- }
45
+ export { reconstructSteps } from "./steps.js";
120
46
  function mostlyOverlap(a, b) {
121
47
  const w = Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x);
122
48
  const h = Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y);
@@ -14,7 +14,7 @@ export function resolveWhisperModel(arg, env = process.env) {
14
14
  throw new ScreencastError(`Whisper model not found: ${model}`, MODEL_HINT);
15
15
  return model;
16
16
  }
17
- export function buildTranscribeArgs(input, model, srtOut, language = "auto") {
17
+ export function buildTranscribeArgs(input, model, srtOut, language = "auto", words = false) {
18
18
  if (!/^[a-z]{2,3}$|^auto$/.test(language)) {
19
19
  throw new ScreencastError(`language must be a code like "en" or "auto", got "${language}".`);
20
20
  }
@@ -22,10 +22,21 @@ export function buildTranscribeArgs(input, model, srtOut, language = "auto") {
22
22
  "-y", "-v", "error", "-i", input, "-vn",
23
23
  "-af",
24
24
  `aresample=16000,whisper=model=${escapeFilterPath(model)}:language=${language}:format=srt:` +
25
- `destination=${escapeFilterPath(srtOut)}:use_gpu=false`,
25
+ `destination=${escapeFilterPath(srtOut)}:use_gpu=false` + (words ? ":max_len=1" : ""),
26
26
  "-f", "null", "-",
27
27
  ];
28
28
  }
29
+ export function mergePunctuation(cues) {
30
+ const out = [];
31
+ for (const c of cues) {
32
+ const prev = out[out.length - 1];
33
+ if (prev && !/[\p{L}\p{N}]/u.test(c.text))
34
+ prev.text += c.text.trim();
35
+ else
36
+ out.push({ ...c });
37
+ }
38
+ return out;
39
+ }
29
40
  const TIME = /(\d+):(\d{2}):(\d{2})[,.](\d{3})/;
30
41
  const toSec = (m) => Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3]) + Number(m[4]) / 1000;
31
42
  function fmt(sec) {
@@ -72,15 +83,17 @@ export const CAPTION_STYLES = {
72
83
  clean: "FontName=Inter,FontSize=16,PrimaryColour=&H00FFFFFF,OutlineColour=&H00000000,BorderStyle=1,Outline=1.5,Shadow=0,MarginV=16",
73
84
  social: "FontName=Inter,Bold=1,FontSize=22,PrimaryColour=&H00FFFFFF,BackColour=&H99000000,BorderStyle=3,Outline=6,Shadow=0,MarginV=40",
74
85
  };
75
- export function buildBurnSubtitlesArgs(input, subtitles, output, fontsDir, style = "clean", quality = "standard") {
86
+ export function subtitlesFilter(subtitles, fontsDir, style = "clean") {
76
87
  const force = style === null ? null : CAPTION_STYLES[style];
77
88
  if (force === undefined)
78
89
  throw new ScreencastError(`Unknown caption style "${style}".`);
90
+ return (`subtitles=filename=${escapeFilterPath(subtitles)}:fontsdir=${escapeFilterPath(fontsDir)}` +
91
+ (force ? `:force_style='${force}'` : ""));
92
+ }
93
+ export function buildBurnSubtitlesArgs(input, subtitles, output, fontsDir, style = "clean", quality = "standard") {
79
94
  return [
80
95
  "-y", "-i", input,
81
- "-vf",
82
- `subtitles=filename=${escapeFilterPath(subtitles)}:fontsdir=${escapeFilterPath(fontsDir)}` +
83
- (force ? `:force_style='${force}'` : ""),
96
+ "-vf", subtitlesFilter(subtitles, fontsDir, style),
84
97
  ...resolveQuality(quality),
85
98
  "-c:a", "copy",
86
99
  output,
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
2
  import { ScreencastError } from "./errors.js";
3
3
  import { requireFfmpeg, runCapture } from "./ffmpeg.js";
4
+ import { cutShift } from "./timeline.js";
4
5
  export const MAX_MARKERS = 500;
5
6
  export const MAX_LABEL = 200;
6
7
  export const YOUTUBE_MIN_CHAPTERS = 3;
@@ -69,6 +70,10 @@ export function retimeMarkers(markers, ops) {
69
70
  cur = cur.map((m) => ({ ...m, t: r3(m.t / op.factor) }));
70
71
  continue;
71
72
  }
73
+ if (op.op === "cut") {
74
+ cur = cur.map((m) => ({ ...m, t: r3(m.t - cutShift(m.t, op.spans)) }));
75
+ continue;
76
+ }
72
77
  const inside = cur.filter((m) => m.t >= op.start && m.t < op.end).map((m) => ({ ...m, t: r3(m.t - op.start) }));
73
78
  const carried = cur.filter((m) => m.t < op.start).at(-1);
74
79
  cur = carried && !inside.some((m) => m.t < 0.001) ? [{ ...carried, t: 0 }, ...inside] : inside;
@@ -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;