@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,33 +1,15 @@
1
- /**
2
- * Bundled font resolution and filtergraph path escaping.
3
- *
4
- * title_card renders text with ffmpeg's drawtext, which needs a real font file.
5
- * Rather than guess at a system font, the package ships two static Inter weights
6
- * (SIL Open Font License) under assets/fonts/. The path is resolved relative to
7
- * the package root so it works the same from dist/ at runtime and from src/
8
- * under tests, and is escaped for ffmpeg's filtergraph parser.
9
- */
1
+ import { closeSync, existsSync, openSync, readSync, statSync } from "node:fs";
2
+ import { basename, isAbsolute, join } from "node:path";
10
3
  import { fileURLToPath } from "node:url";
4
+ import { ScreencastError } from "./errors.js";
5
+ import { missingChars, parseCoverage } from "./fontCoverage.js";
11
6
  const FONT_FILES = {
12
7
  regular: "Inter-Regular.ttf",
13
8
  bold: "Inter-Bold.ttf",
14
9
  };
15
- /** Absolute path to a bundled Inter weight. The compiled file lives at
16
- * dist/utils/fonts.js, so ../../assets/fonts is the package root. */
17
10
  export function bundledFontPath(weight = "bold") {
18
11
  return fileURLToPath(new URL(`../../assets/fonts/${FONT_FILES[weight]}`, import.meta.url));
19
12
  }
20
- /** Escape a filesystem path for an ffmpeg filtergraph option value (e.g. a
21
- * drawtext fontfile / textfile). The value passes through two unescaping
22
- * stages, so on Windows the drive colon must be double-escaped: forward slashes
23
- * and `\\:`, turning `C:\Fonts\x.ttf` into `C\\:/Fonts/x.ttf`. This is the
24
- * documented Windows incantation and is verified against ffmpeg.
25
- *
26
- * The same two stages apply to the other specials a real path can contain
27
- * (#87): a quote needs `\\\'` (option-level `\'`, whose backslash the graph
28
- * level also escapes), and the graph delimiters `, ; [ ]` need one backslash.
29
- * Without this, a Windows username like O'Brien (temp dir, npx cache) broke
30
- * title_card. */
31
13
  export function escapeFilterPath(p) {
32
14
  return p
33
15
  .replace(/\\/g, "/")
@@ -35,4 +17,138 @@ export function escapeFilterPath(p) {
35
17
  .replace(/'/g, "\\\\\\'")
36
18
  .replace(/([,;[\]])/g, "\\$1");
37
19
  }
38
- //# sourceMappingURL=fonts.js.map
20
+ export const FALLBACK_FAMILIES = {
21
+ segoe: { name: "Segoe UI", regular: ["segoeui.ttf"], bold: ["segoeuib.ttf", "segoeui.ttf"] },
22
+ japanese: {
23
+ name: "Yu Gothic",
24
+ regular: ["YuGothM.ttc", "meiryo.ttc", "msgothic.ttc"],
25
+ bold: ["YuGothB.ttc", "meiryob.ttc", "YuGothM.ttc", "msgothic.ttc"],
26
+ },
27
+ chineseSimplified: { name: "Microsoft YaHei", regular: ["msyh.ttc", "simsun.ttc"], bold: ["msyhbd.ttc", "msyh.ttc", "simsun.ttc"] },
28
+ chineseTraditional: { name: "Microsoft JhengHei", regular: ["msjh.ttc", "mingliub.ttc"], bold: ["msjhbd.ttc", "msjh.ttc"] },
29
+ korean: { name: "Malgun Gothic", regular: ["malgun.ttf"], bold: ["malgunbd.ttf", "malgun.ttf"] },
30
+ indic: { name: "Nirmala UI", regular: ["Nirmala.ttc", "Nirmala.ttf"], bold: ["NirmalaB.ttf", "Nirmala.ttc", "Nirmala.ttf"] },
31
+ thai: { name: "Leelawadee UI", regular: ["LeelawUI.ttf", "tahoma.ttf"], bold: ["LeelaUIb.ttf", "LeelawUI.ttf", "tahomabd.ttf"] },
32
+ ethiopic: { name: "Ebrima", regular: ["ebrima.ttf"], bold: ["ebrimabd.ttf", "ebrima.ttf"] },
33
+ emoji: { name: "Segoe UI Emoji", regular: ["seguiemj.ttf"], bold: ["seguiemj.ttf"] },
34
+ symbol: { name: "Segoe UI Symbol", regular: ["seguisym.ttf"], bold: ["seguisym.ttf"] },
35
+ };
36
+ const DEFAULT_ORDER = [
37
+ "segoe", "japanese", "chineseSimplified", "chineseTraditional", "korean",
38
+ "indic", "thai", "ethiopic", "emoji", "symbol",
39
+ ];
40
+ export function fallbackOrder(text) {
41
+ const front = [];
42
+ if (/[\u3040-\u30ff\u31f0-\u31ff\uff66-\uff9f]/u.test(text))
43
+ front.push("japanese");
44
+ if (/[\u1100-\u11ff\u3130-\u318f\uac00-\ud7af]/u.test(text))
45
+ front.push("korean");
46
+ if (/\p{Script=Han}/u.test(text))
47
+ front.push("chineseSimplified");
48
+ return [...front, ...DEFAULT_ORDER.filter((k) => !front.includes(k))].map((k) => FALLBACK_FAMILIES[k]);
49
+ }
50
+ export function chooseFont(text, candidates) {
51
+ let best = null;
52
+ for (const c of candidates) {
53
+ const missing = missingChars(text, c.coverage);
54
+ if (missing.length === 0)
55
+ return { fontFile: c.path, missing };
56
+ if (!best || missing.length < best.missing.length)
57
+ best = { fontFile: c.path, missing };
58
+ }
59
+ return best;
60
+ }
61
+ export function systemFontsDir() {
62
+ return join(process.env.WINDIR ?? process.env.SystemRoot ?? "C:\\Windows", "Fonts");
63
+ }
64
+ const coverageCache = new Map();
65
+ export function fontCoverage(path) {
66
+ const cached = coverageCache.get(path);
67
+ if (cached !== undefined)
68
+ return cached;
69
+ let cov;
70
+ let fd = null;
71
+ try {
72
+ fd = openSync(path, "r");
73
+ const handle = fd;
74
+ const read = (offset, length) => {
75
+ const b = Buffer.alloc(length);
76
+ return b.subarray(0, readSync(handle, b, 0, length, offset));
77
+ };
78
+ cov = parseCoverage(read);
79
+ }
80
+ catch {
81
+ cov = null;
82
+ }
83
+ finally {
84
+ if (fd !== null)
85
+ closeSync(fd);
86
+ }
87
+ coverageCache.set(path, cov);
88
+ return cov;
89
+ }
90
+ export function resolveFontFileArg(fontFile) {
91
+ if (existsSync(fontFile) && statSync(fontFile).isFile())
92
+ return fontFile;
93
+ if (!isAbsolute(fontFile) && basename(fontFile) === fontFile) {
94
+ const sys = join(systemFontsDir(), fontFile);
95
+ if (existsSync(sys))
96
+ return sys;
97
+ }
98
+ throw new ScreencastError(`Font file not found: ${fontFile}`, "Pass a path to a .ttf, .otf or .ttc file, or the file name of a font in C:\\Windows\\Fonts.");
99
+ }
100
+ function excerpt(text) {
101
+ const one = text.replace(/\s+/g, " ").trim();
102
+ return `"${one.length > 40 ? `${one.slice(0, 39)}…` : one}"`;
103
+ }
104
+ export function resolveTextFont(text, opts = {}) {
105
+ if (opts.fontFile) {
106
+ const fontFile = resolveFontFileArg(opts.fontFile);
107
+ const cov = fontCoverage(fontFile);
108
+ if (!cov) {
109
+ return {
110
+ fontFile,
111
+ missing: [],
112
+ fallback: false,
113
+ warning: `Could not read the character map of ${basename(fontFile)}; glyph coverage of ${excerpt(text)} was not checked.`,
114
+ };
115
+ }
116
+ const missing = missingChars(text, cov);
117
+ if (missing.length === 0)
118
+ return { fontFile, missing, fallback: false };
119
+ return {
120
+ fontFile,
121
+ missing,
122
+ fallback: false,
123
+ warning: `${basename(fontFile)} has no glyph for ${missing.join(" ")} in ${excerpt(text)}; they render as empty boxes.`,
124
+ };
125
+ }
126
+ const weight = opts.weight ?? "bold";
127
+ const bundled = bundledFontPath(weight);
128
+ const inter = fontCoverage(bundled);
129
+ if (inter && missingChars(text, inter).length === 0)
130
+ return { fontFile: bundled, missing: [], fallback: false };
131
+ const dir = opts.fontsDir ?? systemFontsDir();
132
+ const candidates = inter ? [{ path: bundled, coverage: inter }] : [];
133
+ for (const fam of fallbackOrder(text)) {
134
+ for (const file of fam[weight]) {
135
+ const path = join(dir, file);
136
+ const coverage = existsSync(path) ? fontCoverage(path) : null;
137
+ if (!coverage)
138
+ continue;
139
+ if (missingChars(text, coverage).length === 0)
140
+ return { fontFile: path, missing: [], fallback: true };
141
+ candidates.push({ path, coverage });
142
+ break;
143
+ }
144
+ }
145
+ const pick = chooseFont(text, candidates) ?? { fontFile: bundled, missing: [] };
146
+ if (pick.missing.length === 0)
147
+ return { ...pick, fallback: pick.fontFile !== bundled };
148
+ return {
149
+ ...pick,
150
+ fallback: pick.fontFile !== bundled,
151
+ warning: `No available font draws ${pick.missing.join(" ")} in ${excerpt(text)}; they render as empty boxes ` +
152
+ `(drawn with ${basename(pick.fontFile)}). Pass fontFile with a font that covers them.`,
153
+ };
154
+ }
@@ -1,18 +1,9 @@
1
- /**
2
- * Dead-air removal (#122). Recordings of an agent at work are full of long
3
- * still stretches while it thinks. A scan finds frozen video (freezedetect)
4
- * and silent audio (silencedetect); idle time is where the picture is frozen
5
- * and, if there is audio, it is also silent. Each idle stretch is cut except
6
- * for a short pad at both edges, in one select/aselect pass. Pure helpers.
7
- */
8
1
  import { ScreencastError } from "./errors.js";
9
2
  import { resolveQuality } from "./targets.js";
3
+ import { sumExpr } from "./expr.js";
10
4
  export const DEFAULT_MIN_IDLE_SEC = 2;
11
5
  export const DEFAULT_KEEP_SEC = 0.4;
12
- /** Cap on cut intervals, keeping the select expression a sane length. */
13
6
  export const MAX_CUTS = 200;
14
- /** Scan for freezes (and silences, when the file has audio); the reports go
15
- * to stderr at info level. */
16
7
  export function buildIdleScanArgs(input, minIdleSec, withAudio) {
17
8
  if (!(minIdleSec > 0))
18
9
  throw new ScreencastError("minIdleSec must be positive.");
@@ -23,8 +14,6 @@ export function buildIdleScanArgs(input, minIdleSec, withAudio) {
23
14
  "-f", "null", "-",
24
15
  ];
25
16
  }
26
- /** Pair start/end markers from the scan. An open interval (the stretch runs to
27
- * the end of the file) is closed at `duration`. Pure. */
28
17
  function pairs(stderr, startRe, endRe, duration) {
29
18
  const out = [];
30
19
  let open = null;
@@ -50,25 +39,26 @@ export function parseFreezes(stderr, duration) {
50
39
  export function parseSilences(stderr, duration) {
51
40
  return pairs(stderr, /silence_start:\s*([\d.]+)/, /silence_end:\s*([\d.]+)/, duration);
52
41
  }
53
- /** Overlap of two sorted interval lists. Pure. */
54
42
  export function intersect(a, b) {
55
43
  const out = [];
56
44
  let i = 0;
57
45
  let j = 0;
58
- while (i < a.length && j < b.length) {
59
- const start = Math.max(a[i].start, b[j].start);
60
- const end = Math.min(a[i].end, b[j].end);
46
+ while (true) {
47
+ const x = a[i];
48
+ const y = b[j];
49
+ if (!x || !y)
50
+ break;
51
+ const start = Math.max(x.start, y.start);
52
+ const end = Math.min(x.end, y.end);
61
53
  if (end > start)
62
54
  out.push({ start, end });
63
- if (a[i].end < b[j].end)
55
+ if (x.end < y.end)
64
56
  i++;
65
57
  else
66
58
  j++;
67
59
  }
68
60
  return out;
69
61
  }
70
- /** Idle stretches (at least minIdleSec long) shrunk by `keep` at each edge,
71
- * i.e. the spans that will actually be removed. Pure. */
72
62
  export function cutsFor(idle, minIdleSec, keep) {
73
63
  return idle
74
64
  .filter((r) => r.end - r.start >= minIdleSec)
@@ -76,21 +66,19 @@ export function cutsFor(idle, minIdleSec, keep) {
76
66
  .filter((r) => r.end - r.start > 0.05)
77
67
  .map((r) => ({ start: Number(r.start.toFixed(3)), end: Number(r.end.toFixed(3)) }));
78
68
  }
79
- /** Remove the cut spans from video (and audio) in one pass. Timestamps are
80
- * regenerated so the result plays continuously. Pure. */
81
69
  export function buildCutIdleArgs(input, output, cuts, withAudio, quality = "standard") {
82
70
  if (cuts.length === 0)
83
71
  throw new ScreencastError("Nothing to cut.");
84
72
  if (cuts.length > MAX_CUTS)
85
73
  throw new ScreencastError(`Too many idle stretches (${cuts.length}); raise minIdleSec.`);
86
- const drop = cuts.map((c) => `between(t,${c.start},${c.end})`).join("+");
74
+ const drop = sumExpr(cuts.map((c) => `between(t,${c.start},${c.end})`));
75
+ const removed = sumExpr(cuts.map((c) => `clip(T-${c.start},0,${Number((c.end - c.start).toFixed(3))})`));
87
76
  return [
88
77
  "-y", "-i", input,
89
- "-vf", `select='not(${drop})',setpts=N/FRAME_RATE/TB`,
78
+ "-vf", `select='not(${drop})',setpts='(T-(${removed}))/TB'`,
90
79
  ...(withAudio ? ["-af", `aselect='not(${drop})',asetpts=N/SR/TB`] : ["-an"]),
91
80
  ...resolveQuality(quality),
92
81
  ...(withAudio ? ["-c:a", "aac", "-b:a", "160k"] : []),
93
82
  output,
94
83
  ];
95
84
  }
96
- //# sourceMappingURL=idle.js.map
@@ -1,24 +1,10 @@
1
- /**
2
- * Inline image results (#79).
3
- *
4
- * Tools that produce frames can return them as MCP `image` content blocks so a
5
- * client shows them to the model directly, with no filesystem tool needed.
6
- * Payloads stay bounded: every frame is downscaled to a max width and
7
- * re-encoded as JPEG, and only the first N frames are embedded.
8
- */
9
1
  import { readFileSync, rmSync } from "node:fs";
10
2
  import { ScreencastError } from "./errors.js";
11
3
  import { runFfmpeg } from "./ffmpeg.js";
12
4
  import { tempPath, stillOutput } from "./paths.js";
13
- /** Default downscale width for inline previews. */
14
5
  export const DEFAULT_MAX_IMAGE_WIDTH = 1280;
15
- /** Default number of frames embedded in one tool result. */
16
6
  export const DEFAULT_MAX_INLINE_IMAGES = 8;
17
- /** Hard ceiling on embedded frames, whatever the caller asks for. */
18
7
  export const MAX_INLINE_IMAGES = 20;
19
- /** Build args that turn one image or video frame into a downscaled JPEG
20
- * preview. The width cap only ever downscales (min of the source width and
21
- * maxWidth); -2 keeps the aspect ratio. */
22
8
  export function buildPreviewArgs(input, output, maxWidth) {
23
9
  if (!Number.isInteger(maxWidth) || maxWidth < 16) {
24
10
  throw new ScreencastError("maxImageWidth must be an integer of at least 16.");
@@ -31,12 +17,10 @@ export function buildPreviewArgs(input, output, maxWidth) {
31
17
  ...stillOutput(output),
32
18
  ];
33
19
  }
34
- /** Clamp a caller-supplied inline-image count to [0, MAX_INLINE_IMAGES]. */
35
20
  export function clampInlineCount(requested) {
36
21
  const n = requested ?? DEFAULT_MAX_INLINE_IMAGES;
37
22
  return Math.max(0, Math.min(MAX_INLINE_IMAGES, Math.floor(n)));
38
23
  }
39
- /** Encode up to `maxCount` image files as downscaled JPEG image blocks. */
40
24
  export async function encodeInlineImages(paths, maxWidth = DEFAULT_MAX_IMAGE_WIDTH, maxCount = DEFAULT_MAX_INLINE_IMAGES) {
41
25
  const chosen = paths.slice(0, maxCount);
42
26
  const images = [];
@@ -52,4 +36,3 @@ export async function encodeInlineImages(paths, maxWidth = DEFAULT_MAX_IMAGE_WID
52
36
  }
53
37
  return { images, omitted: paths.length - chosen.length };
54
38
  }
55
- //# sourceMappingURL=images.js.map
@@ -1,33 +1,11 @@
1
- /**
2
- * Long-running edit jobs (#81).
3
- *
4
- * Edit tools used to run ffmpeg with a fixed 5-20 minute timeout, wrote
5
- * straight to the output path, and reported nothing until they finished. A
6
- * long recording could time out partway, leave a truncated file at `output`
7
- * (which then blocked a retry with "Output already exists"), and the agent had
8
- * no idea how far it got. runEditJob fixes all three:
9
- *
10
- * - the timeout scales with the media's duration (env override available);
11
- * - ffmpeg writes a `.partial` sibling that is renamed onto `output` only on
12
- * success and deleted on any failure, timeout, or cancellation;
13
- * - `-progress pipe:1` is parsed and forwarded as MCP progress notifications
14
- * when the request carried a progressToken.
15
- */
16
1
  import { basename, dirname, extname, join } from "node:path";
17
2
  import { renameSync, rmSync } from "node:fs";
18
3
  import { ScreencastError } from "./errors.js";
19
4
  import { probeMedia, runFfmpeg } from "./ffmpeg.js";
20
- /** Env var that overrides every edit job's timeout, in milliseconds. */
21
5
  export const JOB_TIMEOUT_ENV = "SCREENCAST_JOB_TIMEOUT_MS";
22
- /** Floor for a duration-scaled timeout. */
23
6
  export const BASE_TIMEOUT_MS = 10 * 60_000;
24
- /** Timeout when the media's duration could not be probed. */
25
7
  export const UNKNOWN_DURATION_TIMEOUT_MS = 30 * 60_000;
26
- /** Allow this many seconds of wall-clock time per second of media. A slow
27
- * preset on a laptop runs around real time; 4x leaves ample headroom. */
28
8
  export const SECONDS_PER_MEDIA_SECOND = 4;
29
- /** Timeout for a job over `durationSec` of media: max(base, duration * 4x),
30
- * or the env override when it is a positive integer. */
31
9
  export function jobTimeoutMs(durationSec, env = process.env) {
32
10
  const override = Number(env[JOB_TIMEOUT_ENV]);
33
11
  if (Number.isInteger(override) && override > 0)
@@ -36,14 +14,10 @@ export function jobTimeoutMs(durationSec, env = process.env) {
36
14
  return UNKNOWN_DURATION_TIMEOUT_MS;
37
15
  return Math.max(BASE_TIMEOUT_MS, Math.ceil(durationSec * SECONDS_PER_MEDIA_SECOND * 1000));
38
16
  }
39
- /** `dir/name.partial.ext`: keeps the extension so ffmpeg picks the same muxer. */
40
17
  export function partialPath(output) {
41
18
  const ext = extname(output);
42
19
  return join(dirname(output), `${basename(output, ext)}.partial${ext}`);
43
20
  }
44
- /** Point a builder's args at `partial` instead of `output`. Builders put the
45
- * output path last; replacing the last occurrence leaves an identical input
46
- * path (rare, but legal with overwrite) untouched. */
47
21
  export function retargetOutput(args, output, partial) {
48
22
  const i = args.lastIndexOf(output);
49
23
  if (i === -1) {
@@ -53,8 +27,6 @@ export function retargetOutput(args, output, partial) {
53
27
  next[i] = partial;
54
28
  return next;
55
29
  }
56
- /** Feed `-progress pipe:1` output in chunks; returns the latest media time in
57
- * seconds seen so far. Lines can split across chunks, so it buffers. */
58
30
  export function createProgressParser() {
59
31
  let buffer = "";
60
32
  let latest = null;
@@ -63,8 +35,6 @@ export function createProgressParser() {
63
35
  const lines = buffer.split(/\r?\n/);
64
36
  buffer = lines.pop() ?? "";
65
37
  for (const line of lines) {
66
- // out_time_us is microseconds; ffmpeg's out_time_ms is also microseconds
67
- // (a long-standing naming bug), so either works as a fallback.
68
38
  const m = line.match(/^out_time_(?:us|ms)=(\d+)$/);
69
39
  if (m)
70
40
  latest = Number(m[1]) / 1_000_000;
@@ -72,9 +42,6 @@ export function createProgressParser() {
72
42
  return latest;
73
43
  };
74
44
  }
75
- /** A progress callback that forwards to the client as MCP progress
76
- * notifications, or undefined when the request asked for none. Updates are
77
- * throttled to whole-percent steps. */
78
45
  export function progressReporter(extra) {
79
46
  const token = extra?._meta?.progressToken;
80
47
  if (token === undefined || !extra)
@@ -91,21 +58,29 @@ export function progressReporter(extra) {
91
58
  params: { progressToken: token, progress: percent, total: 100 },
92
59
  })
93
60
  .catch(() => {
94
- /* a client that went away must not fail the job */
95
61
  });
96
62
  };
97
63
  }
98
- /** Run an ffmpeg edit job atomically: write a .partial sibling, rename it onto
99
- * the output on success, and delete it on any failure. */
64
+ const activeJobs = new Set();
65
+ let jobsClosed = false;
100
66
  export async function runEditJob(args, job) {
67
+ if (jobsClosed)
68
+ throw new ScreencastError("The server is shutting down; the edit was not started.");
101
69
  const partial = partialPath(job.output);
102
70
  const report = progressReporter(job.extra);
103
71
  const parse = createProgressParser();
104
72
  const duration = job.durationSec != null && job.durationSec > 0 ? job.durationSec : null;
73
+ const input = job.inputDurationSec != null && job.inputDurationSec > 0 ? job.inputDurationSec : null;
74
+ const decoded = input !== null && duration !== null ? Math.max(input, duration) : (input ?? duration);
105
75
  const ffArgs = ["-progress", "pipe:1", "-nostats", ...retargetOutput(args, job.output, partial)];
76
+ const controller = new AbortController();
77
+ const signal = job.extra?.signal ? AbortSignal.any([job.extra.signal, controller.signal]) : controller.signal;
78
+ let finish;
79
+ const active = { partial, controller, done: new Promise((r) => (finish = r)) };
80
+ activeJobs.add(active);
106
81
  try {
107
- await runFfmpeg(ffArgs, jobTimeoutMs(duration), {
108
- signal: job.extra?.signal,
82
+ await runFfmpeg(ffArgs, jobTimeoutMs(decoded), {
83
+ signal,
109
84
  onStdout: report && duration
110
85
  ? (chunk) => {
111
86
  const t = parse(chunk);
@@ -121,9 +96,36 @@ export async function runEditJob(args, job) {
121
96
  rmSync(partial, { force: true });
122
97
  throw error;
123
98
  }
99
+ finally {
100
+ activeJobs.delete(active);
101
+ finish();
102
+ }
103
+ }
104
+ export function activeEditJobs() {
105
+ return activeJobs.size;
106
+ }
107
+ export async function abortEditJobs(graceMs = 3_000) {
108
+ jobsClosed = true;
109
+ const jobs = [...activeJobs];
110
+ if (jobs.length === 0)
111
+ return 0;
112
+ for (const job of jobs)
113
+ job.controller.abort();
114
+ let timer;
115
+ await Promise.race([
116
+ Promise.all(jobs.map((j) => j.done)),
117
+ new Promise((r) => (timer = setTimeout(r, graceMs))),
118
+ ]);
119
+ clearTimeout(timer);
120
+ for (const job of jobs) {
121
+ try {
122
+ rmSync(job.partial, { force: true });
123
+ }
124
+ catch {
125
+ }
126
+ }
127
+ return jobs.length;
124
128
  }
125
- /** Probe a file's duration, or null when it cannot be read. Used to size
126
- * timeouts and progress; never fails the job on its own. */
127
129
  export async function probeDuration(input) {
128
130
  try {
129
131
  return (await probeMedia(input)).durationSec;
@@ -132,4 +134,3 @@ export async function probeDuration(input) {
132
134
  return null;
133
135
  }
134
136
  }
135
- //# sourceMappingURL=jobs.js.map
@@ -0,0 +1,170 @@
1
+ import { ScreencastError } from "./errors.js";
2
+ import { escapeFilterPath } from "./fonts.js";
3
+ import { sumExpr } from "./expr.js";
4
+ import { resolveQuality } from "./targets.js";
5
+ import { validateColor } from "./validate.js";
6
+ export const BADGE_POSITIONS = ["bottom", "bottom-left", "bottom-right", "top", "top-left", "top-right"];
7
+ export const DEFAULT_LINGER_SEC = 1.2;
8
+ export const DOUBLE_CLICK_SEC = 0.5;
9
+ const DOUBLE_CLICK_PX = 8;
10
+ export const MAX_BADGE_LABELS = 100;
11
+ export const TYPING_LABEL = "Typing…";
12
+ const MODIFIERS = new Set(["Ctrl", "Alt", "Shift", "Win"]);
13
+ const KEY_NAME = /^(?:[A-Z0-9]|F\d{1,2}|Enter|Tab|Esc|Space|Backspace|Delete|Insert|Left|Up|Right|Down|Home|End|PageUp|PageDown|[=\-,./`[\];'\\])$/;
14
+ export function formatChord(keys, display = "shortcuts") {
15
+ const parts = keys.split("+");
16
+ const key = parts.pop();
17
+ if (key === undefined || parts.length === 0 || !KEY_NAME.test(key))
18
+ return null;
19
+ if (!parts.every((p) => MODIFIERS.has(p)) || new Set(parts).size !== parts.length)
20
+ return null;
21
+ return [...parts, display === "masked" ? "…" : key].join(" + ");
22
+ }
23
+ const BUTTON_LABEL = {
24
+ left: "Click",
25
+ right: "Right click",
26
+ middle: "Middle click",
27
+ x1: "Back button",
28
+ x2: "Forward button",
29
+ };
30
+ const r3 = (n) => Math.round(n * 1000) / 1000;
31
+ export function planBadges(events, opts = {}) {
32
+ const linger = opts.lingerSec ?? DEFAULT_LINGER_SEC;
33
+ if (!(linger > 0))
34
+ throw new ScreencastError("lingerSec must be positive.");
35
+ const display = opts.keys ?? "shortcuts";
36
+ const sorted = [...events].filter((e) => Number.isFinite(e.t) && e.t >= 0).sort((a, b) => a.t - b.t);
37
+ const raw = [];
38
+ for (const e of sorted) {
39
+ if (e.type === "key" && e.keys) {
40
+ const label = formatChord(e.keys, display);
41
+ if (!label)
42
+ continue;
43
+ const prev = raw.at(-1);
44
+ if (prev && prev.kind === "shortcut" && prev.base === label && e.t - prev.last <= linger) {
45
+ prev.count++;
46
+ prev.last = e.t;
47
+ prev.label = `${label} ×${prev.count}`;
48
+ prev.to = e.t + linger;
49
+ continue;
50
+ }
51
+ raw.push({ from: e.t, to: e.t + linger, label, base: label, kind: "shortcut", count: 1, last: e.t });
52
+ }
53
+ else if (e.type === "down" && opts.clicks !== false && e.inFrame) {
54
+ const base = BUTTON_LABEL[e.button ?? "left"] ?? "Click";
55
+ const prev = raw.at(-1);
56
+ if (base === "Click" && prev && prev.kind === "click" && prev.base === "Click" && prev.count < 3 &&
57
+ e.t - prev.last <= DOUBLE_CLICK_SEC &&
58
+ Math.abs(e.x - (prev.x ?? e.x)) <= DOUBLE_CLICK_PX && Math.abs(e.y - (prev.y ?? e.y)) <= DOUBLE_CLICK_PX) {
59
+ prev.count++;
60
+ prev.last = e.t;
61
+ prev.label = prev.count === 2 ? "Double click" : "Triple click";
62
+ prev.to = e.t + linger;
63
+ continue;
64
+ }
65
+ raw.push({ from: e.t, to: e.t + linger, label: base, base, kind: "click", count: 1, x: e.x, y: e.y, last: e.t });
66
+ }
67
+ else if (e.type === "typing" && opts.typing !== false) {
68
+ const end = e.t + Math.max(e.durationSec ?? 0, 0);
69
+ const prev = raw.at(-1);
70
+ if (prev && prev.kind === "typing" && e.t <= prev.to) {
71
+ prev.to = Math.max(prev.to, end + linger / 2);
72
+ prev.last = e.t;
73
+ continue;
74
+ }
75
+ raw.push({ from: e.t, to: end + linger / 2, label: TYPING_LABEL, base: TYPING_LABEL, kind: "typing", count: 1, last: e.t });
76
+ }
77
+ }
78
+ const out = [];
79
+ raw.forEach((b, i) => {
80
+ const next = raw[i + 1];
81
+ const to = next ? Math.min(b.to, next.from) : b.to;
82
+ if (to - b.from >= 0.05)
83
+ out.push({ from: r3(b.from), to: r3(to), label: b.label, kind: b.kind });
84
+ });
85
+ return out;
86
+ }
87
+ export function groupBadges(badges) {
88
+ const groups = new Map();
89
+ for (const b of badges) {
90
+ let g = groups.get(b.label);
91
+ if (!g) {
92
+ g = { label: b.label, windows: [] };
93
+ groups.set(b.label, g);
94
+ }
95
+ g.windows.push([b.from, b.to]);
96
+ }
97
+ if (groups.size > MAX_BADGE_LABELS) {
98
+ throw new ScreencastError(`${groups.size} different badges is more than ${MAX_BADGE_LABELS}; trim the video or turn off keys or clicks.`);
99
+ }
100
+ return [...groups.values()];
101
+ }
102
+ export function mapBadges(badges, map) {
103
+ return badges.flatMap((b) => {
104
+ const w = map(b.from, b.to);
105
+ return w && w[1] - w[0] >= 0.05 ? [{ ...b, from: r3(w[0]), to: r3(w[1]) }] : [];
106
+ });
107
+ }
108
+ export function retimeBadges(badges, ops) {
109
+ return mapBadges(badges, (from, to) => {
110
+ let a = from;
111
+ let b = to;
112
+ for (const op of ops) {
113
+ if (op.op === "trim") {
114
+ a = Math.max(a, op.start) - op.start;
115
+ b = Math.min(b, op.end) - op.start;
116
+ if (b <= a)
117
+ return null;
118
+ }
119
+ else {
120
+ a /= op.factor;
121
+ b /= op.factor;
122
+ }
123
+ }
124
+ return [a, b];
125
+ });
126
+ }
127
+ export function badgeSize(frameH, size) {
128
+ if (size !== undefined) {
129
+ if (!(size >= 8 && size <= 400))
130
+ throw new ScreencastError("size must be between 8 and 400.");
131
+ return Math.round(size);
132
+ }
133
+ return Math.max(14, Math.round(frameH * 0.045));
134
+ }
135
+ export function keystrokeSteps(groups, assets, style, frame, input, tag) {
136
+ if (groups.length === 0)
137
+ throw new ScreencastError("No badges to draw.");
138
+ const size = badgeSize(frame.height, style.size);
139
+ const border = Math.round(size / 3);
140
+ const margin = border + Math.round(size * 0.6);
141
+ const pos = style.position ?? "bottom";
142
+ const x = pos.endsWith("left") ? `${margin}` : pos.endsWith("right") ? `w-tw-${margin}` : "(w-tw)/2";
143
+ const y = pos.startsWith("top") ? `${margin}` : `h-lh-${margin}`;
144
+ const color = validateColor(style.color ?? "white");
145
+ const steps = [];
146
+ let cur = input;
147
+ groups.forEach((g, i) => {
148
+ const file = assets.textFiles[g.label];
149
+ if (!file)
150
+ throw new ScreencastError(`Internal: no text file for badge "${g.label}".`);
151
+ const enable = sumExpr(g.windows.map(([a, b]) => `between(t,${a},${b})`));
152
+ const out = `[${tag}k${i}]`;
153
+ steps.push(`${cur}drawtext=fontfile=${escapeFilterPath(assets.fontFile)}:textfile=${escapeFilterPath(file)}:expansion=none` +
154
+ `:fontsize=${size}:fontcolor=${color}:box=1:boxcolor=black@0.6:boxborderw=${border}` +
155
+ `:x=${x}:y=${y}:enable='${enable}'${out}`);
156
+ cur = out;
157
+ });
158
+ return { steps, out: cur };
159
+ }
160
+ export function buildKeystrokeArgs(input, output, groups, assets, style, frame, quality = "standard") {
161
+ const { steps, out } = keystrokeSteps(groups, assets, style, frame, "[0:v]", "");
162
+ return [
163
+ "-y", "-i", input,
164
+ "-filter_complex", steps.join(";"),
165
+ "-map", out, "-map", "0:a?",
166
+ ...resolveQuality(quality),
167
+ "-c:a", "copy",
168
+ output,
169
+ ];
170
+ }