@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
package/dist/utils/gpu.js DELETED
@@ -1,219 +0,0 @@
1
- import { ScreencastError } from "./errors.js";
2
- import { runCapture } from "./ffmpeg.js";
3
- import { runPowerShell } from "./monitors.js";
4
- import { QUALITY_PRESETS, resolveQuality } from "./targets.js";
5
- export const HW_ENCODERS = ["nvenc", "qsv", "amf"];
6
- export const ENCODER_CODECS = {
7
- x264: "libx264",
8
- nvenc: "h264_nvenc",
9
- qsv: "h264_qsv",
10
- amf: "h264_amf",
11
- };
12
- export const HW_QUALITY = {
13
- nvenc: { draft: { preset: "p1", q: 30 }, standard: { preset: "p4", q: 25 }, high: { preset: "p6", q: 20 } },
14
- qsv: { draft: { preset: "veryfast", q: 30 }, standard: { preset: "medium", q: 25 }, high: { preset: "slower", q: 20 } },
15
- amf: { draft: { preset: "speed", q: 30 }, standard: { preset: "balanced", q: 25 }, high: { preset: "quality", q: 20 } },
16
- };
17
- export function encoderArgs(encoder, quality, opts = {}) {
18
- if (!QUALITY_PRESETS[quality])
19
- throw new ScreencastError(`Unknown quality preset "${quality}".`);
20
- if (encoder === "x264")
21
- return resolveQuality(quality);
22
- const { preset, q } = HW_QUALITY[encoder][quality];
23
- const codec = ["-c:v", ENCODER_CODECS[encoder]];
24
- const rate = encoder === "nvenc"
25
- ? ["-preset", preset, "-rc", "vbr", "-cq", String(q), "-b:v", "0"]
26
- : encoder === "qsv"
27
- ? ["-preset", preset, "-global_quality", String(q)]
28
- : ["-quality", preset, "-rc", "cqp", "-qp_i", String(q), "-qp_p", String(q)];
29
- return [...codec, ...rate, ...(opts.gpuFrames ? [] : ["-pix_fmt", "nv12"])];
30
- }
31
- export function buildEncoderProbeArgs(encoder) {
32
- return [
33
- "-hide_banner", "-v", "error",
34
- "-f", "lavfi", "-i", "color=c=black:s=256x256:r=30",
35
- "-frames:v", "3",
36
- ...encoderArgs(encoder, "draft"),
37
- "-f", "null", "-",
38
- ];
39
- }
40
- export function buildDdaProbeArgs(encoder) {
41
- return [
42
- "-hide_banner", "-v", "error",
43
- "-f", "lavfi", "-i", `ddagrab=framerate=10${encoder ? "" : ",hwdownload,format=bgra"}`,
44
- "-frames:v", "2",
45
- ...(encoder ? encoderArgs(encoder, "draft", { gpuFrames: true }) : []),
46
- "-f", "null", "-",
47
- ];
48
- }
49
- const PROBE_TIMEOUT_MS = 20_000;
50
- export function ffmpegRunner(ffmpeg) {
51
- return async (args) => {
52
- try {
53
- const res = await runCapture(ffmpeg, args, PROBE_TIMEOUT_MS, { closeStdin: true });
54
- return res.code === 0;
55
- }
56
- catch {
57
- return false;
58
- }
59
- };
60
- }
61
- const probes = new Map();
62
- function cachedProbe(ffmpeg, key, args, run) {
63
- const k = `${ffmpeg}\u0000${key}`;
64
- let p = probes.get(k);
65
- if (!p) {
66
- p = run(args);
67
- probes.set(k, p);
68
- }
69
- return p;
70
- }
71
- export function clearGpuProbeCache() {
72
- probes.clear();
73
- dxgiCache = null;
74
- }
75
- export async function probeHwEncoders(ffmpeg, run = ffmpegRunner(ffmpeg)) {
76
- const results = await Promise.all(HW_ENCODERS.map((e) => cachedProbe(ffmpeg, `enc:${e}`, buildEncoderProbeArgs(e), run)));
77
- return Object.fromEntries(HW_ENCODERS.map((e, i) => [e, results[i]]));
78
- }
79
- export 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) {
89
- if (choice === "x264")
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
- }
97
- const available = await probeHwEncoders(ffmpeg, run);
98
- const pick = choice === "auto" ? HW_ENCODERS.find((e) => available[e] && fits(e)) : available[choice] ? choice : undefined;
99
- if (!pick) {
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
- }
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.');
113
- }
114
- const gpuFrames = backend === "ddagrab" && (await cachedProbe(ffmpeg, `dda:${pick}`, buildDdaProbeArgs(pick), run));
115
- return { encoder: pick, gpuFrames };
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
- }
138
- export function ddagrabWorks(ffmpeg, run = ffmpegRunner(ffmpeg)) {
139
- return cachedProbe(ffmpeg, "dda", buildDdaProbeArgs(), run);
140
- }
141
- export function parseDxgiOutputs(stdout) {
142
- const out = [];
143
- for (const line of stdout.split(/\r?\n/)) {
144
- const parts = line.trim().split(",");
145
- if (parts.length < 7)
146
- continue;
147
- const n = parts.slice(0, 6).map(Number);
148
- if (n.some((v) => !Number.isInteger(v)))
149
- continue;
150
- const [adapter = 0, output = 0, x = 0, y = 0, w = 0, h = 0] = n;
151
- if (w <= 0 || h <= 0)
152
- continue;
153
- out.push({ adapter, output, x, y, w, h, name: parts.slice(6).join(",") });
154
- }
155
- return out;
156
- }
157
- const PS_DXGI = `
158
- Add-Type -TypeDefinition @"
159
- using System; using System.Runtime.InteropServices; using System.Text;
160
- public static class ScDxgi {
161
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
162
- public struct DESC { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string Name; public int L, T, R, B; public int Attached; public int Rot; public IntPtr Mon; }
163
- [ComImport, Guid("770aae78-f26f-4dba-a829-253c83d1b387"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
164
- interface IF1 { void a(); void b(); void c(); void d(); void e(); void f(); void g(); void h(); void i();
165
- [PreserveSig] int EnumAdapters1(uint i, [MarshalAs(UnmanagedType.Interface)] out IA1 a); }
166
- [ComImport, Guid("29038f61-3839-4626-91fd-086879011a05"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
167
- interface IA1 { void a(); void b(); void c(); void d();
168
- [PreserveSig] int EnumOutputs(uint i, [MarshalAs(UnmanagedType.Interface)] out IO o); }
169
- [ComImport, Guid("ae02eedb-c735-4690-8d52-5a8dc20213aa"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
170
- interface IO { void a(); void b(); void c(); void d(); [PreserveSig] int GetDesc(out DESC d); }
171
- [DllImport("dxgi.dll")] static extern int CreateDXGIFactory1(ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IF1 f);
172
- public static string List() {
173
- Guid g = new Guid("770aae78-f26f-4dba-a829-253c83d1b387"); IF1 f;
174
- if (CreateDXGIFactory1(ref g, out f) != 0) return "";
175
- StringBuilder sb = new StringBuilder(); IA1 a;
176
- for (uint ai = 0; f.EnumAdapters1(ai, out a) == 0; ai++) { IO o;
177
- for (uint oi = 0; a.EnumOutputs(oi, out o) == 0; oi++) { DESC d;
178
- if (o.GetDesc(out d) == 0) sb.AppendFormat("{0},{1},{2},{3},{4},{5},{6}\\n", ai, oi, d.L, d.T, d.R - d.L, d.B - d.T, d.Name); } }
179
- return sb.ToString(); } }
180
- "@
181
- [ScDxgi]::List()
182
- `;
183
- const DXGI_CACHE_MS = 5_000;
184
- let dxgiCache = null;
185
- export function getDxgiOutputs() {
186
- if (dxgiCache && Date.now() - dxgiCache.at < DXGI_CACHE_MS)
187
- return dxgiCache.outputs;
188
- const outputs = runPowerShell(PS_DXGI, "DXGI outputs").then(parseDxgiOutputs);
189
- dxgiCache = { at: Date.now(), outputs };
190
- outputs.catch(() => {
191
- dxgiCache = null;
192
- });
193
- return outputs;
194
- }
195
- const evenDown = (n) => n - (n % 2);
196
- export function planDdaSource(rect, outputs) {
197
- const holds = (o) => rect.x >= o.x && rect.y >= o.y && rect.x + rect.w <= o.x + o.w && rect.y + rect.h <= o.y + o.h;
198
- const host = outputs.find(holds);
199
- if (!host) {
200
- throw new ScreencastError(`backend "ddagrab" captures one display, and ${rect.x},${rect.y} ${rect.w}x${rect.h} is not inside a single one.`, 'Use a monitor:<i> target, a region inside one display, or backend "gdigrab".');
201
- }
202
- if (host.adapter !== 0) {
203
- throw new ScreencastError(`That display (${host.name || `adapter ${host.adapter} output ${host.output}`}) is driven by a second GPU, which ddagrab cannot reach.`, 'Use backend "gdigrab" for it.');
204
- }
205
- const w = evenDown(rect.w);
206
- const h = evenDown(rect.h);
207
- if (w <= 0 || h <= 0)
208
- throw new ScreencastError("The capture rectangle is too small to record (needs at least 2x2 px).");
209
- const whole = rect.x === host.x && rect.y === host.y && w === host.w && h === host.h;
210
- return whole ? { output: host.output } : { output: host.output, crop: { x: rect.x - host.x, y: rect.y - host.y, w, h } };
211
- }
212
- export function buildDdaInputArgs(src, fps, opts) {
213
- const crop = src.crop
214
- ? `:offset_x=${src.crop.x}:offset_y=${src.crop.y}:video_size=${src.crop.w}x${src.crop.h}`
215
- : "";
216
- const mouse = opts.drawMouse === false ? 0 : 1;
217
- const graph = `ddagrab=output_idx=${src.output}:framerate=${fps}:draw_mouse=${mouse}${crop}${opts.download ? ",hwdownload,format=bgra" : ""}`;
218
- return ["-f", "lavfi", "-i", graph];
219
- }
@@ -1,91 +0,0 @@
1
- import { ScreencastError } from "./errors.js";
2
- import { resolveQuality } from "./targets.js";
3
- import { sumExpr } from "./expr.js";
4
- export const DEFAULT_MIN_IDLE_SEC = 2;
5
- export const DEFAULT_KEEP_SEC = 0.4;
6
- export const MAX_CUTS = 200;
7
- export function buildIdleScanArgs(input, minIdleSec, withAudio) {
8
- if (!(minIdleSec > 0))
9
- throw new ScreencastError("minIdleSec must be positive.");
10
- return [
11
- "-hide_banner", "-nostats", "-v", "info", "-i", input,
12
- "-vf", `freezedetect=n=-60dB:d=${minIdleSec}`,
13
- ...(withAudio ? ["-af", `silencedetect=n=-40dB:d=${minIdleSec}`] : ["-an"]),
14
- "-f", "null", "-",
15
- ];
16
- }
17
- function pairs(stderr, startRe, endRe, duration) {
18
- const out = [];
19
- let open = null;
20
- for (const line of stderr.split(/\r?\n/)) {
21
- const s = line.match(startRe);
22
- if (s) {
23
- open = Number(s[1]);
24
- continue;
25
- }
26
- const e = line.match(endRe);
27
- if (e && open !== null) {
28
- out.push({ start: open, end: Number(e[1]) });
29
- open = null;
30
- }
31
- }
32
- if (open !== null && duration > open)
33
- out.push({ start: open, end: duration });
34
- return out;
35
- }
36
- export function parseFreezes(stderr, duration) {
37
- return pairs(stderr, /freeze_start:\s*([\d.]+)/, /freeze_end:\s*([\d.]+)/, duration);
38
- }
39
- export function parseSilences(stderr, duration) {
40
- return pairs(stderr, /silence_start:\s*([\d.]+)/, /silence_end:\s*([\d.]+)/, duration);
41
- }
42
- export function intersect(a, b) {
43
- const out = [];
44
- let i = 0;
45
- let j = 0;
46
- while (true) {
47
- const x = a[i];
48
- const y = b[j];
49
- if (!x || !y)
50
- break;
51
- const start = Math.max(x.start, y.start);
52
- const end = Math.min(x.end, y.end);
53
- if (end > start)
54
- out.push({ start, end });
55
- if (x.end < y.end)
56
- i++;
57
- else
58
- j++;
59
- }
60
- return out;
61
- }
62
- export function cutsFor(idle, minIdleSec, keep) {
63
- return idle
64
- .filter((r) => r.end - r.start >= minIdleSec)
65
- .map((r) => ({ start: r.start + keep, end: r.end - keep }))
66
- .filter((r) => r.end - r.start > 0.05)
67
- .map((r) => ({ start: Number(r.start.toFixed(3)), end: Number(r.end.toFixed(3)) }));
68
- }
69
- export function cutFilters(cuts) {
70
- if (cuts.length === 0)
71
- throw new ScreencastError("Nothing to cut.");
72
- if (cuts.length > MAX_CUTS)
73
- throw new ScreencastError(`Too many idle stretches (${cuts.length}); raise minIdleSec.`);
74
- const drop = sumExpr(cuts.map((c) => `between(t,${c.start},${c.end})`));
75
- const removed = sumExpr(cuts.map((c) => `clip(T-${c.start},0,${Number((c.end - c.start).toFixed(3))})`));
76
- return {
77
- video: `select='not(${drop})',setpts='(T-(${removed}))/TB'`,
78
- audio: `asetnsamples=n=256:p=0,aselect='not(${drop})',asetpts=N/SR/TB`,
79
- };
80
- }
81
- export function buildCutIdleArgs(input, output, cuts, withAudio, quality = "standard") {
82
- const f = cutFilters(cuts);
83
- return [
84
- "-y", "-i", input,
85
- "-vf", f.video,
86
- ...(withAudio ? ["-af", f.audio] : ["-an"]),
87
- ...resolveQuality(quality),
88
- ...(withAudio ? ["-c:a", "aac", "-b:a", "160k"] : []),
89
- output,
90
- ];
91
- }
@@ -1,38 +0,0 @@
1
- import { readFileSync, rmSync } from "node:fs";
2
- import { ScreencastError } from "./errors.js";
3
- import { runFfmpeg } from "./ffmpeg.js";
4
- import { tempPath, stillOutput } from "./paths.js";
5
- import { mapPool } from "./pool.js";
6
- export const DEFAULT_MAX_IMAGE_WIDTH = 1280;
7
- export const DEFAULT_MAX_INLINE_IMAGES = 8;
8
- export const MAX_INLINE_IMAGES = 20;
9
- export function buildPreviewArgs(input, output, maxWidth) {
10
- if (!Number.isInteger(maxWidth) || maxWidth < 16) {
11
- throw new ScreencastError("maxImageWidth must be an integer of at least 16.");
12
- }
13
- return [
14
- "-y", "-v", "error", "-i", input,
15
- "-frames:v", "1",
16
- "-vf", `scale='min(${maxWidth},iw)':-2`,
17
- "-q:v", "4",
18
- ...stillOutput(output),
19
- ];
20
- }
21
- export function clampInlineCount(requested) {
22
- const n = requested ?? DEFAULT_MAX_INLINE_IMAGES;
23
- return Math.max(0, Math.min(MAX_INLINE_IMAGES, Math.floor(n)));
24
- }
25
- export async function encodeInlineImages(paths, maxWidth = DEFAULT_MAX_IMAGE_WIDTH, maxCount = DEFAULT_MAX_INLINE_IMAGES) {
26
- const chosen = paths.slice(0, maxCount);
27
- const images = await mapPool(chosen, async (path) => {
28
- const tmp = tempPath(".jpg");
29
- try {
30
- await runFfmpeg(buildPreviewArgs(path, tmp, maxWidth), 30_000);
31
- return { type: "image", data: readFileSync(tmp).toString("base64"), mimeType: "image/jpeg" };
32
- }
33
- finally {
34
- rmSync(tmp, { force: true });
35
- }
36
- });
37
- return { images, omitted: paths.length - chosen.length };
38
- }
@@ -1,129 +0,0 @@
1
- import { basename, dirname, extname, join } from "node:path";
2
- import { renameSync, rmSync } from "node:fs";
3
- import { ScreencastError } from "./errors.js";
4
- import { runFfmpeg } from "./ffmpeg.js";
5
- export const JOB_TIMEOUT_ENV = "SCREENCAST_JOB_TIMEOUT_MS";
6
- export const BASE_TIMEOUT_MS = 10 * 60_000;
7
- export const UNKNOWN_DURATION_TIMEOUT_MS = 30 * 60_000;
8
- export const SECONDS_PER_MEDIA_SECOND = 4;
9
- export function jobTimeoutMs(durationSec, env = process.env) {
10
- const override = Number(env[JOB_TIMEOUT_ENV]);
11
- if (Number.isInteger(override) && override > 0)
12
- return override;
13
- if (durationSec == null || !(durationSec > 0))
14
- return UNKNOWN_DURATION_TIMEOUT_MS;
15
- return Math.max(BASE_TIMEOUT_MS, Math.ceil(durationSec * SECONDS_PER_MEDIA_SECOND * 1000));
16
- }
17
- export function partialPath(output) {
18
- const ext = extname(output);
19
- return join(dirname(output), `${basename(output, ext)}.partial${ext}`);
20
- }
21
- export function retargetOutput(args, output, partial) {
22
- const i = args.lastIndexOf(output);
23
- if (i === -1) {
24
- throw new ScreencastError(`Internal error: output path ${output} is not in the ffmpeg arguments.`);
25
- }
26
- const next = [...args];
27
- next[i] = partial;
28
- return next;
29
- }
30
- export function createProgressParser() {
31
- let buffer = "";
32
- let latest = null;
33
- return (chunk) => {
34
- buffer += chunk;
35
- const lines = buffer.split(/\r?\n/);
36
- buffer = lines.pop() ?? "";
37
- for (const line of lines) {
38
- const m = line.match(/^out_time_(?:us|ms)=(\d+)$/);
39
- if (m)
40
- latest = Number(m[1]) / 1_000_000;
41
- }
42
- return latest;
43
- };
44
- }
45
- export function progressReporter(extra) {
46
- const token = extra?._meta?.progressToken;
47
- if (token === undefined || !extra)
48
- return undefined;
49
- let lastPercent = -1;
50
- return (fraction) => {
51
- const percent = Math.floor(Math.max(0, Math.min(1, fraction)) * 100);
52
- if (percent <= lastPercent)
53
- return;
54
- lastPercent = percent;
55
- extra
56
- .sendNotification({
57
- method: "notifications/progress",
58
- params: { progressToken: token, progress: percent, total: 100 },
59
- })
60
- .catch(() => {
61
- });
62
- };
63
- }
64
- const activeJobs = new Set();
65
- let jobsClosed = false;
66
- export async function runEditJob(args, job) {
67
- if (jobsClosed)
68
- throw new ScreencastError("The server is shutting down; the edit was not started.");
69
- const partial = partialPath(job.output);
70
- const report = progressReporter(job.extra);
71
- const parse = createProgressParser();
72
- const duration = job.durationSec != null && job.durationSec > 0 ? job.durationSec : null;
73
- const input = job.inputDurationSec != null && job.inputDurationSec > 0 ? job.inputDurationSec : null;
74
- const decoded = input !== null && duration !== null ? Math.max(input, duration) : (input ?? duration);
75
- const ffArgs = ["-progress", "pipe:1", "-nostats", ...retargetOutput(args, job.output, partial)];
76
- const controller = new AbortController();
77
- const signal = job.extra?.signal ? AbortSignal.any([job.extra.signal, controller.signal]) : controller.signal;
78
- let finish;
79
- const active = { partial, controller, done: new Promise((r) => (finish = r)) };
80
- activeJobs.add(active);
81
- try {
82
- await runFfmpeg(ffArgs, jobTimeoutMs(decoded), {
83
- signal,
84
- onStdout: report && duration
85
- ? (chunk) => {
86
- const t = parse(chunk);
87
- if (t !== null)
88
- report(t / duration);
89
- }
90
- : undefined,
91
- });
92
- renameSync(partial, job.output);
93
- report?.(1);
94
- }
95
- catch (error) {
96
- rmSync(partial, { force: true });
97
- throw error;
98
- }
99
- finally {
100
- activeJobs.delete(active);
101
- finish();
102
- }
103
- }
104
- export function activeEditJobs() {
105
- return activeJobs.size;
106
- }
107
- export async function abortEditJobs(graceMs = 3_000) {
108
- jobsClosed = true;
109
- const jobs = [...activeJobs];
110
- if (jobs.length === 0)
111
- return 0;
112
- for (const job of jobs)
113
- job.controller.abort();
114
- let timer;
115
- await Promise.race([
116
- Promise.all(jobs.map((j) => j.done)),
117
- new Promise((r) => (timer = setTimeout(r, graceMs))),
118
- ]);
119
- clearTimeout(timer);
120
- for (const job of jobs) {
121
- try {
122
- rmSync(job.partial, { force: true });
123
- }
124
- catch {
125
- }
126
- }
127
- return jobs.length;
128
- }
129
- export { probeDuration } from "./ffmpeg.js";
@@ -1,155 +0,0 @@
1
- import { ScreencastError } from "./errors.js";
2
- import { escapeFilterPath } from "./fonts.js";
3
- import { sumExpr } from "./expr.js";
4
- import { resolveQuality } from "./targets.js";
5
- import { validateColor } from "./validate.js";
6
- import { mapWindow } from "./timeline.js";
7
- export const BADGE_POSITIONS = ["bottom", "bottom-left", "bottom-right", "top", "top-left", "top-right"];
8
- export const DEFAULT_LINGER_SEC = 1.2;
9
- export const DOUBLE_CLICK_SEC = 0.5;
10
- const DOUBLE_CLICK_PX = 8;
11
- export const MAX_BADGE_LABELS = 100;
12
- export const TYPING_LABEL = "Typing…";
13
- const MODIFIERS = new Set(["Ctrl", "Alt", "Shift", "Win"]);
14
- const KEY_NAME = /^(?:[A-Z0-9]|F\d{1,2}|Enter|Tab|Esc|Space|Backspace|Delete|Insert|Left|Up|Right|Down|Home|End|PageUp|PageDown|[=\-,./`[\];'\\])$/;
15
- export function formatChord(keys, display = "shortcuts") {
16
- const parts = keys.split("+");
17
- const key = parts.pop();
18
- if (key === undefined || parts.length === 0 || !KEY_NAME.test(key))
19
- return null;
20
- if (!parts.every((p) => MODIFIERS.has(p)) || new Set(parts).size !== parts.length)
21
- return null;
22
- return [...parts, display === "masked" ? "…" : key].join(" + ");
23
- }
24
- const BUTTON_LABEL = {
25
- left: "Click",
26
- right: "Right click",
27
- middle: "Middle click",
28
- x1: "Back button",
29
- x2: "Forward button",
30
- };
31
- const r3 = (n) => Math.round(n * 1000) / 1000;
32
- export function planBadges(events, opts = {}) {
33
- const linger = opts.lingerSec ?? DEFAULT_LINGER_SEC;
34
- if (!(linger > 0))
35
- throw new ScreencastError("lingerSec must be positive.");
36
- const display = opts.keys ?? "shortcuts";
37
- const sorted = [...events].filter((e) => Number.isFinite(e.t) && e.t >= 0).sort((a, b) => a.t - b.t);
38
- const raw = [];
39
- for (const e of sorted) {
40
- if (e.type === "key" && e.keys) {
41
- const label = formatChord(e.keys, display);
42
- if (!label)
43
- continue;
44
- const prev = raw.at(-1);
45
- if (prev && prev.kind === "shortcut" && prev.base === label && e.t - prev.last <= linger) {
46
- prev.count++;
47
- prev.last = e.t;
48
- prev.label = `${label} ×${prev.count}`;
49
- prev.to = e.t + linger;
50
- continue;
51
- }
52
- raw.push({ from: e.t, to: e.t + linger, label, base: label, kind: "shortcut", count: 1, last: e.t });
53
- }
54
- else if (e.type === "down" && opts.clicks !== false && e.inFrame) {
55
- const base = BUTTON_LABEL[e.button ?? "left"] ?? "Click";
56
- const prev = raw.at(-1);
57
- if (base === "Click" && prev && prev.kind === "click" && prev.base === "Click" && prev.count < 3 &&
58
- e.t - prev.last <= DOUBLE_CLICK_SEC &&
59
- Math.abs(e.x - (prev.x ?? e.x)) <= DOUBLE_CLICK_PX && Math.abs(e.y - (prev.y ?? e.y)) <= DOUBLE_CLICK_PX) {
60
- prev.count++;
61
- prev.last = e.t;
62
- prev.label = prev.count === 2 ? "Double click" : "Triple click";
63
- prev.to = e.t + linger;
64
- continue;
65
- }
66
- raw.push({ from: e.t, to: e.t + linger, label: base, base, kind: "click", count: 1, x: e.x, y: e.y, last: e.t });
67
- }
68
- else if (e.type === "typing" && opts.typing !== false) {
69
- const end = e.t + Math.max(e.durationSec ?? 0, 0);
70
- const prev = raw.at(-1);
71
- if (prev && prev.kind === "typing" && e.t <= prev.to) {
72
- prev.to = Math.max(prev.to, end + linger / 2);
73
- prev.last = e.t;
74
- continue;
75
- }
76
- raw.push({ from: e.t, to: end + linger / 2, label: TYPING_LABEL, base: TYPING_LABEL, kind: "typing", count: 1, last: e.t });
77
- }
78
- }
79
- const out = [];
80
- raw.forEach((b, i) => {
81
- const next = raw[i + 1];
82
- const to = next ? Math.min(b.to, next.from) : b.to;
83
- if (to - b.from >= 0.05)
84
- out.push({ from: r3(b.from), to: r3(to), label: b.label, kind: b.kind });
85
- });
86
- return out;
87
- }
88
- export function groupBadges(badges) {
89
- const groups = new Map();
90
- for (const b of badges) {
91
- let g = groups.get(b.label);
92
- if (!g) {
93
- g = { label: b.label, windows: [] };
94
- groups.set(b.label, g);
95
- }
96
- g.windows.push([b.from, b.to]);
97
- }
98
- if (groups.size > MAX_BADGE_LABELS) {
99
- throw new ScreencastError(`${groups.size} different badges is more than ${MAX_BADGE_LABELS}; trim the video or turn off keys or clicks.`);
100
- }
101
- return [...groups.values()];
102
- }
103
- export function mapBadges(badges, map) {
104
- return badges.flatMap((b) => {
105
- const w = map(b.from, b.to);
106
- return w && w[1] - w[0] >= 0.05 ? [{ ...b, from: r3(w[0]), to: r3(w[1]) }] : [];
107
- });
108
- }
109
- export function retimeBadges(badges, ops) {
110
- return mapBadges(badges, (from, to) => mapWindow(from, to, ops));
111
- }
112
- export function badgeSize(frameH, size) {
113
- if (size !== undefined) {
114
- if (!(size >= 8 && size <= 400))
115
- throw new ScreencastError("size must be between 8 and 400.");
116
- return Math.round(size);
117
- }
118
- return Math.max(14, Math.round(frameH * 0.045));
119
- }
120
- export function keystrokeSteps(groups, assets, style, frame, input, tag) {
121
- if (groups.length === 0)
122
- throw new ScreencastError("No badges to draw.");
123
- const size = badgeSize(frame.height, style.size);
124
- const border = Math.round(size / 3);
125
- const margin = border + Math.round(size * 0.6);
126
- const pos = style.position ?? "bottom";
127
- const x = pos.endsWith("left") ? `${margin}` : pos.endsWith("right") ? `w-tw-${margin}` : "(w-tw)/2";
128
- const y = pos.startsWith("top") ? `${margin}` : `h-lh-${margin}`;
129
- const color = validateColor(style.color ?? "white");
130
- const steps = [];
131
- let cur = input;
132
- groups.forEach((g, i) => {
133
- const file = assets.textFiles[g.label];
134
- if (!file)
135
- throw new ScreencastError(`Internal: no text file for badge "${g.label}".`);
136
- const enable = sumExpr(g.windows.map(([a, b]) => `between(t,${a},${b})`));
137
- const out = `[${tag}k${i}]`;
138
- steps.push(`${cur}drawtext=fontfile=${escapeFilterPath(assets.fontFile)}:textfile=${escapeFilterPath(file)}:expansion=none` +
139
- `:fontsize=${size}:fontcolor=${color}:box=1:boxcolor=black@0.6:boxborderw=${border}` +
140
- `:x=${x}:y=${y}:enable='${enable}'${out}`);
141
- cur = out;
142
- });
143
- return { steps, out: cur };
144
- }
145
- export function buildKeystrokeArgs(input, output, groups, assets, style, frame, quality = "standard") {
146
- const { steps, out } = keystrokeSteps(groups, assets, style, frame, "[0:v]", "");
147
- return [
148
- "-y", "-i", input,
149
- "-filter_complex", steps.join(";"),
150
- "-map", out, "-map", "0:a?",
151
- ...resolveQuality(quality),
152
- "-c:a", "copy",
153
- output,
154
- ];
155
- }