@tmhs/screencast-mcp 0.49.0 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +13 -8
  2. package/dist/index.js +550 -106
  3. package/dist/wgcRecorder.js +15 -139
  4. package/package.json +8 -4
  5. package/assets/.gitkeep +0 -0
  6. package/assets/icon.png +0 -0
  7. package/dist/cli.js +0 -516
  8. package/dist/context.js +0 -50
  9. package/dist/prompts.js +0 -95
  10. package/dist/resources.js +0 -93
  11. package/dist/server.js +0 -174
  12. package/dist/setup.js +0 -438
  13. package/dist/tools/addMarker.js +0 -93
  14. package/dist/tools/assembleHighlights.js +0 -69
  15. package/dist/tools/backdrop.js +0 -89
  16. package/dist/tools/bugReport.js +0 -266
  17. package/dist/tools/burnSubtitles.js +0 -56
  18. package/dist/tools/callout.js +0 -103
  19. package/dist/tools/chapters.js +0 -156
  20. package/dist/tools/clip.js +0 -52
  21. package/dist/tools/compress.js +0 -51
  22. package/dist/tools/concat.js +0 -67
  23. package/dist/tools/contactSheet.js +0 -135
  24. package/dist/tools/convert.js +0 -46
  25. package/dist/tools/crop.js +0 -43
  26. package/dist/tools/cursor.js +0 -87
  27. package/dist/tools/cutByTranscript.js +0 -86
  28. package/dist/tools/cutIdle.js +0 -84
  29. package/dist/tools/deleteRecording.js +0 -119
  30. package/dist/tools/denoise.js +0 -60
  31. package/dist/tools/doctor.js +0 -146
  32. package/dist/tools/exportGif.js +0 -57
  33. package/dist/tools/exportPreset.js +0 -48
  34. package/dist/tools/extractAudio.js +0 -65
  35. package/dist/tools/findText.js +0 -196
  36. package/dist/tools/getMediaInfo.js +0 -36
  37. package/dist/tools/getSession.js +0 -40
  38. package/dist/tools/indexRecording.js +0 -195
  39. package/dist/tools/keystrokeOverlay.js +0 -131
  40. package/dist/tools/listAudioDevices.js +0 -35
  41. package/dist/tools/listSessions.js +0 -28
  42. package/dist/tools/listTargets.js +0 -76
  43. package/dist/tools/listVideoDevices.js +0 -26
  44. package/dist/tools/musicBed.js +0 -55
  45. package/dist/tools/narrate.js +0 -86
  46. package/dist/tools/normalizeAudio.js +0 -60
  47. package/dist/tools/overlay.js +0 -62
  48. package/dist/tools/pauseRecording.js +0 -44
  49. package/dist/tools/pipeline.js +0 -400
  50. package/dist/tools/readEvents.js +0 -98
  51. package/dist/tools/redactRegion.js +0 -70
  52. package/dist/tools/reframe.js +0 -46
  53. package/dist/tools/resumeRecording.js +0 -46
  54. package/dist/tools/reviewRecording.js +0 -163
  55. package/dist/tools/sampleFrames.js +0 -200
  56. package/dist/tools/saveReplay.js +0 -90
  57. package/dist/tools/scale.js +0 -44
  58. package/dist/tools/screenDiff.js +0 -86
  59. package/dist/tools/screenshot.js +0 -76
  60. package/dist/tools/searchRecording.js +0 -79
  61. package/dist/tools/speed.js +0 -46
  62. package/dist/tools/startRecording.js +0 -398
  63. package/dist/tools/stepGuide.js +0 -250
  64. package/dist/tools/stopRecording.js +0 -132
  65. package/dist/tools/titleCard.js +0 -67
  66. package/dist/tools/transcribe.js +0 -66
  67. package/dist/tools/trim.js +0 -57
  68. package/dist/tools/waitForChange.js +0 -128
  69. package/dist/tools/xfadeTransition.js +0 -58
  70. package/dist/tools/zoom.js +0 -149
  71. package/dist/utils/anim.js +0 -54
  72. package/dist/utils/animExport.js +0 -56
  73. package/dist/utils/argPaths.js +0 -39
  74. package/dist/utils/audio.js +0 -113
  75. package/dist/utils/audioDevices.js +0 -107
  76. package/dist/utils/backdrop.js +0 -151
  77. package/dist/utils/bugReport.js +0 -172
  78. package/dist/utils/callout.js +0 -90
  79. package/dist/utils/calloutAssets.js +0 -42
  80. package/dist/utils/capabilities.js +0 -96
  81. package/dist/utils/captions.js +0 -103
  82. package/dist/utils/chapters.js +0 -227
  83. package/dist/utils/consent.js +0 -29
  84. package/dist/utils/cursor.js +0 -317
  85. package/dist/utils/diff.js +0 -184
  86. package/dist/utils/errors.js +0 -29
  87. package/dist/utils/events.js +0 -403
  88. package/dist/utils/expr.js +0 -11
  89. package/dist/utils/ffmpeg.js +0 -285
  90. package/dist/utils/fontCoverage.js +0 -177
  91. package/dist/utils/fonts.js +0 -154
  92. package/dist/utils/gpu.js +0 -219
  93. package/dist/utils/idle.js +0 -91
  94. package/dist/utils/images.js +0 -38
  95. package/dist/utils/jobs.js +0 -129
  96. package/dist/utils/keystrokes.js +0 -155
  97. package/dist/utils/lifecycle.js +0 -233
  98. package/dist/utils/logging.js +0 -75
  99. package/dist/utils/media.js +0 -574
  100. package/dist/utils/monitors.js +0 -124
  101. package/dist/utils/narrate.js +0 -233
  102. package/dist/utils/ocr.js +0 -222
  103. package/dist/utils/ocrScan.js +0 -91
  104. package/dist/utils/paths.js +0 -155
  105. package/dist/utils/pause.js +0 -190
  106. package/dist/utils/pipeline.js +0 -361
  107. package/dist/utils/player.js +0 -85
  108. package/dist/utils/pool.js +0 -29
  109. package/dist/utils/produce.js +0 -298
  110. package/dist/utils/recipes.js +0 -71
  111. package/dist/utils/recorder.js +0 -173
  112. package/dist/utils/recordingFiles.js +0 -32
  113. package/dist/utils/recordingIndex.js +0 -312
  114. package/dist/utils/replay.js +0 -283
  115. package/dist/utils/resolveTarget.js +0 -25
  116. package/dist/utils/retention.js +0 -48
  117. package/dist/utils/roots.js +0 -43
  118. package/dist/utils/sessions.js +0 -499
  119. package/dist/utils/sheet.js +0 -59
  120. package/dist/utils/stepGuide.js +0 -231
  121. package/dist/utils/steps.js +0 -88
  122. package/dist/utils/still.js +0 -38
  123. package/dist/utils/targetList.js +0 -64
  124. package/dist/utils/targets.js +0 -265
  125. package/dist/utils/timeline.js +0 -85
  126. package/dist/utils/toolSpec.js +0 -31
  127. package/dist/utils/toolsets.js +0 -134
  128. package/dist/utils/transcriptCut.js +0 -149
  129. package/dist/utils/validate.js +0 -23
  130. package/dist/utils/waitLoop.js +0 -50
  131. package/dist/utils/wgc.js +0 -84
  132. package/dist/utils/windows.js +0 -192
  133. package/dist/utils/zoom.js +0 -234
@@ -1,312 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { closeSync, existsSync, openSync, readFileSync, readSync, renameSync, statSync, writeFileSync } from "node:fs";
3
- import { basename, dirname, join, resolve } from "node:path";
4
- import { ScreencastError } from "./errors.js";
5
- import { pickSceneFrames } from "./media.js";
6
- import { normalizeForMatch, regexRanges, MAX_QUERY_LENGTH } from "./ocr.js";
7
- import { maskSecrets, DEFAULT_SECRET_PATTERN } from "./bugReport.js";
8
- import { eventPaths, whenFinalized } from "./events.js";
9
- import { readMarkers } from "./chapters.js";
10
- import { assertOutputAllowed } from "./paths.js";
11
- import { getStore } from "../context.js";
12
- export const INDEX_VERSION = 1;
13
- export const DEFAULT_INDEX_THRESHOLD = 0.03;
14
- export const DEFAULT_INDEX_FRAMES = 120;
15
- export const MAX_INDEX_FRAMES = 600;
16
- export const MAX_SEGMENT_SEC = 10;
17
- export const DEFAULT_SEARCH_LIMIT = 10;
18
- export const MAX_SEARCH_LIMIT = 50;
19
- export const MAX_SNIPPET = 200;
20
- export const MAX_MATCHES_PER_HIT = 5;
21
- const r3 = (v) => Math.round(v * 1000) / 1000;
22
- export function indexSidecarPath(video) {
23
- return `${video}.index.json`;
24
- }
25
- export function legacyIndexSidecarPath(video) {
26
- return `${video.replace(/\.[^./\\]+$/, "")}.index.json`;
27
- }
28
- export function samePath(a, b) {
29
- const norm = (p) => (process.platform === "win32" ? resolve(p).toLowerCase() : resolve(p));
30
- return norm(a) === norm(b);
31
- }
32
- export function indexMatchesVideo(index, video, fingerprint) {
33
- if (typeof index.video === "string" && samePath(index.video, video))
34
- return true;
35
- return fingerprint !== undefined && !!index.fingerprint && sameFingerprint(index.fingerprint, fingerprint);
36
- }
37
- export function fallbackIndexPath(video, editsDir) {
38
- const key = createHash("sha1").update(resolve(video).toLowerCase()).digest("hex").slice(0, 12);
39
- const name = basename(video).replace(/\.[^.]+$/, "");
40
- return join(editsDir, "indexes", `${name}-${key}.index.json`);
41
- }
42
- export function indexWritePath(video, editsDir) {
43
- const sidecar = indexSidecarPath(video);
44
- try {
45
- assertOutputAllowed(sidecar);
46
- return sidecar;
47
- }
48
- catch {
49
- return fallbackIndexPath(video, editsDir);
50
- }
51
- }
52
- export function findIndex(video, editsDir, fingerprint) {
53
- for (const p of [indexSidecarPath(video), fallbackIndexPath(video, editsDir)])
54
- if (existsSync(p))
55
- return p;
56
- const legacy = legacyIndexSidecarPath(video);
57
- if (legacy !== indexSidecarPath(video) && existsSync(legacy)) {
58
- const index = readIndex(legacy);
59
- if (index && indexMatchesVideo(index, video, fingerprint))
60
- return legacy;
61
- }
62
- return null;
63
- }
64
- export function canReuseIndex(prior, want) {
65
- return (prior !== null &&
66
- sameFingerprint(prior.fingerprint, want.fingerprint) &&
67
- prior.sceneThreshold === want.sceneThreshold &&
68
- prior.maxFrames === want.maxFrames &&
69
- (prior.ocr || !want.ocrAvailable));
70
- }
71
- export function maskSegmentText(segments, pattern = DEFAULT_SECRET_PATTERN) {
72
- return segments.map((s) => (s.ocr.length > 0 ? { ...s, ocr: maskSecrets(s.ocr, pattern) } : s));
73
- }
74
- const VIDEO_EXT = /\.(mp4|mkv|mov|webm|avi|m4v|wmv|flv|gif|ts|mpg|mpeg)$/i;
75
- const stemOf = (name) => name.replace(/\.[^.]+$/, "").toLowerCase();
76
- export function defaultTranscriptPath(video, siblings) {
77
- const names = new Set(siblings.map((n) => n.toLowerCase()));
78
- const own = basename(video);
79
- if (names.has(`${own}.srt`.toLowerCase()))
80
- return { path: `${video}.srt`, ambiguous: false };
81
- const shortName = `${own.replace(/\.[^.]+$/, "")}.srt`;
82
- if (!names.has(shortName.toLowerCase()))
83
- return { path: null, ambiguous: false };
84
- const rival = siblings.some((n) => n.toLowerCase() !== own.toLowerCase() && VIDEO_EXT.test(n) && stemOf(n) === stemOf(own));
85
- return rival ? { path: null, ambiguous: true } : { path: join(dirname(video), shortName), ambiguous: false };
86
- }
87
- export function planKeyframes(changes, durationSec, maxFrames, maxGap = MAX_SEGMENT_SEC) {
88
- const times = pickSceneFrames(changes.filter((c) => c.timeSec < durationSec), maxFrames).map(r3);
89
- while (times.length < maxFrames) {
90
- let best = -1;
91
- let gap = 0;
92
- for (let i = 0; i < times.length; i++) {
93
- const g = (times[i + 1] ?? durationSec) - times[i];
94
- if (g > gap) {
95
- gap = g;
96
- best = i;
97
- }
98
- }
99
- if (best === -1 || gap <= maxGap)
100
- break;
101
- times.splice(best + 1, 0, r3(times[best] + gap / 2));
102
- }
103
- return [...new Set(times)].sort((a, b) => a - b);
104
- }
105
- export function segmentsFrom(starts, durationSec) {
106
- return starts.map((start, i) => ({ start, end: r3(starts[i + 1] ?? durationSec) }));
107
- }
108
- export function keyframeTime(seg) {
109
- return r3(seg.start + Math.min(0.25, (seg.end - seg.start) / 2));
110
- }
111
- export function mergeSegments(segments) {
112
- const out = [];
113
- for (const seg of segments) {
114
- const prev = out.at(-1);
115
- if (prev && prev.ocr.join("\n") === seg.ocr.join("\n") && !seg.events && !seg.markers && !seg.transcript) {
116
- prev.end = seg.end;
117
- }
118
- else {
119
- out.push({ ...seg, ocr: [...seg.ocr] });
120
- }
121
- }
122
- return out;
123
- }
124
- export function eventTexts(events) {
125
- const out = [];
126
- for (const e of events) {
127
- const at = `at ${Math.round(e.x)},${Math.round(e.y)}`;
128
- let text = null;
129
- if (e.type === "down")
130
- text = `click ${e.button ?? "left"} ${at}`;
131
- else if (e.type === "key")
132
- text = `shortcut ${e.keys ?? "key"}`;
133
- else if (e.type === "typing")
134
- text = `typing ${r3(e.durationSec ?? 0)} s`;
135
- else if (e.type === "wheel")
136
- text = `scroll ${(e.delta ?? 0) > 0 ? "up" : "down"} ${at}`;
137
- else if (e.type === "gap")
138
- text = `event gap (${e.reason ?? "unknown"})`;
139
- if (text)
140
- out.push({ t: r3(e.t), text });
141
- }
142
- return out;
143
- }
144
- export function markerTexts(markers) {
145
- return markers.map((m) => ({ t: r3(m.t), text: m.label }));
146
- }
147
- export function cueTexts(cues) {
148
- return cues.map((c) => ({ t: r3(c.start), text: c.text.replace(/\s+/g, " ").trim() })).filter((c) => c.text);
149
- }
150
- export function attach(segments, items, field) {
151
- const out = segments.map((s) => {
152
- const { [field]: _old, ...rest } = s;
153
- return rest;
154
- });
155
- if (out.length === 0)
156
- return out;
157
- for (const item of [...items].sort((a, b) => a.t - b.t)) {
158
- let i = out.findIndex((s) => item.t >= s.start && item.t < s.end);
159
- if (i === -1)
160
- i = item.t < out[0].start ? 0 : out.length - 1;
161
- const seg = out[i];
162
- (seg[field] ??= []).push(item);
163
- }
164
- return out;
165
- }
166
- export function fingerprintFile(path) {
167
- const st = statSync(path);
168
- const hash = createHash("sha1");
169
- const chunk = 64 * 1024;
170
- const fd = openSync(path, "r");
171
- try {
172
- const buf = Buffer.alloc(chunk);
173
- for (const pos of st.size > chunk ? [0, st.size - chunk] : [0]) {
174
- const n = readSync(fd, buf, 0, chunk, pos);
175
- hash.update(buf.subarray(0, n));
176
- }
177
- }
178
- finally {
179
- closeSync(fd);
180
- }
181
- return { size: st.size, mtimeMs: Math.round(st.mtimeMs), sample: hash.digest("hex") };
182
- }
183
- export function sameFingerprint(a, b) {
184
- return a.size === b.size && a.mtimeMs === b.mtimeMs && a.sample === b.sample;
185
- }
186
- export function parseIndex(text) {
187
- try {
188
- const data = JSON.parse(text);
189
- if (data?.version !== INDEX_VERSION || !Array.isArray(data.segments) || !data.fingerprint)
190
- return null;
191
- return data;
192
- }
193
- catch {
194
- return null;
195
- }
196
- }
197
- export function readIndex(path) {
198
- try {
199
- return parseIndex(readFileSync(path, "utf8"));
200
- }
201
- catch {
202
- return null;
203
- }
204
- }
205
- export function writeIndex(path, index) {
206
- const tmp = `${path}.${process.pid}.tmp`;
207
- writeFileSync(tmp, JSON.stringify(index));
208
- renameSync(tmp, path);
209
- }
210
- function snippet(text) {
211
- const s = text.replace(/\s+/g, " ").trim();
212
- return s.length > MAX_SNIPPET ? `${s.slice(0, MAX_SNIPPET - 1)}…` : s;
213
- }
214
- function itemsOf(index) {
215
- const items = [];
216
- index.segments.forEach((s, seg) => {
217
- for (const text of s.ocr)
218
- items.push({ seg, source: "screen", t: s.start, text });
219
- for (const [source, list] of [["event", s.events], ["marker", s.markers], ["transcript", s.transcript]]) {
220
- for (const it of list ?? [])
221
- items.push({ seg, source, t: it.t, text: it.text });
222
- }
223
- });
224
- return items;
225
- }
226
- export function searchIndex(index, query, opts = {}) {
227
- if (query.trim().length === 0)
228
- throw new ScreencastError("query must not be empty.");
229
- if (query.length > MAX_QUERY_LENGTH) {
230
- throw new ScreencastError(`The query is ${query.length} characters; at most ${MAX_QUERY_LENGTH} are allowed.`);
231
- }
232
- if (opts.video !== undefined && !indexMatchesVideo(index, opts.video, opts.fingerprint)) {
233
- throw new ScreencastError(`The index found is for ${index.video}, not ${opts.video}.`, "Run index_recording on this recording.");
234
- }
235
- if (!opts.regex && !/[\p{L}\p{N}]/u.test(normalizeForMatch(query))) {
236
- throw new ScreencastError("query needs at least one letter or digit.", "For punctuation, use regex: true.");
237
- }
238
- const pattern = opts.secretPattern === undefined ? DEFAULT_SECRET_PATTERN : opts.secretPattern;
239
- const raw = itemsOf(index);
240
- const masked = pattern ? maskSecrets(raw.map((i) => i.text), pattern) : raw.map((i) => i.text);
241
- const items = raw.map((item, i) => ({ ...item, text: masked[i] ?? "" }));
242
- const matched = new Map();
243
- const add = (item, score) => {
244
- const entry = matched.get(item.seg) ?? { score: 0, matches: [] };
245
- entry.score += score;
246
- entry.matches.push(item);
247
- matched.set(item.seg, entry);
248
- };
249
- if (opts.regex) {
250
- const ranges = regexRanges(items.map((i) => i.text), query);
251
- items.forEach((item, i) => {
252
- if ((ranges[i] ?? []).length > 0)
253
- add(item, 2);
254
- });
255
- }
256
- else {
257
- const needle = normalizeForMatch(query.trim());
258
- const words = needle.split("_").filter(Boolean);
259
- const norm = items.map((i) => normalizeForMatch(i.text));
260
- items.forEach((item, i) => {
261
- if (norm[i].includes(needle))
262
- add(item, 2);
263
- });
264
- if (words.length > 1) {
265
- const bySeg = new Map();
266
- items.forEach((item, i) => bySeg.set(item.seg, [...(bySeg.get(item.seg) ?? []), i]));
267
- for (const [seg, idx] of bySeg) {
268
- if (matched.has(seg))
269
- continue;
270
- if (!words.every((w) => idx.some((i) => norm[i].includes(w))))
271
- continue;
272
- for (const i of idx)
273
- if (words.some((w) => norm[i].includes(w)))
274
- add(items[i], 0);
275
- matched.get(seg).score = 1;
276
- }
277
- }
278
- }
279
- const ranked = [...matched.entries()]
280
- .map(([seg, m]) => ({ seg, ...m }))
281
- .sort((a, b) => b.score - a.score || index.segments[a.seg].start - index.segments[b.seg].start);
282
- const chosen = ranked.slice(0, opts.limit ?? DEFAULT_SEARCH_LIMIT);
283
- const hits = chosen.map((c) => {
284
- const seg = index.segments[c.seg];
285
- const matches = c.matches.slice(0, MAX_MATCHES_PER_HIT).map((m) => ({ source: m.source, t: m.t, text: snippet(m.text) }));
286
- return { start: seg.start, end: seg.end, t: Math.min(...c.matches.map((m) => m.t)), score: c.score, matches };
287
- });
288
- return { hits, total: matched.size };
289
- }
290
- export async function resolveRecording(args) {
291
- if ((args.input === undefined) === (args.sessionId === undefined)) {
292
- throw new ScreencastError("Provide exactly one of: input (a recording path) or sessionId.");
293
- }
294
- if (args.sessionId !== undefined) {
295
- const record = getStore().get(args.sessionId);
296
- if (!record)
297
- throw new ScreencastError(`No session with id "${args.sessionId}".`);
298
- if (record.status === "recording" || record.status === "paused")
299
- throw new ScreencastError("The recording is still running; stop_recording it first.");
300
- await whenFinalized(record.id);
301
- if (!existsSync(record.outputPath))
302
- throw new ScreencastError(`The session's recording is missing: ${record.outputPath}`);
303
- const events = record.events?.path;
304
- const markers = record.markers?.length ? record.markers : readMarkers(record.outputPath);
305
- return { path: record.outputPath, eventsPath: events && existsSync(events) ? events : null, markers };
306
- }
307
- const path = args.input;
308
- if (!existsSync(path))
309
- throw new ScreencastError(`Input file not found: ${path}`);
310
- const { jsonl } = eventPaths(path);
311
- return { path, eventsPath: existsSync(jsonl) ? jsonl : null, markers: readMarkers(path) };
312
- }
@@ -1,283 +0,0 @@
1
- import { createReadStream, createWriteStream, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
2
- import { stat, writeFile } from "node:fs/promises";
3
- import { pipeline } from "node:stream/promises";
4
- import { join } from "node:path";
5
- import { errorMessage, ScreencastError } from "./errors.js";
6
- import { runCapture } from "./ffmpeg.js";
7
- import { jobTimeoutMs } from "./jobs.js";
8
- import { buildConcatArgs, buildProbeArgs, concatListContent, parseMediaInfo } from "./media.js";
9
- import { homeRoot, rand, sequencePattern, stamp } from "./paths.js";
10
- import { resolveQuality } from "./targets.js";
11
- import { convertEvents, eventPaths, formatEventsJsonl, readRawEventLog, selectEvents, summarizeEvents, } from "./events.js";
12
- export const REPLAY_SEGMENT_SEC = 2;
13
- export const REPLAY_SLACK_SEGMENTS = 3;
14
- export const MIN_REPLAY_SEC = 4;
15
- export const MAX_REPLAY_SEC = 3600;
16
- const SEGMENT_PATTERN = "seg%05d.ts";
17
- const SEGMENT_NAME = /^seg(\d{5})\.ts$/;
18
- const LIST_NAME = "segments.csv";
19
- const DIR_NAME = /^buf-[\w-]+$/;
20
- export const REPLAY_EVENT_SLACK_SEC = 60;
21
- export function replayEventRotateSec(bufferSec) {
22
- return bufferSec + REPLAY_EVENT_SLACK_SEC;
23
- }
24
- export function replayRoot() {
25
- return join(homeRoot(), "replay");
26
- }
27
- export function replayWrap(bufferSec, segmentSec = REPLAY_SEGMENT_SEC) {
28
- return Math.ceil(bufferSec / segmentSec) + REPLAY_SLACK_SEGMENTS;
29
- }
30
- export function planReplayBuffer(bufferSec, segmentSec = REPLAY_SEGMENT_SEC) {
31
- if (!Number.isInteger(bufferSec) || bufferSec < MIN_REPLAY_SEC || bufferSec > MAX_REPLAY_SEC) {
32
- throw new ScreencastError(`replayBufferSec must be an integer from ${MIN_REPLAY_SEC} to ${MAX_REPLAY_SEC} seconds.`);
33
- }
34
- return {
35
- dir: join(replayRoot(), `buf-${stamp()}-${rand(6)}`),
36
- bufferSec,
37
- segmentSec,
38
- wrap: replayWrap(bufferSec, segmentSec),
39
- };
40
- }
41
- export function segmentListPath(dir) {
42
- return join(dir, LIST_NAME);
43
- }
44
- export function segmentOutputArgs(captureArgs, buf) {
45
- const args = captureArgs.slice(0, -1);
46
- const mov = args.indexOf("-movflags");
47
- if (mov >= 0)
48
- args.splice(mov, 2);
49
- return [
50
- ...args,
51
- "-force_key_frames", `expr:gte(t,n_forced*${buf.segmentSec})`,
52
- "-f", "segment",
53
- "-segment_time", String(buf.segmentSec),
54
- "-segment_wrap", String(buf.wrap),
55
- "-segment_list", segmentListPath(buf.dir),
56
- "-segment_list_type", "csv",
57
- "-segment_list_size", String(buf.wrap),
58
- "-segment_format", "mpegts",
59
- "-segment_format_options", "flush_packets=1",
60
- sequencePattern(buf.dir, SEGMENT_PATTERN),
61
- ];
62
- }
63
- export function parseSegmentList(csv) {
64
- const out = [];
65
- for (const line of csv.split(/\r?\n/)) {
66
- const [file = "", s, e] = line.trim().split(",");
67
- const m = SEGMENT_NAME.exec(file);
68
- const start = Number(s);
69
- const end = Number(e);
70
- if (!m || s === undefined || e === undefined || !Number.isFinite(start) || !Number.isFinite(end) || end < start)
71
- continue;
72
- out.push({ file, index: Number(m[1]), start, end });
73
- }
74
- return out.sort((a, b) => a.start - b.start);
75
- }
76
- export function pickSegments(entries, lastSec) {
77
- const picked = [];
78
- let covered = 0;
79
- for (let i = entries.length - 1; i >= 0 && covered < lastSec; i--) {
80
- const e = entries[i];
81
- picked.unshift(e);
82
- covered += e.end - e.start;
83
- }
84
- return picked;
85
- }
86
- export function liveSegmentFile(entries, wrap) {
87
- const last = entries.at(-1);
88
- const index = last ? (last.index + 1) % wrap : 0;
89
- return `seg${String(index).padStart(5, "0")}.ts`;
90
- }
91
- export function buildReplayCutArgs(input, output, opts) {
92
- const codec = opts.reencode
93
- ? [...resolveQuality(opts.quality ?? "standard"), ...(opts.audio ? ["-c:a", "aac", "-b:a", "160k"] : [])]
94
- : ["-c", "copy"];
95
- return [
96
- "-y", "-v", "error",
97
- "-ss", String(round3(Math.max(0, opts.startSec))),
98
- "-i", input,
99
- ...codec,
100
- "-movflags", "+faststart",
101
- output,
102
- ];
103
- }
104
- export function sliceEvents(events, from, to) {
105
- return selectEvents(events, { from, to }).map((e) => ({ ...e, t: round3(e.t - from) }));
106
- }
107
- const round3 = (n) => Math.round(n * 1000) / 1000;
108
- export async function copyShared(src, dst, signal) {
109
- const size = (await stat(src)).size;
110
- if (size === 0) {
111
- await writeFile(dst, "");
112
- return 0;
113
- }
114
- await pipeline(createReadStream(src, { start: 0, end: size - 1 }), createWriteStream(dst), { signal });
115
- return (await stat(dst)).size;
116
- }
117
- async function probeStart(ffprobe, path, signal) {
118
- const res = await runCapture(ffprobe, ["-v", "error", "-show_entries", "format=start_time", "-of", "csv=p=0", path], 15_000, { signal });
119
- const n = Number.parseFloat(res.stdout.trim());
120
- return res.code === 0 && Number.isFinite(n) ? n : null;
121
- }
122
- export async function saveReplay(buf, opts) {
123
- if (!existsSync(buf.dir)) {
124
- throw new ScreencastError("This replay buffer has been discarded: its segments are gone.");
125
- }
126
- const listPath = segmentListPath(buf.dir);
127
- const entries = existsSync(listPath) ? parseSegmentList(readFileSync(listPath, "utf8")) : [];
128
- const picked = pickSegments(entries, opts.lastSec);
129
- const snap = mkdtempSync(join(buf.dir, "save-"));
130
- try {
131
- const files = [];
132
- for (const [i, e] of picked.entries()) {
133
- const dst = join(snap, `${String(i).padStart(5, "0")}.ts`);
134
- await copyShared(join(buf.dir, e.file), dst, opts.signal);
135
- files.push(dst);
136
- }
137
- let includesLive = false;
138
- if (opts.live !== false) {
139
- const src = join(buf.dir, liveSegmentFile(entries, buf.wrap));
140
- const dst = join(snap, "live.ts");
141
- if (existsSync(src) && (await copyShared(src, dst, opts.signal)) > 0) {
142
- const newest = files.at(-1);
143
- const [liveStart, lastStart] = await Promise.all([
144
- probeStart(opts.ffprobe, dst, opts.signal),
145
- newest ? probeStart(opts.ffprobe, newest, opts.signal) : Promise.resolve(-Infinity),
146
- ]);
147
- if (liveStart !== null && lastStart !== null && liveStart > lastStart) {
148
- files.push(dst);
149
- includesLive = true;
150
- }
151
- }
152
- }
153
- if (files.length === 0) {
154
- throw new ScreencastError("The replay buffer has no footage yet: the first segment is still being written. Try again in a couple of seconds.");
155
- }
156
- const listFile = join(snap, "join.txt");
157
- writeFileSync(listFile, concatListContent(files));
158
- const joined = join(snap, "joined.mp4");
159
- const timeout = jobTimeoutMs(opts.lastSec + 2 * buf.segmentSec);
160
- const join1 = await runCapture(opts.ffmpeg, buildConcatArgs(listFile, joined, { quiet: true }), timeout, { signal: opts.signal });
161
- if (join1.code !== 0) {
162
- throw new ScreencastError(`Joining the replay segments failed:\n${join1.stderr.trim().split("\n").slice(-4).join("\n")}`);
163
- }
164
- const probe = await runCapture(opts.ffprobe, buildProbeArgs(joined), 30_000, { signal: opts.signal });
165
- const info = probe.code === 0 ? parseMediaInfo(JSON.parse(probe.stdout)) : null;
166
- const total = info?.durationSec ?? null;
167
- if (!total || !(total > 0))
168
- throw new ScreencastError("The joined replay has no duration; the segments may be damaged.");
169
- const startSec = Math.max(0, total - opts.lastSec);
170
- const cut = await runCapture(opts.ffmpeg, buildReplayCutArgs(joined, opts.output, {
171
- startSec,
172
- reencode: opts.reencode,
173
- quality: opts.quality,
174
- audio: !!info?.audioCodec,
175
- }), timeout, { signal: opts.signal });
176
- if (cut.code !== 0) {
177
- throw new ScreencastError(`Writing the replay failed:\n${cut.stderr.trim().split("\n").slice(-4).join("\n")}`);
178
- }
179
- const origin = picked[0]?.start ?? entries.at(-1)?.end ?? 0;
180
- const fromSec = round3(origin + startSec);
181
- const toSec = round3(origin + total);
182
- const result = {
183
- outputPath: opts.output,
184
- durationSec: round3(total - startSec),
185
- fromSec,
186
- toSec,
187
- segments: files.length,
188
- includesLive,
189
- };
190
- if (buf.events) {
191
- const sinceMs = buf.events.startMs + fromSec * 1000 - REPLAY_EVENT_SLACK_SEC * 1000;
192
- const raw = readRawEventLog(buf.events.raw, sinceMs);
193
- const events = sliceEvents(convertEvents(raw, { startMs: buf.events.startMs, frame: buf.events.frame }), fromSec, toSec);
194
- const { jsonl } = eventPaths(opts.output);
195
- writeFileSync(jsonl, formatEventsJsonl(events));
196
- result.eventsPath = jsonl;
197
- result.events = summarizeEvents(events);
198
- }
199
- return result;
200
- }
201
- finally {
202
- rmSync(snap, { recursive: true, force: true });
203
- }
204
- }
205
- export function prepareReplayDir(buf) {
206
- mkdirSync(buf.dir, { recursive: true });
207
- }
208
- export function resetReplaySegments(buf) {
209
- let names;
210
- try {
211
- names = readdirSync(buf.dir);
212
- }
213
- catch {
214
- return;
215
- }
216
- for (const name of names) {
217
- if (SEGMENT_NAME.test(name) || name === LIST_NAME)
218
- rmSync(join(buf.dir, name), { force: true });
219
- }
220
- }
221
- export function discardReplay(buf) {
222
- try {
223
- rmSync(buf.dir, { recursive: true, force: true });
224
- return !existsSync(buf.dir);
225
- }
226
- catch {
227
- return false;
228
- }
229
- }
230
- export function replayDiskBytes(buf) {
231
- let total = 0;
232
- try {
233
- for (const name of readdirSync(buf.dir)) {
234
- try {
235
- const st = statSync(join(buf.dir, name));
236
- if (st.isFile())
237
- total += st.size;
238
- }
239
- catch {
240
- }
241
- }
242
- }
243
- catch {
244
- }
245
- return total;
246
- }
247
- export function cleanupReplayDirs(keep, root = replayRoot()) {
248
- const keepSet = new Set([...keep].map((d) => d.toLowerCase()));
249
- let names;
250
- try {
251
- names = readdirSync(root);
252
- }
253
- catch {
254
- return 0;
255
- }
256
- let removed = 0;
257
- for (const name of names) {
258
- const dir = join(root, name);
259
- if (!DIR_NAME.test(name) || keepSet.has(dir.toLowerCase()))
260
- continue;
261
- try {
262
- rmSync(dir, { recursive: true, force: true });
263
- removed++;
264
- }
265
- catch {
266
- }
267
- }
268
- return removed;
269
- }
270
- export async function finishReplay(buf, opts) {
271
- if (!opts.save)
272
- return { saved: false, discarded: discardReplay(buf) };
273
- try {
274
- const tools = opts.tools?.();
275
- if (!tools)
276
- throw new ScreencastError("ffmpeg is not available to save the replay buffer.");
277
- const save = await saveReplay(buf, { ...tools, lastSec: buf.bufferSec, output: opts.output, quality: opts.quality, live: false });
278
- return { saved: true, discarded: discardReplay(buf), save };
279
- }
280
- catch (err) {
281
- return { saved: false, discarded: false, error: errorMessage(err) };
282
- }
283
- }
@@ -1,25 +0,0 @@
1
- import { parseTarget, validateRegionOnDesktop } from "./targets.js";
2
- import { getMonitors } from "./monitors.js";
3
- import { resolveWindowBounds } from "./windows.js";
4
- export async function resolveCaptureTarget(spec, opts = {}) {
5
- const parsed = parseTarget(spec);
6
- if (parsed.kind === "window") {
7
- const w = await resolveWindowBounds(parsed.title, {
8
- exactOnly: opts.exactTitle,
9
- allowCloaked: opts.backend === "wgc",
10
- });
11
- return {
12
- target: { kind: "region", x: w.x, y: w.y, w: w.width, h: w.height },
13
- monitors: [],
14
- window: w,
15
- };
16
- }
17
- if (parsed.kind === "monitor") {
18
- return { target: parsed, monitors: await getMonitors() };
19
- }
20
- if (parsed.kind === "region") {
21
- validateRegionOnDesktop(parsed, await getMonitors());
22
- return { target: parsed, monitors: [] };
23
- }
24
- return { target: parsed, monitors: await getMonitors() };
25
- }
@@ -1,48 +0,0 @@
1
- import { readdir, rmdir, stat, unlink } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import { homeRoot } from "./paths.js";
4
- export const RETENTION_ENV = "SCREENCAST_RETENTION_DAYS";
5
- export function retentionDays(env = process.env) {
6
- const n = Number(env[RETENTION_ENV]);
7
- return Number.isFinite(n) && n > 0 ? n : null;
8
- }
9
- const INDEX_FILE = /\.index\.json(\.\d+\.tmp)?$/;
10
- export async function pruneCaptures(days, now = Date.now(), root = homeRoot()) {
11
- const cutoff = now - days * 86_400_000;
12
- const result = { removed: 0, bytes: 0 };
13
- const prune = async (dir, keep, recurse) => {
14
- let names;
15
- try {
16
- names = await readdir(dir);
17
- }
18
- catch {
19
- return;
20
- }
21
- for (const name of names) {
22
- const path = join(dir, name);
23
- try {
24
- const st = await stat(path);
25
- if (st.isDirectory()) {
26
- if (!recurse)
27
- continue;
28
- await prune(path, keep, true);
29
- if ((await readdir(path)).length === 0 && st.mtimeMs < cutoff)
30
- await rmdir(path);
31
- }
32
- else if (!keep(name) && st.mtimeMs < cutoff) {
33
- await unlink(path);
34
- result.removed++;
35
- result.bytes += st.size;
36
- }
37
- }
38
- catch {
39
- }
40
- }
41
- };
42
- await prune(join(root, "screenshots"), () => false, true);
43
- await prune(join(root, "frames"), () => false, true);
44
- await prune(join(root, "recordings"), (name) => !/\.events\.raw(\.stop)?$/.test(name) && !INDEX_FILE.test(name), false);
45
- await prune(join(root, "edits"), (name) => !INDEX_FILE.test(name), false);
46
- await prune(join(root, "edits", "indexes"), (name) => !INDEX_FILE.test(name), false);
47
- return result;
48
- }