@tmhs/screencast-mcp 0.46.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.
@@ -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();
@@ -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;
@@ -0,0 +1,173 @@
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 async function resolveEncoder(choice, backend, ffmpeg, run = ffmpegRunner(ffmpeg)) {
80
+ if (choice === "x264")
81
+ return { encoder: "x264", gpuFrames: false };
82
+ const available = await probeHwEncoders(ffmpeg, run);
83
+ const pick = choice === "auto" ? HW_ENCODERS.find((e) => available[e]) : available[choice] ? choice : undefined;
84
+ if (!pick) {
85
+ if (choice === "auto")
86
+ return { encoder: "x264", gpuFrames: false, note: "No hardware encoder passed a trial encode; using libx264." };
87
+ 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
+ }
89
+ const gpuFrames = backend === "ddagrab" && (await cachedProbe(ffmpeg, `dda:${pick}`, buildDdaProbeArgs(pick), run));
90
+ return { encoder: pick, gpuFrames };
91
+ }
92
+ export function ddagrabWorks(ffmpeg, run = ffmpegRunner(ffmpeg)) {
93
+ return cachedProbe(ffmpeg, "dda", buildDdaProbeArgs(), run);
94
+ }
95
+ export function parseDxgiOutputs(stdout) {
96
+ const out = [];
97
+ for (const line of stdout.split(/\r?\n/)) {
98
+ const parts = line.trim().split(",");
99
+ if (parts.length < 7)
100
+ continue;
101
+ const n = parts.slice(0, 6).map(Number);
102
+ if (n.some((v) => !Number.isInteger(v)))
103
+ continue;
104
+ const [adapter = 0, output = 0, x = 0, y = 0, w = 0, h = 0] = n;
105
+ if (w <= 0 || h <= 0)
106
+ continue;
107
+ out.push({ adapter, output, x, y, w, h, name: parts.slice(6).join(",") });
108
+ }
109
+ return out;
110
+ }
111
+ const PS_DXGI = `
112
+ Add-Type -TypeDefinition @"
113
+ using System; using System.Runtime.InteropServices; using System.Text;
114
+ public static class ScDxgi {
115
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
116
+ 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; }
117
+ [ComImport, Guid("770aae78-f26f-4dba-a829-253c83d1b387"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
118
+ interface IF1 { void a(); void b(); void c(); void d(); void e(); void f(); void g(); void h(); void i();
119
+ [PreserveSig] int EnumAdapters1(uint i, [MarshalAs(UnmanagedType.Interface)] out IA1 a); }
120
+ [ComImport, Guid("29038f61-3839-4626-91fd-086879011a05"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
121
+ interface IA1 { void a(); void b(); void c(); void d();
122
+ [PreserveSig] int EnumOutputs(uint i, [MarshalAs(UnmanagedType.Interface)] out IO o); }
123
+ [ComImport, Guid("ae02eedb-c735-4690-8d52-5a8dc20213aa"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
124
+ interface IO { void a(); void b(); void c(); void d(); [PreserveSig] int GetDesc(out DESC d); }
125
+ [DllImport("dxgi.dll")] static extern int CreateDXGIFactory1(ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IF1 f);
126
+ public static string List() {
127
+ Guid g = new Guid("770aae78-f26f-4dba-a829-253c83d1b387"); IF1 f;
128
+ if (CreateDXGIFactory1(ref g, out f) != 0) return "";
129
+ StringBuilder sb = new StringBuilder(); IA1 a;
130
+ for (uint ai = 0; f.EnumAdapters1(ai, out a) == 0; ai++) { IO o;
131
+ for (uint oi = 0; a.EnumOutputs(oi, out o) == 0; oi++) { DESC d;
132
+ 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); } }
133
+ return sb.ToString(); } }
134
+ "@
135
+ [ScDxgi]::List()
136
+ `;
137
+ const DXGI_CACHE_MS = 5_000;
138
+ let dxgiCache = null;
139
+ export function getDxgiOutputs() {
140
+ if (dxgiCache && Date.now() - dxgiCache.at < DXGI_CACHE_MS)
141
+ return dxgiCache.outputs;
142
+ const outputs = runPowerShell(PS_DXGI, "DXGI outputs").then(parseDxgiOutputs);
143
+ dxgiCache = { at: Date.now(), outputs };
144
+ outputs.catch(() => {
145
+ dxgiCache = null;
146
+ });
147
+ return outputs;
148
+ }
149
+ const evenDown = (n) => n - (n % 2);
150
+ export function planDdaSource(rect, outputs) {
151
+ 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;
152
+ const host = outputs.find(holds);
153
+ if (!host) {
154
+ 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".');
155
+ }
156
+ if (host.adapter !== 0) {
157
+ 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.');
158
+ }
159
+ const w = evenDown(rect.w);
160
+ const h = evenDown(rect.h);
161
+ if (w <= 0 || h <= 0)
162
+ throw new ScreencastError("The capture rectangle is too small to record (needs at least 2x2 px).");
163
+ const whole = rect.x === host.x && rect.y === host.y && w === host.w && h === host.h;
164
+ return whole ? { output: host.output } : { output: host.output, crop: { x: rect.x - host.x, y: rect.y - host.y, w, h } };
165
+ }
166
+ export function buildDdaInputArgs(src, fps, opts) {
167
+ const crop = src.crop
168
+ ? `:offset_x=${src.crop.x}:offset_y=${src.crop.y}:video_size=${src.crop.w}x${src.crop.h}`
169
+ : "";
170
+ const mouse = opts.drawMouse === false ? 0 : 1;
171
+ const graph = `ddagrab=output_idx=${src.output}:framerate=${fps}:draw_mouse=${mouse}${crop}${opts.download ? ",hwdownload,format=bgra" : ""}`;
172
+ return ["-f", "lavfi", "-i", graph];
173
+ }