@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,124 +0,0 @@
1
- import { execFile } from "node:child_process";
2
- import { randomBytes } from "node:crypto";
3
- import { rmSync, writeFileSync } from "node:fs";
4
- import { tmpdir } from "node:os";
5
- import { join } from "node:path";
6
- import { errorMessage, ScreencastError } from "./errors.js";
7
- export function parseMonitors(raw) {
8
- const arr = Array.isArray(raw) ? raw : raw ? [raw] : [];
9
- const screens = arr.map((s) => ({
10
- x: Number(s.X ?? 0),
11
- y: Number(s.Y ?? 0),
12
- width: Number(s.Width ?? 0),
13
- height: Number(s.Height ?? 0),
14
- primary: Boolean(s.Primary),
15
- ...(Number(s.Dpi) > 0 ? { dpi: Number(s.Dpi) } : {}),
16
- }));
17
- screens.sort((a, b) => {
18
- if (a.primary !== b.primary)
19
- return a.primary ? -1 : 1;
20
- if (a.x !== b.x)
21
- return a.x - b.x;
22
- return a.y - b.y;
23
- });
24
- return screens.map((s, index) => ({ index, ...s }));
25
- }
26
- const PS_SCRIPT = `
27
- Add-Type @"
28
- using System;using System.Runtime.InteropServices;
29
- public class DpiShim{ [DllImport("user32.dll")] public static extern IntPtr SetProcessDpiAwarenessContext(IntPtr v);
30
- public struct PT{public int X,Y;}
31
- [DllImport("user32.dll")] public static extern IntPtr MonitorFromPoint(PT p,uint f);
32
- [DllImport("shcore.dll")] public static extern int GetDpiForMonitor(IntPtr m,int t,out uint x,out uint y);
33
- public static int Dpi(int x,int y){try{PT p=new PT();p.X=x;p.Y=y;uint dx,dy;if(GetDpiForMonitor(MonitorFromPoint(p,2),0,out dx,out dy)==0)return (int)dx;}catch{}return 0;} }
34
- "@
35
- try{[void][DpiShim]::SetProcessDpiAwarenessContext([IntPtr](-4))}catch{}
36
- Add-Type -AssemblyName System.Windows.Forms
37
- [System.Windows.Forms.Screen]::AllScreens | ForEach-Object {
38
- [pscustomobject]@{ X=$_.Bounds.X; Y=$_.Bounds.Y; Width=$_.Bounds.Width; Height=$_.Bounds.Height; Primary=$_.Primary; Dpi=[DpiShim]::Dpi($_.Bounds.X,$_.Bounds.Y) }
39
- } | ConvertTo-Json -Compress
40
- `;
41
- export const MONITOR_CACHE_MS = 5_000;
42
- let cache = null;
43
- export const PS_UTF8_PREAMBLE = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8\n";
44
- export const PS_TIMEOUT_MS = 20_000;
45
- export const PS_TIMEOUT_ENV = "SCREENCAST_PS_TIMEOUT_MS";
46
- export function psTimeoutMs(fallback, env = process.env) {
47
- const override = Number(env[PS_TIMEOUT_ENV]);
48
- return Number.isInteger(override) && override > 0 ? override : fallback;
49
- }
50
- export const MAX_COMMAND_LINE_CHARS = 32_767;
51
- export function payloadPreamble(path) {
52
- const b64 = Buffer.from(path, "utf8").toString("base64");
53
- return `$Payload = [IO.File]::ReadAllText([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64}')), [Text.Encoding]::UTF8)\n`;
54
- }
55
- export function powerShellArgs(script, payloadPath) {
56
- const full = PS_UTF8_PREAMBLE + (payloadPath === undefined ? "" : payloadPreamble(payloadPath)) + script;
57
- return ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(full, "utf16le").toString("base64")];
58
- }
59
- export function commandLineLength(file, args) {
60
- return [file, ...args].reduce((n, a) => n + a.length + 3, 0);
61
- }
62
- export async function withPayloadFile(payload, fn) {
63
- const path = join(tmpdir(), `screencast-ps-${process.pid}-${randomBytes(6).toString("hex")}.json`);
64
- writeFileSync(path, payload, { encoding: "utf8", mode: 0o600 });
65
- try {
66
- return await fn(path);
67
- }
68
- finally {
69
- rmSync(path, { force: true });
70
- }
71
- }
72
- export function runPowerShell(script, what, opts = {}) {
73
- if (opts.payload === undefined)
74
- return execPowerShell(script, what, opts);
75
- return withPayloadFile(opts.payload, (path) => execPowerShell(script, what, opts, path));
76
- }
77
- function execPowerShell(script, what, opts, payloadPath) {
78
- const timeout = opts.timeoutMs ?? psTimeoutMs(PS_TIMEOUT_MS);
79
- const file = opts.command?.file ?? "powershell";
80
- const args = opts.command?.args ?? powerShellArgs(script, payloadPath);
81
- return new Promise((resolve, reject) => {
82
- execFile(file, args, { encoding: "utf8", windowsHide: true, maxBuffer: 8 * 1024 * 1024, timeout, killSignal: "SIGKILL", signal: opts.signal }, (err, stdout, stderr) => {
83
- if (opts.signal?.aborted) {
84
- reject(new ScreencastError(`Cancelled while reading ${what}.`));
85
- }
86
- else if (err && err.killed) {
87
- reject(new ScreencastError(`Timed out reading ${what} after ${timeout / 1000} s (PowerShell did not answer).`, `Retry; if it keeps happening, restart the app being captured or raise ${PS_TIMEOUT_ENV}.`));
88
- }
89
- else if (err || !stdout) {
90
- const label = opts.failure ?? `Could not enumerate ${what}`;
91
- reject(new ScreencastError(`${label}: ${stderr?.trim() || err?.message || "powershell failed"}`));
92
- }
93
- else {
94
- resolve(stdout);
95
- }
96
- });
97
- });
98
- }
99
- async function queryMonitors() {
100
- const stdout = await runPowerShell(PS_SCRIPT, "monitors");
101
- try {
102
- return parseMonitors(JSON.parse(stdout));
103
- }
104
- catch (err) {
105
- throw new ScreencastError(`Could not parse monitor geometry: ${errorMessage(err)}`);
106
- }
107
- }
108
- export function getMonitors(now = Date.now()) {
109
- if (process.platform !== "win32") {
110
- return Promise.reject(new ScreencastError("Monitor enumeration is implemented for Windows (gdigrab) only."));
111
- }
112
- if (cache && now - cache.at < MONITOR_CACHE_MS)
113
- return cache.monitors;
114
- const entry = { at: now, monitors: queryMonitors() };
115
- cache = entry;
116
- entry.monitors.catch(() => {
117
- if (cache === entry)
118
- cache = null;
119
- });
120
- return entry.monitors;
121
- }
122
- export function clearMonitorCache() {
123
- cache = null;
124
- }
@@ -1,233 +0,0 @@
1
- import { errorMessage, ScreencastError } from "./errors.js";
2
- import { runPowerShell, psTimeoutMs } from "./monitors.js";
3
- import { audioCodecFor } from "./audio.js";
4
- import { isAudioOnlyPath } from "./media.js";
5
- export const MAX_LINES = 200;
6
- export const MAX_LINE_CHARS = 1_000;
7
- export const MIN_RATE = 0.5;
8
- export const MAX_RATE = 3;
9
- const r3 = (v) => Math.round(v * 1000) / 1000;
10
- export function resolveLines(lines, markers) {
11
- if (lines.length === 0)
12
- throw new ScreencastError("lines is empty: give at least one { t | marker, text }.");
13
- if (lines.length > MAX_LINES)
14
- throw new ScreencastError(`At most ${MAX_LINES} lines are allowed (got ${lines.length}).`);
15
- const out = lines.map((line, i) => {
16
- const text = line.text.replace(/\s+/g, " ").trim();
17
- if (!text)
18
- throw new ScreencastError(`lines[${i}] has no text.`);
19
- if (text.length > MAX_LINE_CHARS) {
20
- throw new ScreencastError(`lines[${i}] is ${text.length} characters; at most ${MAX_LINE_CHARS} are allowed. Split it.`);
21
- }
22
- if (line.t !== undefined && line.marker !== undefined) {
23
- throw new ScreencastError(`lines[${i}] has both t and marker; give one.`);
24
- }
25
- if (line.t !== undefined) {
26
- if (!Number.isFinite(line.t) || line.t < 0)
27
- throw new ScreencastError(`lines[${i}].t must be a non-negative number.`);
28
- return { t: r3(line.t), text };
29
- }
30
- if (line.marker !== undefined) {
31
- const want = line.marker.trim().toLowerCase();
32
- const m = markers.find((k) => k.label.trim().toLowerCase() === want);
33
- if (!m) {
34
- const known = markers.map((k) => `"${k.label}"`).join(", ");
35
- throw new ScreencastError(`lines[${i}]: no marker labelled "${line.marker}".`, known ? `Markers on this video: ${known}.` : "This video has no markers; add_marker stamps one, or give t.");
36
- }
37
- return { t: r3(m.t), text };
38
- }
39
- throw new ScreencastError(`lines[${i}] needs t (seconds) or marker (a marker label).`);
40
- });
41
- return out.sort((a, b) => a.t - b.t);
42
- }
43
- export function placementWarnings(placed, videoDurationSec) {
44
- const warnings = [];
45
- placed.forEach((p, i) => {
46
- const end = p.t + p.durationSec;
47
- const next = placed[i + 1];
48
- const quote = `"${p.text.length > 40 ? `${p.text.slice(0, 40)}...` : p.text}"`;
49
- if (p.t >= videoDurationSec) {
50
- warnings.push(`Line at ${p.t}s ${quote} starts after the video ends (${r3(videoDurationSec)}s) and is not heard.`);
51
- }
52
- else if (next && end > next.t + 0.05) {
53
- warnings.push(`Line at ${p.t}s ${quote} runs ${r3(end - next.t)}s past the next line (${next.t}s); they overlap. Move the next line, shorten this one, or raise rate.`);
54
- }
55
- else if (end > videoDurationSec + 0.05) {
56
- warnings.push(`Line at ${p.t}s ${quote} runs ${r3(end - videoDurationSec)}s past the end of the video and is cut off.`);
57
- }
58
- });
59
- return warnings;
60
- }
61
- export function narrationCues(placed, videoDurationSec) {
62
- return placed
63
- .map((p, i) => {
64
- const next = placed[i + 1];
65
- const end = Math.min(p.t + p.durationSec, next ? next.t : Infinity, videoDurationSec);
66
- return { start: p.t, end: r3(end), text: p.text };
67
- })
68
- .filter((c) => c.end > c.start);
69
- }
70
- export function wavDurationSec(buf) {
71
- if (buf.length < 12 || buf.toString("ascii", 0, 4) !== "RIFF" || buf.toString("ascii", 8, 12) !== "WAVE") {
72
- throw new ScreencastError("The speech engine did not return a WAV file.");
73
- }
74
- let byteRate = 0;
75
- for (let off = 12; off + 8 <= buf.length;) {
76
- const id = buf.toString("ascii", off, off + 4);
77
- const size = buf.readUInt32LE(off + 4);
78
- if (id === "fmt " && off + 16 <= buf.length)
79
- byteRate = buf.readUInt32LE(off + 16);
80
- if (id === "data") {
81
- if (byteRate <= 0)
82
- break;
83
- const available = buf.length - (off + 8);
84
- const bytes = size === 0 || size === 0xffffffff || size > available ? available : size;
85
- return bytes / byteRate;
86
- }
87
- off += 8 + size + (size % 2);
88
- }
89
- throw new ScreencastError("Could not read the WAV header the speech engine wrote.");
90
- }
91
- export function buildNarrateArgs(video, wavs, output, placed, videoDurationSec, opts) {
92
- if (!Number.isFinite(videoDurationSec) || videoDurationSec <= 0) {
93
- throw new ScreencastError("video duration must be known and positive.");
94
- }
95
- if (wavs.length === 0 || wavs.length !== placed.length) {
96
- throw new ScreencastError("Every placed line needs its WAV.");
97
- }
98
- const D = r3(videoDurationSec);
99
- const mix = (n) => `amix=inputs=${n}:duration=longest:dropout_transition=0:normalize=0`;
100
- const parts = placed.map((p, i) => {
101
- const ms = Math.round(p.t * 1000);
102
- return `[${i + 1}:a]aresample=48000,aformat=channel_layouts=mono,adelay=${ms}[l${i}]`;
103
- });
104
- const lines = placed.map((_, i) => `[l${i}]`).join("");
105
- const stereo = !(opts.hasAudio && opts.channels === 1);
106
- const bus = `apad,atrim=end=${D}${stereo ? ",pan=stereo|c0=c0|c1=c0" : ""}`;
107
- const voice = opts.hasAudio ? "voice" : "aout";
108
- parts.push(placed.length > 1 ? `${lines}${mix(placed.length)},${bus}[${voice}]` : `[l0]${bus}[${voice}]`);
109
- if (opts.hasAudio) {
110
- parts.push(`[0:a]aresample=48000,aformat=channel_layouts=${stereo ? "stereo" : "mono"}[orig]`);
111
- if (opts.duck ?? true) {
112
- parts.push("[voice]asplit=2[vo][key]");
113
- parts.push("[orig][key]sidechaincompress=threshold=0.02:ratio=8:attack=20:release=400[bed]");
114
- parts.push(`[bed][vo]${mix(2)}[aout]`);
115
- }
116
- else {
117
- parts.push(`[orig][voice]${mix(2)}[aout]`);
118
- }
119
- }
120
- const audioOnly = isAudioOnlyPath(output);
121
- return [
122
- "-y",
123
- "-i", video,
124
- ...wavs.flatMap((w) => ["-i", w]),
125
- "-filter_complex", parts.join(";"),
126
- ...(audioOnly ? [] : ["-map", "0:v?", "-c:v", "copy"]),
127
- "-map", "[aout]",
128
- "-t", String(D),
129
- ...audioCodecFor(output),
130
- ...(/\.(mp4|mov|m4a)$/i.test(output) ? ["-movflags", "+faststart"] : []),
131
- output,
132
- ];
133
- }
134
- export const TTS_TIMEOUT_MS = 30_000;
135
- export const TTS_PER_LINE_MS = 10_000;
136
- export const TTS_STEP_TIMEOUT_MS = 30_000;
137
- const asArray = (v) => (Array.isArray(v) ? v : v === undefined || v === null ? [] : [v]);
138
- export function parseVoices(raw) {
139
- return asArray(raw.voices).map((v) => ({ name: String(v.name ?? ""), language: String(v.language ?? ""), gender: String(v.gender ?? "") }));
140
- }
141
- export function ttsCall(request) {
142
- return { script: PS_TTS, payload: JSON.stringify(request) };
143
- }
144
- async function runTts(request, timeoutMs, signal) {
145
- if (process.platform !== "win32") {
146
- throw new ScreencastError("narrate uses the speech engine built into Windows and runs on Windows only.");
147
- }
148
- const { script, payload } = ttsCall(request);
149
- const list = "list" in request;
150
- const stdout = await runPowerShell(script, list ? "speech voices" : "the speech engine", {
151
- timeoutMs,
152
- signal,
153
- payload,
154
- failure: list ? "Could not list speech voices" : "Could not synthesize speech",
155
- });
156
- try {
157
- return JSON.parse(stdout);
158
- }
159
- catch (err) {
160
- throw new ScreencastError(`Could not parse the speech engine's output: ${errorMessage(err)}`);
161
- }
162
- }
163
- export async function listVoices(signal) {
164
- const raw = await runTts({ list: true }, psTimeoutMs(15_000), signal);
165
- if (raw.error)
166
- throw new ScreencastError(`Windows speech is unavailable: ${raw.error}`);
167
- return parseVoices(raw);
168
- }
169
- export async function ttsStatus() {
170
- if (process.platform !== "win32")
171
- return { available: false, voices: [], error: "Windows speech is available on Windows only." };
172
- try {
173
- const voices = (await listVoices()).map((v) => `${v.name} (${v.language})`);
174
- return { available: voices.length > 0, voices, ...(voices.length ? {} : { error: "No speech voices are installed." }) };
175
- }
176
- catch (err) {
177
- return { available: false, voices: [], error: errorMessage(err) };
178
- }
179
- }
180
- export async function synthesize(items, opts) {
181
- const rate = opts.rate ?? 1;
182
- if (!Number.isFinite(rate) || rate < MIN_RATE || rate > MAX_RATE) {
183
- throw new ScreencastError(`rate must be between ${MIN_RATE} and ${MAX_RATE} (1 is normal speed).`);
184
- }
185
- const raw = await runTts({ voice: opts.voice ?? null, rate, items }, psTimeoutMs(TTS_TIMEOUT_MS + items.length * TTS_PER_LINE_MS), opts.signal);
186
- if (raw.error) {
187
- const voices = parseVoices(raw);
188
- if (raw.error === "unknown voice") {
189
- throw new ScreencastError(`No installed voice matches "${opts.voice}".`, voices.length ? `Installed voices: ${voices.map((v) => `${v.name} (${v.language})`).join(", ")}.` : "No voices are installed.");
190
- }
191
- throw new ScreencastError(`Windows speech is unavailable: ${raw.error}`, "Install a voice: Settings > Time & language > Speech > Manage voices.");
192
- }
193
- asArray(raw.results).forEach((r, i) => {
194
- if (r.error)
195
- throw new ScreencastError(`Could not synthesize line ${i + 1}: ${r.error}`);
196
- });
197
- return String(raw.voice ?? "");
198
- }
199
- const PS_TTS = `
200
- $ErrorActionPreference = 'Stop'
201
- function Out($o) { ConvertTo-Json -InputObject $o -Depth 5 -Compress }
202
- try {
203
- Add-Type -AssemblyName System.Runtime.WindowsRuntime
204
- $null = [Windows.Media.SpeechSynthesis.SpeechSynthesizer, Windows.Media, ContentType = WindowsRuntime]
205
- $req = $Payload | ConvertFrom-Json
206
- $all = @([Windows.Media.SpeechSynthesis.SpeechSynthesizer]::AllVoices)
207
- $voices = @($all | ForEach-Object { [pscustomobject]@{ name = $_.DisplayName; language = $_.Language; gender = [string]$_.Gender } })
208
- if ($req.list) { Out ([pscustomobject]@{ voices = $voices }); return }
209
- if ($all.Count -eq 0) { Out ([pscustomobject]@{ error = 'No speech voices are installed.'; voices = $voices }); return }
210
- $synth = New-Object Windows.Media.SpeechSynthesis.SpeechSynthesizer
211
- if ($req.voice) {
212
- $want = [string]$req.voice
213
- $v = $all | Where-Object { $_.DisplayName -eq $want -or $_.Id -eq $want } | Select-Object -First 1
214
- if (-not $v) { $v = $all | Where-Object { $_.DisplayName.IndexOf($want, [StringComparison]::OrdinalIgnoreCase) -ge 0 } | Select-Object -First 1 }
215
- if (-not $v) { Out ([pscustomobject]@{ error = 'unknown voice'; voices = $voices }); return }
216
- $synth.Voice = $v
217
- }
218
- $synth.Options.SpeakingRate = [double]$req.rate
219
- $asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation\`1' })[0]
220
- $results = foreach ($item in @($req.items)) {
221
- try {
222
- $task = $asTask.MakeGenericMethod([Windows.Media.SpeechSynthesis.SpeechSynthesisStream]).Invoke($null, @($synth.SynthesizeTextToStreamAsync([string]$item.text)))
223
- if (-not $task.Wait(${TTS_STEP_TIMEOUT_MS})) { throw "The speech engine did not answer within ${TTS_STEP_TIMEOUT_MS / 1000} s." }
224
- $stream = $task.Result
225
- $in = [System.IO.WindowsRuntimeStreamExtensions]::AsStreamForRead($stream)
226
- $fs = [System.IO.File]::Create([string]$item.path)
227
- try { $in.CopyTo($fs) } finally { $fs.Dispose(); $in.Dispose(); $stream.Dispose() }
228
- [pscustomobject]@{ ok = $true }
229
- } catch { [pscustomobject]@{ error = $_.Exception.Message } }
230
- }
231
- Out ([pscustomobject]@{ voice = $synth.Voice.DisplayName; results = @($results) })
232
- } catch { Out ([pscustomobject]@{ error = $_.Exception.Message }) }
233
- `;
package/dist/utils/ocr.js DELETED
@@ -1,222 +0,0 @@
1
- import { runInNewContext } from "node:vm";
2
- import { errorMessage, ScreencastError } from "./errors.js";
3
- import { runPowerShell, psTimeoutMs } from "./monitors.js";
4
- export const OCR_SCALES = [2, 4];
5
- export const OCR_MAX_DIMENSION = 10_000;
6
- export function ocrCall(paths) {
7
- return { script: PS_OCR, payload: JSON.stringify(paths) };
8
- }
9
- export async function recognize(paths, scales) {
10
- if (process.platform !== "win32") {
11
- throw new ScreencastError("find_text uses the Windows OCR engine and runs on Windows only.");
12
- }
13
- const { script, payload } = ocrCall(paths);
14
- const stdout = await runPowerShell(script, "text (OCR)", {
15
- timeoutMs: psTimeoutMs(OCR_TIMEOUT_MS + Math.max(0, paths.length - 2) * OCR_PER_IMAGE_MS),
16
- payload,
17
- failure: "Could not run OCR",
18
- });
19
- let raw;
20
- try {
21
- raw = JSON.parse(stdout);
22
- }
23
- catch (err) {
24
- throw new ScreencastError(`Could not parse OCR output: ${errorMessage(err)}`);
25
- }
26
- const passes = Array.isArray(raw) ? raw : [raw];
27
- return passes.map((p, i) => parseOcrPass(p, scales[i] ?? 1));
28
- }
29
- export function parseOcrPass(raw, scale) {
30
- const pass = (raw ?? {});
31
- if (pass.error) {
32
- if (/language|recognizer/i.test(pass.error)) {
33
- throw new ScreencastError(`Windows OCR is unavailable: ${pass.error}`, "Install an OCR language: Settings > Time & language > Language > (your language) > Options > Optical character recognition.");
34
- }
35
- throw new ScreencastError(`OCR failed: ${pass.error}`);
36
- }
37
- const lines = [];
38
- for (const l of pass.lines ?? []) {
39
- const words = (Array.isArray(l.words) ? l.words : l.words ? [l.words] : []).map((w) => ({
40
- text: String(w.text ?? ""),
41
- x: Math.round((w.x ?? 0) / scale),
42
- y: Math.round((w.y ?? 0) / scale),
43
- width: Math.max(1, Math.round((w.width ?? 0) / scale)),
44
- height: Math.max(1, Math.round((w.height ?? 0) / scale)),
45
- }));
46
- if (words.length === 0)
47
- continue;
48
- lines.push({ text: String(l.text ?? words.map((w) => w.text).join(" ")), words, ...unionRect(words) });
49
- }
50
- return lines;
51
- }
52
- export function unionRect(rects) {
53
- const x0 = Math.min(...rects.map((r) => r.x));
54
- const y0 = Math.min(...rects.map((r) => r.y));
55
- const x1 = Math.max(...rects.map((r) => r.x + r.width));
56
- const y1 = Math.max(...rects.map((r) => r.y + r.height));
57
- return { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };
58
- }
59
- function overlapRatio(a, b) {
60
- const w = Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x);
61
- const h = Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y);
62
- if (w <= 0 || h <= 0)
63
- return 0;
64
- return (w * h) / Math.min(a.width * a.height, b.width * b.height);
65
- }
66
- export function mergePasses(passes) {
67
- const kept = [];
68
- for (const pass of passes) {
69
- for (const line of pass) {
70
- const i = kept.findIndex((k) => overlapRatio(k, line) > 0.5);
71
- const match = kept[i];
72
- if (!match)
73
- kept.push(line);
74
- else if (line.text.length > match.text.length)
75
- kept[i] = line;
76
- }
77
- }
78
- return kept.sort((a, b) => a.y - b.y || a.x - b.x);
79
- }
80
- export function normalizeForMatch(s) {
81
- return s.toLowerCase().replace(/[-_\s]+/g, "_").replace(/[l1|]/g, "i").replace(/0/g, "o");
82
- }
83
- export const MAX_QUERY_LENGTH = 500;
84
- export const REGEX_BUDGET_MS = 1_000;
85
- const REGEX_SCAN = `JSON.stringify(texts.map((text) => {
86
- const re = new RegExp(query, "gi");
87
- const seen = new Set();
88
- const ranges = [];
89
- for (const variant of [text, text.replace(/-/g, "_"), text.replace(/_/g, "-")]) {
90
- for (const m of variant.matchAll(re)) {
91
- const key = m.index + ":" + m[0].length;
92
- if (m[0].length > 0 && !seen.has(key)) {
93
- seen.add(key);
94
- ranges.push([m.index, m.index + m[0].length]);
95
- }
96
- }
97
- }
98
- return ranges;
99
- }))`;
100
- export function regexRanges(texts, query, budgetMs = REGEX_BUDGET_MS) {
101
- try {
102
- new RegExp(query, "gi");
103
- }
104
- catch (err) {
105
- throw new ScreencastError(`Invalid regex: ${errorMessage(err)}`);
106
- }
107
- try {
108
- return JSON.parse(runInNewContext(REGEX_SCAN, { texts, query }, { timeout: budgetMs }));
109
- }
110
- catch (err) {
111
- if (err.code === "ERR_SCRIPT_EXECUTION_TIMEOUT") {
112
- throw new ScreencastError(`The regex took longer than ${budgetMs / 1000} s to run and was stopped.`, "Simplify it: nested quantifiers such as (a+)+ backtrack catastrophically.");
113
- }
114
- throw err;
115
- }
116
- }
117
- export function findMatches(lines, query, regex = false) {
118
- if (query.length > MAX_QUERY_LENGTH) {
119
- throw new ScreencastError(`The query is ${query.length} characters; at most ${MAX_QUERY_LENGTH} are allowed.`);
120
- }
121
- const rebuilt = lines.map((line) => {
122
- const spans = [];
123
- let text = "";
124
- for (const w of line.words) {
125
- if (text)
126
- text += " ";
127
- spans.push({ start: text.length, end: text.length + w.text.length, word: w });
128
- text += w.text;
129
- }
130
- return { line, spans, text };
131
- });
132
- const regexHits = regex ? regexRanges(rebuilt.map((r) => r.text), query) : null;
133
- const out = [];
134
- rebuilt.forEach(({ line, spans }, i) => {
135
- let ranges = [];
136
- if (regexHits) {
137
- ranges = regexHits[i] ?? [];
138
- }
139
- else {
140
- const needle = normalizeForMatch(query);
141
- if (!needle)
142
- return;
143
- const hay = spans.map((s) => normalizeForMatch(s.word.text)).join("_");
144
- let from = 0;
145
- for (let at = hay.indexOf(needle, from); at !== -1; at = hay.indexOf(needle, from)) {
146
- ranges.push(normalizedRangeToText(spans, at, at + needle.length));
147
- from = at + needle.length;
148
- }
149
- }
150
- const boxed = new Set();
151
- for (const [start, end] of ranges) {
152
- const words = spans.filter((s) => s.start < end && s.end > start).map((s) => s.word);
153
- if (words.length === 0 || words.every((w) => boxed.has(w)))
154
- continue;
155
- words.forEach((w) => boxed.add(w));
156
- out.push({ text: words.map((w) => w.text).join(" "), line: line.text, ...unionRect(words) });
157
- }
158
- });
159
- return out;
160
- }
161
- function normalizedRangeToText(spans, start, end) {
162
- let pos = 0;
163
- let textStart = -1;
164
- let textEnd = -1;
165
- for (const s of spans) {
166
- const len = normalizeForMatch(s.word.text).length;
167
- if (textStart === -1 && start < pos + len)
168
- textStart = s.start;
169
- if (end <= pos + len + 1) {
170
- textEnd = s.end;
171
- break;
172
- }
173
- pos += len + 1;
174
- }
175
- return [textStart === -1 ? 0 : textStart, textEnd === -1 ? (spans.at(-1)?.end ?? 0) : textEnd];
176
- }
177
- export function redactionRects(matches, frame, pad = 4) {
178
- return matches.map((m) => {
179
- const x = Math.max(0, m.x - pad);
180
- const y = Math.max(0, m.y - pad);
181
- return {
182
- x,
183
- y,
184
- width: Math.min(frame.width, m.x + m.width + pad) - x,
185
- height: Math.min(frame.height, m.y + m.height + pad) - y,
186
- };
187
- });
188
- }
189
- export function passScales(width, height) {
190
- const cap = OCR_MAX_DIMENSION / Math.max(width, height);
191
- const scales = OCR_SCALES.map((s) => Math.min(s, Math.floor(cap * 100) / 100)).filter((s) => s >= 1);
192
- return [...new Set(scales.length ? scales : [Math.min(1, cap)])];
193
- }
194
- export const OCR_TIMEOUT_MS = 60_000;
195
- export const OCR_PER_IMAGE_MS = 5_000;
196
- export const OCR_STEP_TIMEOUT_MS = 20_000;
197
- const PS_OCR = `
198
- $ErrorActionPreference = 'Stop'
199
- Add-Type -AssemblyName System.Runtime.WindowsRuntime
200
- $null = [Windows.Storage.StorageFile, Windows.Storage, ContentType = WindowsRuntime]
201
- $null = [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsRuntime]
202
- $null = [Windows.Graphics.Imaging.BitmapDecoder, Windows.Foundation, ContentType = WindowsRuntime]
203
- $asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation\`1' })[0]
204
- function Await($op, [Type]$t) { $task = $asTask.MakeGenericMethod($t).Invoke($null, @($op)); if (-not $task.Wait(${OCR_STEP_TIMEOUT_MS})) { throw "The OCR engine did not answer within ${OCR_STEP_TIMEOUT_MS / 1000} s." }; $task.Result }
205
- $paths = $Payload | ConvertFrom-Json
206
- $engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages()
207
- $out = foreach ($p in $paths) {
208
- try {
209
- if ($null -eq $engine) { throw 'No OCR recognizer language is installed.' }
210
- $file = Await ([Windows.Storage.StorageFile]::GetFileFromPathAsync($p)) ([Windows.Storage.StorageFile])
211
- $stream = Await ($file.OpenAsync([Windows.Storage.FileAccessMode]::Read)) ([Windows.Storage.Streams.IRandomAccessStream])
212
- $decoder = Await ([Windows.Graphics.Imaging.BitmapDecoder]::CreateAsync($stream)) ([Windows.Graphics.Imaging.BitmapDecoder])
213
- $bitmap = Await ($decoder.GetSoftwareBitmapAsync()) ([Windows.Graphics.Imaging.SoftwareBitmap])
214
- $result = Await ($engine.RecognizeAsync($bitmap)) ([Windows.Media.Ocr.OcrResult])
215
- $stream.Dispose()
216
- [pscustomobject]@{ lines = @(foreach ($l in $result.Lines) {
217
- [pscustomobject]@{ text = $l.Text; words = @(foreach ($w in $l.Words) {
218
- [pscustomobject]@{ text = $w.Text; x = $w.BoundingRect.X; y = $w.BoundingRect.Y; width = $w.BoundingRect.Width; height = $w.BoundingRect.Height } }) } }) }
219
- } catch { [pscustomobject]@{ error = $_.Exception.Message } }
220
- }
221
- ConvertTo-Json -InputObject @($out) -Depth 6 -Compress
222
- `;
@@ -1,91 +0,0 @@
1
- import { join } from "node:path";
2
- import { readdirSync } from "node:fs";
3
- import { ScreencastError } from "./errors.js";
4
- import { probeMedia, runFfmpeg } from "./ffmpeg.js";
5
- import { jobTimeoutMs } from "./jobs.js";
6
- import { buildSampleByFpsArgs, planFpsSampling } from "./media.js";
7
- import { recognize, mergePasses, findMatches, redactionRects, passScales } from "./ocr.js";
8
- import { mapPool } from "./pool.js";
9
- export function buildOcrPassArgs(source, scales, outputs) {
10
- if (scales.length === 0 || scales.length !== outputs.length) {
11
- throw new ScreencastError("Each OCR pass needs one output.");
12
- }
13
- const scale = (s) => `scale=iw*${s}:ih*${s}:flags=lanczos`;
14
- const png = ["-compression_level", "0"];
15
- if (scales.length === 1)
16
- return ["-y", "-v", "error", "-i", source, "-vf", scale(scales[0]), ...png, outputs[0]];
17
- const labels = scales.map((_s, i) => `[s${i}]`);
18
- const graph = [`[0:v]split=${scales.length}${labels.join("")}`, ...scales.map((s, i) => `${labels[i]}${scale(s)}[o${i}]`)].join(";");
19
- return [
20
- "-y", "-v", "error", "-i", source, "-filter_complex", graph,
21
- ...outputs.flatMap((out, i) => ["-map", `[o${i}]`, ...png, out]),
22
- ];
23
- }
24
- export async function readFrames(sources, work, signal, opts = {}) {
25
- const sizeOf = async (source) => {
26
- const { width, height } = await probeMedia(source);
27
- if (!width || !height)
28
- throw new ScreencastError("Could not read the image size.");
29
- return { width, height };
30
- };
31
- const shared = opts.sameSize && sources[0] ? await sizeOf(sources[0]) : null;
32
- const sized = await mapPool(sources, async (source) => ({ source, ...(shared ?? (await sizeOf(source))) }));
33
- const perFrame = await mapPool(sized, async ({ source, width, height }, f) => {
34
- const scales = passScales(width, height);
35
- const outs = scales.map((_s, i) => join(work, `pass${f}-${i}.png`));
36
- await runFfmpeg(buildOcrPassArgs(source, scales, outs), 60_000, { signal });
37
- return scales.map((scale, i) => ({ out: outs[i], scale, f }));
38
- });
39
- const flat = perFrame.flat();
40
- const passes = flat.map((p) => p.out);
41
- const passScaleList = flat.map((p) => p.scale);
42
- const owner = flat.map((p) => p.f);
43
- const results = await recognize(passes, passScaleList);
44
- return sized.map(({ width, height }, f) => ({
45
- lines: mergePasses(results.filter((_r, i) => owner[i] === f)),
46
- width,
47
- height,
48
- }));
49
- }
50
- export async function scanVideoFrames(input, opts, work, signal) {
51
- const info = await probeMedia(input);
52
- const full = info.videoDurationSec ?? info.durationSec;
53
- const length = opts.range ? opts.range.duration : full;
54
- const plan = planFpsSampling(length, 1 / opts.everySec, opts.maxFrames);
55
- await runFfmpeg(buildSampleByFpsArgs(input, plan.fps, join(work, "scan_%05d.png"), opts.maxFrames, false, opts.range), jobTimeoutMs(info.durationSec), { signal });
56
- const paths = readdirSync(work).filter((f) => f.startsWith("scan_")).sort().map((f) => join(work, f));
57
- if (paths.length === 0)
58
- throw new ScreencastError("Could not read any frames from the video.");
59
- const step = 1 / plan.fps;
60
- const timeAt = (i) => Math.round(i * step * 1000) / 1000;
61
- const end = length ?? timeAt(paths.length - 1) + step;
62
- const read = await readFrames(paths, work, signal, { sameSize: true });
63
- return {
64
- frames: read.map((frame, i) => ({ ...frame, t: timeAt(i), path: paths[i] ?? "" })),
65
- step,
66
- end,
67
- clamped: plan.clamped,
68
- };
69
- }
70
- export function sampleWindow(t, step, end) {
71
- return {
72
- start: Math.max(0, Math.round((t - step) * 1000) / 1000),
73
- end: Math.min(end, Math.round((t + step) * 1000) / 1000),
74
- };
75
- }
76
- export function scanMatches(scan, query, regex, scope = "match") {
77
- const matches = [];
78
- const redactRegions = [];
79
- for (const frame of scan.frames) {
80
- const hits = findMatches(frame.lines, query, regex);
81
- const window = sampleWindow(frame.t, scan.step, scan.end);
82
- const boxes = scope === "line"
83
- ? [...new Set(hits.map((h) => frame.lines.find((l) => l.text === h.line) ?? h))]
84
- : hits;
85
- for (const hit of hits)
86
- matches.push({ t: frame.t, ...hit });
87
- for (const rect of redactionRects(boxes, frame))
88
- redactRegions.push({ ...rect, ...window });
89
- }
90
- return { matches, redactRegions };
91
- }