@clipy/cli 0.15.0 → 0.16.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.
- package/README.md +53 -3
- package/dist/cdpClient.js +277 -0
- package/dist/cdpDiagnostics.js +644 -0
- package/dist/chromeExtensionCapture.js +197 -56
- package/dist/chromeForClipy.js +588 -111
- package/dist/index.js +1187 -125
- package/dist/linuxScreen.js +655 -0
- package/dist/macBridge.js +11 -1
- package/dist/processProbe.js +265 -0
- package/dist/skill.js +55 -21
- package/package.json +4 -4
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Linux screen capture for agents (`--source screen` on Linux).
|
|
3
|
+
*
|
|
4
|
+
* There is no Clipy desktop app on Linux, so the CLI records the X11 display
|
|
5
|
+
* itself with ffmpeg's x11grab, the same tool `clipy proof` already uses:
|
|
6
|
+
*
|
|
7
|
+
* - a display (one monitor of an X screen, or the whole screen);
|
|
8
|
+
* - one window by id, which is that window's own pixels. Under a compositor
|
|
9
|
+
* (GNOME, KDE, picom, xcompmgr) a window that is covered still records in
|
|
10
|
+
* full, and nothing from the window on top appears, which matches the Mac
|
|
11
|
+
* app's window-only mode. Without a compositor the covered part is black;
|
|
12
|
+
* - a private virtual display (Xvfb) that only the agent draws on, so the
|
|
13
|
+
* user's screen, cursor and keyboard are never involved.
|
|
14
|
+
*
|
|
15
|
+
* ffmpeg's window capture keeps the size it started with and fails when the
|
|
16
|
+
* window shrinks, so a window take is recorded in segments: a size change
|
|
17
|
+
* closes the segment and opens a new one, and `finish` joins them, fitting
|
|
18
|
+
* every segment into the first one's frame and holding the last frame across
|
|
19
|
+
* the short restart gap so marks stay in sync with the picture.
|
|
20
|
+
*
|
|
21
|
+
* Wayland does not let an app read the screen without the desktop portal's
|
|
22
|
+
* consent dialog, so a Wayland session can record a virtual display or an
|
|
23
|
+
* explicitly named X display, not the user's own screen. That limit is
|
|
24
|
+
* reported, never worked around.
|
|
25
|
+
*/
|
|
26
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
27
|
+
import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
|
|
28
|
+
import { join } from "node:path";
|
|
29
|
+
export const realRunner = (cmd, args, env) => {
|
|
30
|
+
const r = spawnSync(cmd, args, { env, encoding: "utf8", timeout: 10_000 });
|
|
31
|
+
return {
|
|
32
|
+
status: r.error ? null : r.status,
|
|
33
|
+
stdout: r.stdout ?? "",
|
|
34
|
+
stderr: r.stderr ?? (r.error ? String(r.error.message) : ""),
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
// ---------------------------------------------------------------------------
|
|
38
|
+
// Environment checks
|
|
39
|
+
// ---------------------------------------------------------------------------
|
|
40
|
+
/** True when the user's session is Wayland, where reading the real screen
|
|
41
|
+
* needs the desktop portal's consent and x11grab sees only XWayland. */
|
|
42
|
+
export function isWaylandSession(env) {
|
|
43
|
+
return env.XDG_SESSION_TYPE === "wayland" || (!!env.WAYLAND_DISPLAY && !env.DISPLAY);
|
|
44
|
+
}
|
|
45
|
+
export function ffmpegCaps(run, env = process.env) {
|
|
46
|
+
const devices = run("ffmpeg", ["-hide_banner", "-devices"], env);
|
|
47
|
+
if (devices.status === null)
|
|
48
|
+
return { available: false, x11grab: false, windowId: false, encoder: null };
|
|
49
|
+
const x11grab = /\bx11grab\b/.test(devices.stdout + devices.stderr);
|
|
50
|
+
const help = x11grab ? run("ffmpeg", ["-hide_banner", "-h", "demuxer=x11grab"], env) : null;
|
|
51
|
+
const encoders = run("ffmpeg", ["-hide_banner", "-encoders"], env).stdout;
|
|
52
|
+
const encoder = /\blibx264\b/.test(encoders) ? "libx264" : /\blibvpx\b/.test(encoders) ? "libvpx" : null;
|
|
53
|
+
return {
|
|
54
|
+
available: true,
|
|
55
|
+
x11grab,
|
|
56
|
+
windowId: !!help && /-window_id\b/.test(help.stdout + help.stderr),
|
|
57
|
+
encoder,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
function hasCommand(run, cmd, env) {
|
|
61
|
+
return run("sh", ["-c", `command -v ${cmd}`], env).status === 0;
|
|
62
|
+
}
|
|
63
|
+
// ---------------------------------------------------------------------------
|
|
64
|
+
// Source discovery (pure parsers + thin runners)
|
|
65
|
+
// ---------------------------------------------------------------------------
|
|
66
|
+
/** `xrandr --listactivemonitors`: ` 0: +*eDP-1 1920/344x1080/194+0+0 eDP-1` */
|
|
67
|
+
export function parseMonitors(text) {
|
|
68
|
+
const out = [];
|
|
69
|
+
for (const line of text.split("\n")) {
|
|
70
|
+
const m = /^\s*(\d+):\s+[+*]*(\S+)\s+(\d+)\/\d+x(\d+)\/\d+\+(-?\d+)\+(-?\d+)/.exec(line);
|
|
71
|
+
if (!m)
|
|
72
|
+
continue;
|
|
73
|
+
out.push({
|
|
74
|
+
id: Number(m[1]),
|
|
75
|
+
name: m[2],
|
|
76
|
+
width: Number(m[3]),
|
|
77
|
+
height: Number(m[4]),
|
|
78
|
+
x: Number(m[5]),
|
|
79
|
+
y: Number(m[6]),
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
/** The X screen size from ffmpeg's own probe of the display, so a display
|
|
85
|
+
* can be recorded without any X11 utilities installed. */
|
|
86
|
+
export function parseProbedScreenSize(ffmpegStderr) {
|
|
87
|
+
const m = /Video: [^\n]*?(\d{2,5})x(\d{2,5})/.exec(ffmpegStderr);
|
|
88
|
+
return m ? { width: Number(m[1]), height: Number(m[2]) } : null;
|
|
89
|
+
}
|
|
90
|
+
/** `xprop -root _NET_CLIENT_LIST`: the managed top-level windows. */
|
|
91
|
+
export function parseClientList(text) {
|
|
92
|
+
const m = /_NET_CLIENT_LIST\(WINDOW\): window id # (.*)/.exec(text);
|
|
93
|
+
if (!m)
|
|
94
|
+
return [];
|
|
95
|
+
return m[1]
|
|
96
|
+
.split(",")
|
|
97
|
+
.map((s) => s.trim())
|
|
98
|
+
.filter((s) => /^0x[0-9a-f]+$/i.test(s))
|
|
99
|
+
.map((s) => parseInt(s, 16));
|
|
100
|
+
}
|
|
101
|
+
/** `xwininfo -root -children` lines: ` 0x200003 "Title": ("inst" "Class") 500x400+0+0 +0+0` */
|
|
102
|
+
export function parseChildren(text) {
|
|
103
|
+
const ids = [];
|
|
104
|
+
for (const line of text.split("\n")) {
|
|
105
|
+
const m = /^\s+(0x[0-9a-f]+)\s/i.exec(line);
|
|
106
|
+
if (m && !/\(has no name\)/.test(line))
|
|
107
|
+
ids.push(parseInt(m[1], 16));
|
|
108
|
+
}
|
|
109
|
+
return ids;
|
|
110
|
+
}
|
|
111
|
+
/** `xwininfo -id <id>`: absolute geometry and whether it is on screen. */
|
|
112
|
+
export function parseWindowGeometry(text) {
|
|
113
|
+
const num = (label) => {
|
|
114
|
+
const m = new RegExp(`${label}:\\s+(-?\\d+)`).exec(text);
|
|
115
|
+
return m ? Number(m[1]) : null;
|
|
116
|
+
};
|
|
117
|
+
const x = num("Absolute upper-left X");
|
|
118
|
+
const y = num("Absolute upper-left Y");
|
|
119
|
+
const width = num("Width");
|
|
120
|
+
const height = num("Height");
|
|
121
|
+
if (x === null || y === null || width === null || height === null)
|
|
122
|
+
return null;
|
|
123
|
+
return { x, y, width, height, viewable: /Map State:\s+IsViewable/.test(text) };
|
|
124
|
+
}
|
|
125
|
+
/** `xprop -id <id> _NET_WM_NAME WM_NAME WM_CLASS`: title and owning app. */
|
|
126
|
+
export function parseWindowProps(text) {
|
|
127
|
+
const quoted = (re) => {
|
|
128
|
+
const m = re.exec(text);
|
|
129
|
+
return m ? m[1].replace(/\\"/g, '"') : "";
|
|
130
|
+
};
|
|
131
|
+
const title = quoted(/_NET_WM_NAME\([^)]*\) = "((?:[^"\\]|\\.)*)"/) || quoted(/WM_NAME\([^)]*\) = "((?:[^"\\]|\\.)*)"/);
|
|
132
|
+
const cls = /WM_CLASS\([^)]*\) = "((?:[^"\\]|\\.)*)", "((?:[^"\\]|\\.)*)"/.exec(text);
|
|
133
|
+
return { title, app: cls ? cls[2] : "" };
|
|
134
|
+
}
|
|
135
|
+
/** List what can be recorded on an X display. Displays need only ffmpeg;
|
|
136
|
+
* the window list needs `xwininfo` and `xprop` (Debian/Ubuntu: x11-utils). */
|
|
137
|
+
/** The X display's monitors, or the whole screen as one display. */
|
|
138
|
+
export function listDisplays(xDisplay, run = realRunner, env = process.env) {
|
|
139
|
+
const xenv = { ...env, DISPLAY: xDisplay };
|
|
140
|
+
let displays = [];
|
|
141
|
+
const monitors = run("xrandr", ["--listactivemonitors"], xenv);
|
|
142
|
+
if (monitors.status === 0)
|
|
143
|
+
displays = parseMonitors(monitors.stdout);
|
|
144
|
+
if (displays.length === 0) {
|
|
145
|
+
// One display: the whole X screen. Its size from xwininfo when present,
|
|
146
|
+
// else from ffmpeg's own probe of the display.
|
|
147
|
+
const root = run("xwininfo", ["-root"], xenv);
|
|
148
|
+
const geometry = root.status === 0 ? parseWindowGeometry(root.stdout) : null;
|
|
149
|
+
let size = geometry ? { width: geometry.width, height: geometry.height } : null;
|
|
150
|
+
if (!size) {
|
|
151
|
+
const probe = run("ffmpeg", ["-hide_banner", "-f", "x11grab", "-i", xDisplay, "-frames:v", "1", "-f", "null", "-"], xenv);
|
|
152
|
+
size = parseProbedScreenSize(probe.stderr);
|
|
153
|
+
}
|
|
154
|
+
if (size)
|
|
155
|
+
displays = [{ id: 0, name: `screen ${xDisplay}`, x: 0, y: 0, ...size }];
|
|
156
|
+
}
|
|
157
|
+
return displays;
|
|
158
|
+
}
|
|
159
|
+
/** The X screen's size: the box around all its monitors. */
|
|
160
|
+
export function screenSize(displays) {
|
|
161
|
+
if (displays.length === 0)
|
|
162
|
+
return undefined;
|
|
163
|
+
return {
|
|
164
|
+
width: Math.max(...displays.map((d) => d.x + d.width)),
|
|
165
|
+
height: Math.max(...displays.map((d) => d.y + d.height)),
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
export function listLinuxSources(xDisplay, run = realRunner, env = process.env) {
|
|
169
|
+
const xenv = { ...env, DISPLAY: xDisplay };
|
|
170
|
+
const displays = listDisplays(xDisplay, run, env);
|
|
171
|
+
if (!hasCommand(run, "xwininfo", xenv) || !hasCommand(run, "xprop", xenv)) {
|
|
172
|
+
return {
|
|
173
|
+
xDisplay,
|
|
174
|
+
displays,
|
|
175
|
+
windows: [],
|
|
176
|
+
windowsUnavailable: "listing windows needs xwininfo and xprop (install x11-utils, e.g. `sudo apt install x11-utils`)",
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
// A window manager publishes its managed windows; a bare X server (Xvfb
|
|
180
|
+
// with no manager) has only the root's children.
|
|
181
|
+
const clientList = run("xprop", ["-root", "_NET_CLIENT_LIST"], xenv);
|
|
182
|
+
let ids = clientList.status === 0 ? parseClientList(clientList.stdout) : [];
|
|
183
|
+
if (ids.length === 0) {
|
|
184
|
+
const children = run("xwininfo", ["-root", "-children"], xenv);
|
|
185
|
+
ids = children.status === 0 ? parseChildren(children.stdout) : [];
|
|
186
|
+
}
|
|
187
|
+
const windows = [];
|
|
188
|
+
for (const id of ids) {
|
|
189
|
+
const hex = `0x${id.toString(16)}`;
|
|
190
|
+
const info = run("xwininfo", ["-id", hex], xenv);
|
|
191
|
+
const geometry = info.status === 0 ? parseWindowGeometry(info.stdout) : null;
|
|
192
|
+
if (!geometry || !geometry.viewable || geometry.width < 32 || geometry.height < 32)
|
|
193
|
+
continue;
|
|
194
|
+
const props = parseWindowProps(run("xprop", ["-id", hex, "_NET_WM_NAME", "WM_NAME", "WM_CLASS"], xenv).stdout);
|
|
195
|
+
if (!props.title && !props.app)
|
|
196
|
+
continue;
|
|
197
|
+
windows.push({ id, app_name: props.app, title: props.title, x: geometry.x, y: geometry.y, width: geometry.width, height: geometry.height });
|
|
198
|
+
}
|
|
199
|
+
return { xDisplay, displays, windows };
|
|
200
|
+
}
|
|
201
|
+
/** Current geometry of a window, or null once it is closed or unmapped. */
|
|
202
|
+
export function windowGeometry(xDisplay, id, run = realRunner, env = process.env) {
|
|
203
|
+
const info = run("xwininfo", ["-id", `0x${id.toString(16)}`], { ...env, DISPLAY: xDisplay });
|
|
204
|
+
const g = info.status === 0 ? parseWindowGeometry(info.stdout) : null;
|
|
205
|
+
return g && g.viewable ? g : null;
|
|
206
|
+
}
|
|
207
|
+
// ---------------------------------------------------------------------------
|
|
208
|
+
// ffmpeg arguments (pure)
|
|
209
|
+
// ---------------------------------------------------------------------------
|
|
210
|
+
export const CAPTURE_FPS = 30;
|
|
211
|
+
/** H.264 and VP8 both need even dimensions. */
|
|
212
|
+
function even(n) {
|
|
213
|
+
return Math.max(2, Math.floor(n / 2) * 2);
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* One capture segment. A window by id when ffmpeg supports it, else the
|
|
217
|
+
* window's current rectangle of the screen (which follows it only across
|
|
218
|
+
* segments, and can include what covers it). Matroska survives an abrupt
|
|
219
|
+
* exit, which matters for the segment that is live when something fails.
|
|
220
|
+
*/
|
|
221
|
+
/**
|
|
222
|
+
* The screen area a rectangle covers, clipped on every side and rounded to
|
|
223
|
+
* even sizes. A window partly off the screen covers only its on-screen part:
|
|
224
|
+
* past the left or top the area would slide over pixels the window does not
|
|
225
|
+
* cover, and past the right or bottom x11grab refuses the area outright.
|
|
226
|
+
*/
|
|
227
|
+
export function clipToScreen(r, screen) {
|
|
228
|
+
const x = Math.max(0, r.x);
|
|
229
|
+
const y = Math.max(0, r.y);
|
|
230
|
+
const right = screen ? Math.min(r.x + r.width, screen.width) : r.x + r.width;
|
|
231
|
+
const bottom = screen ? Math.min(r.y + r.height, screen.height) : r.y + r.height;
|
|
232
|
+
if (right - x < 2 || bottom - y < 2)
|
|
233
|
+
throw new Error("the window to record is off the screen");
|
|
234
|
+
return { x, y, width: even(right - x), height: even(bottom - y) };
|
|
235
|
+
}
|
|
236
|
+
export function segmentArgs(opts) {
|
|
237
|
+
const input = ["-f", "x11grab", "-draw_mouse", "1", "-framerate", String(CAPTURE_FPS)];
|
|
238
|
+
if (opts.target.kind === "window" && opts.windowIdCapture) {
|
|
239
|
+
input.push("-window_id", `0x${opts.target.window.id.toString(16)}`);
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
const r = opts.target.kind === "display"
|
|
243
|
+
? opts.target.display
|
|
244
|
+
: (opts.rect ?? opts.target.window);
|
|
245
|
+
const area = clipToScreen(r, opts.screen);
|
|
246
|
+
input.push("-video_size", `${area.width}x${area.height}`, "-grab_x", String(area.x), "-grab_y", String(area.y));
|
|
247
|
+
}
|
|
248
|
+
input.push("-i", opts.xDisplay);
|
|
249
|
+
const scale = ["-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2,format=yuv420p"];
|
|
250
|
+
const codec = opts.encoder === "libx264"
|
|
251
|
+
? ["-c:v", "libx264", "-preset", "veryfast", "-crf", "23"]
|
|
252
|
+
: ["-c:v", "libvpx", "-deadline", "realtime", "-cpu-used", "8", "-b:v", "2M"];
|
|
253
|
+
// Matroska keeps a cluster in memory until it closes (5 s by default) and
|
|
254
|
+
// a still window compresses to almost nothing, so without these a segment
|
|
255
|
+
// stays at its header for seconds and a crash loses what was buffered.
|
|
256
|
+
const mux = ["-flush_packets", "1", "-cluster_time_limit", "1000", "-f", "matroska"];
|
|
257
|
+
return ["-hide_banner", "-loglevel", "error", "-nostats", "-y", ...input, ...scale, ...codec, ...mux, opts.output];
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Join segments into the uploaded file. One segment is copied as is. Several
|
|
261
|
+
* are fitted into the first segment's frame (letterboxed, never stretched),
|
|
262
|
+
* each holding its last frame for the restart gap that followed it.
|
|
263
|
+
*/
|
|
264
|
+
export function finalizeArgs(opts) {
|
|
265
|
+
const container = opts.encoder === "libx264" ? ["-movflags", "+faststart", "-f", "mp4"] : ["-f", "webm"];
|
|
266
|
+
if (opts.segments.length === 1) {
|
|
267
|
+
return ["-hide_banner", "-loglevel", "error", "-y", "-i", opts.segments[0].path, "-c", "copy", ...container, opts.output];
|
|
268
|
+
}
|
|
269
|
+
const w = even(opts.frame.width);
|
|
270
|
+
const h = even(opts.frame.height);
|
|
271
|
+
const inputs = opts.segments.flatMap((s) => ["-i", s.path]);
|
|
272
|
+
const chains = opts.segments.map((s, i) => {
|
|
273
|
+
const hold = s.gapAfterSec > 0.01 ? `,tpad=stop_mode=clone:stop_duration=${s.gapAfterSec.toFixed(3)}` : "";
|
|
274
|
+
return (`[${i}:v]scale=${w}:${h}:force_original_aspect_ratio=decrease,` +
|
|
275
|
+
`pad=${w}:${h}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=${CAPTURE_FPS}${hold}[v${i}]`);
|
|
276
|
+
});
|
|
277
|
+
const filter = `${chains.join(";")};${opts.segments.map((_, i) => `[v${i}]`).join("")}concat=n=${opts.segments.length}:v=1:a=0[out]`;
|
|
278
|
+
const codec = opts.encoder === "libx264"
|
|
279
|
+
? ["-c:v", "libx264", "-preset", "veryfast", "-crf", "23", "-pix_fmt", "yuv420p"]
|
|
280
|
+
: ["-c:v", "libvpx", "-deadline", "good", "-b:v", "2M"];
|
|
281
|
+
return ["-hide_banner", "-loglevel", "error", "-y", ...inputs, "-filter_complex", filter, "-map", "[out]", ...codec, ...container, opts.output];
|
|
282
|
+
}
|
|
283
|
+
/** Parse `--virtual-display` / `--virtual-display 1600x900`. */
|
|
284
|
+
export function parseDisplaySize(value) {
|
|
285
|
+
if (!value || value === "true")
|
|
286
|
+
return { width: 1280, height: 720 };
|
|
287
|
+
const m = /^(\d{3,4})x(\d{3,4})$/.exec(value.trim());
|
|
288
|
+
if (!m)
|
|
289
|
+
throw new Error(`--virtual-display takes WIDTHxHEIGHT, e.g. 1280x720 (got "${value}")`);
|
|
290
|
+
const width = Number(m[1]);
|
|
291
|
+
const height = Number(m[2]);
|
|
292
|
+
if (width < 320 || height < 240 || width > 3840 || height > 2160) {
|
|
293
|
+
throw new Error("--virtual-display size must be between 320x240 and 3840x2160");
|
|
294
|
+
}
|
|
295
|
+
return { width: even(width), height: even(height) };
|
|
296
|
+
}
|
|
297
|
+
function freeDisplayNumber() {
|
|
298
|
+
for (let n = 90; n < 200; n++) {
|
|
299
|
+
if (!existsSync(`/tmp/.X11-unix/X${n}`) && !existsSync(`/tmp/.X${n}-lock`))
|
|
300
|
+
return n;
|
|
301
|
+
}
|
|
302
|
+
throw new Error("no free X display number between :90 and :199");
|
|
303
|
+
}
|
|
304
|
+
async function waitFor(check, ms) {
|
|
305
|
+
const deadline = Date.now() + ms;
|
|
306
|
+
while (Date.now() < deadline) {
|
|
307
|
+
if (check())
|
|
308
|
+
return true;
|
|
309
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
310
|
+
}
|
|
311
|
+
return check();
|
|
312
|
+
}
|
|
313
|
+
async function terminate(child, graceMs = 3000) {
|
|
314
|
+
if (!child || child.exitCode !== null || child.signalCode !== null)
|
|
315
|
+
return;
|
|
316
|
+
const exited = new Promise((r) => child.once("exit", () => r()));
|
|
317
|
+
child.kill("SIGTERM");
|
|
318
|
+
const timer = setTimeout(() => child.kill("SIGKILL"), graceMs);
|
|
319
|
+
await exited;
|
|
320
|
+
clearTimeout(timer);
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Start a private X display for the agent. A compositor is started on it when
|
|
324
|
+
* one is installed, so a covered window still records in full; it is not
|
|
325
|
+
* required for display capture.
|
|
326
|
+
*/
|
|
327
|
+
export async function startVirtualDisplay(size, run = realRunner, env = process.env) {
|
|
328
|
+
if (!hasCommand(run, "Xvfb", env)) {
|
|
329
|
+
throw new Error("--virtual-display needs Xvfb (Debian/Ubuntu: `sudo apt install xvfb`)");
|
|
330
|
+
}
|
|
331
|
+
const n = freeDisplayNumber();
|
|
332
|
+
const display = `:${n}`;
|
|
333
|
+
const xvfb = spawn("Xvfb", [display, "-screen", "0", `${size.width}x${size.height}x24`, "-nolisten", "tcp"], {
|
|
334
|
+
stdio: "ignore",
|
|
335
|
+
env,
|
|
336
|
+
});
|
|
337
|
+
const up = await waitFor(() => existsSync(`/tmp/.X11-unix/X${n}`) || hasExited(xvfb), 5000);
|
|
338
|
+
if (!up || hasExited(xvfb)) {
|
|
339
|
+
await terminate(xvfb);
|
|
340
|
+
throw new Error(`Xvfb did not start on ${display}`);
|
|
341
|
+
}
|
|
342
|
+
let compositor = null;
|
|
343
|
+
for (const name of ["picom", "xcompmgr"]) {
|
|
344
|
+
if (hasCommand(run, name, env)) {
|
|
345
|
+
compositor = spawn(name, [], { stdio: "ignore", env: { ...env, DISPLAY: display } });
|
|
346
|
+
break;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
return {
|
|
350
|
+
display,
|
|
351
|
+
pid: xvfb.pid ?? 0,
|
|
352
|
+
compositorPid: compositor?.pid,
|
|
353
|
+
async stop() {
|
|
354
|
+
await terminate(compositor);
|
|
355
|
+
await terminate(xvfb);
|
|
356
|
+
},
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
/** Ask ffmpeg to finish its file cleanly ('q'), then insist. */
|
|
360
|
+
async function stopFfmpeg(seg) {
|
|
361
|
+
seg.stopping = true;
|
|
362
|
+
seg.stopRequestedAt ??= Date.now();
|
|
363
|
+
if (seg.child.exitCode !== null || seg.child.signalCode !== null)
|
|
364
|
+
return;
|
|
365
|
+
const exited = new Promise((r) => seg.child.once("exit", () => r()));
|
|
366
|
+
try {
|
|
367
|
+
seg.child.stdin?.write("q");
|
|
368
|
+
seg.child.stdin?.end();
|
|
369
|
+
}
|
|
370
|
+
catch {
|
|
371
|
+
// stdin already closed
|
|
372
|
+
}
|
|
373
|
+
const term = setTimeout(() => seg.child.kill("SIGINT"), 5000);
|
|
374
|
+
const kill = setTimeout(() => seg.child.kill("SIGKILL"), 10_000);
|
|
375
|
+
await exited;
|
|
376
|
+
clearTimeout(term);
|
|
377
|
+
clearTimeout(kill);
|
|
378
|
+
}
|
|
379
|
+
function nonEmpty(path, minBytes = 1) {
|
|
380
|
+
try {
|
|
381
|
+
return statSync(path).size >= minBytes;
|
|
382
|
+
}
|
|
383
|
+
catch {
|
|
384
|
+
return false;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* When a segment's last frame was captured. ffmpeg exits by itself when a
|
|
389
|
+
* window shrinks, up to a tick before it is noticed, and the wall-clock gap to
|
|
390
|
+
* the next segment has to start at that exit or every later mark drifts.
|
|
391
|
+
*/
|
|
392
|
+
export function segmentEndedAt(seg, now) {
|
|
393
|
+
return Math.min(seg.exitedAt ?? now, seg.stopRequestedAt ?? now, now);
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* Whether a child process is gone. A process killed by a signal (an OOM
|
|
397
|
+
* SIGKILL, say) keeps `exitCode` null and sets `signalCode` instead.
|
|
398
|
+
*/
|
|
399
|
+
export function hasExited(child) {
|
|
400
|
+
return child.exitCode !== null || child.signalCode !== null;
|
|
401
|
+
}
|
|
402
|
+
function exitDescription(child) {
|
|
403
|
+
return child.signalCode !== null ? `ffmpeg was killed by ${child.signalCode}` : `ffmpeg exited with ${child.exitCode}`;
|
|
404
|
+
}
|
|
405
|
+
/** A Matroska header alone is ~600 bytes; past this, frames are landing. */
|
|
406
|
+
const FIRST_FRAMES_BYTES = 1024;
|
|
407
|
+
/** Segments in order with the wall-clock gap that followed each one. */
|
|
408
|
+
export function segmentsWithGaps(done) {
|
|
409
|
+
return done.map((s, i) => ({
|
|
410
|
+
path: s.path,
|
|
411
|
+
gapAfterSec: i + 1 < done.length ? Math.max(0, (done[i + 1].startedAt - s.endedAt) / 1000) : 0,
|
|
412
|
+
}));
|
|
413
|
+
}
|
|
414
|
+
/** Whether a window's live geometry needs a new segment. */
|
|
415
|
+
export function needsNewSegment(recording, now, windowIdCapture) {
|
|
416
|
+
if (even(now.width) !== even(recording.width) || even(now.height) !== even(recording.height))
|
|
417
|
+
return true;
|
|
418
|
+
// Captured by id, the picture follows the window by itself; captured as a
|
|
419
|
+
// screen area, the area has to be moved with it.
|
|
420
|
+
return !windowIdCapture && (now.x !== recording.x || now.y !== recording.y);
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Start recording. Resolves once the first segment is producing bytes, so a
|
|
424
|
+
* recording that cannot capture (no display, a refused window) fails here,
|
|
425
|
+
* loudly, rather than looking like it runs while writing nothing.
|
|
426
|
+
*/
|
|
427
|
+
export async function startScreenRecorder(opts) {
|
|
428
|
+
const run = opts.run ?? realRunner;
|
|
429
|
+
const env = opts.env ?? process.env;
|
|
430
|
+
const log = opts.log ?? (() => { });
|
|
431
|
+
if (!opts.caps.available)
|
|
432
|
+
throw new Error("recording the screen needs ffmpeg on PATH");
|
|
433
|
+
if (!opts.caps.x11grab)
|
|
434
|
+
throw new Error("this ffmpeg was built without x11grab, so it cannot record an X display");
|
|
435
|
+
const encoder = opts.caps.encoder;
|
|
436
|
+
if (!encoder)
|
|
437
|
+
throw new Error("this ffmpeg has neither libx264 nor libvpx, so it cannot encode the recording");
|
|
438
|
+
ensurePrivateDir(opts.tmpDir);
|
|
439
|
+
// Only the rectangle fallback needs the screen's edges to clip to.
|
|
440
|
+
const screen = opts.target.kind === "window" && !opts.caps.windowId ? screenSize(listDisplays(opts.xDisplay, run, env)) : undefined;
|
|
441
|
+
const done = [];
|
|
442
|
+
let live = null;
|
|
443
|
+
let firstSize = null;
|
|
444
|
+
let closed = false;
|
|
445
|
+
// True while a segment change is queued, so ticks wait for it.
|
|
446
|
+
let busy = false;
|
|
447
|
+
let failures = 0;
|
|
448
|
+
let segmentCount = 0;
|
|
449
|
+
let fatal = null;
|
|
450
|
+
// Every segment change runs through this one queue, so a restart and a
|
|
451
|
+
// stop can never interleave and `finish` waits for whatever is in flight.
|
|
452
|
+
let queue = Promise.resolve();
|
|
453
|
+
const enqueue = (step) => {
|
|
454
|
+
queue = queue.then(step).catch((e) => {
|
|
455
|
+
fatal ??= e;
|
|
456
|
+
log(`screen capture: ${e.message}`);
|
|
457
|
+
});
|
|
458
|
+
};
|
|
459
|
+
const currentRect = () => {
|
|
460
|
+
if (opts.target.kind === "display")
|
|
461
|
+
return opts.target.display;
|
|
462
|
+
return windowGeometry(opts.xDisplay, opts.target.window.id, run, env);
|
|
463
|
+
};
|
|
464
|
+
const openSegment = async () => {
|
|
465
|
+
const rect = currentRect();
|
|
466
|
+
if (!rect)
|
|
467
|
+
throw new Error("the window to record is closed or minimized");
|
|
468
|
+
const path = join(opts.tmpDir, `segment-${segmentCount++}.mkv`);
|
|
469
|
+
const args = segmentArgs({
|
|
470
|
+
xDisplay: opts.xDisplay,
|
|
471
|
+
target: opts.target,
|
|
472
|
+
rect,
|
|
473
|
+
screen,
|
|
474
|
+
windowIdCapture: opts.caps.windowId,
|
|
475
|
+
encoder,
|
|
476
|
+
output: path,
|
|
477
|
+
});
|
|
478
|
+
const child = spawn("ffmpeg", args, { stdio: ["pipe", "ignore", "pipe"], env: { ...env, DISPLAY: opts.xDisplay } });
|
|
479
|
+
const seg = { path, child, startedAt: Date.now(), rect: { ...rect }, stderr: "", stopping: false };
|
|
480
|
+
child.once("exit", () => {
|
|
481
|
+
seg.exitedAt ??= Date.now();
|
|
482
|
+
});
|
|
483
|
+
child.stderr?.on("data", (d) => {
|
|
484
|
+
seg.stderr = (seg.stderr + d.toString()).slice(-4000);
|
|
485
|
+
});
|
|
486
|
+
// The first bytes prove capture works; a refused display or window makes
|
|
487
|
+
// ffmpeg exit instead.
|
|
488
|
+
const ok = await waitFor(() => nonEmpty(path, FIRST_FRAMES_BYTES) || hasExited(child), 8000);
|
|
489
|
+
if (!ok || hasExited(child)) {
|
|
490
|
+
await stopFfmpeg(seg);
|
|
491
|
+
rmSync(path, { force: true });
|
|
492
|
+
const detail = seg.stderr.trim().split("\n").slice(-2).join(" ");
|
|
493
|
+
throw new Error(`ffmpeg could not record ${opts.xDisplay}: ${detail || "it wrote nothing"}`);
|
|
494
|
+
}
|
|
495
|
+
// The frame later segments are fitted into is what this one recorded:
|
|
496
|
+
// in the area fallback that is the clipped on-screen part of the window.
|
|
497
|
+
const recorded = opts.target.kind === "window" && !opts.caps.windowId ? clipToScreen(rect, screen) : rect;
|
|
498
|
+
firstSize ??= { width: even(recorded.width), height: even(recorded.height) };
|
|
499
|
+
live = seg;
|
|
500
|
+
log(`recording segment ${path} at ${even(recorded.width)}x${even(recorded.height)}`);
|
|
501
|
+
};
|
|
502
|
+
// Reads `live` when the queued step runs, not when it was queued, so it
|
|
503
|
+
// always closes the segment that is actually recording.
|
|
504
|
+
const closeSegment = async () => {
|
|
505
|
+
const seg = live;
|
|
506
|
+
if (!seg)
|
|
507
|
+
return;
|
|
508
|
+
live = null;
|
|
509
|
+
await stopFfmpeg(seg);
|
|
510
|
+
if (nonEmpty(seg.path))
|
|
511
|
+
done.push({ path: seg.path, startedAt: seg.startedAt, endedAt: segmentEndedAt(seg, Date.now()) });
|
|
512
|
+
};
|
|
513
|
+
await openSegment();
|
|
514
|
+
const startedAt = live?.startedAt ?? Date.now();
|
|
515
|
+
return {
|
|
516
|
+
startedAt,
|
|
517
|
+
tick() {
|
|
518
|
+
if (fatal)
|
|
519
|
+
throw fatal;
|
|
520
|
+
if (closed || busy)
|
|
521
|
+
return null;
|
|
522
|
+
const seg = live;
|
|
523
|
+
if (!seg)
|
|
524
|
+
return null;
|
|
525
|
+
if (opts.target.kind === "window") {
|
|
526
|
+
const g = currentRect();
|
|
527
|
+
if (!g) {
|
|
528
|
+
closed = true;
|
|
529
|
+
enqueue(closeSegment);
|
|
530
|
+
return "[auto] the recorded window closed or was minimized; recording ended";
|
|
531
|
+
}
|
|
532
|
+
if (needsNewSegment(seg.rect, g, opts.caps.windowId)) {
|
|
533
|
+
busy = true;
|
|
534
|
+
enqueue(async () => {
|
|
535
|
+
await closeSegment();
|
|
536
|
+
await openSegment();
|
|
537
|
+
busy = false;
|
|
538
|
+
});
|
|
539
|
+
return even(g.width) !== even(seg.rect.width) || even(g.height) !== even(seg.rect.height)
|
|
540
|
+
? `[auto] window resized to ${even(g.width)}x${even(g.height)}`
|
|
541
|
+
: null;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
if (!seg.stopping && hasExited(seg.child)) {
|
|
545
|
+
// ffmpeg died on its own. Keep what it wrote and start again, a few
|
|
546
|
+
// times; past that the capture is broken and the session must fail.
|
|
547
|
+
failures += 1;
|
|
548
|
+
const reason = seg.stderr.trim().split("\n").pop() || exitDescription(seg.child);
|
|
549
|
+
if (failures > 3)
|
|
550
|
+
throw new Error(`screen capture keeps failing: ${reason}`);
|
|
551
|
+
busy = true;
|
|
552
|
+
live = null;
|
|
553
|
+
if (nonEmpty(seg.path))
|
|
554
|
+
done.push({ path: seg.path, startedAt: seg.startedAt, endedAt: segmentEndedAt(seg, Date.now()) });
|
|
555
|
+
enqueue(async () => {
|
|
556
|
+
await openSegment();
|
|
557
|
+
busy = false;
|
|
558
|
+
});
|
|
559
|
+
return "[auto] screen capture restarted after an interruption";
|
|
560
|
+
}
|
|
561
|
+
return null;
|
|
562
|
+
},
|
|
563
|
+
ended: () => closed,
|
|
564
|
+
async finish() {
|
|
565
|
+
closed = true;
|
|
566
|
+
enqueue(closeSegment);
|
|
567
|
+
await queue;
|
|
568
|
+
if (done.length === 0)
|
|
569
|
+
throw fatal ?? new Error("the screen capture produced no video");
|
|
570
|
+
const output = join(opts.tmpDir, encoder === "libx264" ? "recording.mp4" : "recording.webm");
|
|
571
|
+
const r = spawnSync("ffmpeg", finalizeArgs({ segments: segmentsWithGaps(done), frame: firstSize ?? { width: 1280, height: 720 }, encoder, output }), { encoding: "utf8", env });
|
|
572
|
+
if (r.status !== 0 || !nonEmpty(output)) {
|
|
573
|
+
const detail = (r.stderr ?? "").trim().split("\n").pop();
|
|
574
|
+
throw new Error(`could not finish the recording: ${detail || "ffmpeg failed"}`);
|
|
575
|
+
}
|
|
576
|
+
return output;
|
|
577
|
+
},
|
|
578
|
+
async discard() {
|
|
579
|
+
closed = true;
|
|
580
|
+
enqueue(closeSegment);
|
|
581
|
+
await queue;
|
|
582
|
+
rmSync(opts.tmpDir, { recursive: true, force: true });
|
|
583
|
+
},
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* Creates the directory a recording is written into, readable only by this
|
|
588
|
+
* user: on a shared machine `/tmp` is listable by everyone, and the segments
|
|
589
|
+
* are the user's screen. A directory that already exists must be ours.
|
|
590
|
+
*/
|
|
591
|
+
export function ensurePrivateDir(dir) {
|
|
592
|
+
try {
|
|
593
|
+
mkdirSync(dir, { mode: 0o700 });
|
|
594
|
+
}
|
|
595
|
+
catch (e) {
|
|
596
|
+
const code = e.code;
|
|
597
|
+
if (code === "ENOENT")
|
|
598
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
599
|
+
else if (code !== "EEXIST")
|
|
600
|
+
throw e;
|
|
601
|
+
}
|
|
602
|
+
const st = lstatSync(dir);
|
|
603
|
+
if (!st.isDirectory() || (process.getuid && st.uid !== process.getuid())) {
|
|
604
|
+
throw new Error(`refusing to record into ${dir}: it is not a directory owned by this user`);
|
|
605
|
+
}
|
|
606
|
+
chmodSync(dir, 0o700);
|
|
607
|
+
}
|
|
608
|
+
/** The whole X screen (or its first monitor) as a display target. */
|
|
609
|
+
export function defaultDisplay(sources) {
|
|
610
|
+
const first = sources.displays[0];
|
|
611
|
+
if (!first)
|
|
612
|
+
throw new Error(`could not read the size of X display ${sources.xDisplay}`);
|
|
613
|
+
return first;
|
|
614
|
+
}
|
|
615
|
+
/** For tests and `clipy doctor`: write a short capability summary. */
|
|
616
|
+
export function describeCaps(caps) {
|
|
617
|
+
if (!caps.available)
|
|
618
|
+
return "ffmpeg missing";
|
|
619
|
+
if (!caps.x11grab)
|
|
620
|
+
return "ffmpeg without x11grab";
|
|
621
|
+
return `ffmpeg x11grab${caps.windowId ? " with window capture" : " (no window_id: windows are recorded as their screen area)"}, ${caps.encoder ?? "no encoder"}`;
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* The ffmpeg processes still writing segments into `tmpDir`. A session daemon
|
|
625
|
+
* that was killed outright cannot stop its ffmpeg, which would otherwise keep
|
|
626
|
+
* encoding into a directory nobody reads. Matching both the process name and
|
|
627
|
+
* this session's own segment path means a reused pid, or another session's
|
|
628
|
+
* capture, is never picked up.
|
|
629
|
+
*/
|
|
630
|
+
export function orphanedCaptureProcesses(tmpDir, procRoot = "/proc") {
|
|
631
|
+
const marker = `${join(tmpDir, "segment-")}`;
|
|
632
|
+
let entries;
|
|
633
|
+
try {
|
|
634
|
+
entries = readdirSync(procRoot);
|
|
635
|
+
}
|
|
636
|
+
catch {
|
|
637
|
+
return [];
|
|
638
|
+
}
|
|
639
|
+
const pids = [];
|
|
640
|
+
for (const entry of entries) {
|
|
641
|
+
if (!/^\d+$/.test(entry))
|
|
642
|
+
continue;
|
|
643
|
+
try {
|
|
644
|
+
if (readFileSync(join(procRoot, entry, "comm"), "utf8").trim() !== "ffmpeg")
|
|
645
|
+
continue;
|
|
646
|
+
const argv = readFileSync(join(procRoot, entry, "cmdline"), "utf8").split("\0");
|
|
647
|
+
if (argv.some((arg) => arg.startsWith(marker)))
|
|
648
|
+
pids.push(Number(entry));
|
|
649
|
+
}
|
|
650
|
+
catch {
|
|
651
|
+
// exited while we looked, or not ours to read
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
return pids;
|
|
655
|
+
}
|
package/dist/macBridge.js
CHANGED
|
@@ -279,7 +279,17 @@ export async function resolveCaptureSource(info, opts) {
|
|
|
279
279
|
if (opts.window && opts.display) {
|
|
280
280
|
throw new Error("--window and --display are mutually exclusive — pick one capture source");
|
|
281
281
|
}
|
|
282
|
-
|
|
282
|
+
return resolveFromSources(await listSources(info), opts);
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* The matching rules behind --window/--display, shared by the Mac app's
|
|
286
|
+
* sources and the Linux CLI's own X11 listing so both resolve a pick the
|
|
287
|
+
* same way and report the same ambiguity.
|
|
288
|
+
*/
|
|
289
|
+
export function resolveFromSources(sources, opts) {
|
|
290
|
+
if (opts.window && opts.display) {
|
|
291
|
+
throw new Error("--window and --display are mutually exclusive — pick one capture source");
|
|
292
|
+
}
|
|
283
293
|
if (opts.window) {
|
|
284
294
|
const q = opts.window.trim();
|
|
285
295
|
let matches;
|