@tmhs/screencast-mcp 0.47.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.
- package/README.md +28 -247
- package/assets/fonts/Inter-Bold.ttf +0 -0
- package/assets/fonts/Inter-Regular.ttf +0 -0
- package/dist/cli.js +189 -34
- package/dist/server.js +13 -0
- package/dist/setup.js +437 -0
- package/dist/tools/cutByTranscript.js +3 -3
- package/dist/tools/indexRecording.js +37 -15
- package/dist/tools/narrate.js +3 -1
- package/dist/tools/pipeline.js +20 -11
- package/dist/tools/searchRecording.js +9 -3
- package/dist/tools/startRecording.js +72 -42
- package/dist/tools/stepGuide.js +57 -4
- package/dist/utils/argPaths.js +39 -0
- package/dist/utils/captions.js +5 -3
- package/dist/utils/events.js +40 -8
- package/dist/utils/gpu.js +50 -4
- package/dist/utils/lifecycle.js +56 -16
- package/dist/utils/media.js +3 -2
- package/dist/utils/monitors.js +34 -3
- package/dist/utils/narrate.js +12 -3
- package/dist/utils/ocr.js +8 -3
- package/dist/utils/paths.js +41 -3
- package/dist/utils/pause.js +15 -1
- package/dist/utils/pipeline.js +5 -1
- package/dist/utils/recipes.js +7 -3
- package/dist/utils/recorder.js +20 -11
- package/dist/utils/recordingIndex.js +54 -8
- package/dist/utils/replay.js +20 -2
- package/dist/utils/retention.js +4 -1
- package/dist/utils/roots.js +1 -1
- package/dist/utils/sessions.js +3 -1
- package/dist/utils/stepGuide.js +26 -0
- package/dist/utils/transcriptCut.js +20 -5
- package/package.json +3 -1
|
@@ -29,13 +29,19 @@ export function register(server) {
|
|
|
29
29
|
}, async (args, extra) => {
|
|
30
30
|
try {
|
|
31
31
|
const source = await resolveRecording(args);
|
|
32
|
-
const
|
|
32
|
+
const fingerprint = fingerprintFile(source.path);
|
|
33
|
+
const indexPath = findIndex(source.path, subdir("edits"), fingerprint);
|
|
33
34
|
const index = indexPath ? readIndex(indexPath) : null;
|
|
34
35
|
if (!indexPath || !index) {
|
|
35
36
|
throw new ScreencastError(`No index for ${source.path}.`, "Run index_recording on it first.");
|
|
36
37
|
}
|
|
37
|
-
const stale = !sameFingerprint(index.fingerprint,
|
|
38
|
-
const { hits, total } = searchIndex(index, args.query, {
|
|
38
|
+
const stale = !sameFingerprint(index.fingerprint, fingerprint);
|
|
39
|
+
const { hits, total } = searchIndex(index, args.query, {
|
|
40
|
+
regex: args.regex === true,
|
|
41
|
+
limit: args.limit,
|
|
42
|
+
video: source.path,
|
|
43
|
+
fingerprint,
|
|
44
|
+
});
|
|
39
45
|
const want = Math.min(clampInlineCount(args.images ?? 0), hits.length);
|
|
40
46
|
let images = [];
|
|
41
47
|
if (want > 0) {
|
|
@@ -13,11 +13,11 @@ import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
|
|
|
13
13
|
import { getStore } from "../context.js";
|
|
14
14
|
import { killPid, serverIdentity } from "../utils/sessions.js";
|
|
15
15
|
import { mkdirSync, rmSync } from "node:fs";
|
|
16
|
-
import { buildDdaInputArgs, ddagrabWorks, encoderArgs, getDxgiOutputs, planDdaSource, resolveEncoder, } from "../utils/gpu.js";
|
|
16
|
+
import { buildDdaInputArgs, ddagrabWorks, encoderArgs, getDxgiOutputs, planDdaSource, resolveEncoder, startWithEncoderFallback, } from "../utils/gpu.js";
|
|
17
17
|
import { attachExitHandler, captureStartMs, settleCapture, tailLines, watchStderr, } from "../utils/recorder.js";
|
|
18
18
|
import { DEFAULT_WEBCAM_SIZE, eventClock, partsDir, sessionEnded, webcamOutputPath, webcamPartPath, } from "../utils/pause.js";
|
|
19
19
|
import { basename, join } from "node:path";
|
|
20
|
-
import { MAX_REPLAY_SEC, MIN_REPLAY_SEC, discardReplay, planReplayBuffer, prepareReplayDir, segmentOutputArgs, } from "../utils/replay.js";
|
|
20
|
+
import { MAX_REPLAY_SEC, MIN_REPLAY_SEC, discardReplay, planReplayBuffer, prepareReplayDir, replayEventRotateSec, resetReplaySegments, segmentOutputArgs, } from "../utils/replay.js";
|
|
21
21
|
import { DEFAULT_KEY_MODE, eventPaths, parseCaptureStart, prepareEventPaths, startEventLogger, stopEventLogger, summarizeEvents, trackFinalizer, writeEventsFile, } from "../utils/events.js";
|
|
22
22
|
const inputSchema = {
|
|
23
23
|
target: z
|
|
@@ -103,8 +103,17 @@ const inputSchema = {
|
|
|
103
103
|
.min(MIN_REPLAY_SEC)
|
|
104
104
|
.max(MAX_REPLAY_SEC)
|
|
105
105
|
.optional()
|
|
106
|
-
.describe("Instant replay: keep only the last N s (bounded disk) for save_replay. gdigrab
|
|
106
|
+
.describe("Instant replay: keep only the last N s (bounded disk) for save_replay. gdigrab or ddagrab, not wgc."),
|
|
107
107
|
};
|
|
108
|
+
function frameSize(target, monitors) {
|
|
109
|
+
try {
|
|
110
|
+
const f = captureFrame(target, monitors);
|
|
111
|
+
return { width: f.w, height: f.h };
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
108
117
|
function webcamStart(watch, audio) {
|
|
109
118
|
const ms = parseCaptureStart(watch.head(), audio ? 2 : 1);
|
|
110
119
|
return ms !== null ? { webcamStartMs: ms } : {};
|
|
@@ -143,7 +152,7 @@ export function register(server) {
|
|
|
143
152
|
}
|
|
144
153
|
}
|
|
145
154
|
if (args.replayBufferSec !== undefined && backend === "wgc") {
|
|
146
|
-
throw new ScreencastError('replayBufferSec is not supported with backend "wgc" yet; use gdigrab.');
|
|
155
|
+
throw new ScreencastError('replayBufferSec is not supported with backend "wgc" yet; use gdigrab or ddagrab.');
|
|
147
156
|
}
|
|
148
157
|
const replay = args.replayBufferSec !== undefined ? planReplayBuffer(args.replayBufferSec) : null;
|
|
149
158
|
const fps = args.fps ?? DEFAULT_FPS;
|
|
@@ -165,33 +174,36 @@ export function register(server) {
|
|
|
165
174
|
(webcamDevice ? `, with the webcam (${webcamDevice})` : "") +
|
|
166
175
|
(args.events ? ", logging mouse clicks and typing" : "") +
|
|
167
176
|
(replay ? ", kept only until save_replay or stop_recording { save: true } writes it out?" : `, saved to ${output}?`), extra.signal);
|
|
168
|
-
|
|
169
|
-
|
|
177
|
+
let pick = await resolveEncoder(args.encoder ?? (backend === "ddagrab" ? "auto" : "x264"), backend === "ddagrab" ? "ddagrab" : "gdigrab", ffmpeg, undefined, backend === "wgc" ? undefined : frameSize(target, monitors));
|
|
178
|
+
const ddaUsable = async (p) => !dda || p.gpuFrames || (await ddagrabWorks(ffmpeg));
|
|
179
|
+
if (!(await ddaUsable(pick))) {
|
|
170
180
|
throw new ScreencastError("Desktop Duplication (ddagrab) does not capture on this machine (a remote session, or no D3D11 GPU).", 'Use backend "gdigrab".');
|
|
171
181
|
}
|
|
172
|
-
const
|
|
173
|
-
const captureOpts = {
|
|
174
|
-
fps,
|
|
175
|
-
quality,
|
|
176
|
-
monitors,
|
|
177
|
-
audio,
|
|
178
|
-
drawMouse: !hideCursor,
|
|
179
|
-
...(dda ? { videoInput: buildDdaInputArgs(dda, fps, { download: !pick.gpuFrames, drawMouse: !hideCursor }) } : {}),
|
|
180
|
-
...(hw ? { videoCodec: encoderArgs(pick.encoder, quality, { gpuFrames: pick.gpuFrames }) } : {}),
|
|
181
|
-
};
|
|
182
|
-
const webcam = webcamDevice
|
|
183
|
-
? { device: webcamDevice, ...(hw ? { codec: encoderArgs(pick.encoder, quality) } : {}) }
|
|
184
|
-
: undefined;
|
|
185
|
-
const webcamRaw = webcam ? webcamPartPath(output, 0) : undefined;
|
|
182
|
+
const webcamRaw = webcamDevice ? webcamPartPath(output, 0) : undefined;
|
|
186
183
|
if (webcamRaw)
|
|
187
184
|
mkdirSync(partsDir(output), { recursive: true });
|
|
188
|
-
const
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
185
|
+
const plan = (p) => {
|
|
186
|
+
const hw = p.encoder !== "x264";
|
|
187
|
+
const captureOpts = {
|
|
188
|
+
fps,
|
|
189
|
+
quality,
|
|
190
|
+
monitors,
|
|
191
|
+
audio,
|
|
192
|
+
drawMouse: !hideCursor,
|
|
193
|
+
...(dda ? { videoInput: buildDdaInputArgs(dda, fps, { download: !p.gpuFrames, drawMouse: !hideCursor }) } : {}),
|
|
194
|
+
...(hw ? { videoCodec: encoderArgs(p.encoder, quality, { gpuFrames: p.gpuFrames }) } : {}),
|
|
195
|
+
};
|
|
196
|
+
const webcam = webcamDevice
|
|
197
|
+
? { device: webcamDevice, ...(hw ? { codec: encoderArgs(p.encoder, quality) } : {}) }
|
|
198
|
+
: undefined;
|
|
199
|
+
const captureArgs = buildCaptureArgs(target, {
|
|
200
|
+
...captureOpts,
|
|
201
|
+
output,
|
|
202
|
+
maxDurationSec,
|
|
203
|
+
...(webcam && webcamRaw ? { webcam: { ...webcam, output: webcamRaw } } : {}),
|
|
204
|
+
});
|
|
205
|
+
return { captureOpts, webcam, ffArgs: replay ? segmentOutputArgs(captureArgs, replay) : captureArgs };
|
|
206
|
+
};
|
|
195
207
|
if (replay)
|
|
196
208
|
prepareReplayDir(replay);
|
|
197
209
|
const keyMode = args.keys ?? DEFAULT_KEY_MODE;
|
|
@@ -201,21 +213,38 @@ export function register(server) {
|
|
|
201
213
|
let frame = args.events
|
|
202
214
|
? captureFrame(target, monitors)
|
|
203
215
|
: null;
|
|
204
|
-
const logger = evPaths
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
? spawn(process.execPath, [
|
|
208
|
-
fileURLToPath(new URL("../wgcRecorder.js", import.meta.url)),
|
|
209
|
-
JSON.stringify({ ffmpeg, hwnd: window.hwnd, fps, encode: [...encoderArgs(pick.encoder, quality), ...captureKeyframeArgs(fps)], output, maxDurationSec, cursor: !hideCursor }),
|
|
210
|
-
], { stdio: ["pipe", "ignore", "pipe"], windowsHide: true })
|
|
211
|
-
: spawn(ffmpeg, ffArgs, {
|
|
212
|
-
stdio: ["pipe", "ignore", "pipe"],
|
|
213
|
-
windowsHide: true,
|
|
214
|
-
});
|
|
216
|
+
const logger = evPaths
|
|
217
|
+
? await startEventLogger(evPaths.raw, keyMode, replay ? { rotateSec: replayEventRotateSec(replay.bufferSec) } : {})
|
|
218
|
+
: null;
|
|
215
219
|
const id = `rec-${stamp()}-${rand(6)}`;
|
|
216
|
-
const
|
|
217
|
-
|
|
218
|
-
|
|
220
|
+
const launch = async (p) => {
|
|
221
|
+
const settings = plan(p);
|
|
222
|
+
const spawnedAt = Date.now();
|
|
223
|
+
const child = backend === "wgc"
|
|
224
|
+
? spawn(process.execPath, [
|
|
225
|
+
fileURLToPath(new URL("../wgcRecorder.js", import.meta.url)),
|
|
226
|
+
JSON.stringify({ ffmpeg, hwnd: window.hwnd, fps, encode: [...encoderArgs(p.encoder, quality), ...captureKeyframeArgs(fps)], output, maxDurationSec, cursor: !hideCursor }),
|
|
227
|
+
], { stdio: ["pipe", "ignore", "pipe"], windowsHide: true })
|
|
228
|
+
: spawn(ffmpeg, settings.ffArgs, {
|
|
229
|
+
stdio: ["pipe", "ignore", "pipe"],
|
|
230
|
+
windowsHide: true,
|
|
231
|
+
});
|
|
232
|
+
const watch = watchStderr(child, id);
|
|
233
|
+
const settled = await settleCapture(child, watch, backend);
|
|
234
|
+
return { ...settings, child, watch, spawnedAt, settled };
|
|
235
|
+
};
|
|
236
|
+
const started = await startWithEncoderFallback(pick, launch, {
|
|
237
|
+
why: (r) => tailLines(r.watch, 3),
|
|
238
|
+
canFallback: () => ddaUsable({ encoder: "x264", gpuFrames: false }),
|
|
239
|
+
beforeRetry: () => {
|
|
240
|
+
if (replay)
|
|
241
|
+
resetReplaySegments(replay);
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
const { run, failure: retried } = started;
|
|
245
|
+
pick = started.pick;
|
|
246
|
+
const { child, watch, spawnedAt, captureOpts, webcam } = run;
|
|
247
|
+
if (run.settled === "exited") {
|
|
219
248
|
if (logger)
|
|
220
249
|
await stopEventLogger(logger);
|
|
221
250
|
if (evPaths)
|
|
@@ -224,7 +253,8 @@ export function register(server) {
|
|
|
224
253
|
discardReplay(replay);
|
|
225
254
|
if (webcamRaw)
|
|
226
255
|
rmSync(partsDir(output), { recursive: true, force: true });
|
|
227
|
-
throw new ScreencastError(`Recording failed to start (${backend === "wgc" ? "window capture" : "ffmpeg"} exited immediately):\n${tailLines(watch)}`
|
|
256
|
+
throw new ScreencastError(`Recording failed to start (${backend === "wgc" ? "window capture" : "ffmpeg"} exited immediately):\n${tailLines(watch)}` +
|
|
257
|
+
(retried ? `\n(Retried with libx264 after ${retried})` : ""));
|
|
228
258
|
}
|
|
229
259
|
const startMs = captureStartMs(watch, backend, spawnedAt);
|
|
230
260
|
if (backend === "wgc" && frame && window?.client) {
|
package/dist/tools/stepGuide.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, rmdirSync, statSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
|
|
@@ -13,9 +13,10 @@ import { ocrStatus } from "../utils/capabilities.js";
|
|
|
13
13
|
import { readFrames, scanMatches } from "../utils/ocrScan.js";
|
|
14
14
|
import { DEFAULT_SECRET_PATTERN } from "../utils/bugReport.js";
|
|
15
15
|
import { resolveOutputDir, subdir, stamp, rand } from "../utils/paths.js";
|
|
16
|
-
import { GUIDE_FILES, MAX_GUIDE_STEPS, assignSections, buildGuideHtml, buildGuideMarkdown, buildStepFrameArgs, buildStepShotArgs, caption, guideSteps, labelAt, shotFilter, } from "../utils/stepGuide.js";
|
|
16
|
+
import { GUIDE_FILES, HTML_IMAGE_LADDER, HTML_MAX_BYTES, MAX_GUIDE_STEPS, assignSections, base64Bytes, buildHtmlImageArgs, buildGuideHtml, buildGuideMarkdown, buildStepFrameArgs, buildStepShotArgs, caption, guideSteps, htmlImageName, labelAt, nextHtmlRung, shotFilter, } from "../utils/stepGuide.js";
|
|
17
17
|
import { resolveSource } from "./bugReport.js";
|
|
18
18
|
const OCR_BATCH = 10;
|
|
19
|
+
const HTML_SAMPLE = 5;
|
|
19
20
|
const inputSchema = {
|
|
20
21
|
input: z.string().min(1).optional().describe("Recording path (uses its .events.jsonl)."),
|
|
21
22
|
sessionId: z.string().min(1).optional().describe("Or a stopped session's id."),
|
|
@@ -149,10 +150,62 @@ export function register(server) {
|
|
|
149
150
|
written.push(paths.markdown);
|
|
150
151
|
}
|
|
151
152
|
if (wantHtml) {
|
|
152
|
-
const
|
|
153
|
-
|
|
153
|
+
const htmlDir = join(work, "html");
|
|
154
|
+
mkdirSync(htmlDir, { recursive: true });
|
|
155
|
+
const files = steps.flatMap((s) => (s.image ? [s.image] : []));
|
|
156
|
+
const src = (file) => `data:image/jpeg;base64,${readFileSync(join(htmlDir, htmlImageName(file))).toString("base64")}`;
|
|
157
|
+
const encode = async (file, rung) => {
|
|
158
|
+
const out = join(htmlDir, htmlImageName(file));
|
|
159
|
+
await runFfmpeg(buildHtmlImageArgs(join(imageDir, file), rung, out), 60_000, { signal: extra.signal });
|
|
160
|
+
return base64Bytes(statSync(out).size);
|
|
161
|
+
};
|
|
162
|
+
const sample = files.length > HTML_SAMPLE ? files.filter((_, k) => k % Math.ceil(files.length / HTML_SAMPLE) === 0) : [];
|
|
163
|
+
let start = 0;
|
|
164
|
+
for (; sample.length > 0 && start < HTML_IMAGE_LADDER.length - 1; start++) {
|
|
165
|
+
let bytes = 0;
|
|
166
|
+
for (const f of sample)
|
|
167
|
+
bytes += await encode(f, HTML_IMAGE_LADDER[start]);
|
|
168
|
+
if ((bytes / sample.length) * files.length <= HTML_MAX_BYTES * 0.9)
|
|
169
|
+
break;
|
|
170
|
+
}
|
|
171
|
+
let page = "";
|
|
172
|
+
for (let r = start; r !== null;) {
|
|
173
|
+
const rung = HTML_IMAGE_LADDER[r];
|
|
174
|
+
let images = 0;
|
|
175
|
+
for (const file of files)
|
|
176
|
+
images += await encode(file, rung);
|
|
177
|
+
page = images <= HTML_MAX_BYTES ? buildGuideHtml(data, src) : "";
|
|
178
|
+
const bytes = page ? Buffer.byteLength(page) : images;
|
|
179
|
+
if (bytes <= HTML_MAX_BYTES)
|
|
180
|
+
break;
|
|
181
|
+
const next = nextHtmlRung(r, bytes);
|
|
182
|
+
if (next === null) {
|
|
183
|
+
page ||= buildGuideHtml(data, src);
|
|
184
|
+
warnings.push(`guide.html is ${(Buffer.byteLength(page) / 1e6).toFixed(1)} MB, over the ${HTML_MAX_BYTES / 1e6} MB budget even with ${rung.width} px JPEGs; ` +
|
|
185
|
+
"use format: md for a guide this long.");
|
|
186
|
+
}
|
|
187
|
+
r = next;
|
|
188
|
+
}
|
|
189
|
+
writeFileSync(paths.html, page);
|
|
154
190
|
written.push(paths.html);
|
|
155
191
|
}
|
|
192
|
+
if (args.overwrite) {
|
|
193
|
+
if (!wantHtml)
|
|
194
|
+
rmSync(paths.html, { force: true });
|
|
195
|
+
if (!wantMd) {
|
|
196
|
+
rmSync(paths.markdown, { force: true });
|
|
197
|
+
if (existsSync(paths.images)) {
|
|
198
|
+
for (const f of readdirSync(paths.images))
|
|
199
|
+
if (/^step-\d+\.png$/.test(f))
|
|
200
|
+
rmSync(join(paths.images, f), { force: true });
|
|
201
|
+
try {
|
|
202
|
+
rmdirSync(paths.images);
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
156
209
|
if (data.stepsOmitted)
|
|
157
210
|
warnings.push(`Only the first ${MAX_GUIDE_STEPS} steps were written; ${data.stepsOmitted} more were left out.`);
|
|
158
211
|
if (stepsNote)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { assertInputAllowed, assertLocalPath } from "./paths.js";
|
|
2
|
+
const INPUT_KEYS = new Set([
|
|
3
|
+
"input", "inputs", "inputA", "inputB", "clips", "a", "b", "image", "overlay",
|
|
4
|
+
"music", "video", "subtitles", "srt", "transcript", "events",
|
|
5
|
+
]);
|
|
6
|
+
const LOCAL_ONLY_KEYS = new Set(["output", "outputDir", "model", "fontFile"]);
|
|
7
|
+
const KEYWORDS = new Set(["whisper"]);
|
|
8
|
+
function strings(value) {
|
|
9
|
+
if (typeof value === "string")
|
|
10
|
+
return [value];
|
|
11
|
+
if (Array.isArray(value))
|
|
12
|
+
return value.filter((v) => typeof v === "string");
|
|
13
|
+
return [];
|
|
14
|
+
}
|
|
15
|
+
export function assertArgPaths(args) {
|
|
16
|
+
const visit = (node) => {
|
|
17
|
+
if (Array.isArray(node)) {
|
|
18
|
+
node.forEach(visit);
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
if (!node || typeof node !== "object")
|
|
22
|
+
return;
|
|
23
|
+
for (const [key, value] of Object.entries(node)) {
|
|
24
|
+
if (INPUT_KEYS.has(key)) {
|
|
25
|
+
for (const s of strings(value)) {
|
|
26
|
+
if (s.trim().length > 0 && !KEYWORDS.has(s))
|
|
27
|
+
assertInputAllowed(s, `Input "${key}"`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
else if (LOCAL_ONLY_KEYS.has(key)) {
|
|
31
|
+
for (const s of strings(value))
|
|
32
|
+
assertLocalPath(s, `"${key}"`);
|
|
33
|
+
}
|
|
34
|
+
if (value && typeof value === "object")
|
|
35
|
+
visit(value);
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
visit(args);
|
|
39
|
+
}
|
package/dist/utils/captions.js
CHANGED
|
@@ -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
|
-
|
|
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
|
}
|
package/dist/utils/events.js
CHANGED
|
@@ -178,6 +178,7 @@ public static class ScEvents{
|
|
|
178
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);
|
|
179
179
|
struct LII{public uint cb;public uint t;}
|
|
180
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;
|
|
181
182
|
static HashSet<uint> held=new HashSet<uint>();
|
|
182
183
|
static readonly object q=new object();static StringBuilder buf=new StringBuilder();
|
|
183
184
|
static double typeStart=-1,typeLast;static int lastHook=Environment.TickCount;static bool missing;
|
|
@@ -193,15 +194,18 @@ public static class ScEvents{
|
|
|
193
194
|
static void Typed(){double t=Now();lock(q){if(typeStart<0)typeStart=t;typeLast=t;}}
|
|
194
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;}
|
|
195
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));}
|
|
196
|
-
static void Drain(){lock(
|
|
197
|
-
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));}}
|
|
198
201
|
static void Pump(string stop){int tick=0;while(true){Thread.Sleep(250);tick++;
|
|
199
202
|
EndTyping(false);
|
|
200
203
|
lock(held){foreach(uint vk in new List<uint>(held)){if(!Down((int)vk))held.Remove(vk);}}
|
|
201
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,"");}
|
|
202
205
|
if(tick%4==0)Put("hb",0,0,"");
|
|
203
206
|
if(File.Exists(stop))Quit();
|
|
204
|
-
Drain();
|
|
207
|
+
Drain();
|
|
208
|
+
if(Rot>0&&unchecked(Environment.TickCount-lastRot)>=Rot){lastRot=Environment.TickCount;Rotate();}}}
|
|
205
209
|
static IntPtr Mouse(int n,IntPtr wp,IntPtr lp){
|
|
206
210
|
if(n>=0){Seen();MS s=(MS)Marshal.PtrToStructure(lp,typeof(MS));int m=(int)wp;cx=s.x;cy=s.y;
|
|
207
211
|
if(m==0x200){double t=Now();if(t-lastMove>=${MOVE_SAMPLE_MS}){lastMove=t;Put("move",s.x,s.y,"");}}
|
|
@@ -234,7 +238,7 @@ public static class ScEvents{
|
|
|
234
238
|
return CallNextHookEx(IntPtr.Zero,n,wp,lp);}
|
|
235
239
|
public static void Run(string path,bool shortcuts,int parent){
|
|
236
240
|
try{SetProcessDpiAwarenessContext(new IntPtr(-4));}catch{}
|
|
237
|
-
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));
|
|
238
242
|
IntPtr mod=GetModuleHandle(null);mp=Mouse;kp=Key;
|
|
239
243
|
if(SetWindowsHookEx(14,mp,mod,0)==IntPtr.Zero||SetWindowsHookEx(13,kp,mod,0)==IntPtr.Zero)throw new Exception("SetWindowsHookEx failed: "+Marshal.GetLastWin32Error());
|
|
240
244
|
var watch=new Thread(()=>{while(true){Thread.Sleep(500);bool gone;try{gone=Process.GetProcessById(parent).HasExited;}catch{gone=true;}if(gone)Quit();}});
|
|
@@ -245,12 +249,40 @@ public static class ScEvents{
|
|
|
245
249
|
}
|
|
246
250
|
}
|
|
247
251
|
"@
|
|
252
|
+
[ScEvents]::Rot=__ROTATE__
|
|
248
253
|
[ScEvents]::Run([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PATH__')), [bool]__MODE__, __PARENT__)
|
|
249
254
|
`;
|
|
250
|
-
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));
|
|
251
257
|
return PS_HOOK.replace("__PATH__", Buffer.from(rawPath, "utf8").toString("base64"))
|
|
252
258
|
.replace("__MODE__", mode === "shortcuts" ? "1" : "0")
|
|
253
|
-
.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);
|
|
254
286
|
}
|
|
255
287
|
export function cleanPsError(stderr) {
|
|
256
288
|
if (!stderr.startsWith("#< CLIXML"))
|
|
@@ -265,12 +297,12 @@ export function cleanPsError(stderr) {
|
|
|
265
297
|
.trim();
|
|
266
298
|
}
|
|
267
299
|
export const LOGGER_READY_TIMEOUT_MS = 20_000;
|
|
268
|
-
export async function startEventLogger(rawPath, mode) {
|
|
300
|
+
export async function startEventLogger(rawPath, mode, opts = {}) {
|
|
269
301
|
if (process.platform !== "win32") {
|
|
270
302
|
throw new ScreencastError("The input event log is implemented for Windows only.");
|
|
271
303
|
}
|
|
272
304
|
rmSync(`${rawPath}.stop`, { force: true });
|
|
273
|
-
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");
|
|
274
306
|
const child = spawn("powershell", ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], {
|
|
275
307
|
stdio: ["ignore", "pipe", "pipe"],
|
|
276
308
|
windowsHide: true,
|
package/dist/utils/gpu.js
CHANGED
|
@@ -76,19 +76,65 @@ export async function probeHwEncoders(ffmpeg, run = ffmpegRunner(ffmpeg)) {
|
|
|
76
76
|
const results = await Promise.all(HW_ENCODERS.map((e) => cachedProbe(ffmpeg, `enc:${e}`, buildEncoderProbeArgs(e), run)));
|
|
77
77
|
return Object.fromEntries(HW_ENCODERS.map((e, i) => [e, results[i]]));
|
|
78
78
|
}
|
|
79
|
-
export
|
|
79
|
+
export const HW_MAX_FRAME = {
|
|
80
|
+
nvenc: { width: 4096, height: 4096 },
|
|
81
|
+
qsv: { width: 4096, height: 2304 },
|
|
82
|
+
amf: { width: 4096, height: 2304 },
|
|
83
|
+
};
|
|
84
|
+
export function encoderFits(encoder, frame) {
|
|
85
|
+
const max = HW_MAX_FRAME[encoder];
|
|
86
|
+
return frame.width <= max.width && frame.height <= max.height;
|
|
87
|
+
}
|
|
88
|
+
export async function resolveEncoder(choice, backend, ffmpeg, run = ffmpegRunner(ffmpeg), frame) {
|
|
80
89
|
if (choice === "x264")
|
|
81
90
|
return { encoder: "x264", gpuFrames: false };
|
|
91
|
+
const fits = (e) => !frame || encoderFits(e, frame);
|
|
92
|
+
const size = frame ? `${frame.width}x${frame.height}` : "";
|
|
93
|
+
if (choice !== "auto" && !fits(choice)) {
|
|
94
|
+
const max = HW_MAX_FRAME[choice];
|
|
95
|
+
throw new ScreencastError(`The ${choice} encoder (${ENCODER_CODECS[choice]}) cannot encode a ${size} frame (at most ${max.width}x${max.height}).`, 'Use encoder: "x264" (or "auto", which picks libx264 for it), or record a smaller target.');
|
|
96
|
+
}
|
|
82
97
|
const available = await probeHwEncoders(ffmpeg, run);
|
|
83
|
-
const pick = choice === "auto" ? HW_ENCODERS.find((e) => available[e]) : available[choice] ? choice : undefined;
|
|
98
|
+
const pick = choice === "auto" ? HW_ENCODERS.find((e) => available[e] && fits(e)) : available[choice] ? choice : undefined;
|
|
84
99
|
if (!pick) {
|
|
85
|
-
if (choice === "auto")
|
|
86
|
-
|
|
100
|
+
if (choice === "auto") {
|
|
101
|
+
const working = HW_ENCODERS.filter((e) => available[e]);
|
|
102
|
+
return {
|
|
103
|
+
encoder: "x264",
|
|
104
|
+
gpuFrames: false,
|
|
105
|
+
note: working.length > 0
|
|
106
|
+
? `The capture is ${size}, larger than the hardware encoders here take (${working
|
|
107
|
+
.map((e) => `${e}: ${HW_MAX_FRAME[e].width}x${HW_MAX_FRAME[e].height}`)
|
|
108
|
+
.join(", ")}); using libx264.`
|
|
109
|
+
: "No hardware encoder passed a trial encode; using libx264.",
|
|
110
|
+
};
|
|
111
|
+
}
|
|
87
112
|
throw new ScreencastError(`The ${choice} encoder (${ENCODER_CODECS[choice]}) failed a trial encode on this machine.`, 'Use encoder: "auto" (falls back to libx264) or "x264"; doctor lists the encoders that work here.');
|
|
88
113
|
}
|
|
89
114
|
const gpuFrames = backend === "ddagrab" && (await cachedProbe(ffmpeg, `dda:${pick}`, buildDdaProbeArgs(pick), run));
|
|
90
115
|
return { encoder: pick, gpuFrames };
|
|
91
116
|
}
|
|
117
|
+
export async function startWithEncoderFallback(pick, launch, opts) {
|
|
118
|
+
const first = await launch(pick);
|
|
119
|
+
if (first.settled === "running" || pick.encoder === "x264")
|
|
120
|
+
return { run: first, pick };
|
|
121
|
+
const fallback = { encoder: "x264", gpuFrames: false };
|
|
122
|
+
if (opts.canFallback && !(await opts.canFallback()))
|
|
123
|
+
return { run: first, pick };
|
|
124
|
+
const name = `${pick.encoder} (${ENCODER_CODECS[pick.encoder]})`;
|
|
125
|
+
const why = opts.why(first).trim();
|
|
126
|
+
const failure = `the ${name} encoder exited at start${why ? `:\n${why}` : ""}`;
|
|
127
|
+
opts.beforeRetry?.();
|
|
128
|
+
const run = await launch(fallback);
|
|
129
|
+
if (run.settled === "exited")
|
|
130
|
+
return { run, pick: fallback, failure };
|
|
131
|
+
const last = why.split("\n").at(-1) ?? "";
|
|
132
|
+
return {
|
|
133
|
+
run,
|
|
134
|
+
pick: { ...fallback, note: `The ${name} encoder exited at start; recording with libx264 instead.${last ? ` ffmpeg said: ${last}` : ""}` },
|
|
135
|
+
failure,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
92
138
|
export function ddagrabWorks(ffmpeg, run = ffmpegRunner(ffmpeg)) {
|
|
93
139
|
return cachedProbe(ffmpeg, "dda", buildDdaProbeArgs(), run);
|
|
94
140
|
}
|
package/dist/utils/lifecycle.js
CHANGED
|
@@ -6,7 +6,7 @@ import { buildProbeArgs, parseMediaInfo } from "./media.js";
|
|
|
6
6
|
import { ScreencastError } from "./errors.js";
|
|
7
7
|
import { wgcStopFile } from "./wgc.js";
|
|
8
8
|
import { encoderArgs } from "./gpu.js";
|
|
9
|
-
import { clearPausing, endSession, finishSegments, markPausing, pauseBlocker, recordedSec, webcamOutputPath, } from "./pause.js";
|
|
9
|
+
import { clearPausing, endSession, finishSegments, markPausing, pauseBlocker, recordedSec, segmentDurationSec, webcamOutputPath, } from "./pause.js";
|
|
10
10
|
import { expectedImage, isAlive, isRecorderProcess, killPid, } from "./sessions.js";
|
|
11
11
|
async function waitForPidExit(pid, ms) {
|
|
12
12
|
const deadline = Date.now() + ms;
|
|
@@ -57,7 +57,9 @@ export async function finalParts(record, ffprobe) {
|
|
|
57
57
|
return [];
|
|
58
58
|
const parts = [...seg.parts];
|
|
59
59
|
if (seg.current) {
|
|
60
|
-
const
|
|
60
|
+
const probed = await probeDuration(ffprobe, seg.current.path);
|
|
61
|
+
const endMs = record.stoppedAt ? Date.parse(record.stoppedAt) : Date.now();
|
|
62
|
+
const durationSec = segmentDurationSec(seg.current.path, probed, seg.current.startMs, endMs) ?? 0;
|
|
61
63
|
parts.push({ ...seg.current, durationSec });
|
|
62
64
|
}
|
|
63
65
|
return parts;
|
|
@@ -82,7 +84,44 @@ export async function joinSegments(record, tools) {
|
|
|
82
84
|
error: res.error,
|
|
83
85
|
};
|
|
84
86
|
}
|
|
85
|
-
|
|
87
|
+
const sessionOps = new WeakMap();
|
|
88
|
+
export function sessionOpInFlight(store, id) {
|
|
89
|
+
return sessionOps.get(store)?.get(id)?.kind ?? null;
|
|
90
|
+
}
|
|
91
|
+
export function withSessionOp(store, id, kind, fn, opts = {}) {
|
|
92
|
+
let ops = sessionOps.get(store);
|
|
93
|
+
if (!ops)
|
|
94
|
+
sessionOps.set(store, (ops = new Map()));
|
|
95
|
+
const running = ops.get(id);
|
|
96
|
+
if (running?.kind === kind)
|
|
97
|
+
return running.promise;
|
|
98
|
+
if (running && !opts.queue) {
|
|
99
|
+
return Promise.reject(new ScreencastError(`Cannot ${kind} ${id}: a ${running.kind} of it is in progress.`, "Retry once it finishes (get_recording shows the session's status)."));
|
|
100
|
+
}
|
|
101
|
+
let start;
|
|
102
|
+
if (running) {
|
|
103
|
+
start = running.promise.then(() => fn(true), () => fn(true));
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
try {
|
|
107
|
+
start = fn(false);
|
|
108
|
+
}
|
|
109
|
+
catch (err) {
|
|
110
|
+
start = Promise.reject(err);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
const map = ops;
|
|
114
|
+
const op = start.finally(() => {
|
|
115
|
+
if (map.get(id)?.promise === op)
|
|
116
|
+
map.delete(id);
|
|
117
|
+
});
|
|
118
|
+
map.set(id, { kind, promise: op });
|
|
119
|
+
return op;
|
|
120
|
+
}
|
|
121
|
+
export function pauseSession(store, record, opts) {
|
|
122
|
+
return withSessionOp(store, record.id, "pause", () => runPause(store, store.get(record.id) ?? record, opts));
|
|
123
|
+
}
|
|
124
|
+
async function runPause(store, record, opts) {
|
|
86
125
|
const child = store.getChild(record.id);
|
|
87
126
|
const blocker = pauseBlocker(record, !!child);
|
|
88
127
|
if (blocker)
|
|
@@ -90,10 +129,12 @@ export async function pauseSession(store, record, opts) {
|
|
|
90
129
|
markPausing(record.id);
|
|
91
130
|
store.markStopping(record.id);
|
|
92
131
|
try {
|
|
132
|
+
const pausedAt = Date.now();
|
|
93
133
|
const graceful = await quitChild(child, record.pid, opts.gracefulMs ?? 8000);
|
|
94
|
-
store.detachChild(record.id);
|
|
134
|
+
store.detachChild(record.id, child);
|
|
95
135
|
const cur = record.segments.current;
|
|
96
|
-
const
|
|
136
|
+
const probed = await opts.probe(cur.path);
|
|
137
|
+
const segmentSec = segmentDurationSec(cur.path, probed, cur.startMs, pausedAt) ?? 0;
|
|
97
138
|
const parts = record.segments.parts;
|
|
98
139
|
const next = segmentSec > 0 ? [...parts, { ...cur, durationSec: segmentSec }] : parts;
|
|
99
140
|
if (segmentSec <= 0 && cur.path !== record.outputPath)
|
|
@@ -128,17 +169,16 @@ export async function stopAll(store, probe, capMs = 10_000) {
|
|
|
128
169
|
clearTimeout(timer);
|
|
129
170
|
return ids;
|
|
130
171
|
}
|
|
131
|
-
const inFlight = new WeakMap();
|
|
132
172
|
export function stopSession(store, record, opts) {
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
173
|
+
return withSessionOp(store, record.id, "stop", async (waited) => {
|
|
174
|
+
if (!waited)
|
|
175
|
+
return runStop(store, record, opts);
|
|
176
|
+
const cur = store.get(record.id) ?? record;
|
|
177
|
+
if (cur.status !== "recording" && cur.status !== "paused") {
|
|
178
|
+
return { record: cur, graceful: true, durationSec: cur.durationSec ?? null };
|
|
179
|
+
}
|
|
180
|
+
return runStop(store, cur, opts);
|
|
181
|
+
}, { queue: true });
|
|
142
182
|
}
|
|
143
183
|
async function runStop(store, record, opts) {
|
|
144
184
|
store.markStopping(record.id);
|
|
@@ -171,7 +211,7 @@ async function runStop(store, record, opts) {
|
|
|
171
211
|
}
|
|
172
212
|
}
|
|
173
213
|
}
|
|
174
|
-
store.detachChild(record.id);
|
|
214
|
+
store.detachChild(record.id, child);
|
|
175
215
|
if (record.status === "paused")
|
|
176
216
|
graceful = true;
|
|
177
217
|
endSession(record.id);
|
package/dist/utils/media.js
CHANGED
|
@@ -484,8 +484,9 @@ export const BLUR_PASSES = 3;
|
|
|
484
484
|
export const MIN_PIXEL_BLOCK = 16;
|
|
485
485
|
export function blurRadius(r) {
|
|
486
486
|
const m = Math.min(r.w, r.h);
|
|
487
|
-
const
|
|
488
|
-
const
|
|
487
|
+
const maxRadius = (side) => Math.max(0, Math.floor((side - 1) / 2));
|
|
488
|
+
const lr = Math.min(maxRadius(m), Math.max(MIN_BLUR_RADIUS, Math.min(20, Math.floor(m / 4))));
|
|
489
|
+
const cr = Math.min(lr, maxRadius(Math.ceil(m / 2)));
|
|
489
490
|
return `lr=${lr}:lp=${BLUR_PASSES}:cr=${cr}:cp=${BLUR_PASSES}`;
|
|
490
491
|
}
|
|
491
492
|
export function pixelateFilter(r) {
|