@tmhs/screencast-mcp 0.39.0 → 0.45.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 (344) hide show
  1. package/README.md +95 -17
  2. package/assets/icon.png +0 -0
  3. package/assets/ui/player.html +47 -302
  4. package/assets/ui/player.js +402 -0
  5. package/dist/context.js +0 -5
  6. package/dist/index.js +17 -21
  7. package/dist/prompts.js +18 -8
  8. package/dist/resources.js +2 -14
  9. package/dist/server.js +49 -11
  10. package/dist/tools/addMarker.js +89 -0
  11. package/dist/tools/assembleHighlights.js +12 -7
  12. package/dist/tools/backdrop.js +89 -0
  13. package/dist/tools/bugReport.js +266 -0
  14. package/dist/tools/burnSubtitles.js +12 -6
  15. package/dist/tools/callout.js +32 -16
  16. package/dist/tools/chapters.js +156 -0
  17. package/dist/tools/clip.js +12 -9
  18. package/dist/tools/compress.js +10 -5
  19. package/dist/tools/concat.js +16 -15
  20. package/dist/tools/contactSheet.js +39 -33
  21. package/dist/tools/convert.js +12 -6
  22. package/dist/tools/crop.js +12 -7
  23. package/dist/tools/cutIdle.js +15 -9
  24. package/dist/tools/denoise.js +12 -6
  25. package/dist/tools/doctor.js +133 -0
  26. package/dist/tools/exportGif.js +14 -10
  27. package/dist/tools/exportPreset.js +11 -8
  28. package/dist/tools/extractAudio.js +10 -8
  29. package/dist/tools/findText.js +52 -98
  30. package/dist/tools/getMediaInfo.js +17 -3
  31. package/dist/tools/getSession.js +15 -3
  32. package/dist/tools/keystrokeOverlay.js +131 -0
  33. package/dist/tools/listAudioDevices.js +14 -7
  34. package/dist/tools/listSessions.js +13 -3
  35. package/dist/tools/listTargets.js +76 -0
  36. package/dist/tools/musicBed.js +14 -10
  37. package/dist/tools/normalizeAudio.js +12 -8
  38. package/dist/tools/overlay.js +16 -12
  39. package/dist/tools/pipeline.js +86 -25
  40. package/dist/tools/readEvents.js +21 -12
  41. package/dist/tools/redactRegion.js +19 -17
  42. package/dist/tools/reframe.js +9 -5
  43. package/dist/tools/reviewRecording.js +75 -22
  44. package/dist/tools/sampleFrames.js +33 -40
  45. package/dist/tools/saveReplay.js +90 -0
  46. package/dist/tools/scale.js +9 -3
  47. package/dist/tools/screenDiff.js +23 -17
  48. package/dist/tools/screenshot.js +21 -17
  49. package/dist/tools/speed.js +15 -4
  50. package/dist/tools/startRecording.js +96 -59
  51. package/dist/tools/stopRecording.js +35 -10
  52. package/dist/tools/titleCard.js +19 -11
  53. package/dist/tools/transcribe.js +13 -7
  54. package/dist/tools/trim.js +11 -10
  55. package/dist/tools/waitForChange.js +37 -22
  56. package/dist/tools/xfadeTransition.js +12 -8
  57. package/dist/tools/zoom.js +26 -29
  58. package/dist/utils/anim.js +1 -21
  59. package/dist/utils/animExport.js +5 -10
  60. package/dist/utils/audio.js +4 -33
  61. package/dist/utils/audioDevices.js +1 -48
  62. package/dist/utils/backdrop.js +151 -0
  63. package/dist/utils/bugReport.js +246 -0
  64. package/dist/utils/callout.js +1 -19
  65. package/dist/utils/calloutAssets.js +21 -11
  66. package/dist/utils/capabilities.js +95 -0
  67. package/dist/utils/captions.js +9 -26
  68. package/dist/utils/chapters.js +222 -0
  69. package/dist/utils/consent.js +29 -0
  70. package/dist/utils/diff.js +0 -46
  71. package/dist/utils/errors.js +5 -13
  72. package/dist/utils/events.js +21 -77
  73. package/dist/utils/expr.js +11 -0
  74. package/dist/utils/ffmpeg.js +119 -48
  75. package/dist/utils/fontCoverage.js +177 -0
  76. package/dist/utils/fonts.js +139 -23
  77. package/dist/utils/idle.js +12 -24
  78. package/dist/utils/images.js +0 -17
  79. package/dist/utils/jobs.js +42 -41
  80. package/dist/utils/keystrokes.js +170 -0
  81. package/dist/utils/lifecycle.js +11 -31
  82. package/dist/utils/logging.js +75 -0
  83. package/dist/utils/media.js +16 -124
  84. package/dist/utils/monitors.js +7 -43
  85. package/dist/utils/ocr.js +53 -71
  86. package/dist/utils/ocrScan.js +77 -0
  87. package/dist/utils/paths.js +68 -31
  88. package/dist/utils/pipeline.js +39 -25
  89. package/dist/utils/player.js +50 -27
  90. package/dist/utils/produce.js +6 -66
  91. package/dist/utils/replay.js +278 -0
  92. package/dist/utils/resolveTarget.js +0 -19
  93. package/dist/utils/retention.js +1 -15
  94. package/dist/utils/roots.js +42 -0
  95. package/dist/utils/sessions.js +195 -160
  96. package/dist/utils/sheet.js +0 -19
  97. package/dist/utils/still.js +0 -15
  98. package/dist/utils/targetList.js +63 -0
  99. package/dist/utils/targets.js +5 -70
  100. package/dist/utils/toolSpec.js +25 -0
  101. package/dist/utils/toolsets.js +122 -0
  102. package/dist/utils/validate.js +0 -22
  103. package/dist/utils/wgc.js +0 -46
  104. package/dist/utils/windows.js +5 -50
  105. package/dist/utils/zoom.js +55 -85
  106. package/dist/wgcRecorder.js +1 -30
  107. package/package.json +7 -3
  108. package/dist/context.d.ts +0 -9
  109. package/dist/context.d.ts.map +0 -1
  110. package/dist/context.js.map +0 -1
  111. package/dist/index.d.ts +0 -3
  112. package/dist/index.d.ts.map +0 -1
  113. package/dist/index.js.map +0 -1
  114. package/dist/prompts.d.ts +0 -10
  115. package/dist/prompts.d.ts.map +0 -1
  116. package/dist/prompts.js.map +0 -1
  117. package/dist/resources.d.ts +0 -3
  118. package/dist/resources.d.ts.map +0 -1
  119. package/dist/resources.js.map +0 -1
  120. package/dist/server.d.ts +0 -3
  121. package/dist/server.d.ts.map +0 -1
  122. package/dist/server.js.map +0 -1
  123. package/dist/tools/assembleHighlights.d.ts +0 -3
  124. package/dist/tools/assembleHighlights.d.ts.map +0 -1
  125. package/dist/tools/assembleHighlights.js.map +0 -1
  126. package/dist/tools/burnSubtitles.d.ts +0 -3
  127. package/dist/tools/burnSubtitles.d.ts.map +0 -1
  128. package/dist/tools/burnSubtitles.js.map +0 -1
  129. package/dist/tools/callout.d.ts +0 -37
  130. package/dist/tools/callout.d.ts.map +0 -1
  131. package/dist/tools/callout.js.map +0 -1
  132. package/dist/tools/clip.d.ts +0 -3
  133. package/dist/tools/clip.d.ts.map +0 -1
  134. package/dist/tools/clip.js.map +0 -1
  135. package/dist/tools/compress.d.ts +0 -3
  136. package/dist/tools/compress.d.ts.map +0 -1
  137. package/dist/tools/compress.js.map +0 -1
  138. package/dist/tools/concat.d.ts +0 -3
  139. package/dist/tools/concat.d.ts.map +0 -1
  140. package/dist/tools/concat.js.map +0 -1
  141. package/dist/tools/contactSheet.d.ts +0 -3
  142. package/dist/tools/contactSheet.d.ts.map +0 -1
  143. package/dist/tools/contactSheet.js.map +0 -1
  144. package/dist/tools/convert.d.ts +0 -3
  145. package/dist/tools/convert.d.ts.map +0 -1
  146. package/dist/tools/convert.js.map +0 -1
  147. package/dist/tools/crop.d.ts +0 -3
  148. package/dist/tools/crop.d.ts.map +0 -1
  149. package/dist/tools/crop.js.map +0 -1
  150. package/dist/tools/cutIdle.d.ts +0 -3
  151. package/dist/tools/cutIdle.d.ts.map +0 -1
  152. package/dist/tools/cutIdle.js.map +0 -1
  153. package/dist/tools/denoise.d.ts +0 -3
  154. package/dist/tools/denoise.d.ts.map +0 -1
  155. package/dist/tools/denoise.js.map +0 -1
  156. package/dist/tools/exportGif.d.ts +0 -3
  157. package/dist/tools/exportGif.d.ts.map +0 -1
  158. package/dist/tools/exportGif.js.map +0 -1
  159. package/dist/tools/exportPreset.d.ts +0 -3
  160. package/dist/tools/exportPreset.d.ts.map +0 -1
  161. package/dist/tools/exportPreset.js.map +0 -1
  162. package/dist/tools/extractAudio.d.ts +0 -3
  163. package/dist/tools/extractAudio.d.ts.map +0 -1
  164. package/dist/tools/extractAudio.js.map +0 -1
  165. package/dist/tools/findText.d.ts +0 -6
  166. package/dist/tools/findText.d.ts.map +0 -1
  167. package/dist/tools/findText.js.map +0 -1
  168. package/dist/tools/getMediaInfo.d.ts +0 -3
  169. package/dist/tools/getMediaInfo.d.ts.map +0 -1
  170. package/dist/tools/getMediaInfo.js.map +0 -1
  171. package/dist/tools/getSession.d.ts +0 -3
  172. package/dist/tools/getSession.d.ts.map +0 -1
  173. package/dist/tools/getSession.js.map +0 -1
  174. package/dist/tools/listAudioDevices.d.ts +0 -3
  175. package/dist/tools/listAudioDevices.d.ts.map +0 -1
  176. package/dist/tools/listAudioDevices.js.map +0 -1
  177. package/dist/tools/listSessions.d.ts +0 -3
  178. package/dist/tools/listSessions.d.ts.map +0 -1
  179. package/dist/tools/listSessions.js.map +0 -1
  180. package/dist/tools/musicBed.d.ts +0 -3
  181. package/dist/tools/musicBed.d.ts.map +0 -1
  182. package/dist/tools/musicBed.js.map +0 -1
  183. package/dist/tools/normalizeAudio.d.ts +0 -3
  184. package/dist/tools/normalizeAudio.d.ts.map +0 -1
  185. package/dist/tools/normalizeAudio.js.map +0 -1
  186. package/dist/tools/overlay.d.ts +0 -3
  187. package/dist/tools/overlay.d.ts.map +0 -1
  188. package/dist/tools/overlay.js.map +0 -1
  189. package/dist/tools/pipeline.d.ts +0 -3
  190. package/dist/tools/pipeline.d.ts.map +0 -1
  191. package/dist/tools/pipeline.js.map +0 -1
  192. package/dist/tools/readEvents.d.ts +0 -6
  193. package/dist/tools/readEvents.d.ts.map +0 -1
  194. package/dist/tools/readEvents.js.map +0 -1
  195. package/dist/tools/redactRegion.d.ts +0 -13
  196. package/dist/tools/redactRegion.d.ts.map +0 -1
  197. package/dist/tools/redactRegion.js.map +0 -1
  198. package/dist/tools/reframe.d.ts +0 -3
  199. package/dist/tools/reframe.d.ts.map +0 -1
  200. package/dist/tools/reframe.js.map +0 -1
  201. package/dist/tools/reviewRecording.d.ts +0 -5
  202. package/dist/tools/reviewRecording.d.ts.map +0 -1
  203. package/dist/tools/reviewRecording.js.map +0 -1
  204. package/dist/tools/sampleFrames.d.ts +0 -3
  205. package/dist/tools/sampleFrames.d.ts.map +0 -1
  206. package/dist/tools/sampleFrames.js.map +0 -1
  207. package/dist/tools/scale.d.ts +0 -3
  208. package/dist/tools/scale.d.ts.map +0 -1
  209. package/dist/tools/scale.js.map +0 -1
  210. package/dist/tools/screenDiff.d.ts +0 -3
  211. package/dist/tools/screenDiff.d.ts.map +0 -1
  212. package/dist/tools/screenDiff.js.map +0 -1
  213. package/dist/tools/screenshot.d.ts +0 -3
  214. package/dist/tools/screenshot.d.ts.map +0 -1
  215. package/dist/tools/screenshot.js.map +0 -1
  216. package/dist/tools/speed.d.ts +0 -3
  217. package/dist/tools/speed.d.ts.map +0 -1
  218. package/dist/tools/speed.js.map +0 -1
  219. package/dist/tools/startRecording.d.ts +0 -3
  220. package/dist/tools/startRecording.d.ts.map +0 -1
  221. package/dist/tools/startRecording.js.map +0 -1
  222. package/dist/tools/stopRecording.d.ts +0 -3
  223. package/dist/tools/stopRecording.d.ts.map +0 -1
  224. package/dist/tools/stopRecording.js.map +0 -1
  225. package/dist/tools/titleCard.d.ts +0 -3
  226. package/dist/tools/titleCard.d.ts.map +0 -1
  227. package/dist/tools/titleCard.js.map +0 -1
  228. package/dist/tools/transcribe.d.ts +0 -3
  229. package/dist/tools/transcribe.d.ts.map +0 -1
  230. package/dist/tools/transcribe.js.map +0 -1
  231. package/dist/tools/trim.d.ts +0 -3
  232. package/dist/tools/trim.d.ts.map +0 -1
  233. package/dist/tools/trim.js.map +0 -1
  234. package/dist/tools/waitForChange.d.ts +0 -3
  235. package/dist/tools/waitForChange.d.ts.map +0 -1
  236. package/dist/tools/waitForChange.js.map +0 -1
  237. package/dist/tools/xfadeTransition.d.ts +0 -3
  238. package/dist/tools/xfadeTransition.d.ts.map +0 -1
  239. package/dist/tools/xfadeTransition.js.map +0 -1
  240. package/dist/tools/zoom.d.ts +0 -15
  241. package/dist/tools/zoom.d.ts.map +0 -1
  242. package/dist/tools/zoom.js.map +0 -1
  243. package/dist/utils/anim.d.ts +0 -33
  244. package/dist/utils/anim.d.ts.map +0 -1
  245. package/dist/utils/anim.js.map +0 -1
  246. package/dist/utils/animExport.d.ts +0 -27
  247. package/dist/utils/animExport.d.ts.map +0 -1
  248. package/dist/utils/animExport.js.map +0 -1
  249. package/dist/utils/audio.d.ts +0 -49
  250. package/dist/utils/audio.d.ts.map +0 -1
  251. package/dist/utils/audio.js.map +0 -1
  252. package/dist/utils/audioDevices.d.ts +0 -33
  253. package/dist/utils/audioDevices.d.ts.map +0 -1
  254. package/dist/utils/audioDevices.js.map +0 -1
  255. package/dist/utils/callout.d.ts +0 -72
  256. package/dist/utils/callout.d.ts.map +0 -1
  257. package/dist/utils/callout.js.map +0 -1
  258. package/dist/utils/calloutAssets.d.ts +0 -3
  259. package/dist/utils/calloutAssets.d.ts.map +0 -1
  260. package/dist/utils/calloutAssets.js.map +0 -1
  261. package/dist/utils/captions.d.ts +0 -26
  262. package/dist/utils/captions.d.ts.map +0 -1
  263. package/dist/utils/captions.js.map +0 -1
  264. package/dist/utils/diff.d.ts +0 -112
  265. package/dist/utils/diff.d.ts.map +0 -1
  266. package/dist/utils/diff.js.map +0 -1
  267. package/dist/utils/errors.d.ts +0 -33
  268. package/dist/utils/errors.d.ts.map +0 -1
  269. package/dist/utils/errors.js.map +0 -1
  270. package/dist/utils/events.d.ts +0 -143
  271. package/dist/utils/events.d.ts.map +0 -1
  272. package/dist/utils/events.js.map +0 -1
  273. package/dist/utils/ffmpeg.d.ts +0 -50
  274. package/dist/utils/ffmpeg.d.ts.map +0 -1
  275. package/dist/utils/ffmpeg.js.map +0 -1
  276. package/dist/utils/fonts.d.ts +0 -17
  277. package/dist/utils/fonts.d.ts.map +0 -1
  278. package/dist/utils/fonts.js.map +0 -1
  279. package/dist/utils/idle.d.ts +0 -23
  280. package/dist/utils/idle.d.ts.map +0 -1
  281. package/dist/utils/idle.js.map +0 -1
  282. package/dist/utils/images.d.ts +0 -21
  283. package/dist/utils/images.d.ts.map +0 -1
  284. package/dist/utils/images.js.map +0 -1
  285. package/dist/utils/jobs.d.ts +0 -44
  286. package/dist/utils/jobs.d.ts.map +0 -1
  287. package/dist/utils/jobs.js.map +0 -1
  288. package/dist/utils/lifecycle.d.ts +0 -29
  289. package/dist/utils/lifecycle.d.ts.map +0 -1
  290. package/dist/utils/lifecycle.js.map +0 -1
  291. package/dist/utils/media.d.ts +0 -272
  292. package/dist/utils/media.d.ts.map +0 -1
  293. package/dist/utils/media.js.map +0 -1
  294. package/dist/utils/monitors.d.ts +0 -47
  295. package/dist/utils/monitors.d.ts.map +0 -1
  296. package/dist/utils/monitors.js.map +0 -1
  297. package/dist/utils/ocr.d.ts +0 -50
  298. package/dist/utils/ocr.d.ts.map +0 -1
  299. package/dist/utils/ocr.js.map +0 -1
  300. package/dist/utils/paths.d.ts +0 -28
  301. package/dist/utils/paths.d.ts.map +0 -1
  302. package/dist/utils/paths.js.map +0 -1
  303. package/dist/utils/pipeline.d.ts +0 -69
  304. package/dist/utils/pipeline.d.ts.map +0 -1
  305. package/dist/utils/pipeline.js.map +0 -1
  306. package/dist/utils/player.d.ts +0 -30
  307. package/dist/utils/player.d.ts.map +0 -1
  308. package/dist/utils/player.js.map +0 -1
  309. package/dist/utils/produce.d.ts +0 -126
  310. package/dist/utils/produce.d.ts.map +0 -1
  311. package/dist/utils/produce.js.map +0 -1
  312. package/dist/utils/resolveTarget.d.ts +0 -32
  313. package/dist/utils/resolveTarget.d.ts.map +0 -1
  314. package/dist/utils/resolveTarget.js.map +0 -1
  315. package/dist/utils/retention.d.ts +0 -10
  316. package/dist/utils/retention.d.ts.map +0 -1
  317. package/dist/utils/retention.js.map +0 -1
  318. package/dist/utils/sessions.d.ts +0 -154
  319. package/dist/utils/sessions.d.ts.map +0 -1
  320. package/dist/utils/sessions.js.map +0 -1
  321. package/dist/utils/sheet.d.ts +0 -26
  322. package/dist/utils/sheet.d.ts.map +0 -1
  323. package/dist/utils/sheet.js.map +0 -1
  324. package/dist/utils/still.d.ts +0 -7
  325. package/dist/utils/still.d.ts.map +0 -1
  326. package/dist/utils/still.js.map +0 -1
  327. package/dist/utils/targets.d.ts +0 -113
  328. package/dist/utils/targets.d.ts.map +0 -1
  329. package/dist/utils/targets.js.map +0 -1
  330. package/dist/utils/validate.d.ts +0 -15
  331. package/dist/utils/validate.d.ts.map +0 -1
  332. package/dist/utils/validate.js.map +0 -1
  333. package/dist/utils/wgc.d.ts +0 -46
  334. package/dist/utils/wgc.d.ts.map +0 -1
  335. package/dist/utils/wgc.js.map +0 -1
  336. package/dist/utils/windows.d.ts +0 -94
  337. package/dist/utils/windows.d.ts.map +0 -1
  338. package/dist/utils/windows.js.map +0 -1
  339. package/dist/utils/zoom.d.ts +0 -95
  340. package/dist/utils/zoom.d.ts.map +0 -1
  341. package/dist/utils/zoom.js.map +0 -1
  342. package/dist/wgcRecorder.d.ts +0 -2
  343. package/dist/wgcRecorder.d.ts.map +0 -1
  344. package/dist/wgcRecorder.js.map +0 -1
@@ -1,24 +1,5 @@
1
- /**
2
- * Monitor geometry discovery.
3
- *
4
- * gdigrab has no native "capture monitor N" selector: you capture the whole
5
- * virtual desktop and crop to a monitor's bounds with -offset_x / -offset_y /
6
- * -video_size. To do that correctly on a multi-monitor setup (for example a
7
- * 4480x1440 dual-monitor desktop where the second display starts at x=2560),
8
- * we need each monitor's pixel bounds. On Windows those come from
9
- * System.Windows.Forms.Screen.AllScreens via PowerShell. The enumeration must be
10
- * per-monitor-DPI-aware, or Screen.Bounds returns LOGICAL (DPI-scaled)
11
- * coordinates while gdigrab works in PHYSICAL pixels - on a scaled display that
12
- * makes monitor:N capture a cropped top-left slice (e.g. 1280x800 of a 1920x1200
13
- * screen at 150%). So the shim sets DPI awareness before reading bounds, exactly
14
- * as the window-bounds shim in windows.ts does.
15
- *
16
- * `parseMonitors` is pure so the offset math is unit-tested without Windows.
17
- */
18
1
  import { execFile } from "node:child_process";
19
2
  import { ScreencastError } from "./errors.js";
20
- /** Normalize raw PowerShell screen objects into ordered Monitor records.
21
- * Primary monitor is sorted first so monitor:0 is the primary display. */
22
3
  export function parseMonitors(raw) {
23
4
  const arr = Array.isArray(raw) ? raw : raw ? [raw] : [];
24
5
  const screens = arr.map((s) => ({
@@ -27,6 +8,7 @@ export function parseMonitors(raw) {
27
8
  width: Number(s.Width ?? 0),
28
9
  height: Number(s.Height ?? 0),
29
10
  primary: Boolean(s.Primary),
11
+ ...(Number(s.Dpi) > 0 ? { dpi: Number(s.Dpi) } : {}),
30
12
  }));
31
13
  screens.sort((a, b) => {
32
14
  if (a.primary !== b.primary)
@@ -37,43 +19,30 @@ export function parseMonitors(raw) {
37
19
  });
38
20
  return screens.map((s, index) => ({ index, ...s }));
39
21
  }
40
- // Set per-monitor-DPI-awareness-v2 (-4) before reading Screen.AllScreens so the
41
- // bounds are PHYSICAL pixels (matching gdigrab), not DPI-scaled logical ones.
42
- // Passed base64 (EncodedCommand) so the C# shim needs no quoting through argv.
43
22
  const PS_SCRIPT = `
44
23
  Add-Type @"
45
24
  using System;using System.Runtime.InteropServices;
46
- public class DpiShim{ [DllImport("user32.dll")] public static extern IntPtr SetProcessDpiAwarenessContext(IntPtr v); }
25
+ public class DpiShim{ [DllImport("user32.dll")] public static extern IntPtr SetProcessDpiAwarenessContext(IntPtr v);
26
+ public struct PT{public int X,Y;}
27
+ [DllImport("user32.dll")] public static extern IntPtr MonitorFromPoint(PT p,uint f);
28
+ [DllImport("shcore.dll")] public static extern int GetDpiForMonitor(IntPtr m,int t,out uint x,out uint y);
29
+ 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;} }
47
30
  "@
48
31
  try{[void][DpiShim]::SetProcessDpiAwarenessContext([IntPtr](-4))}catch{}
49
32
  Add-Type -AssemblyName System.Windows.Forms
50
33
  [System.Windows.Forms.Screen]::AllScreens | ForEach-Object {
51
- [pscustomobject]@{ X=$_.Bounds.X; Y=$_.Bounds.Y; Width=$_.Bounds.Width; Height=$_.Bounds.Height; Primary=$_.Primary }
34
+ [pscustomobject]@{ X=$_.Bounds.X; Y=$_.Bounds.Y; Width=$_.Bounds.Width; Height=$_.Bounds.Height; Primary=$_.Primary; Dpi=[DpiShim]::Dpi($_.Bounds.X,$_.Bounds.Y) }
52
35
  } | ConvertTo-Json -Compress
53
36
  `;
54
- /** How long a monitor layout is reused before it is queried again (#88). The
55
- * layout changes only when a display is plugged in or rearranged, while an
56
- * agent's screenshot loop can call this every few seconds. */
57
37
  export const MONITOR_CACHE_MS = 5_000;
58
38
  let cache = null;
59
- /** Make PowerShell write UTF-8. By default it writes the console's OEM code
60
- * page (e.g. 437), which turns "é" into a replacement character and maps
61
- * symbols such as "•" and "→" to raw control bytes (0x07, 0x1A): window
62
- * titles stopped matching and OCR output stopped parsing as JSON. */
63
39
  export const PS_UTF8_PREAMBLE = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8\n";
64
- /** Default limit for one enumeration script (monitors, windows) (#183). */
65
40
  export const PS_TIMEOUT_MS = 20_000;
66
- /** Overrides every PowerShell helper's limit, in ms. */
67
41
  export const PS_TIMEOUT_ENV = "SCREENCAST_PS_TIMEOUT_MS";
68
- /** The env override when it is a positive integer, else `fallback`. */
69
42
  export function psTimeoutMs(fallback, env = process.env) {
70
43
  const override = Number(env[PS_TIMEOUT_ENV]);
71
44
  return Number.isInteger(override) && override > 0 ? override : fallback;
72
45
  }
73
- /** Run a base64-encoded PowerShell script without blocking the event loop and
74
- * return its stdout (UTF-8). Shared by window enumeration and OCR. A script
75
- * that runs past the timeout is killed, so a stuck WinRT or user32 call fails
76
- * the tool instead of hanging it (#183). */
77
46
  export function runPowerShell(script, what, opts = {}) {
78
47
  const encoded = Buffer.from(PS_UTF8_PREAMBLE + script, "utf16le").toString("base64");
79
48
  const timeout = opts.timeoutMs ?? psTimeoutMs(PS_TIMEOUT_MS);
@@ -102,9 +71,6 @@ async function queryMonitors() {
102
71
  throw new ScreencastError(`Could not parse monitor geometry: ${err.message}`);
103
72
  }
104
73
  }
105
- /** Query live monitor geometry on Windows, reusing a result from the last
106
- * MONITOR_CACHE_MS. Concurrent callers share one query; a failure is not
107
- * cached. Throws on non-Windows or failure. */
108
74
  export function getMonitors(now = Date.now()) {
109
75
  if (process.platform !== "win32") {
110
76
  return Promise.reject(new ScreencastError("Monitor enumeration is implemented for Windows (gdigrab) only."));
@@ -119,8 +85,6 @@ export function getMonitors(now = Date.now()) {
119
85
  });
120
86
  return entry.monitors;
121
87
  }
122
- /** Drop the cached layout (tests, or after a capture failure). */
123
88
  export function clearMonitorCache() {
124
89
  cache = null;
125
90
  }
126
- //# sourceMappingURL=monitors.js.map
package/dist/utils/ocr.js CHANGED
@@ -1,30 +1,13 @@
1
- /**
2
- * On-screen text recognition with the OCR engine built into Windows
3
- * (Windows.Media.Ocr), so no model or package is installed (#117).
4
- *
5
- * The engine misses small text and, notably, drops ALL_CAPS words joined by
6
- * underscores (an env-var name like OPENAI_API_KEY, and anything glued to it
7
- * with `=`) at ordinary sizes. Measured on 18 px UI text: missing at 1x-3x,
8
- * recovered at 4x. So recognition runs two passes (2x and 4x upscales) in one
9
- * PowerShell process and merges them, and matching tolerates the engine's
10
- * usual confusions (`_` read as `-`, `I` as `l`).
11
- *
12
- * The PowerShell/WinRT call is impure; parsing, merging, and matching are pure.
13
- */
1
+ import { runInNewContext } from "node:vm";
14
2
  import { ScreencastError } from "./errors.js";
15
3
  import { runPowerShell, psTimeoutMs } from "./monitors.js";
16
- /** Upscale factors for the two recognition passes. */
17
4
  export const OCR_SCALES = [2, 4];
18
- /** Windows.Media.Ocr refuses images larger than this on either side. */
19
5
  export const OCR_MAX_DIMENSION = 10_000;
20
- /** Recognise every image in `paths` (already upscaled by `scales[i]`) in one
21
- * PowerShell run. Paths travel base64-encoded, so no quoting is involved. */
22
6
  export async function recognize(paths, scales) {
23
7
  if (process.platform !== "win32") {
24
8
  throw new ScreencastError("find_text uses the Windows OCR engine and runs on Windows only.");
25
9
  }
26
10
  const list = Buffer.from(JSON.stringify(paths), "utf8").toString("base64");
27
- // The limit grows with the image count, so a whole-clip scan gets the time it needs.
28
11
  const stdout = await runPowerShell(PS_OCR.replace("__PATHS__", list), "text (OCR)", {
29
12
  timeoutMs: psTimeoutMs(OCR_TIMEOUT_MS + Math.max(0, paths.length - 2) * OCR_PER_IMAGE_MS),
30
13
  });
@@ -38,8 +21,6 @@ export async function recognize(paths, scales) {
38
21
  const passes = Array.isArray(raw) ? raw : [raw];
39
22
  return passes.map((p, i) => parseOcrPass(p, scales[i] ?? 1));
40
23
  }
41
- /** Turn one pass's JSON into lines in ORIGINAL image pixels (dividing out the
42
- * upscale), each with a bounding box around its words. Pure. */
43
24
  export function parseOcrPass(raw, scale) {
44
25
  const pass = (raw ?? {});
45
26
  if (pass.error) {
@@ -77,34 +58,62 @@ function overlapRatio(a, b) {
77
58
  return 0;
78
59
  return (w * h) / Math.min(a.width * a.height, b.width * b.height);
79
60
  }
80
- /** Merge recognition passes: start from the first, then add lines a later pass
81
- * found that overlap nothing already kept; where they overlap, keep the
82
- * longer reading. Result is in reading order. Pure. */
83
61
  export function mergePasses(passes) {
84
62
  const kept = [];
85
63
  for (const pass of passes) {
86
64
  for (const line of pass) {
87
65
  const i = kept.findIndex((k) => overlapRatio(k, line) > 0.5);
88
- if (i === -1)
66
+ const match = kept[i];
67
+ if (!match)
89
68
  kept.push(line);
90
- else if (line.text.length > kept[i].text.length)
69
+ else if (line.text.length > match.text.length)
91
70
  kept[i] = line;
92
71
  }
93
72
  }
94
73
  return kept.sort((a, b) => a.y - b.y || a.x - b.x);
95
74
  }
96
- /** Fold the engine's usual confusions so a query still matches a misread:
97
- * case, `-`/`_`/space, `l`/`I`/`1`/`|`, and `O`/`0`. Pure. */
98
75
  export function normalizeForMatch(s) {
99
76
  return s.toLowerCase().replace(/[-_\s]+/g, "_").replace(/[l1|]/g, "i").replace(/0/g, "o");
100
77
  }
101
- /** Find `query` (plain text, or a regular expression when `regex`) in the
102
- * lines. Plain queries also match through normalizeForMatch. Each hit is
103
- * boxed around the words it spans. Pure. */
78
+ export const MAX_QUERY_LENGTH = 500;
79
+ export const REGEX_BUDGET_MS = 1_000;
80
+ const REGEX_SCAN = `JSON.stringify(texts.map((text) => {
81
+ const re = new RegExp(query, "gi");
82
+ const seen = new Set();
83
+ const ranges = [];
84
+ for (const variant of [text, text.replace(/-/g, "_"), text.replace(/_/g, "-")]) {
85
+ for (const m of variant.matchAll(re)) {
86
+ const key = m.index + ":" + m[0].length;
87
+ if (m[0].length > 0 && !seen.has(key)) {
88
+ seen.add(key);
89
+ ranges.push([m.index, m.index + m[0].length]);
90
+ }
91
+ }
92
+ }
93
+ return ranges;
94
+ }))`;
95
+ export function regexRanges(texts, query, budgetMs = REGEX_BUDGET_MS) {
96
+ try {
97
+ new RegExp(query, "gi");
98
+ }
99
+ catch (err) {
100
+ throw new ScreencastError(`Invalid regex: ${err.message}`);
101
+ }
102
+ try {
103
+ return JSON.parse(runInNewContext(REGEX_SCAN, { texts, query }, { timeout: budgetMs }));
104
+ }
105
+ catch (err) {
106
+ if (err.code === "ERR_SCRIPT_EXECUTION_TIMEOUT") {
107
+ 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.");
108
+ }
109
+ throw err;
110
+ }
111
+ }
104
112
  export function findMatches(lines, query, regex = false) {
105
- const out = [];
106
- for (const line of lines) {
107
- // Rebuild the line from its words so character offsets map to words.
113
+ if (query.length > MAX_QUERY_LENGTH) {
114
+ throw new ScreencastError(`The query is ${query.length} characters; at most ${MAX_QUERY_LENGTH} are allowed.`);
115
+ }
116
+ const rebuilt = lines.map((line) => {
108
117
  const spans = [];
109
118
  let text = "";
110
119
  for (const w of line.words) {
@@ -113,35 +122,19 @@ export function findMatches(lines, query, regex = false) {
113
122
  spans.push({ start: text.length, end: text.length + w.text.length, word: w });
114
123
  text += w.text;
115
124
  }
116
- const ranges = [];
117
- if (regex) {
118
- let re;
119
- try {
120
- re = new RegExp(query, "gi");
121
- }
122
- catch (err) {
123
- throw new ScreencastError(`Invalid regex: ${err.message}`);
124
- }
125
- // Also try the text with `_` and `-` swapped either way: the engine
126
- // often reads one as the other, and a secret pattern like `ghp_` must
127
- // still match `ghp-` (#236). Same length, so offsets map to words as is.
128
- const seen = new Set();
129
- for (const variant of [text, text.replace(/-/g, "_"), text.replace(/_/g, "-")]) {
130
- for (const m of variant.matchAll(re)) {
131
- const key = `${m.index}:${m[0].length}`;
132
- if (m[0].length > 0 && !seen.has(key)) {
133
- seen.add(key);
134
- ranges.push([m.index, m.index + m[0].length]);
135
- }
136
- }
137
- }
125
+ return { line, spans, text };
126
+ });
127
+ const regexHits = regex ? regexRanges(rebuilt.map((r) => r.text), query) : null;
128
+ const out = [];
129
+ rebuilt.forEach(({ line, spans }, i) => {
130
+ let ranges = [];
131
+ if (regexHits) {
132
+ ranges = regexHits[i] ?? [];
138
133
  }
139
134
  else {
140
- // normalizeForMatch keeps string length except for collapsing runs of
141
- // separators, so search the normalized text and map back word by word.
142
135
  const needle = normalizeForMatch(query);
143
136
  if (!needle)
144
- continue;
137
+ return;
145
138
  const hay = spans.map((s) => normalizeForMatch(s.word.text)).join("_");
146
139
  let from = 0;
147
140
  for (let at = hay.indexOf(needle, from); at !== -1; at = hay.indexOf(needle, from)) {
@@ -157,11 +150,9 @@ export function findMatches(lines, query, regex = false) {
157
150
  words.forEach((w) => boxed.add(w));
158
151
  out.push({ text: words.map((w) => w.text).join(" "), line: line.text, ...unionRect(words) });
159
152
  }
160
- }
153
+ });
161
154
  return out;
162
155
  }
163
- /** Map a range in the `_`-joined normalized word string back to a range in
164
- * the space-joined text (both join words with one character). */
165
156
  function normalizedRangeToText(spans, start, end) {
166
157
  let pos = 0;
167
158
  let textStart = -1;
@@ -176,9 +167,8 @@ function normalizedRangeToText(spans, start, end) {
176
167
  }
177
168
  pos += len + 1;
178
169
  }
179
- return [textStart === -1 ? 0 : textStart, textEnd === -1 ? spans[spans.length - 1].end : textEnd];
170
+ return [textStart === -1 ? 0 : textStart, textEnd === -1 ? (spans.at(-1)?.end ?? 0) : textEnd];
180
171
  }
181
- /** Padded rectangles for redact_region, clamped to the frame. Pure. */
182
172
  export function redactionRects(matches, frame, pad = 4) {
183
173
  return matches.map((m) => {
184
174
  const x = Math.max(0, m.x - pad);
@@ -191,21 +181,14 @@ export function redactionRects(matches, frame, pad = 4) {
191
181
  };
192
182
  });
193
183
  }
194
- /** The scales actually used for an image of this size: each OCR_SCALES entry,
195
- * capped so the upscaled image stays within the engine's limit. Pure. */
196
184
  export function passScales(width, height) {
197
185
  const cap = OCR_MAX_DIMENSION / Math.max(width, height);
198
186
  const scales = OCR_SCALES.map((s) => Math.min(s, Math.floor(cap * 100) / 100)).filter((s) => s >= 1);
199
187
  return [...new Set(scales.length ? scales : [Math.min(1, cap)])];
200
188
  }
201
- /** Limit for one OCR run (all passes of all images) (#183). */
202
189
  export const OCR_TIMEOUT_MS = 60_000;
203
- /** Extra time per image beyond the first two (a whole-clip scan, #204). */
204
190
  export const OCR_PER_IMAGE_MS = 5_000;
205
- /** Limit for one WinRT call inside it (open, decode, recognise). */
206
191
  export const OCR_STEP_TIMEOUT_MS = 20_000;
207
- // Windows PowerShell 5.1 + WinRT: decode each image, recognise it with the
208
- // user's profile languages, and print one JSON object per image.
209
192
  const PS_OCR = `
210
193
  $ErrorActionPreference = 'Stop'
211
194
  Add-Type -AssemblyName System.Runtime.WindowsRuntime
@@ -232,4 +215,3 @@ $out = foreach ($p in $paths) {
232
215
  }
233
216
  ConvertTo-Json -InputObject @($out) -Depth 6 -Compress
234
217
  `;
235
- //# sourceMappingURL=ocr.js.map
@@ -0,0 +1,77 @@
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
+ export async function readFrames(sources, work, signal) {
9
+ const sized = await Promise.all(sources.map(async (source) => {
10
+ const { width, height } = await probeMedia(source);
11
+ if (!width || !height)
12
+ throw new ScreencastError("Could not read the image size.");
13
+ return { source, width, height };
14
+ }));
15
+ const passes = [];
16
+ const passScaleList = [];
17
+ const owner = [];
18
+ for (const [f, { source, width, height }] of sized.entries()) {
19
+ for (const [i, scale] of passScales(width, height).entries()) {
20
+ const out = join(work, `pass${f}-${i}.png`);
21
+ await runFfmpeg(["-y", "-v", "error", "-i", source, "-vf", `scale=iw*${scale}:ih*${scale}:flags=lanczos`, out], 60_000, {
22
+ signal,
23
+ });
24
+ passes.push(out);
25
+ passScaleList.push(scale);
26
+ owner.push(f);
27
+ }
28
+ }
29
+ const results = await recognize(passes, passScaleList);
30
+ return sized.map(({ width, height }, f) => ({
31
+ lines: mergePasses(results.filter((_r, i) => owner[i] === f)),
32
+ width,
33
+ height,
34
+ }));
35
+ }
36
+ export async function scanVideoFrames(input, opts, work, signal) {
37
+ const info = await probeMedia(input);
38
+ const full = info.videoDurationSec ?? info.durationSec;
39
+ const length = opts.range ? opts.range.duration : full;
40
+ const plan = planFpsSampling(length, 1 / opts.everySec, opts.maxFrames);
41
+ await runFfmpeg(buildSampleByFpsArgs(input, plan.fps, join(work, "scan_%05d.png"), opts.maxFrames, false, opts.range), jobTimeoutMs(info.durationSec), { signal });
42
+ const paths = readdirSync(work).filter((f) => f.startsWith("scan_")).sort().map((f) => join(work, f));
43
+ if (paths.length === 0)
44
+ throw new ScreencastError("Could not read any frames from the video.");
45
+ const step = 1 / plan.fps;
46
+ const timeAt = (i) => Math.round(i * step * 1000) / 1000;
47
+ const end = length ?? timeAt(paths.length - 1) + step;
48
+ const read = await readFrames(paths, work, signal);
49
+ return {
50
+ frames: read.map((frame, i) => ({ ...frame, t: timeAt(i), path: paths[i] ?? "" })),
51
+ step,
52
+ end,
53
+ clamped: plan.clamped,
54
+ };
55
+ }
56
+ export function sampleWindow(t, step, end) {
57
+ return {
58
+ start: Math.max(0, Math.round((t - step) * 1000) / 1000),
59
+ end: Math.min(end, Math.round((t + step) * 1000) / 1000),
60
+ };
61
+ }
62
+ export function scanMatches(scan, query, regex, scope = "match") {
63
+ const matches = [];
64
+ const redactRegions = [];
65
+ for (const frame of scan.frames) {
66
+ const hits = findMatches(frame.lines, query, regex);
67
+ const window = sampleWindow(frame.t, scan.step, scan.end);
68
+ const boxes = scope === "line"
69
+ ? [...new Set(hits.map((h) => frame.lines.find((l) => l.text === h.line) ?? h))]
70
+ : hits;
71
+ for (const hit of hits)
72
+ matches.push({ t: frame.t, ...hit });
73
+ for (const rect of redactionRects(boxes, frame))
74
+ redactRegions.push({ ...rect, ...window });
75
+ }
76
+ return { matches, redactRegions };
77
+ }
@@ -1,15 +1,6 @@
1
- /**
2
- * Output location and filename helpers.
3
- *
4
- * By default everything the server writes lands under SCREENCAST_HOME
5
- * (default: <homedir>/.screencast-mcp), NOT the current working directory, so
6
- * captures never accidentally land inside a checked-out repo. Callers may still
7
- * pass an absolute `output` path per call. The repo .gitignore is a second line
8
- * of defence for the case where output is pointed back into the project.
9
- */
10
1
  import { homedir, tmpdir } from "node:os";
11
- import { join, isAbsolute, resolve } from "node:path";
12
- import { mkdirSync, existsSync } from "node:fs";
2
+ import { basename, delimiter, dirname, join, isAbsolute, relative, resolve, sep } from "node:path";
3
+ import { mkdirSync, existsSync, realpathSync } from "node:fs";
13
4
  import { ScreencastError } from "./errors.js";
14
5
  export function homeRoot() {
15
6
  const override = process.env.SCREENCAST_HOME;
@@ -22,50 +13,90 @@ export function subdir(name) {
22
13
  mkdirSync(dir, { recursive: true });
23
14
  return dir;
24
15
  }
25
- /** The on-disk session registry path. */
26
16
  export function registryPath() {
27
17
  const dir = homeRoot();
28
18
  mkdirSync(dir, { recursive: true });
29
19
  return join(dir, "sessions.json");
30
20
  }
31
- /** A compact UTC timestamp like 20260615-192430-880. */
32
21
  export function stamp(date = new Date()) {
33
22
  const iso = date.toISOString().replace(/[-:T]/g, "").replace(/\..+/, "");
34
23
  const ms = String(date.getMilliseconds()).padStart(3, "0");
35
24
  return `${iso.slice(0, 8)}-${iso.slice(8, 14)}-${ms}`;
36
25
  }
37
- /** Short random suffix to make ids/filenames unique within the same ms. */
38
26
  export function rand(n = 4) {
39
27
  return Math.random().toString(36).slice(2, 2 + n);
40
28
  }
41
- /** An ffmpeg image-sequence pattern (`name` holds the `%0Nd`) inside `dir`. A
42
- * `%` in the directory itself is escaped as `%%` so ffmpeg reads it literally
43
- * (#238). */
44
29
  export function sequencePattern(dir, name) {
45
30
  return join(dir.replace(/%/g, "%%"), name);
46
31
  }
47
32
  const STILL_IMAGE = /\.(png|jpe?g|bmp|tiff?)$/i;
48
- /** The output args for a single still image. ffmpeg's image2 muxer reads a `%`
49
- * in the file name as a sequence pattern (`b%dx.png` becomes `b1x.png`), so
50
- * `-update 1` keeps the name literal and the returned path real (#238). */
51
33
  export function stillOutput(output) {
52
34
  return STILL_IMAGE.test(output) ? ["-update", "1", output] : [output];
53
35
  }
54
- /** A unique scratch path in the OS temp dir for short-lived working files (a
55
- * concat list, a drawtext textfile). Kept out of SCREENCAST_HOME/edits so a hard
56
- * crash before cleanup leaves it where the OS reaps it, not next to outputs. */
57
36
  export function tempPath(suffix = "") {
58
37
  return join(tmpdir(), `screencast-${stamp()}-${rand()}${suffix}`);
59
38
  }
60
- /** Resolve a caller-supplied output path, or build a default under a subdir.
61
- *
62
- * A caller-supplied path that already exists is refused unless the caller
63
- * passed overwrite: true - every ffmpeg builder runs with -y, so this is the
64
- * one place that stands between a reused path and a silently clobbered file.
65
- * Auto-generated default names are unique and skip the check. */
39
+ export const ALLOWED_DIRS_ENV = "SCREENCAST_ALLOWED_DIRS";
40
+ export function envAllowedDirs(env = process.env) {
41
+ const raw = env[ALLOWED_DIRS_ENV];
42
+ if (!raw)
43
+ return [];
44
+ return raw
45
+ .split(delimiter)
46
+ .map((d) => d.trim())
47
+ .filter((d) => d.length > 0)
48
+ .map((d) => resolve(d));
49
+ }
50
+ let clientRoots = null;
51
+ export function setClientRoots(dirs) {
52
+ clientRoots = dirs === null || dirs === "pending" ? dirs : dirs.map((d) => resolve(d));
53
+ }
54
+ export function getClientRoots() {
55
+ return Array.isArray(clientRoots) ? clientRoots : null;
56
+ }
57
+ export function allowedOutputDirs(env = process.env) {
58
+ const fromEnv = envAllowedDirs(env);
59
+ if (clientRoots === null && fromEnv.length === 0)
60
+ return null;
61
+ const roots = Array.isArray(clientRoots) ? clientRoots : [];
62
+ return [resolve(homeRoot()), ...fromEnv, ...roots];
63
+ }
64
+ function realish(path) {
65
+ const tail = [];
66
+ let cur = resolve(path);
67
+ for (;;) {
68
+ try {
69
+ return join(realpathSync.native(cur), ...tail.reverse());
70
+ }
71
+ catch {
72
+ const parent = dirname(cur);
73
+ if (parent === cur)
74
+ return resolve(path);
75
+ tail.push(basename(cur));
76
+ cur = parent;
77
+ }
78
+ }
79
+ }
80
+ export function isWithin(path, dir) {
81
+ const rel = relative(realish(dir), realish(path));
82
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
83
+ }
84
+ export function assertOutputAllowed(path) {
85
+ if (clientRoots === "pending" && envAllowedDirs().length === 0 && !isWithin(path, homeRoot())) {
86
+ throw new ScreencastError(`Output ${path} is outside SCREENCAST_HOME and the client's workspace roots have not loaded yet. ` +
87
+ "Retry the call in a moment, or omit the path to write under SCREENCAST_HOME.");
88
+ }
89
+ const allowed = allowedOutputDirs();
90
+ if (allowed === null || allowed.some((dir) => isWithin(path, dir)))
91
+ return;
92
+ throw new ScreencastError(`Output ${path} is outside the allowed directories: ${allowed.join(", ")}. ` +
93
+ `Write under one of them (a relative path lands in SCREENCAST_HOME), or add the folder to ` +
94
+ `${ALLOWED_DIRS_ENV} or the client's workspace roots.`);
95
+ }
66
96
  export function resolveOutput(provided, defaultDir, defaultName, overwrite = false) {
67
97
  if (provided && provided.trim().length > 0) {
68
- const path = isAbsolute(provided) ? provided : resolve(provided);
98
+ const path = resolve(defaultDir, provided);
99
+ assertOutputAllowed(path);
69
100
  if (!overwrite && existsSync(path)) {
70
101
  throw new ScreencastError(`Output already exists: ${path}. Pass overwrite: true to replace it, ` +
71
102
  `or choose a different path.`);
@@ -74,4 +105,10 @@ export function resolveOutput(provided, defaultDir, defaultName, overwrite = fal
74
105
  }
75
106
  return join(defaultDir, defaultName);
76
107
  }
77
- //# sourceMappingURL=paths.js.map
108
+ export function resolveOutputDir(provided, defaultParent) {
109
+ if (!provided || provided.trim().length === 0)
110
+ return undefined;
111
+ const dir = resolve(defaultParent, provided);
112
+ assertOutputAllowed(dir);
113
+ return dir;
114
+ }
@@ -1,29 +1,14 @@
1
- /**
2
- * pipeline (#125): run a chain of edits as ONE ffmpeg process instead of one
3
- * re-encode (and one intermediate file) per tool call.
4
- *
5
- * Each step contributes filter-graph steps over the current video label, built
6
- * by the same helpers as the standalone tools, so a pipeline step behaves like
7
- * its tool. Frame size, fps, and duration are tracked through the chain so each
8
- * step is validated against the frame it actually receives, and times inside a
9
- * step (callout from/to, redact start/end, zoom keyframes) are on the timeline
10
- * as it is at that step (after an earlier trim or speed change).
11
- *
12
- * A leading trim becomes an input seek, the cheapest form. export_preset and
13
- * export_gif can only be the last step: export_preset sets the encoder; an
14
- * export_gif tail renders the chain to a temporary high-quality mp4 first and
15
- * then runs the size-budget ladder, so it is two stages. All of this is pure.
16
- */
17
1
  import { ScreencastError } from "./errors.js";
18
2
  import { atempoChain, cropFilter, redactSteps, scaleFilter, scaledSize } from "./media.js";
19
3
  import { calloutSteps } from "./callout.js";
20
4
  import { ASPECT_DIMS, exportPresetParts, reframeFilter } from "./produce.js";
21
5
  import { keyframesToViews, zoomFilter, DEFAULT_TRANSITION_SEC } from "./zoom.js";
22
6
  import { resolveQuality } from "./targets.js";
7
+ import { backdropSteps } from "./backdrop.js";
8
+ import { groupBadges, keystrokeSteps, retimeBadges } from "./keystrokes.js";
23
9
  export const MAX_PIPELINE_STEPS = 30;
24
10
  const r3 = (v) => Math.round(v * 1000) / 1000;
25
- /** Plan the fused command. `assets[i]` holds the files callout step i needs. */
26
- export function planPipeline(input, output, steps, src, assets = {}, quality = "standard") {
11
+ export function planPipeline(input, output, steps, src, assets = {}, quality = "standard", opts = {}) {
27
12
  if (steps.length === 0)
28
13
  throw new ScreencastError("Give at least one step.");
29
14
  if (steps.length > MAX_PIPELINE_STEPS)
@@ -33,8 +18,6 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
33
18
  throw new ScreencastError(`${s.op} must be the last step (it is step ${i + 1} of ${steps.length}).`);
34
19
  }
35
20
  });
36
- // A zoom moves the content within the frame over time, so a fixed redact
37
- // box after it would slide off the secret (#204).
38
21
  const zoomAt = steps.findIndex((s) => s.op === "zoom");
39
22
  const lateRedact = zoomAt === -1 ? -1 : steps.findIndex((s, i) => i > zoomAt && s.op === "redact");
40
23
  if (lateRedact !== -1) {
@@ -56,6 +39,7 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
56
39
  let encode = null;
57
40
  let gif;
58
41
  const summary = [];
42
+ const timeOps = [];
59
43
  const trimRange = (s, at) => {
60
44
  if (!Number.isFinite(s.start) || s.start < 0)
61
45
  throw new ScreencastError(`step ${at}: trim start must be a non-negative number.`);
@@ -92,6 +76,7 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
92
76
  }
93
77
  audioReencode = true;
94
78
  dur = end - start;
79
+ timeOps.push({ op: "trim", start, end });
95
80
  break;
96
81
  }
97
82
  case "crop":
@@ -115,6 +100,7 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
115
100
  audioReencode = true;
116
101
  if (dur !== null)
117
102
  dur /= s.factor;
103
+ timeOps.push({ op: "speed", factor: s.factor });
118
104
  summary.push(`speed x${s.factor}`);
119
105
  break;
120
106
  case "redact": {
@@ -152,6 +138,33 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
152
138
  summary.push(`zoom ${s.keyframes.length} keyframe(s)`);
153
139
  break;
154
140
  }
141
+ case "backdrop": {
142
+ const { op: _op, ...bo } = s;
143
+ const { steps: st, out: o, extraInputs: ex, layout } = backdropSteps(bo, { width: W, height: H }, cur, nextInput, tag);
144
+ graph.push(...st);
145
+ extraInputs.push(...ex);
146
+ nextInput += ex.length / 2;
147
+ cur = o;
148
+ W = layout.canvasW;
149
+ H = layout.canvasH;
150
+ summary.push(`backdrop to ${W}x${H}`);
151
+ break;
152
+ }
153
+ case "keystroke_overlay": {
154
+ const k = opts.keystrokes?.[i];
155
+ if (!k)
156
+ throw new ScreencastError(`Internal: missing keystroke badges for step ${at}.`);
157
+ const badges = retimeBadges(k.badges, timeOps);
158
+ if (badges.length === 0) {
159
+ summary.push("keystroke_overlay: no badges in this part of the video");
160
+ break;
161
+ }
162
+ const { steps: st, out: o } = keystrokeSteps(groupBadges(badges), k, s, { height: H }, cur, tag);
163
+ graph.push(...st);
164
+ cur = o;
165
+ summary.push(`keystroke_overlay ${badges.length} badge(s)`);
166
+ break;
167
+ }
155
168
  case "export_preset": {
156
169
  const p = exportPresetParts(s.platform, s.fit ?? "pad", tag);
157
170
  chain(p.vf);
@@ -174,6 +187,9 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
174
187
  }
175
188
  });
176
189
  const args = ["-y", ...inputArgs, "-i", input, ...extraInputs];
190
+ const chaptersInput = opts.chaptersFile ? args.filter((a) => a === "-i").length : -1;
191
+ if (opts.chaptersFile)
192
+ args.push("-f", "ffmetadata", "-i", opts.chaptersFile);
177
193
  if (graph.length > 0) {
178
194
  if (src.hasAudio && audio.length > 0)
179
195
  graph.push(`[0:a]${audio.join(",")}[aout]`);
@@ -184,20 +200,18 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
184
200
  }
185
201
  if (src.hasAudio)
186
202
  args.push("-map", audio.length > 0 && graph.length > 0 ? "[aout]" : "0:a");
187
- // Assigned inside the forEach above, which TypeScript does not track.
188
203
  const finalEncode = encode;
189
204
  if (finalEncode) {
190
205
  args.push(...finalEncode);
191
206
  }
192
207
  else {
193
- // An export_gif tail reads this file once, so give it more quality; a
194
- // redaction gets it too, like redact_region, so its edges stay crisp (#204).
195
208
  args.push(...resolveQuality(gif || redacts ? "high" : quality));
196
209
  if (src.hasAudio)
197
210
  args.push(...(audioReencode ? ["-c:a", "aac", "-b:a", "160k"] : ["-c:a", "copy"]));
198
211
  args.push("-movflags", "+faststart");
199
212
  }
213
+ if (chaptersInput !== -1)
214
+ args.push("-map_chapters", String(chaptersInput));
200
215
  args.push(output);
201
- return { args, width: W, height: H, fps, durationSec: dur === null ? null : r3(dur), gif, summary };
216
+ return { args, width: W, height: H, fps, durationSec: dur === null ? null : r3(dur), gif, summary, timeOps };
202
217
  }
203
- //# sourceMappingURL=pipeline.js.map