@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,47 +1,71 @@
1
- /**
2
- * The review player (#128): an MCP Apps view (a sandboxed HTML page the host
3
- * shows inline) where a person scrubs a recording, sets trim handles, and
4
- * draws redaction boxes; their choices come back as a pipeline call.
5
- *
6
- * The page gets the video as JPEG frames (data: images work under the strict
7
- * CSP hosts apply to apps, unlike a local file or HTTP server, and keep
8
- * "output stays local"). These helpers plan and split those frames. Pure.
9
- */
10
1
  import { ScreencastError } from "./errors.js";
11
- /** The MCP Apps resource the player is served as, and its MIME type. */
2
+ import { escapeFilterPath } from "./fonts.js";
12
3
  export const PLAYER_URI = "ui://screencast/player";
13
4
  export const MCP_APP_MIME = "text/html;profile=mcp-app";
14
- /** Tool _meta that tells an Apps host to render the player for a tool's
15
- * result. Both the current and the legacy key, as the spec asks hosts to read. */
16
5
  export const PLAYER_TOOL_META = { ui: { resourceUri: PLAYER_URI }, "ui/resourceUri": PLAYER_URI };
6
+ export const MCP_APPS_EXTENSION = "io.modelcontextprotocol/ui";
7
+ export function clientSupportsApps(caps) {
8
+ const c = caps;
9
+ const ext = (c?.extensions?.[MCP_APPS_EXTENSION] ?? c?.experimental?.[MCP_APPS_EXTENSION]);
10
+ if (!ext || typeof ext !== "object")
11
+ return false;
12
+ return !Array.isArray(ext.mimeTypes) || ext.mimeTypes.includes(MCP_APP_MIME);
13
+ }
17
14
  export const DEFAULT_PLAYER_FRAMES = 120;
18
15
  export const MAX_PLAYER_FRAMES = 300;
19
16
  export const PLAYER_FPS = 4;
20
17
  export const DEFAULT_PLAYER_WIDTH = 640;
21
- /** How many preview frames, and at what rate, to cover `durationSec`: up to
22
- * PLAYER_FPS per second, at most `maxFrames`, spread evenly. */
18
+ export const PLAYER_SCENE_THRESHOLD = 0.01;
23
19
  export function playerFramePlan(durationSec, maxFrames = DEFAULT_PLAYER_FRAMES) {
24
20
  if (!(durationSec > 0))
25
21
  throw new ScreencastError("The video has no duration to review.");
26
22
  const count = Math.max(1, Math.min(maxFrames, Math.ceil(durationSec * PLAYER_FPS)));
27
- return { count, fps: count / durationSec };
28
- }
29
- /** Each frame's time: the middle of its slice of the video. */
30
- export function playerFrameTimes(durationSec, count) {
31
- return Array.from({ length: count }, (_, i) => Math.round(((i + 0.5) * durationSec * 1000) / count) / 1000);
23
+ const intervalSec = Number((durationSec / count).toFixed(6));
24
+ return { count, intervalSec, sceneGapSec: Number(Math.max(0.25, intervalSec / 4).toFixed(6)) };
32
25
  }
33
- /** Decode `input` to JPEG frames on stdout at `fps`, `width` wide. */
34
- export function buildPlayerFramesArgs(input, fps, width, count) {
26
+ export function buildPlayerFramesArgs(input, plan, width, logFile, threshold = PLAYER_SCENE_THRESHOLD) {
27
+ const i = plan.intervalSec;
28
+ const grid = `isnan(prev_t)+gt(floor((t-start_t)/${i})\\,floor((prev_t-start_t)/${i}))`;
29
+ const scene = `gt(scene\\,${threshold})*not(${grid})*(isnan(prev_selected_t)+gte(t-prev_selected_t\\,${plan.sceneGapSec}))`;
35
30
  return [
36
31
  "-v", "error", "-i", input, "-an",
37
- "-vf", `fps=${Number(fps.toFixed(6))},scale='min(${width},iw)':-2`,
38
- "-frames:v", String(count),
32
+ "-vf",
33
+ `scale='min(${width},iw)':-2,split[g][s];` +
34
+ `[g]select='${grid}',metadata=add:key=kind:value=grid[g1];` +
35
+ `[s]select='${scene}',metadata=add:key=kind:value=scene[s1];` +
36
+ `[g1][s1]interleave,metadata=print:file=${escapeFilterPath(logFile)}`,
37
+ "-fps_mode", "passthrough",
39
38
  "-q:v", "6", "-f", "image2pipe", "-c:v", "mjpeg", "-",
40
39
  ];
41
40
  }
42
- /** Split concatenated JPEGs (ffmpeg's mjpeg image2pipe) at their start/end
43
- * markers. In entropy-coded data 0xFF is always followed by 0x00 or a restart
44
- * marker, so 0xFFD9 only ever ends an image. */
41
+ export function parsePlayerFrameLog(text) {
42
+ const out = [];
43
+ for (const line of text.split(/\r?\n/)) {
44
+ const t = line.match(/pts_time:\s*(-?[\d.]+)/);
45
+ if (t) {
46
+ out.push({ timeSec: Number(t[1]), scene: false, score: 0 });
47
+ continue;
48
+ }
49
+ const last = out.at(-1);
50
+ if (!last)
51
+ continue;
52
+ if (line === "kind=scene")
53
+ last.scene = true;
54
+ const s = line.match(/^lavfi\.scene_score=([\d.]+)/);
55
+ if (s)
56
+ last.score = Number(s[1]);
57
+ }
58
+ return out;
59
+ }
60
+ export function pickPlayerFrames(frames, maxScene) {
61
+ const scene = frames
62
+ .map((f, i) => ({ f, i }))
63
+ .filter((x) => x.f.scene)
64
+ .sort((a, b) => b.f.score - a.f.score)
65
+ .slice(0, Math.max(0, maxScene));
66
+ const keep = new Set(scene.map((x) => x.i));
67
+ return frames.flatMap((f, i) => (!f.scene || keep.has(i) ? [i] : []));
68
+ }
45
69
  export function splitJpegs(buf) {
46
70
  const out = [];
47
71
  let start = -1;
@@ -59,4 +83,3 @@ export function splitJpegs(buf) {
59
83
  }
60
84
  return out;
61
85
  }
62
- //# sourceMappingURL=player.js.map
@@ -1,12 +1,3 @@
1
- /**
2
- * Phase 3 produce / trailer-layer argument builders.
3
- *
4
- * These stitch, title, score, and reframe finished pieces. They re-encode (the
5
- * filters rewrite frames) and, where they combine clips, normalize every input
6
- * to a common resolution / fps / SAR / audio rate first so heterogeneous
7
- * sources compose cleanly. All builders are pure (string in, args out) and are
8
- * unit-tested without ffmpeg present.
9
- */
10
1
  import { ScreencastError } from "./errors.js";
11
2
  import { resolveQuality } from "./targets.js";
12
3
  import { escapeFilterPath } from "./fonts.js";
@@ -20,8 +11,6 @@ const DEFAULT_QUALITY = "standard";
20
11
  function round3(n) {
21
12
  return Math.round(n * 1000) / 1000;
22
13
  }
23
- /** Output W/H for a produce builder: explicit values must be even (H.264 +
24
- * yuv420p rejects odd dimensions); the defaults already are. */
25
14
  function producedDims(opts) {
26
15
  if (opts.width !== undefined)
27
16
  validateEvenDimension(opts.width, "width");
@@ -32,41 +21,28 @@ function producedDims(opts) {
32
21
  h: opts.height ?? DEFAULT_PRODUCE_HEIGHT,
33
22
  };
34
23
  }
35
- /** Video normalization chain: fit inside WxH, letterbox, square pixels, fixed
36
- * fps, web-safe pixel format. Makes any clip compatible with concat / xfade. */
37
24
  export function videoNormalizeChain(w, h, fps) {
38
25
  return (`scale=${w}:${h}:force_original_aspect_ratio=decrease,` +
39
26
  `pad=${w}:${h}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=${fps},format=yuv420p`);
40
27
  }
41
- /** Audio normalization chain: common sample rate, stereo, float planar. */
42
28
  export function audioNormalizeChain(rate) {
43
29
  return `aresample=${rate},aformat=sample_fmts=fltp:channel_layouts=stereo`;
44
30
  }
45
31
  function encodeArgs(quality) {
46
32
  return resolveQuality(quality);
47
33
  }
48
- /**
49
- * Offsets for an xfade chain. Joining clip m (m >= 1) onto the running result,
50
- * the transition starts at sum(d_0..d_{m-1}) - m*D. Returns one offset per join
51
- * (length = durations.length - 1).
52
- */
53
34
  export function xfadeOffsets(durations, transitionDur) {
54
35
  const offsets = [];
55
36
  let running = 0;
56
- for (let m = 1; m < durations.length; m++) {
57
- running += durations[m - 1];
58
- offsets.push(Math.max(0, round3(running - m * transitionDur)));
37
+ for (const [k, d] of durations.slice(0, -1).entries()) {
38
+ running += d;
39
+ offsets.push(Math.max(0, round3(running - (k + 1) * transitionDur)));
59
40
  }
60
41
  return offsets;
61
42
  }
62
- /** The length to cut and crossfade a clip on: its video stream, not the
63
- * container, which is the longest stream (#205). */
64
43
  export function clipLength(info) {
65
44
  return info.videoDurationSec ?? info.durationSec;
66
45
  }
67
- /** Crossfade two clips: assemble_highlights with one xfade join. durations
68
- * are the clips' video lengths; a clip without audio gets matching silence,
69
- * so one silent clip no longer drops the other's audio (#188). */
70
46
  export function buildXfadeArgs(inputA, inputB, durations, output, opts = {}, clipHasAudio = [false, false]) {
71
47
  const transition = validateTransition(opts.transition ?? "fade");
72
48
  const d = opts.duration ?? DEFAULT_TRANSITION_DUR;
@@ -78,12 +54,6 @@ export function buildXfadeArgs(inputA, inputB, durations, output, opts = {}, cli
78
54
  }
79
55
  return buildAssembleArgs([inputA, inputB], durations, output, { ...opts, transition }, clipHasAudio);
80
56
  }
81
- /**
82
- * Stitch N clips into one. transition "cut" uses the concat filter; any other
83
- * value is an xfade transition name and chains xfade (video) + acrossfade
84
- * (audio) using the supplied per-clip durations. hasAudio means every input
85
- * carries audio.
86
- */
87
57
  export function buildAssembleArgs(inputs, durations, output, opts = {}, clipHasAudio = []) {
88
58
  if (inputs.length < 2) {
89
59
  throw new ScreencastError("assemble_highlights requires at least two clips.");
@@ -96,10 +66,6 @@ export function buildAssembleArgs(inputs, durations, output, opts = {}, clipHasA
96
66
  const n = inputs.length;
97
67
  const vf = videoNormalizeChain(w, h, fps);
98
68
  const af = audioNormalizeChain(rate);
99
- // If any clip has audio, the output carries audio: clips that lack a track get
100
- // a matching length of generated silence, so a single video-only clip no
101
- // longer drops audio from the whole result. If no clip has audio, stay
102
- // video-only.
103
69
  const anyAudio = clipHasAudio.some(Boolean);
104
70
  const parts = [];
105
71
  for (let i = 0; i < n; i++) {
@@ -107,14 +73,12 @@ export function buildAssembleArgs(inputs, durations, output, opts = {}, clipHasA
107
73
  if (!anyAudio)
108
74
  continue;
109
75
  if (clipHasAudio[i]) {
110
- // Pad or trim each track to its clip's video length, so audio joins
111
- // where the video does (#205).
112
- const dur = durations[i];
76
+ const dur = durations[i] ?? Number.NaN;
113
77
  const fit = Number.isFinite(dur) && dur > 0 ? `,apad,atrim=duration=${round3(dur)}` : "";
114
78
  parts.push(`[${i}:a]${af}${fit}[a${i}]`);
115
79
  }
116
80
  else {
117
- const dur = durations[i];
81
+ const dur = durations[i] ?? Number.NaN;
118
82
  if (!Number.isFinite(dur) || dur <= 0) {
119
83
  throw new ScreencastError(`clip ${i} has no audio track and its duration is unknown, so a ` +
120
84
  `matching silent track cannot be generated.`);
@@ -143,8 +107,6 @@ export function buildAssembleArgs(inputs, durations, output, opts = {}, clipHasA
143
107
  if (!Number.isFinite(d) || d <= 0) {
144
108
  throw new ScreencastError("transition duration must be a positive number.");
145
109
  }
146
- // Every clip must be longer than the transition, or xfade offsets collapse
147
- // (a too-short or unknown-duration clip yields overlapping/garbled cuts).
148
110
  const badClip = durations.findIndex((dur) => !Number.isFinite(dur) || dur <= d);
149
111
  if (badClip !== -1) {
150
112
  throw new ScreencastError(`clip ${badClip} (${durations[badClip]}s) must be longer than the ` +
@@ -179,10 +141,6 @@ export function buildAssembleArgs(inputs, durations, output, opts = {}, clipHasA
179
141
  output,
180
142
  ];
181
143
  }
182
- /** Generate a standalone title clip: a solid background with centered text from
183
- * a font file and a temp text file (so arbitrary text needs no inline
184
- * escaping), plus a silent stereo track so it composes with audio-bearing
185
- * clips. Caller resolves fontFile (a bundled weight) and writes textFile. */
186
144
  export const DEFAULT_TITLE_DURATION = 3;
187
145
  export function buildTitleCardArgs(textFile, fontFile, output, opts = {}) {
188
146
  const { w, h } = producedDims(opts);
@@ -214,10 +172,6 @@ export function buildTitleCardArgs(textFile, fontFile, output, opts = {}) {
214
172
  output,
215
173
  ];
216
174
  }
217
- /** Lay a music track under a video: loop/trim the music to the video duration,
218
- * fade it in/out, and set its level. When the video already has audio the two
219
- * are mixed (optionally ducking the music under the original via a sidechain).
220
- * The video stream is copied; only audio is re-encoded. */
221
175
  export function buildMusicBedArgs(video, music, output, videoDuration, hasVideoAudio, opts = {}) {
222
176
  if (!Number.isFinite(videoDuration) || videoDuration <= 0) {
223
177
  throw new ScreencastError("video duration must be known and positive.");
@@ -233,8 +187,6 @@ export function buildMusicBedArgs(video, music, output, videoDuration, hasVideoA
233
187
  const duck = opts.duck ?? false;
234
188
  const fadeOutStart = Math.max(0, round3(videoDuration - fout));
235
189
  const musicChain = `[1:a]afade=t=in:st=0:d=${fin},afade=t=out:st=${fadeOutStart}:d=${fout},volume=${vol}`;
236
- // normalize=0: amix otherwise scales every input by 1/N, dropping the
237
- // original track ~6 dB (#77). The music level is set by musicVolume alone.
238
190
  const mix = "amix=inputs=2:duration=first:dropout_transition=0:normalize=0";
239
191
  const parts = [];
240
192
  if (hasVideoAudio) {
@@ -263,15 +215,12 @@ export function buildMusicBedArgs(video, music, output, videoDuration, hasVideoA
263
215
  output,
264
216
  ];
265
217
  }
266
- /** Canonical target dimensions per aspect (even dims, social-ready). */
267
218
  export const ASPECT_DIMS = {
268
219
  "16:9": { w: 1920, h: 1080 },
269
220
  "9:16": { w: 1080, h: 1920 },
270
221
  "1:1": { w: 1080, h: 1080 },
271
222
  "4:5": { w: 1080, h: 1350 },
272
223
  };
273
- /** Filter chain to fit content into a WxH canvas. pad scales to fit and adds
274
- * bars (no content lost); crop scales to fill and center-crops the overflow. */
275
224
  export function reframeFilter(w, h, fit) {
276
225
  if (fit === "crop") {
277
226
  return `scale=${w}:${h}:force_original_aspect_ratio=increase,crop=${w}:${h},setsar=1`;
@@ -279,7 +228,6 @@ export function reframeFilter(w, h, fit) {
279
228
  return (`scale=${w}:${h}:force_original_aspect_ratio=decrease,` +
280
229
  `pad=${w}:${h}:(ow-iw)/2:(oh-ih)/2,setsar=1`);
281
230
  }
282
- /** Re-aspect a video to a target aspect with pad (default) or crop. */
283
231
  export function buildReframeArgs(input, output, aspect, fit = "pad", quality = DEFAULT_QUALITY) {
284
232
  const dim = ASPECT_DIMS[aspect];
285
233
  if (!dim)
@@ -294,8 +242,6 @@ export function buildReframeArgs(input, output, aspect, fit = "pad", quality = D
294
242
  ];
295
243
  }
296
244
  export const PLATFORMS = ["youtube", "instagram_reel", "tiktok", "x", "square", "steam_trailer", "vertical_reel"];
297
- /** Export presets. steam_trailer and vertical_reel come from the Game-Systems
298
- * media-layer spec (#107). */
299
245
  export const PLATFORM_PRESETS = {
300
246
  youtube: { aspect: "16:9", fps: 30, videoBitrate: "8M", bufsize: "16M", audioBitrate: "192k" },
301
247
  instagram_reel: { aspect: "9:16", fps: 30, videoBitrate: "6M", bufsize: "12M", audioBitrate: "160k" },
@@ -311,17 +257,12 @@ export const PLATFORM_PRESETS = {
311
257
  blurFill: true, loudness: {},
312
258
  },
313
259
  };
314
- /** A vertical-reel canvas: the footage fitted into a centred W x W square over
315
- * a blurred, darkened copy that fills W x H. Labels carry `tag`. Pure. */
316
260
  export function blurFillFilter(w, h, tag = "") {
317
261
  return (`split=2[${tag}bg][${tag}fg];` +
318
262
  `[${tag}bg]scale=${w}:${h}:force_original_aspect_ratio=increase,crop=${w}:${h},boxblur=20:2,eq=brightness=-0.08[${tag}b];` +
319
263
  `[${tag}fg]scale=${w}:${w}:force_original_aspect_ratio=decrease:force_divisible_by=2[${tag}f];` +
320
264
  `[${tag}b][${tag}f]overlay=(W-w)/2:(H-h)/2,setsar=1`);
321
265
  }
322
- /** The filter chain and encoder settings for a platform-ready file: reframe to
323
- * the platform aspect, cap fps, and encode H.264 at the platform's bitrate with
324
- * faststart. Shared by export_preset and pipeline. */
325
266
  export function exportPresetParts(platform, fit = "pad", tag = "") {
326
267
  const p = PLATFORM_PRESETS[platform];
327
268
  if (!p)
@@ -329,7 +270,7 @@ export function exportPresetParts(platform, fit = "pad", tag = "") {
329
270
  const dim = ASPECT_DIMS[p.aspect];
330
271
  const frame = p.blurFill ? blurFillFilter(dim.w, dim.h, tag) : reframeFilter(dim.w, dim.h, fit);
331
272
  const af = p.loudness
332
- ? // One-pass loudnorm resamples to 192 kHz; always bring it back (#188).
273
+ ?
333
274
  `loudnorm=I=-14:TP=-1:LRA=11,aresample=${p.loudness.sampleRate ?? DEFAULT_AUDIO_RATE}`
334
275
  : undefined;
335
276
  return {
@@ -355,4 +296,3 @@ export function buildExportPresetArgs(input, output, platform, fit = "pad") {
355
296
  const { vf, af, encode } = exportPresetParts(platform, fit);
356
297
  return ["-y", "-i", input, "-vf", vf, ...(af ? ["-af", af] : []), ...encode, output];
357
298
  }
358
- //# sourceMappingURL=produce.js.map
@@ -0,0 +1,278 @@
1
+ import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { ScreencastError } from "./errors.js";
4
+ import { runCapture } from "./ffmpeg.js";
5
+ import { jobTimeoutMs } from "./jobs.js";
6
+ import { buildProbeArgs, parseMediaInfo } from "./media.js";
7
+ import { homeRoot, rand, sequencePattern, stamp } from "./paths.js";
8
+ import { resolveQuality } from "./targets.js";
9
+ import { convertEvents, eventPaths, formatEventsJsonl, selectEvents, summarizeEvents, } from "./events.js";
10
+ export const REPLAY_SEGMENT_SEC = 2;
11
+ export const REPLAY_SLACK_SEGMENTS = 3;
12
+ export const MIN_REPLAY_SEC = 4;
13
+ export const MAX_REPLAY_SEC = 3600;
14
+ const SEGMENT_PATTERN = "seg%05d.ts";
15
+ const SEGMENT_NAME = /^seg(\d{5})\.ts$/;
16
+ const LIST_NAME = "segments.csv";
17
+ const DIR_NAME = /^buf-[\w-]+$/;
18
+ export function replayRoot() {
19
+ return join(homeRoot(), "replay");
20
+ }
21
+ export function replayWrap(bufferSec, segmentSec = REPLAY_SEGMENT_SEC) {
22
+ return Math.ceil(bufferSec / segmentSec) + REPLAY_SLACK_SEGMENTS;
23
+ }
24
+ export function planReplayBuffer(bufferSec, segmentSec = REPLAY_SEGMENT_SEC) {
25
+ if (!Number.isInteger(bufferSec) || bufferSec < MIN_REPLAY_SEC || bufferSec > MAX_REPLAY_SEC) {
26
+ throw new ScreencastError(`replayBufferSec must be an integer from ${MIN_REPLAY_SEC} to ${MAX_REPLAY_SEC} seconds.`);
27
+ }
28
+ return {
29
+ dir: join(replayRoot(), `buf-${stamp()}-${rand(6)}`),
30
+ bufferSec,
31
+ segmentSec,
32
+ wrap: replayWrap(bufferSec, segmentSec),
33
+ };
34
+ }
35
+ export function segmentListPath(dir) {
36
+ return join(dir, LIST_NAME);
37
+ }
38
+ export function segmentOutputArgs(captureArgs, buf) {
39
+ const args = captureArgs.slice(0, -1);
40
+ const mov = args.indexOf("-movflags");
41
+ if (mov >= 0)
42
+ args.splice(mov, 2);
43
+ return [
44
+ ...args,
45
+ "-force_key_frames", `expr:gte(t,n_forced*${buf.segmentSec})`,
46
+ "-f", "segment",
47
+ "-segment_time", String(buf.segmentSec),
48
+ "-segment_wrap", String(buf.wrap),
49
+ "-segment_list", segmentListPath(buf.dir),
50
+ "-segment_list_type", "csv",
51
+ "-segment_list_size", String(buf.wrap),
52
+ "-segment_format", "mpegts",
53
+ "-segment_format_options", "flush_packets=1",
54
+ sequencePattern(buf.dir, SEGMENT_PATTERN),
55
+ ];
56
+ }
57
+ export function parseSegmentList(csv) {
58
+ const out = [];
59
+ for (const line of csv.split(/\r?\n/)) {
60
+ const [file = "", s, e] = line.trim().split(",");
61
+ const m = SEGMENT_NAME.exec(file);
62
+ const start = Number(s);
63
+ const end = Number(e);
64
+ if (!m || s === undefined || e === undefined || !Number.isFinite(start) || !Number.isFinite(end) || end < start)
65
+ continue;
66
+ out.push({ file, index: Number(m[1]), start, end });
67
+ }
68
+ return out.sort((a, b) => a.start - b.start);
69
+ }
70
+ export function pickSegments(entries, lastSec) {
71
+ const picked = [];
72
+ let covered = 0;
73
+ for (let i = entries.length - 1; i >= 0 && covered < lastSec; i--) {
74
+ const e = entries[i];
75
+ picked.unshift(e);
76
+ covered += e.end - e.start;
77
+ }
78
+ return picked;
79
+ }
80
+ export function liveSegmentFile(entries, wrap) {
81
+ const last = entries.at(-1);
82
+ const index = last ? (last.index + 1) % wrap : 0;
83
+ return `seg${String(index).padStart(5, "0")}.ts`;
84
+ }
85
+ export function concatList(files) {
86
+ return files.map((p) => `file '${p.replace(/'/g, "'\\''")}'`).join("\n") + "\n";
87
+ }
88
+ export function buildReplayJoinArgs(listFile, output) {
89
+ return ["-y", "-v", "error", "-f", "concat", "-safe", "0", "-i", listFile, "-c", "copy", output];
90
+ }
91
+ export function buildReplayCutArgs(input, output, opts) {
92
+ const codec = opts.reencode
93
+ ? [...resolveQuality(opts.quality ?? "standard"), ...(opts.audio ? ["-c:a", "aac", "-b:a", "160k"] : [])]
94
+ : ["-c", "copy"];
95
+ return [
96
+ "-y", "-v", "error",
97
+ "-ss", String(round3(Math.max(0, opts.startSec))),
98
+ "-i", input,
99
+ ...codec,
100
+ "-movflags", "+faststart",
101
+ output,
102
+ ];
103
+ }
104
+ export function sliceEvents(events, from, to) {
105
+ return selectEvents(events, { from, to }).map((e) => ({ ...e, t: round3(e.t - from) }));
106
+ }
107
+ const round3 = (n) => Math.round(n * 1000) / 1000;
108
+ function copyShared(src, dst) {
109
+ const fd = openSync(src, "r");
110
+ try {
111
+ const size = statSync(src).size;
112
+ const buf = Buffer.alloc(size);
113
+ let read = 0;
114
+ while (read < size) {
115
+ const n = readSync(fd, buf, read, size - read, read);
116
+ if (n === 0)
117
+ break;
118
+ read += n;
119
+ }
120
+ writeFileSync(dst, buf.subarray(0, read));
121
+ return read;
122
+ }
123
+ finally {
124
+ closeSync(fd);
125
+ }
126
+ }
127
+ async function probeStart(ffprobe, path, signal) {
128
+ const res = await runCapture(ffprobe, ["-v", "error", "-show_entries", "format=start_time", "-of", "csv=p=0", path], 15_000, { signal });
129
+ const n = Number.parseFloat(res.stdout.trim());
130
+ return res.code === 0 && Number.isFinite(n) ? n : null;
131
+ }
132
+ export async function saveReplay(buf, opts) {
133
+ if (!existsSync(buf.dir)) {
134
+ throw new ScreencastError("This replay buffer has been discarded: its segments are gone.");
135
+ }
136
+ const listPath = segmentListPath(buf.dir);
137
+ const entries = existsSync(listPath) ? parseSegmentList(readFileSync(listPath, "utf8")) : [];
138
+ const picked = pickSegments(entries, opts.lastSec);
139
+ const snap = mkdtempSync(join(buf.dir, "save-"));
140
+ try {
141
+ const files = picked.map((e, i) => {
142
+ const dst = join(snap, `${String(i).padStart(5, "0")}.ts`);
143
+ copyShared(join(buf.dir, e.file), dst);
144
+ return dst;
145
+ });
146
+ let includesLive = false;
147
+ if (opts.live !== false) {
148
+ const src = join(buf.dir, liveSegmentFile(entries, buf.wrap));
149
+ const dst = join(snap, "live.ts");
150
+ if (existsSync(src) && copyShared(src, dst) > 0) {
151
+ const newest = files.at(-1);
152
+ const [liveStart, lastStart] = await Promise.all([
153
+ probeStart(opts.ffprobe, dst, opts.signal),
154
+ newest ? probeStart(opts.ffprobe, newest, opts.signal) : Promise.resolve(-Infinity),
155
+ ]);
156
+ if (liveStart !== null && lastStart !== null && liveStart > lastStart) {
157
+ files.push(dst);
158
+ includesLive = true;
159
+ }
160
+ }
161
+ }
162
+ if (files.length === 0) {
163
+ throw new ScreencastError("The replay buffer has no footage yet: the first segment is still being written. Try again in a couple of seconds.");
164
+ }
165
+ const listFile = join(snap, "join.txt");
166
+ writeFileSync(listFile, concatList(files));
167
+ const joined = join(snap, "joined.mp4");
168
+ const timeout = jobTimeoutMs(opts.lastSec + 2 * buf.segmentSec);
169
+ const join1 = await runCapture(opts.ffmpeg, buildReplayJoinArgs(listFile, joined), timeout, { signal: opts.signal });
170
+ if (join1.code !== 0) {
171
+ throw new ScreencastError(`Joining the replay segments failed:\n${join1.stderr.trim().split("\n").slice(-4).join("\n")}`);
172
+ }
173
+ const probe = await runCapture(opts.ffprobe, buildProbeArgs(joined), 30_000, { signal: opts.signal });
174
+ const info = probe.code === 0 ? parseMediaInfo(JSON.parse(probe.stdout)) : null;
175
+ const total = info?.durationSec ?? null;
176
+ if (!total || !(total > 0))
177
+ throw new ScreencastError("The joined replay has no duration; the segments may be damaged.");
178
+ const startSec = Math.max(0, total - opts.lastSec);
179
+ const cut = await runCapture(opts.ffmpeg, buildReplayCutArgs(joined, opts.output, {
180
+ startSec,
181
+ reencode: opts.reencode,
182
+ quality: opts.quality,
183
+ audio: !!info?.audioCodec,
184
+ }), timeout, { signal: opts.signal });
185
+ if (cut.code !== 0) {
186
+ throw new ScreencastError(`Writing the replay failed:\n${cut.stderr.trim().split("\n").slice(-4).join("\n")}`);
187
+ }
188
+ const origin = picked[0]?.start ?? entries.at(-1)?.end ?? 0;
189
+ const fromSec = round3(origin + startSec);
190
+ const toSec = round3(origin + total);
191
+ const result = {
192
+ outputPath: opts.output,
193
+ durationSec: round3(total - startSec),
194
+ fromSec,
195
+ toSec,
196
+ segments: files.length,
197
+ includesLive,
198
+ };
199
+ if (buf.events) {
200
+ const raw = existsSync(buf.events.raw) ? readFileSync(buf.events.raw, "utf8") : "";
201
+ const events = sliceEvents(convertEvents(raw, { startMs: buf.events.startMs, frame: buf.events.frame }), fromSec, toSec);
202
+ const { jsonl } = eventPaths(opts.output);
203
+ writeFileSync(jsonl, formatEventsJsonl(events));
204
+ result.eventsPath = jsonl;
205
+ result.events = summarizeEvents(events);
206
+ }
207
+ return result;
208
+ }
209
+ finally {
210
+ rmSync(snap, { recursive: true, force: true });
211
+ }
212
+ }
213
+ export function prepareReplayDir(buf) {
214
+ mkdirSync(buf.dir, { recursive: true });
215
+ }
216
+ export function discardReplay(buf) {
217
+ try {
218
+ rmSync(buf.dir, { recursive: true, force: true });
219
+ return !existsSync(buf.dir);
220
+ }
221
+ catch {
222
+ return false;
223
+ }
224
+ }
225
+ export function replayDiskBytes(buf) {
226
+ let total = 0;
227
+ try {
228
+ for (const name of readdirSync(buf.dir)) {
229
+ try {
230
+ const st = statSync(join(buf.dir, name));
231
+ if (st.isFile())
232
+ total += st.size;
233
+ }
234
+ catch {
235
+ }
236
+ }
237
+ }
238
+ catch {
239
+ }
240
+ return total;
241
+ }
242
+ export function cleanupReplayDirs(keep, root = replayRoot()) {
243
+ const keepSet = new Set([...keep].map((d) => d.toLowerCase()));
244
+ let names;
245
+ try {
246
+ names = readdirSync(root);
247
+ }
248
+ catch {
249
+ return 0;
250
+ }
251
+ let removed = 0;
252
+ for (const name of names) {
253
+ const dir = join(root, name);
254
+ if (!DIR_NAME.test(name) || keepSet.has(dir.toLowerCase()))
255
+ continue;
256
+ try {
257
+ rmSync(dir, { recursive: true, force: true });
258
+ removed++;
259
+ }
260
+ catch {
261
+ }
262
+ }
263
+ return removed;
264
+ }
265
+ export async function finishReplay(buf, opts) {
266
+ if (!opts.save)
267
+ return { saved: false, discarded: discardReplay(buf) };
268
+ try {
269
+ const tools = opts.tools?.();
270
+ if (!tools)
271
+ throw new ScreencastError("ffmpeg is not available to save the replay buffer.");
272
+ const save = await saveReplay(buf, { ...tools, lastSec: buf.bufferSec, output: opts.output, quality: opts.quality, live: false });
273
+ return { saved: true, discarded: discardReplay(buf), save };
274
+ }
275
+ catch (err) {
276
+ return { saved: false, discarded: false, error: err instanceof Error ? err.message : String(err) };
277
+ }
278
+ }
@@ -1,21 +1,6 @@
1
- /**
2
- * Shared capture-target resolution for screenshot and start_recording.
3
- *
4
- * This is the one place that turns a raw target spec into the concrete
5
- * (target, monitors) pair the gdigrab argument builders consume, so both the
6
- * still and the recording paths get identical behaviour:
7
- * - monitor:<i> -> its pixel bounds (queried live)
8
- * - window:<title> -> the on-screen RECTANGLE the window occupies, captured
9
- * via the proven region path (NOT gdigrab title=, which grabs a blank
10
- * surface for GPU-composited windows). The rect is resolved once, here.
11
- * - region -> validated against the live desktop, then passed through.
12
- * - full -> passed through, with the live monitor list so callers can size
13
- * the virtual desktop (#180).
14
- */
15
1
  import { parseTarget, validateRegionOnDesktop } from "./targets.js";
16
2
  import { getMonitors } from "./monitors.js";
17
3
  import { resolveWindowBounds } from "./windows.js";
18
- /** Resolve a raw target spec into builder-ready (target, monitors). */
19
4
  export async function resolveCaptureTarget(spec, opts = {}) {
20
5
  const parsed = parseTarget(spec);
21
6
  if (parsed.kind === "window") {
@@ -33,12 +18,8 @@ export async function resolveCaptureTarget(spec, opts = {}) {
33
18
  return { target: parsed, monitors: await getMonitors() };
34
19
  }
35
20
  if (parsed.kind === "region") {
36
- // A window resolves to a region already clamped to the desktop; a raw
37
- // region does not, so validate it against the live desktop bounds before
38
- // gdigrab fails cryptically on an off-desktop rectangle.
39
21
  validateRegionOnDesktop(parsed, await getMonitors());
40
22
  return { target: parsed, monitors: [] };
41
23
  }
42
24
  return { target: parsed, monitors: await getMonitors() };
43
25
  }
44
- //# sourceMappingURL=resolveTarget.js.map
@@ -1,23 +1,11 @@
1
- /**
2
- * Retention for captures the server keeps under SCREENCAST_HOME (#209).
3
- *
4
- * Screenshots and sampled frames pile up: every screenshot, sample_frames,
5
- * and contact_sheet call writes files, and they can show whatever was on
6
- * screen. With SCREENCAST_RETENTION_DAYS set, files in screenshots/ and
7
- * frames/ older than that are deleted when the server starts, along with
8
- * leftover raw event logs in recordings/. Recordings and edits are never
9
- * touched: they are the user's work. Off by default.
10
- */
11
1
  import { readdirSync, rmdirSync, statSync, unlinkSync } from "node:fs";
12
2
  import { join } from "node:path";
13
3
  import { homeRoot } from "./paths.js";
14
4
  export const RETENTION_ENV = "SCREENCAST_RETENTION_DAYS";
15
- /** The configured retention in days, or null when it is off (unset, 0, or invalid). */
16
5
  export function retentionDays(env = process.env) {
17
6
  const n = Number(env[RETENTION_ENV]);
18
7
  return Number.isFinite(n) && n > 0 ? n : null;
19
8
  }
20
- /** Delete capture files older than `days` under `root`. Returns what went. */
21
9
  export function pruneCaptures(days, now = Date.now(), root = homeRoot()) {
22
10
  const cutoff = now - days * 86_400_000;
23
11
  const result = { removed: 0, bytes: 0 };
@@ -27,7 +15,7 @@ export function pruneCaptures(days, now = Date.now(), root = homeRoot()) {
27
15
  names = readdirSync(dir);
28
16
  }
29
17
  catch {
30
- return; // not created yet
18
+ return;
31
19
  }
32
20
  for (const name of names) {
33
21
  const path = join(dir, name);
@@ -47,7 +35,6 @@ export function pruneCaptures(days, now = Date.now(), root = homeRoot()) {
47
35
  }
48
36
  }
49
37
  catch {
50
- // Locked or already gone: try again next start.
51
38
  }
52
39
  }
53
40
  };
@@ -56,4 +43,3 @@ export function pruneCaptures(days, now = Date.now(), root = homeRoot()) {
56
43
  prune(join(root, "recordings"), (name) => !/\.events\.raw(\.stop)?$/.test(name), false);
57
44
  return result;
58
45
  }
59
- //# sourceMappingURL=retention.js.map