@tmhs/screencast-mcp 0.49.1 → 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 (134) 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 -79
  16. package/dist/tools/bugReport.js +0 -243
  17. package/dist/tools/burnSubtitles.js +0 -56
  18. package/dist/tools/callout.js +0 -62
  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 -113
  24. package/dist/tools/convert.js +0 -46
  25. package/dist/tools/crop.js +0 -43
  26. package/dist/tools/cursor.js +0 -67
  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 -194
  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 -90
  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 -59
  47. package/dist/tools/overlay.js +0 -62
  48. package/dist/tools/pauseRecording.js +0 -44
  49. package/dist/tools/pipeline.js +0 -397
  50. package/dist/tools/readEvents.js +0 -98
  51. package/dist/tools/redactRegion.js +0 -62
  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 -249
  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 -142
  69. package/dist/tools/xfadeTransition.js +0 -58
  70. package/dist/tools/zoom.js +0 -134
  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 -117
  75. package/dist/utils/audioDevices.js +0 -107
  76. package/dist/utils/backdrop.js +0 -162
  77. package/dist/utils/bugReport.js +0 -195
  78. package/dist/utils/callout.js +0 -132
  79. package/dist/utils/calloutAssets.js +0 -42
  80. package/dist/utils/capabilities.js +0 -96
  81. package/dist/utils/captions.js +0 -104
  82. package/dist/utils/chapters.js +0 -227
  83. package/dist/utils/consent.js +0 -29
  84. package/dist/utils/cursor.js +0 -338
  85. package/dist/utils/diff.js +0 -186
  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/frameQueue.js +0 -50
  93. package/dist/utils/gpu.js +0 -219
  94. package/dist/utils/idle.js +0 -91
  95. package/dist/utils/images.js +0 -38
  96. package/dist/utils/jobs.js +0 -129
  97. package/dist/utils/keystrokes.js +0 -198
  98. package/dist/utils/lifecycle.js +0 -233
  99. package/dist/utils/logging.js +0 -75
  100. package/dist/utils/media.js +0 -584
  101. package/dist/utils/monitors.js +0 -124
  102. package/dist/utils/narrate.js +0 -233
  103. package/dist/utils/ocr.js +0 -222
  104. package/dist/utils/ocrScan.js +0 -93
  105. package/dist/utils/paths.js +0 -155
  106. package/dist/utils/pause.js +0 -190
  107. package/dist/utils/pipeline.js +0 -361
  108. package/dist/utils/player.js +0 -85
  109. package/dist/utils/pool.js +0 -29
  110. package/dist/utils/produce.js +0 -300
  111. package/dist/utils/recipes.js +0 -71
  112. package/dist/utils/recorder.js +0 -173
  113. package/dist/utils/recordingFiles.js +0 -32
  114. package/dist/utils/recordingIndex.js +0 -312
  115. package/dist/utils/replay.js +0 -283
  116. package/dist/utils/resolveTarget.js +0 -25
  117. package/dist/utils/retention.js +0 -48
  118. package/dist/utils/roots.js +0 -43
  119. package/dist/utils/sessions.js +0 -499
  120. package/dist/utils/sheet.js +0 -82
  121. package/dist/utils/stepGuide.js +0 -231
  122. package/dist/utils/steps.js +0 -88
  123. package/dist/utils/still.js +0 -38
  124. package/dist/utils/targetList.js +0 -64
  125. package/dist/utils/targets.js +0 -265
  126. package/dist/utils/timeline.js +0 -85
  127. package/dist/utils/toolSpec.js +0 -31
  128. package/dist/utils/toolsets.js +0 -134
  129. package/dist/utils/transcriptCut.js +0 -149
  130. package/dist/utils/validate.js +0 -23
  131. package/dist/utils/waitLoop.js +0 -50
  132. package/dist/utils/wgc.js +0 -84
  133. package/dist/utils/windows.js +0 -192
  134. package/dist/utils/zoom.js +0 -252
@@ -1,50 +0,0 @@
1
- import { diffFrames, SettleTracker } from "./diff.js";
2
- const defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
3
- export async function waitLoop(o) {
4
- const now = o.now ?? Date.now;
5
- const sleep = o.sleep ?? defaultSleep;
6
- const startedAt = now();
7
- const baseline = await o.grab();
8
- const settle = new SettleTracker(baseline, o.width, o.height, o.diff);
9
- let lastChangeAt = startedAt;
10
- let everChanged = false;
11
- let regions = [];
12
- let outcome = "timeout";
13
- while (now() - startedAt < o.timeoutMs) {
14
- if (o.signal.aborted) {
15
- outcome = "cancelled";
16
- break;
17
- }
18
- await sleep(o.intervalMs);
19
- const current = await o.grab().catch((error) => {
20
- if (o.signal.aborted)
21
- return null;
22
- throw error;
23
- });
24
- if (!current) {
25
- outcome = "cancelled";
26
- break;
27
- }
28
- if (o.mode === "change") {
29
- const d = diffFrames(baseline, current, o.width, o.height, o.diff);
30
- if (d.regions.length > 0) {
31
- regions = d.regions;
32
- outcome = "changed";
33
- break;
34
- }
35
- }
36
- else {
37
- const changed = settle.push(current);
38
- if (changed.length > 0) {
39
- everChanged = true;
40
- lastChangeAt = now();
41
- regions = changed;
42
- }
43
- else if (now() - lastChangeAt >= o.settleMs) {
44
- outcome = "settled";
45
- break;
46
- }
47
- }
48
- }
49
- return { outcome, regions, everChanged, startedAt };
50
- }
package/dist/utils/wgc.js DELETED
@@ -1,84 +0,0 @@
1
- import { ScreencastError } from "./errors.js";
2
- export function buildWgcGrabArgs(hwnd, fps, cursor = true) {
3
- if (!Number.isSafeInteger(hwnd) || hwnd <= 0)
4
- throw new ScreencastError("Invalid window handle.");
5
- return [
6
- "-hide_banner", "-nostats", "-loglevel", "info",
7
- "-f", "lavfi",
8
- "-i", `gfxcapture=hwnd=${hwnd}:max_framerate=${fps}${cursor ? "" : ":capture_cursor=0"},hwdownload,format=bgra,crop=trunc(iw/2)*2:trunc(ih/2)*2,format=yuv420p`,
9
- "-flush_packets", "1",
10
- "-f", "rawvideo", "-",
11
- ];
12
- }
13
- export function parseRawSize(stderr) {
14
- const out = stderr.indexOf("Output #0");
15
- if (out < 0)
16
- return null;
17
- const m = /Video: rawvideo[^\n]*?, (\d{2,5})x(\d{2,5})/.exec(stderr.slice(out));
18
- return m ? { width: Number(m[1]), height: Number(m[2]) } : null;
19
- }
20
- export function yuv420FrameBytes(width, height) {
21
- return (width * height * 3) / 2;
22
- }
23
- export class FrameAssembler {
24
- parts = [];
25
- length = 0;
26
- frameBytes = 0;
27
- push(chunk) {
28
- if (!chunk.length)
29
- return;
30
- this.parts.push(chunk);
31
- this.length += chunk.length;
32
- }
33
- get buffered() {
34
- return this.length;
35
- }
36
- take() {
37
- const fb = this.frameBytes;
38
- if (fb <= 0 || this.length < fb)
39
- return null;
40
- const frames = Math.floor(this.length / fb);
41
- const all = this.parts.length === 1 && this.parts[0] ? this.parts[0] : Buffer.concat(this.parts, this.length);
42
- const end = frames * fb;
43
- const frame = all.subarray(end - fb, end);
44
- const rest = this.length - end;
45
- this.parts = rest ? [Buffer.from(all.subarray(end))] : [];
46
- this.length = rest;
47
- return frame;
48
- }
49
- }
50
- export function buildWgcEncodeArgs(width, height, cfg) {
51
- return [
52
- "-hide_banner", "-nostats", "-loglevel", "error", "-y",
53
- "-f", "rawvideo", "-pix_fmt", "yuv420p", "-s", `${width}x${height}`, "-framerate", String(cfg.fps),
54
- "-i", "pipe:0",
55
- ...cfg.encode,
56
- "-movflags", "+frag_keyframe+empty_moov+default_base_moof",
57
- cfg.output,
58
- ];
59
- }
60
- export function framesDue(elapsedMs, fps) {
61
- return Math.floor((elapsedMs * fps) / 1000) + 1;
62
- }
63
- export const WGC_WINDOW_CLOSED_EXIT = 3;
64
- export function wgcStopFile(output) {
65
- return `${output}.stop`;
66
- }
67
- export function startBanner(epochMs) {
68
- return `Input #0, wgc, from 'window':\n Duration: N/A, start: ${(epochMs / 1000).toFixed(6)}, bitrate: N/A\n`;
69
- }
70
- export function nudgeScript(hwnd, intervalMs, parentPid) {
71
- const watch = parentPid ? `$p=Get-Process -Id ${parentPid} -ErrorAction SilentlyContinue
72
- ` : "";
73
- const alive = parentPid ? ` -and $p -and !$p.HasExited` : "";
74
- return `Add-Type @"
75
- using System;using System.Runtime.InteropServices;
76
- public class ScNudge{
77
- [StructLayout(LayoutKind.Sequential)] public struct RECT{public int L,T,R,B;}
78
- [DllImport("user32.dll")] public static extern bool RedrawWindow(IntPtr h,ref RECT r,IntPtr g,uint f);
79
- [DllImport("user32.dll")] public static extern bool IsWindow(IntPtr h);
80
- }
81
- "@
82
- $r=New-Object ScNudge+RECT;$r.R=1;$r.B=1
83
- ${watch}while([ScNudge]::IsWindow([IntPtr]${hwnd})${alive}){[void][ScNudge]::RedrawWindow([IntPtr]${hwnd},[ref]$r,[IntPtr]::Zero,0x0105);Start-Sleep -Milliseconds ${intervalMs}}`;
84
- }
@@ -1,192 +0,0 @@
1
- import { errorMessage, ScreencastError } from "./errors.js";
2
- import { runPowerShell } from "./monitors.js";
3
- export const MAX_CANDIDATES = 5;
4
- export function parseWindowSelector(wanted) {
5
- const h = /^hwnd=(0x[0-9a-f]+|\d+)$/i.exec(wanted.trim());
6
- if (h)
7
- return { kind: "hwnd", hwnd: Number(h[1]) };
8
- const e = /^exe=(.+)$/i.exec(wanted.trim());
9
- if (e?.[1])
10
- return { kind: "exe", exe: e[1].trim().toLowerCase().replace(/\.exe$/, "") };
11
- return null;
12
- }
13
- export function selectWindow(query, wanted, opts = {}) {
14
- const windows = Array.isArray(query.windows) ? query.windows : [];
15
- const visible = windows.filter((w) => !w.cloaked);
16
- try {
17
- return matchWindow(query, visible, wanted, opts);
18
- }
19
- catch (err) {
20
- if (!(err instanceof NoWindowMatch) || visible.length === windows.length)
21
- throw err;
22
- let hit;
23
- try {
24
- hit = matchWindow(query, windows, wanted, opts);
25
- }
26
- catch {
27
- throw err;
28
- }
29
- if (!opts.allowCloaked) {
30
- throw new ScreencastError(`Window "${hit.matchedTitle}" is cloaked: Windows reports it as open but it is not on screen ` +
31
- "(a suspended app, or a window on another virtual desktop), so a screen capture would record whatever is there instead.", "Bring the window up on this desktop, or use backend: \"wgc\", which captures the window's own surface.");
32
- }
33
- return { ...hit, cloaked: true };
34
- }
35
- }
36
- class NoWindowMatch extends ScreencastError {
37
- }
38
- function matchWindow(query, all, wanted, opts) {
39
- const selector = parseWindowSelector(wanted);
40
- if (selector) {
41
- const hits = selector.kind === "hwnd"
42
- ? all.filter((w) => w.hwnd === selector.hwnd)
43
- : all.filter((w) => (w.exe ?? "").toLowerCase().replace(/\.exe$/, "") === selector.exe);
44
- if (hits.length === 0) {
45
- throw new NoWindowMatch(selector.kind === "hwnd"
46
- ? `No visible top-level window with handle ${wanted.trim().slice(5)}. It may have closed; handles change when an app restarts.`
47
- : `No visible window belonging to ${selector.exe}.exe. Is the app running with a window open (and not minimized)?`);
48
- }
49
- return toBounds(query, hits, selector.kind);
50
- }
51
- const needle = wanted.trim().toLowerCase();
52
- const exact = all.filter((w) => w.title.toLowerCase() === needle);
53
- const substring = all.filter((w) => w.title.toLowerCase().includes(needle));
54
- const quote = (ws) => ws.slice(0, MAX_CANDIDATES).map((w) => `"${w.title}"`).join(", ");
55
- if (exact.length === 0 && opts.exactOnly) {
56
- throw new NoWindowMatch(`No visible window titled exactly "${wanted}" (exactTitle is on).` +
57
- (substring.length > 0 ? ` Windows containing it: ${quote(substring)}.` : ""));
58
- }
59
- const matchKind = exact.length > 0 ? "exact" : "substring";
60
- const matches = exact.length > 0 ? exact : substring;
61
- if (matches.length === 0) {
62
- throw new NoWindowMatch(`No visible window matching title "${wanted}". Open the window (it must ` +
63
- `be on screen and not minimized), or use an exact/substring of its title, ` +
64
- `or target it by window:exe=<app.exe> or window:hwnd=<handle>.`);
65
- }
66
- return toBounds(query, matches, matchKind);
67
- }
68
- function toBounds(query, matches, matchKind) {
69
- const chosen = matches[0];
70
- if (!chosen)
71
- throw new NoWindowMatch("No visible window matched.");
72
- if (chosen.minimized) {
73
- throw new ScreencastError(`Window "${chosen.title}" is minimized. Restore it before capturing - ` +
74
- `window capture grabs whatever is on screen at the window's rectangle.`);
75
- }
76
- const v = query.virtual;
77
- const x = Math.max(chosen.left, v.x);
78
- const y = Math.max(chosen.top, v.y);
79
- const right = Math.min(chosen.right, v.x + v.w);
80
- const bottom = Math.min(chosen.bottom, v.y + v.h);
81
- let width = right - x;
82
- let height = bottom - y;
83
- if (width <= 0 || height <= 0) {
84
- throw new ScreencastError(`Window "${chosen.title}" has no visible on-screen area to capture ` +
85
- `(off-screen or fully occluded by the desktop edge).`);
86
- }
87
- width -= width % 2;
88
- height -= height % 2;
89
- if (width <= 0 || height <= 0) {
90
- throw new ScreencastError(`Window "${chosen.title}" is too small to capture.`);
91
- }
92
- return {
93
- x, y, width, height,
94
- matchedTitle: chosen.title,
95
- ...(chosen.hwnd !== undefined ? { hwnd: chosen.hwnd } : {}),
96
- ...(chosen.clientX !== undefined && chosen.clientY !== undefined ? { client: { x: chosen.clientX, y: chosen.clientY } } : {}),
97
- matchCount: matches.length,
98
- matchKind,
99
- candidates: matches.slice(0, MAX_CANDIDATES).map((w) => w.title),
100
- };
101
- }
102
- export function windowMatchReport(w) {
103
- const reasons = [];
104
- if (w.matchKind === "substring")
105
- reasons.push("the title matched only as a substring");
106
- if (w.matchCount > 1)
107
- reasons.push(`${w.matchCount} windows matched and the topmost was used`);
108
- if (w.cloaked)
109
- reasons.push("the window is cloaked (not on screen: suspended, or on another virtual desktop)");
110
- return {
111
- matchedWindow: w.matchedTitle,
112
- matchCount: w.matchCount,
113
- matchKind: w.matchKind,
114
- region: { x: w.x, y: w.y, width: w.width, height: w.height },
115
- ...(reasons.length > 0
116
- ? {
117
- windowWarning: `Check this is the intended window: ${reasons.join(", and ")}. ` +
118
- `Candidates: ${w.candidates.map((t) => `"${t}"`).join(", ")}. ` +
119
- "Pass the full title with exactTitle: true to match only that window.",
120
- }
121
- : {}),
122
- };
123
- }
124
- const PS_ENUM = `
125
- $ErrorActionPreference='Stop'
126
- Add-Type @"
127
- using System;using System.Text;using System.Collections.Generic;using System.Runtime.InteropServices;
128
- public class WinShim{
129
- [DllImport("user32.dll")] public static extern bool EnumWindows(EnumWindowsProc f,IntPtr l);
130
- public delegate bool EnumWindowsProc(IntPtr h,IntPtr l);
131
- [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);
132
- [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr h);
133
- [DllImport("user32.dll",CharSet=CharSet.Unicode)] public static extern int GetWindowText(IntPtr h,StringBuilder s,int n);
134
- [DllImport("user32.dll")] public static extern int GetWindowTextLength(IntPtr h);
135
- [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h,out RECT r);
136
- [DllImport("user32.dll")] public static extern int GetSystemMetrics(int i);
137
- [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h,out uint p);
138
- [DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr h,ref PT p);
139
- public struct PT{public int X,Y;}
140
- [DllImport("user32.dll")] public static extern IntPtr SetProcessDpiAwarenessContext(IntPtr v);
141
- public struct RECT{public int Left,Top,Right,Bottom;}
142
- static List<IntPtr> _h;
143
- static bool Col(IntPtr h,IntPtr l){_h.Add(h);return true;}
144
- public static IntPtr[] Z(){_h=new List<IntPtr>();EnumWindows(Col,IntPtr.Zero);return _h.ToArray();}
145
- public static string T(IntPtr h){int n=GetWindowTextLength(h);if(n==0)return "";var s=new StringBuilder(n+1);GetWindowText(h,s,s.Capacity);return s.ToString();}
146
- [DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr h,int a,out RECT r,int n);
147
- public static int[] R(IntPtr h){RECT r;if(DwmGetWindowAttribute(h,9,out r,Marshal.SizeOf(typeof(RECT)))!=0){GetWindowRect(h,out r);}return new int[]{r.Left,r.Top,r.Right,r.Bottom};}
148
- [DllImport("dwmapi.dll",EntryPoint="DwmGetWindowAttribute")] public static extern int DwmInt(IntPtr h,int a,out int v,int n);
149
- public static bool Ck(IntPtr h){int v;return DwmInt(h,14,out v,4)==0&&v!=0;}
150
- public static bool Ic(IntPtr h){return IsIconic(h);}
151
- public static bool Vis(IntPtr h){return IsWindowVisible(h);}
152
- public static int SM(int i){return GetSystemMetrics(i);}
153
- public static uint P(IntPtr h){uint p;GetWindowThreadProcessId(h,out p);return p;}
154
- public static int[] C(IntPtr h){PT p=new PT();ClientToScreen(h,ref p);return new int[]{p.X,p.Y};}
155
- }
156
- "@
157
- try{[void][WinShim]::SetProcessDpiAwarenessContext([IntPtr](-4))}catch{}
158
- $ws=New-Object System.Collections.ArrayList
159
- $exes=@{}
160
- foreach($h in [WinShim]::Z()){
161
- if(-not [WinShim]::Vis($h)){continue}
162
- $t=[WinShim]::T($h)
163
- if([string]::IsNullOrEmpty($t)){continue}
164
- $r=[WinShim]::R($h)
165
- $procId=[WinShim]::P($h)
166
- $c=[WinShim]::C($h)
167
- if(-not $exes.ContainsKey($procId)){$exes[$procId]=try{(Get-Process -Id $procId -ErrorAction Stop).ProcessName+'.exe'}catch{''}}
168
- [void]$ws.Add([pscustomobject]@{title=$t;left=$r[0];top=$r[1];right=$r[2];bottom=$r[3];minimized=[bool][WinShim]::Ic($h);hwnd=[int64]$h;exe=$exes[$procId];pid=$procId;clientX=$c[0];clientY=$c[1];cloaked=[WinShim]::Ck($h)})
169
- }
170
- $v=[pscustomobject]@{x=[WinShim]::SM(76);y=[WinShim]::SM(77);w=[WinShim]::SM(78);h=[WinShim]::SM(79)}
171
- [pscustomobject]@{virtual=$v;windows=@($ws)}|ConvertTo-Json -Compress -Depth 4
172
- `;
173
- export async function getRawWindows() {
174
- if (process.platform !== "win32") {
175
- throw new ScreencastError("Window capture is implemented for Windows (gdigrab) only.");
176
- }
177
- const stdout = await runPowerShell(PS_ENUM, "windows");
178
- let parsed;
179
- try {
180
- parsed = JSON.parse(stdout);
181
- }
182
- catch (err) {
183
- throw new ScreencastError(`Could not parse window geometry: ${errorMessage(err)}`);
184
- }
185
- const obj = parsed;
186
- const windows = Array.isArray(obj.windows) ? obj.windows : obj.windows ? [obj.windows] : [];
187
- const v = obj.virtual ?? { x: 0, y: 0, w: 0, h: 0 };
188
- return { virtual: v, windows };
189
- }
190
- export async function resolveWindowBounds(title, opts = {}) {
191
- return selectWindow(await getRawWindows(), title, opts);
192
- }
@@ -1,252 +0,0 @@
1
- import { ScreencastError } from "./errors.js";
2
- import { diffFrames } from "./diff.js";
3
- import { resolveQuality } from "./targets.js";
4
- import { sumExpr } from "./expr.js";
5
- import { z } from "zod";
6
- import { existsSync, readFileSync } from "node:fs";
7
- import { parseEventsJsonl } from "./events.js";
8
- export const DEFAULT_TRANSITION_SEC = 0.6;
9
- export const MAX_ZOOM = 6;
10
- export const DEFAULT_AUTO_MAX_ZOOM = 2.5;
11
- export function keyframesToViews(kfs, W, H, maxZoom = MAX_ZOOM) {
12
- if (kfs.length === 0)
13
- throw new ScreencastError("Give at least one keyframe.");
14
- const sorted = [...kfs].sort((a, b) => a.t - b.t);
15
- const views = sorted.map((k) => {
16
- if (!Number.isFinite(k.t) || k.t < 0)
17
- throw new ScreencastError("Keyframe t must be a non-negative number.");
18
- if (k.full || k.width === undefined || k.height === undefined)
19
- return { t: k.t, z: 1, cx: W / 2, cy: H / 2 };
20
- if (!(k.width > 0) || !(k.height > 0))
21
- throw new ScreencastError("Keyframe width and height must be positive.");
22
- const z = Math.max(1, Math.min(maxZoom, W / k.width, H / k.height));
23
- return { t: k.t, z, cx: (k.x ?? 0) + k.width / 2, cy: (k.y ?? 0) + k.height / 2 };
24
- });
25
- if (views[0] && views[0].t > 0)
26
- views.unshift({ t: 0, z: 1, cx: W / 2, cy: H / 2 });
27
- return views;
28
- }
29
- const n = (v) => Number(v.toFixed(4)).toString();
30
- export function viewExpr(views, key, transition) {
31
- const [first, ...rest] = views;
32
- if (!first)
33
- throw new ScreencastError("Give at least one keyframe.");
34
- const terms = [n(first[key])];
35
- let prev = first;
36
- for (const next of rest) {
37
- const a = prev[key];
38
- const b = next[key];
39
- const start = prev.t;
40
- prev = next;
41
- if (a === b)
42
- continue;
43
- const end = next.t;
44
- const T = Math.max(0.001, Math.min(transition, end - start));
45
- const s = `clip((it-${n(end - T)})/${n(T)},0,1)`;
46
- terms.push(`(${n(b - a)})*${s}*${s}*(3-2*${s})`);
47
- }
48
- return sumExpr(terms);
49
- }
50
- export function zoomFilter(views, size, transition = DEFAULT_TRANSITION_SEC) {
51
- const { width: W, height: H, fps } = size;
52
- const up = W <= 1920 ? 2 : 1;
53
- const z = viewExpr(views, "z", transition);
54
- const cx = viewExpr(views, "cx", transition);
55
- const cy = viewExpr(views, "cy", transition);
56
- return (`fps=${n(fps)},scale=${W * up}:${H * up},` +
57
- `zoompan=z='${z}':x='clip((${cx})*${up}-iw/zoom/2,0,iw-iw/zoom)':y='clip((${cy})*${up}-ih/zoom/2,0,ih-ih/zoom)'` +
58
- `:d=1:s=${W}x${H}:fps=${n(fps)}`);
59
- }
60
- export function buildZoomArgs(input, output, views, size, transition = DEFAULT_TRANSITION_SEC, quality = "standard", rings) {
61
- const { width: W, height: H, fps } = size;
62
- const vf = zoomFilter(views, size, transition);
63
- if (!rings || rings.clicks.length === 0) {
64
- return ["-y", "-i", input, "-vf", vf, ...resolveQuality(quality), "-c:a", "copy", output];
65
- }
66
- const graph = [
67
- "[0:v]null[in]",
68
- ...ringFilters(rings.clicks, W, H, fps, rings.color),
69
- `[out]${vf}[v]`,
70
- ].join(";");
71
- return [
72
- "-y", "-i", input, "-filter_complex", graph,
73
- "-map", "[v]", "-map", "0:a?", ...resolveQuality(quality), "-c:a", "copy", output,
74
- ];
75
- }
76
- export function planAutoZoom(frames, w, h, W, H, opts = {}) {
77
- const planner = createAutoZoomPlanner(w, h, W, H, opts);
78
- for (const f of frames)
79
- planner.push(f);
80
- return planner.finish();
81
- }
82
- export function createAutoZoomPlanner(w, h, W, H, opts = {}) {
83
- const step = opts.step ?? 0.25;
84
- const hold = opts.holdSec ?? 2;
85
- const maxZoom = opts.maxZoom ?? DEFAULT_AUTO_MAX_ZOOM;
86
- const globalFraction = opts.globalFraction ?? 0.3;
87
- const T = opts.transition ?? DEFAULT_TRANSITION_SEC;
88
- const scale = W / w;
89
- const minW = W / maxZoom;
90
- const minH = H / maxZoom;
91
- const focuses = [];
92
- let cur = null;
93
- const close = () => {
94
- if (cur)
95
- focuses.push(cur);
96
- cur = null;
97
- };
98
- let prev = null;
99
- let i = 0;
100
- const push = (frame) => {
101
- const before = prev;
102
- prev = frame;
103
- if (!before) {
104
- i = 1;
105
- return;
106
- }
107
- const t = i++ * step;
108
- const d = diffFrames(before, frame, w, h, { scale });
109
- if (d.regions.length === 0) {
110
- if (cur && t - cur.last > hold)
111
- close();
112
- return;
113
- }
114
- if (d.changedFraction > globalFraction) {
115
- close();
116
- return;
117
- }
118
- const box = unionRects(d.regions);
119
- if (cur && t - cur.last <= hold && near(cur.box, box, W, H)) {
120
- cur.box = unionRects([cur.box, box]);
121
- cur.last = t;
122
- }
123
- else {
124
- close();
125
- cur = { start: t, last: t, box };
126
- }
127
- };
128
- const finish = () => {
129
- close();
130
- const kfs = [];
131
- let lastT = 0;
132
- for (const f of focuses) {
133
- const view = fitView(f.box, W, H, minW, minH);
134
- const inAt = Math.max(f.start, lastT + T);
135
- const outAt = Math.max(f.last + hold, inAt + T);
136
- kfs.push({ t: round(inAt), ...view }, { t: round(outAt), full: true });
137
- lastT = outAt;
138
- }
139
- return kfs;
140
- };
141
- return { push, finish };
142
- }
143
- const round = (v) => Math.round(v * 100) / 100;
144
- function unionRects(rs) {
145
- const x0 = Math.min(...rs.map((r) => r.x));
146
- const y0 = Math.min(...rs.map((r) => r.y));
147
- const x1 = Math.max(...rs.map((r) => r.x + r.width));
148
- const y1 = Math.max(...rs.map((r) => r.y + r.height));
149
- return { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };
150
- }
151
- function near(a, b, W, H) {
152
- const u = unionRects([a, b]);
153
- return u.width <= W / 2 && u.height <= H / 2;
154
- }
155
- export function fitView(box, W, H, minW, minH) {
156
- let width = Math.max(box.width * 1.4, minW);
157
- let height = Math.max(box.height * 1.4, minH);
158
- const aspect = W / H;
159
- if (width / height > aspect)
160
- height = width / aspect;
161
- else
162
- width = height * aspect;
163
- width = Math.min(width, W);
164
- height = Math.min(height, H);
165
- const cx = box.x + box.width / 2;
166
- const cy = box.y + box.height / 2;
167
- const x = Math.max(0, Math.min(W - width, cx - width / 2));
168
- const y = Math.max(0, Math.min(H - height, cy - height / 2));
169
- return { x: Math.round(x), y: Math.round(y), width: Math.round(width), height: Math.round(height) };
170
- }
171
- export function buildAnalysisArgs(input, size, step) {
172
- return [
173
- "-v", "error", "-i", input, "-an",
174
- "-vf", `fps=${n(1 / step)},scale=${size.width}:${size.height}:flags=area,format=gray`,
175
- "-f", "rawvideo", "-",
176
- ];
177
- }
178
- export function planClickZoom(clicks, W, H, opts = {}) {
179
- const hold = opts.holdSec ?? 2;
180
- const maxZoom = opts.maxZoom ?? DEFAULT_AUTO_MAX_ZOOM;
181
- const T = opts.transition ?? DEFAULT_TRANSITION_SEC;
182
- const minW = W / maxZoom;
183
- const minH = H / maxZoom;
184
- const pad = Math.min(W, H) * 0.05;
185
- const sorted = [...clicks].sort((a, b) => a.t - b.t);
186
- const kfs = [];
187
- let lastT = 0;
188
- let runEnd = -Infinity;
189
- for (const c of sorted) {
190
- const view = fitView({ x: c.x - pad, y: c.y - pad, width: 2 * pad, height: 2 * pad }, W, H, minW, minH);
191
- const prev = kfs[kfs.length - 1];
192
- if (prev && !prev.full && c.t - runEnd <= hold && insideView(prev, c)) {
193
- runEnd = c.t;
194
- continue;
195
- }
196
- if (c.t - runEnd > hold && kfs.length > 0) {
197
- const outAt = Math.max(runEnd + hold, lastT + T);
198
- kfs.push({ t: round(outAt), full: true });
199
- lastT = outAt;
200
- }
201
- const at = Math.max(c.t, lastT + T);
202
- kfs.push({ t: round(at), ...view });
203
- lastT = at;
204
- runEnd = c.t;
205
- }
206
- if (kfs.length > 0)
207
- kfs.push({ t: round(Math.max(runEnd + hold, lastT + T)), full: true });
208
- return kfs;
209
- }
210
- function insideView(v, p) {
211
- const mx = v.width * 0.15;
212
- const my = v.height * 0.15;
213
- return p.x >= v.x + mx && p.x <= v.x + v.width - mx && p.y >= v.y + my && p.y <= v.y + v.height - my;
214
- }
215
- export const RING_SEC = 0.6;
216
- export const DEFAULT_RING_COLOR = "#FF4545";
217
- export function ringSize(W, H) {
218
- return Math.max(40, 2 * Math.round(Math.min(W, H) * 0.045));
219
- }
220
- export function ringFilters(clicks, W, H, fps, color) {
221
- const D = ringSize(W, H);
222
- const c = D / 2;
223
- const th = Math.max(3, Math.round(D / 10));
224
- const r0 = c * 0.3;
225
- const dr = c - th / 2 - r0;
226
- const steps = [];
227
- let cur = "[in]";
228
- clicks.forEach((k, i) => {
229
- const alpha = `if(lt(abs(hypot(X-${c},Y-${c})-(${n(r0)}+${n(dr)}*T/${RING_SEC})),${th / 2}),255*min(1,2-2*T/${RING_SEC}),0)`;
230
- steps.push(`color=c=${color}:s=${D}x${D}:r=${n(fps)}:d=${RING_SEC},format=rgba,` +
231
- `geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='${alpha}',setpts=PTS+${n(k.t)}/TB[ring${i}]`);
232
- const out = i === clicks.length - 1 ? "[out]" : `[r${i}]`;
233
- steps.push(`${cur}[ring${i}]overlay=x=${n(k.x - c)}:y=${n(k.y - c)}:eof_action=pass${out}`);
234
- cur = `[r${i}]`;
235
- });
236
- return steps;
237
- }
238
- export function readClicks(path) {
239
- if (!existsSync(path))
240
- return null;
241
- return parseEventsJsonl(readFileSync(path, "utf8"))
242
- .filter((e) => e.type === "down" && e.inFrame)
243
- .map((e) => ({ t: e.t, x: e.x, y: e.y }));
244
- }
245
- export const zoomKeyframeSchema = z.object({
246
- t: z.number().nonnegative(),
247
- x: z.number().optional(),
248
- y: z.number().optional(),
249
- width: z.number().positive().optional(),
250
- height: z.number().positive().optional(),
251
- full: z.boolean().optional(),
252
- });