@tmhs/screencast-mcp 0.49.0 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +13 -8
  2. package/dist/index.js +550 -106
  3. package/dist/wgcRecorder.js +15 -139
  4. package/package.json +8 -4
  5. package/assets/.gitkeep +0 -0
  6. package/assets/icon.png +0 -0
  7. package/dist/cli.js +0 -516
  8. package/dist/context.js +0 -50
  9. package/dist/prompts.js +0 -95
  10. package/dist/resources.js +0 -93
  11. package/dist/server.js +0 -174
  12. package/dist/setup.js +0 -438
  13. package/dist/tools/addMarker.js +0 -93
  14. package/dist/tools/assembleHighlights.js +0 -69
  15. package/dist/tools/backdrop.js +0 -89
  16. package/dist/tools/bugReport.js +0 -266
  17. package/dist/tools/burnSubtitles.js +0 -56
  18. package/dist/tools/callout.js +0 -103
  19. package/dist/tools/chapters.js +0 -156
  20. package/dist/tools/clip.js +0 -52
  21. package/dist/tools/compress.js +0 -51
  22. package/dist/tools/concat.js +0 -67
  23. package/dist/tools/contactSheet.js +0 -135
  24. package/dist/tools/convert.js +0 -46
  25. package/dist/tools/crop.js +0 -43
  26. package/dist/tools/cursor.js +0 -87
  27. package/dist/tools/cutByTranscript.js +0 -86
  28. package/dist/tools/cutIdle.js +0 -84
  29. package/dist/tools/deleteRecording.js +0 -119
  30. package/dist/tools/denoise.js +0 -60
  31. package/dist/tools/doctor.js +0 -146
  32. package/dist/tools/exportGif.js +0 -57
  33. package/dist/tools/exportPreset.js +0 -48
  34. package/dist/tools/extractAudio.js +0 -65
  35. package/dist/tools/findText.js +0 -196
  36. package/dist/tools/getMediaInfo.js +0 -36
  37. package/dist/tools/getSession.js +0 -40
  38. package/dist/tools/indexRecording.js +0 -195
  39. package/dist/tools/keystrokeOverlay.js +0 -131
  40. package/dist/tools/listAudioDevices.js +0 -35
  41. package/dist/tools/listSessions.js +0 -28
  42. package/dist/tools/listTargets.js +0 -76
  43. package/dist/tools/listVideoDevices.js +0 -26
  44. package/dist/tools/musicBed.js +0 -55
  45. package/dist/tools/narrate.js +0 -86
  46. package/dist/tools/normalizeAudio.js +0 -60
  47. package/dist/tools/overlay.js +0 -62
  48. package/dist/tools/pauseRecording.js +0 -44
  49. package/dist/tools/pipeline.js +0 -400
  50. package/dist/tools/readEvents.js +0 -98
  51. package/dist/tools/redactRegion.js +0 -70
  52. package/dist/tools/reframe.js +0 -46
  53. package/dist/tools/resumeRecording.js +0 -46
  54. package/dist/tools/reviewRecording.js +0 -163
  55. package/dist/tools/sampleFrames.js +0 -200
  56. package/dist/tools/saveReplay.js +0 -90
  57. package/dist/tools/scale.js +0 -44
  58. package/dist/tools/screenDiff.js +0 -86
  59. package/dist/tools/screenshot.js +0 -76
  60. package/dist/tools/searchRecording.js +0 -79
  61. package/dist/tools/speed.js +0 -46
  62. package/dist/tools/startRecording.js +0 -398
  63. package/dist/tools/stepGuide.js +0 -250
  64. package/dist/tools/stopRecording.js +0 -132
  65. package/dist/tools/titleCard.js +0 -67
  66. package/dist/tools/transcribe.js +0 -66
  67. package/dist/tools/trim.js +0 -57
  68. package/dist/tools/waitForChange.js +0 -128
  69. package/dist/tools/xfadeTransition.js +0 -58
  70. package/dist/tools/zoom.js +0 -149
  71. package/dist/utils/anim.js +0 -54
  72. package/dist/utils/animExport.js +0 -56
  73. package/dist/utils/argPaths.js +0 -39
  74. package/dist/utils/audio.js +0 -113
  75. package/dist/utils/audioDevices.js +0 -107
  76. package/dist/utils/backdrop.js +0 -151
  77. package/dist/utils/bugReport.js +0 -172
  78. package/dist/utils/callout.js +0 -90
  79. package/dist/utils/calloutAssets.js +0 -42
  80. package/dist/utils/capabilities.js +0 -96
  81. package/dist/utils/captions.js +0 -103
  82. package/dist/utils/chapters.js +0 -227
  83. package/dist/utils/consent.js +0 -29
  84. package/dist/utils/cursor.js +0 -317
  85. package/dist/utils/diff.js +0 -184
  86. package/dist/utils/errors.js +0 -29
  87. package/dist/utils/events.js +0 -403
  88. package/dist/utils/expr.js +0 -11
  89. package/dist/utils/ffmpeg.js +0 -285
  90. package/dist/utils/fontCoverage.js +0 -177
  91. package/dist/utils/fonts.js +0 -154
  92. package/dist/utils/gpu.js +0 -219
  93. package/dist/utils/idle.js +0 -91
  94. package/dist/utils/images.js +0 -38
  95. package/dist/utils/jobs.js +0 -129
  96. package/dist/utils/keystrokes.js +0 -155
  97. package/dist/utils/lifecycle.js +0 -233
  98. package/dist/utils/logging.js +0 -75
  99. package/dist/utils/media.js +0 -574
  100. package/dist/utils/monitors.js +0 -124
  101. package/dist/utils/narrate.js +0 -233
  102. package/dist/utils/ocr.js +0 -222
  103. package/dist/utils/ocrScan.js +0 -91
  104. package/dist/utils/paths.js +0 -155
  105. package/dist/utils/pause.js +0 -190
  106. package/dist/utils/pipeline.js +0 -361
  107. package/dist/utils/player.js +0 -85
  108. package/dist/utils/pool.js +0 -29
  109. package/dist/utils/produce.js +0 -298
  110. package/dist/utils/recipes.js +0 -71
  111. package/dist/utils/recorder.js +0 -173
  112. package/dist/utils/recordingFiles.js +0 -32
  113. package/dist/utils/recordingIndex.js +0 -312
  114. package/dist/utils/replay.js +0 -283
  115. package/dist/utils/resolveTarget.js +0 -25
  116. package/dist/utils/retention.js +0 -48
  117. package/dist/utils/roots.js +0 -43
  118. package/dist/utils/sessions.js +0 -499
  119. package/dist/utils/sheet.js +0 -59
  120. package/dist/utils/stepGuide.js +0 -231
  121. package/dist/utils/steps.js +0 -88
  122. package/dist/utils/still.js +0 -38
  123. package/dist/utils/targetList.js +0 -64
  124. package/dist/utils/targets.js +0 -265
  125. package/dist/utils/timeline.js +0 -85
  126. package/dist/utils/toolSpec.js +0 -31
  127. package/dist/utils/toolsets.js +0 -134
  128. package/dist/utils/transcriptCut.js +0 -149
  129. package/dist/utils/validate.js +0 -23
  130. package/dist/utils/waitLoop.js +0 -50
  131. package/dist/utils/wgc.js +0 -84
  132. package/dist/utils/windows.js +0 -192
  133. package/dist/utils/zoom.js +0 -234
@@ -1,128 +0,0 @@
1
- import { z } from "zod";
2
- import { errorResponse, okResponse } from "../utils/errors.js";
3
- import { READ_ONLY, looseOutput } from "../utils/toolSpec.js";
4
- import { requireFfmpeg, runFfmpeg, runFfmpegBuffer } from "../utils/ffmpeg.js";
5
- import { resolveCaptureTarget } from "../utils/resolveTarget.js";
6
- import { buildScreenshotArgs } from "../utils/targets.js";
7
- import { detectionSize, targetSize, buildRawGrabArgs, targetDiffOptions, DEFAULT_PIXEL_THRESHOLD, } from "../utils/diff.js";
8
- import { waitLoop } from "../utils/waitLoop.js";
9
- import { windowMatchReport } from "../utils/windows.js";
10
- import { confirmCapture, describeTarget } from "../utils/consent.js";
11
- import { subdir, stamp, rand } from "../utils/paths.js";
12
- import { join } from "node:path";
13
- import { rmSync } from "node:fs";
14
- import { tmpdir } from "node:os";
15
- import { encodeInlineImages, DEFAULT_MAX_IMAGE_WIDTH } from "../utils/images.js";
16
- const inputSchema = {
17
- target: z
18
- .string()
19
- .describe("What to watch: full | monitor:<i> | window:<title> (or exe=/hwnd=) | region:<x>,<y>,<w>,<h>."),
20
- exactTitle: z.boolean().optional().describe("window: targets match the whole title only (default false)."),
21
- mode: z
22
- .enum(["change", "settle"])
23
- .optional()
24
- .describe("change (default): return once it differs from the start. settle: once it has been still for settleSec."),
25
- timeoutSec: z
26
- .number()
27
- .positive()
28
- .max(600)
29
- .optional()
30
- .describe("Give up after this many seconds (default 30; a timeout is a result, not an error)."),
31
- settleSec: z
32
- .number()
33
- .positive()
34
- .max(60)
35
- .optional()
36
- .describe("Mode settle: seconds of stillness (default 1)."),
37
- intervalMs: z
38
- .number()
39
- .int()
40
- .min(100)
41
- .max(5000)
42
- .optional()
43
- .describe("Pause between checks in ms (default 250)."),
44
- pixelThreshold: z
45
- .number()
46
- .min(0)
47
- .max(255)
48
- .optional()
49
- .describe(`Mean 0-255 difference for a ~32x32 cell to count as changed (default ${DEFAULT_PIXEL_THRESHOLD}).`),
50
- returnImage: z
51
- .boolean()
52
- .optional()
53
- .describe("Return the final state inline (default true)."),
54
- keep: z
55
- .boolean()
56
- .optional()
57
- .describe("Keep the final screenshot on disk and return its path (default false)."),
58
- };
59
- export function register(server) {
60
- server.registerTool("wait_for_change", {
61
- title: "Wait for Screen Change",
62
- description: "Wait until part of the screen changes or settles, instead of guessing a sleep. Returns the " +
63
- "elapsed time, changed regions (screenshot pixels; add `origin` for desktop), and the final state.",
64
- inputSchema,
65
- outputSchema: looseOutput({
66
- outcome: z.string(),
67
- mode: z.string(),
68
- elapsedSec: z.number(),
69
- regions: z.array(z.unknown()),
70
- origin: looseOutput({ x: z.number(), y: z.number() }),
71
- }),
72
- annotations: READ_ONLY,
73
- }, async (args, extra) => {
74
- try {
75
- requireFfmpeg();
76
- const mode = args.mode ?? "change";
77
- const timeoutMs = (args.timeoutSec ?? 30) * 1000;
78
- const settleMs = (args.settleSec ?? 1) * 1000;
79
- const interval = args.intervalMs ?? 250;
80
- const { target, monitors, window } = await resolveCaptureTarget(args.target, { exactTitle: args.exactTitle });
81
- await confirmCapture(server, `Watch ${describeTarget(args.target, window)} for up to ${timeoutMs / 1000} s, until it ${mode === "settle" ? "stops changing" : "changes"}?`, extra.signal);
82
- const area = targetSize(target, monitors);
83
- const size = detectionSize(area.width, area.height);
84
- const grab = () => runFfmpegBuffer(buildRawGrabArgs(target, monitors, size), 15_000, { signal: extra.signal });
85
- const opts = targetDiffOptions(area, size, args.pixelThreshold);
86
- const { outcome, regions, everChanged, startedAt: started } = await waitLoop({
87
- grab,
88
- mode,
89
- width: size.width,
90
- height: size.height,
91
- diff: opts,
92
- timeoutMs,
93
- settleMs,
94
- intervalMs: interval,
95
- signal: extra.signal,
96
- });
97
- const result = {
98
- outcome,
99
- mode,
100
- elapsedSec: Number(((Date.now() - started) / 1000).toFixed(2)),
101
- ...(mode === "settle" ? { changedWhileWaiting: everChanged } : {}),
102
- regions,
103
- origin: { x: area.x, y: area.y },
104
- ...(window ? windowMatchReport(window) : {}),
105
- };
106
- const images = [];
107
- if (args.returnImage !== false && outcome !== "cancelled") {
108
- const shot = args.keep
109
- ? join(subdir("screenshots"), `wait-${stamp()}-${rand()}.png`)
110
- : join(tmpdir(), `screencast-wait-${stamp()}-${rand()}.png`);
111
- try {
112
- await runFfmpeg(buildScreenshotArgs(target, shot, monitors), 60_000, { signal: extra.signal });
113
- if (args.keep)
114
- result.screenshotPath = shot;
115
- images.push(...(await encodeInlineImages([shot], DEFAULT_MAX_IMAGE_WIDTH, 1)).images);
116
- }
117
- finally {
118
- if (!args.keep)
119
- rmSync(shot, { force: true });
120
- }
121
- }
122
- return okResponse(result, images);
123
- }
124
- catch (error) {
125
- return errorResponse(error);
126
- }
127
- });
128
- }
@@ -1,58 +0,0 @@
1
- import { z } from "zod";
2
- import { existsSync } from "node:fs";
3
- import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
4
- import { OUTPUT_PATH, WRITES_FILE } from "../utils/toolSpec.js";
5
- import { requireFfmpeg, probeMedia } from "../utils/ffmpeg.js";
6
- import { runEditJob } from "../utils/jobs.js";
7
- import { buildXfadeArgs, clipLength, DEFAULT_TRANSITION_DUR } from "../utils/produce.js";
8
- import { assertEditContainer } from "../utils/media.js";
9
- import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
10
- const inputSchema = {
11
- inputA: z.string().min(1).describe("Outgoing video."),
12
- inputB: z.string().min(1).describe("Incoming video."),
13
- transition: z
14
- .string()
15
- .optional()
16
- .describe("xfade name (default fade): fade, wipeleft, slideup, circleopen, dissolve, ..."),
17
- duration: z
18
- .number()
19
- .positive()
20
- .optional()
21
- .describe(`Transition length in seconds (default ${DEFAULT_TRANSITION_DUR}).`),
22
- output: z.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),
23
- overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
24
- };
25
- export function register(server) {
26
- server.registerTool("xfade_transition", {
27
- title: "Crossfade Transition",
28
- description: "Join two videos with an xfade transition (audio crossfaded); they need not match in size, " +
29
- "fps, or audio. For more clips use assemble_highlights.",
30
- inputSchema,
31
- outputSchema: OUTPUT_PATH,
32
- annotations: WRITES_FILE,
33
- }, async (args, extra) => {
34
- try {
35
- requireFfmpeg();
36
- for (const f of [args.inputA, args.inputB]) {
37
- if (!existsSync(f))
38
- throw new ScreencastError(`Input file not found: ${f}`);
39
- }
40
- assertEditContainer(args.output);
41
- const [a, b] = await Promise.all([probeMedia(args.inputA), probeMedia(args.inputB)]);
42
- const durA = clipLength(a);
43
- const durB = clipLength(b);
44
- if (durA === null || durB === null) {
45
- throw new ScreencastError(`Could not read duration of ${durA === null ? args.inputA : args.inputB}.`);
46
- }
47
- const clipHasAudio = [a.audioCodec !== null, b.audioCodec !== null];
48
- const hasAudio = clipHasAudio[0] || clipHasAudio[1];
49
- const output = resolveOutput(args.output, subdir("edits"), `xfade-${stamp()}-${rand()}.mp4`, args.overwrite);
50
- const ffArgs = buildXfadeArgs(args.inputA, args.inputB, [durA, durB], output, { transition: args.transition, duration: args.duration }, clipHasAudio);
51
- await runEditJob(ffArgs, { output, durationSec: durA + durB, extra });
52
- return okResponse({ outputPath: output, audio: hasAudio });
53
- }
54
- catch (error) {
55
- return errorResponse(error);
56
- }
57
- });
58
- }
@@ -1,149 +0,0 @@
1
- import { z } from "zod";
2
- import { existsSync, readFileSync } from "node:fs";
3
- import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
4
- import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
5
- import { requireFfmpeg, runFfmpegFrames, probeMedia } from "../utils/ffmpeg.js";
6
- import { runEditJob, jobTimeoutMs } from "../utils/jobs.js";
7
- import { analysisSize } from "../utils/diff.js";
8
- import { keyframesToViews, buildZoomArgs, createAutoZoomPlanner, planClickZoom, buildAnalysisArgs, DEFAULT_TRANSITION_SEC, DEFAULT_AUTO_MAX_ZOOM, DEFAULT_RING_COLOR, MAX_ZOOM, } from "../utils/zoom.js";
9
- import { eventPaths, parseEventsJsonl } from "../utils/events.js";
10
- import { validateColor } from "../utils/validate.js";
11
- export const MAX_RINGS = 200;
12
- export function readClicks(path) {
13
- if (!existsSync(path))
14
- return null;
15
- return parseEventsJsonl(readFileSync(path, "utf8"))
16
- .filter((e) => e.type === "down" && e.inFrame)
17
- .map((e) => ({ t: e.t, x: e.x, y: e.y }));
18
- }
19
- import { editOutputExt, assertEditContainer } from "../utils/media.js";
20
- import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
21
- export const zoomKeyframeSchema = z.object({
22
- t: z.number().nonnegative(),
23
- x: z.number().optional(),
24
- y: z.number().optional(),
25
- width: z.number().positive().optional(),
26
- height: z.number().positive().optional(),
27
- full: z.boolean().optional(),
28
- });
29
- const inputSchema = {
30
- input: z.string().min(1).describe("Path to the source video."),
31
- keyframes: z
32
- .array(zoomKeyframeSchema)
33
- .max(100)
34
- .optional()
35
- .describe("Views reached by time t: a source rectangle (x, y, width, height), or { t, full: true } to " +
36
- "zoom out. Omit to plan them (see follow)."),
37
- follow: z
38
- .enum(["auto", "clicks", "changes"])
39
- .optional()
40
- .describe("Without keyframes: clicks (from the events log of start_recording events: true) or changes " +
41
- "(where the screen changed). auto (default): clicks if logged, else changes."),
42
- events: z
43
- .string()
44
- .optional()
45
- .describe("Events log (default: the input's .events.jsonl); must match the input's timing and size, so " +
46
- "use the original recording."),
47
- highlightClicks: z
48
- .boolean()
49
- .optional()
50
- .describe("Ring each logged click (default false)."),
51
- highlightColor: z.string().optional().describe("Ring color (default #FF4545)."),
52
- transitionSec: z
53
- .number()
54
- .positive()
55
- .max(5)
56
- .optional()
57
- .describe(`How long each zoom/pan eases (default ${DEFAULT_TRANSITION_SEC}).`),
58
- maxZoom: z
59
- .number()
60
- .min(1)
61
- .max(MAX_ZOOM)
62
- .optional()
63
- .describe(`Auto mode: the furthest it zooms in (default ${DEFAULT_AUTO_MAX_ZOOM}).`),
64
- holdSec: z.number().positive().max(30).optional().describe("Auto mode: stay zoomed this long after activity (default 2)."),
65
- dryRun: z.boolean().optional().describe("Return the planned keyframes only (editable, pass back)."),
66
- output: z.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),
67
- overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
68
- };
69
- export function register(server) {
70
- server.registerTool("zoom", {
71
- title: "Zoom and Pan",
72
- description: "Smooth animated zoom-and-pan into the action and back out, from keyframes or planned from " +
73
- "logged clicks or screen changes.",
74
- inputSchema,
75
- outputSchema: looseOutput({ keyframes: z.array(z.unknown()) }),
76
- annotations: WRITES_FILE,
77
- }, async (args, extra) => {
78
- try {
79
- requireFfmpeg();
80
- if (!existsSync(args.input))
81
- throw new ScreencastError(`Input file not found: ${args.input}`);
82
- const info = await probeMedia(args.input);
83
- const { width: W, height: H, durationSec } = info;
84
- if (!W || !H)
85
- throw new ScreencastError(`Could not read the size of ${args.input}.`);
86
- const fps = info.fps ?? 30;
87
- const transition = args.transitionSec ?? DEFAULT_TRANSITION_SEC;
88
- const eventsPath = args.events ?? eventPaths(args.input).jsonl;
89
- const clicks = readClicks(eventsPath);
90
- if (args.events && !clicks)
91
- throw new ScreencastError(`No event log at ${args.events}.`);
92
- if ((args.follow === "clicks" || args.highlightClicks) && !clicks) {
93
- throw new ScreencastError(`No event log for ${args.input} (looked for ${eventsPath}). Record with start_recording ` +
94
- "events: true, or pass events: <path to .events.jsonl>.");
95
- }
96
- const ringColor = validateColor(args.highlightColor ?? DEFAULT_RING_COLOR, "highlightColor");
97
- let keyframes = args.keyframes;
98
- const planned = !keyframes;
99
- const follow = args.follow === "clicks" || (args.follow !== "changes" && clicks && clicks.length > 0) ? "clicks" : "changes";
100
- if (!keyframes && follow === "clicks") {
101
- keyframes = planClickZoom(clicks ?? [], W, H, { holdSec: args.holdSec, maxZoom: args.maxZoom, transition });
102
- if (keyframes.length === 0) {
103
- return okResponse({ keyframes: [], follow, note: "The event log has no clicks inside the frame; nothing written." });
104
- }
105
- }
106
- if (!keyframes) {
107
- const size = analysisSize(W, H);
108
- const step = 0.25;
109
- const planner = createAutoZoomPlanner(size.width, size.height, W, H, {
110
- step,
111
- holdSec: args.holdSec,
112
- maxZoom: args.maxZoom,
113
- transition,
114
- });
115
- await runFfmpegFrames(buildAnalysisArgs(args.input, size, step), size.width * size.height, (f) => planner.push(f), jobTimeoutMs(durationSec), { signal: extra.signal });
116
- keyframes = planner.finish();
117
- if (keyframes.length === 0) {
118
- return okResponse({ keyframes: [], note: "No localised changes found to zoom into; nothing written." });
119
- }
120
- }
121
- if (args.dryRun) {
122
- return okResponse({ planned, ...(planned ? { follow } : {}), keyframes, transitionSec: transition });
123
- }
124
- if (args.highlightClicks && clicks && clicks.length > MAX_RINGS) {
125
- throw new ScreencastError(`${clicks.length} clicks is more than ${MAX_RINGS} rings; trim the video or the event log first.`);
126
- }
127
- const views = keyframesToViews(keyframes, W, H);
128
- assertEditContainer(args.output);
129
- const ext = editOutputExt(args.input);
130
- const output = resolveOutput(args.output, subdir("edits"), `zoom-${stamp()}-${rand()}${ext}`, args.overwrite);
131
- const rings = args.highlightClicks ? { clicks: clicks ?? [], color: ringColor } : undefined;
132
- await runEditJob(buildZoomArgs(args.input, output, views, { width: W, height: H, fps }, transition, "standard", rings), {
133
- output,
134
- durationSec,
135
- extra,
136
- });
137
- return okResponse({
138
- outputPath: output,
139
- planned,
140
- ...(planned ? { follow } : {}),
141
- keyframes,
142
- ...(rings ? { ringedClicks: rings.clicks.length } : {}),
143
- });
144
- }
145
- catch (error) {
146
- return errorResponse(error);
147
- }
148
- });
149
- }
@@ -1,54 +0,0 @@
1
- import { ScreencastError } from "./errors.js";
2
- export const DEFAULT_ANIM_FPS = 12;
3
- export const DEFAULT_ANIM_WIDTH = 960;
4
- export const DEFAULT_MAX_BYTES = 10_000_000;
5
- export const MAX_ATTEMPTS = 5;
6
- export function animLadder(format, fps, width) {
7
- const steps = format === "gif"
8
- ? [[1, 1, 256], [0.83, 0.8, 256], [0.67, 0.67, 128], [0.5, 0.5, 64], [0.4, 0.4, 32], [0.33, 0.33, 16]]
9
- : [[1, 1, 75], [0.83, 0.8, 65], [0.67, 0.67, 55], [0.5, 0.5, 45], [0.4, 0.4, 35], [0.33, 0.33, 25]];
10
- return steps.map(([f, w, q]) => ({
11
- fps: Math.max(1, Math.round(fps * f * 10) / 10),
12
- width: Math.max(64, Math.round((width * w) / 2) * 2),
13
- ...(format === "gif" ? { colors: q } : { quality: q }),
14
- }));
15
- }
16
- export function nextLadderIndex(index, size, maxBytes, ladderLength) {
17
- const last = ladderLength - 1;
18
- if (index >= last)
19
- return null;
20
- const jump = Math.max(1, Math.ceil(Math.log(size / maxBytes) / Math.log(1.8)));
21
- return Math.min(last, index + jump);
22
- }
23
- export function buildAnimArgs(input, output, format, s, clip = {}) {
24
- if (!(s.fps > 0) || !Number.isInteger(s.width) || s.width < 16) {
25
- throw new ScreencastError("fps must be positive and width an integer of at least 16.");
26
- }
27
- if (clip.start !== undefined && !(clip.start >= 0))
28
- throw new ScreencastError("start must be >= 0.");
29
- if (clip.duration !== undefined && !(clip.duration > 0))
30
- throw new ScreencastError("duration must be > 0.");
31
- const window = [
32
- ...(clip.start ? ["-ss", String(clip.start)] : []),
33
- ...(clip.duration ? ["-t", String(clip.duration)] : []),
34
- ];
35
- const base = `fps=${s.fps},scale='min(${s.width},iw)':-1:flags=lanczos`;
36
- if (format === "gif") {
37
- const colors = s.colors ?? 256;
38
- return [
39
- "-y", ...window, "-i", input, "-an",
40
- "-vf",
41
- `${base},split[a][b];[a]palettegen=stats_mode=diff:max_colors=${colors}[p];` +
42
- "[b][p]paletteuse=dither=sierra2_4a:diff_mode=rectangle",
43
- "-loop", "0",
44
- output,
45
- ];
46
- }
47
- return [
48
- "-y", ...window, "-i", input, "-an",
49
- "-vf", base,
50
- "-c:v", "libwebp_anim", "-lossless", "0", "-q:v", String(s.quality ?? 75),
51
- "-compression_level", "4", "-loop", "0",
52
- output,
53
- ];
54
- }
@@ -1,56 +0,0 @@
1
- import { basename, dirname, extname, join } from "node:path";
2
- import { renameSync, rmSync, statSync } from "node:fs";
3
- import { runEditJob, probeDuration } from "./jobs.js";
4
- import { animLadder, nextLadderIndex, buildAnimArgs, DEFAULT_ANIM_FPS, DEFAULT_ANIM_WIDTH, DEFAULT_MAX_BYTES, MAX_ATTEMPTS, } from "./anim.js";
5
- export async function exportAnimation(input, output, opts, extra) {
6
- const format = opts.format ?? "gif";
7
- const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES;
8
- const full = await probeDuration(input);
9
- const clipSec = opts.duration ?? (full !== null ? full - (opts.start ?? 0) : null);
10
- const ladder = animLadder(format, opts.fps ?? DEFAULT_ANIM_FPS, opts.width ?? DEFAULT_ANIM_WIDTH);
11
- const ext = extname(output);
12
- const attemptPath = (i) => join(dirname(output), `${basename(output, ext)}.try${i}${ext}`);
13
- const attempts = [];
14
- try {
15
- let index = 0;
16
- while (index !== null && attempts.length < MAX_ATTEMPTS) {
17
- const settings = ladder[index];
18
- if (!settings)
19
- break;
20
- const path = attemptPath(attempts.length);
21
- const clip = { start: opts.start, duration: opts.duration };
22
- await runEditJob(buildAnimArgs(input, path, format, settings, clip), {
23
- output: path,
24
- durationSec: clipSec,
25
- extra,
26
- });
27
- const size = statSync(path).size;
28
- attempts.push({ path, size, settings });
29
- if (size <= maxBytes)
30
- break;
31
- index = nextLadderIndex(index, size, maxBytes, ladder.length);
32
- }
33
- const fits = attempts.find((a) => a.size <= maxBytes);
34
- const chosen = fits ?? attempts.reduce((a, b) => (b.size < a.size ? b : a));
35
- renameSync(chosen.path, output);
36
- return {
37
- outputPath: output,
38
- format,
39
- sizeBytes: chosen.size,
40
- maxBytes,
41
- withinBudget: chosen.size <= maxBytes,
42
- settings: chosen.settings,
43
- attempts: attempts.map((a) => ({ ...a.settings, sizeBytes: a.size })),
44
- ...(fits
45
- ? {}
46
- : {
47
- note: `Could not get under ${maxBytes} bytes; kept the smallest attempt. ` +
48
- "Export a shorter clip (start/duration), or try format: 'webp'.",
49
- }),
50
- };
51
- }
52
- finally {
53
- for (const a of attempts)
54
- rmSync(a.path, { force: true });
55
- }
56
- }
@@ -1,39 +0,0 @@
1
- import { assertInputAllowed, assertLocalPath } from "./paths.js";
2
- const INPUT_KEYS = new Set([
3
- "input", "inputs", "inputA", "inputB", "clips", "a", "b", "image", "overlay",
4
- "music", "video", "subtitles", "srt", "transcript", "events",
5
- ]);
6
- const LOCAL_ONLY_KEYS = new Set(["output", "outputDir", "model", "fontFile"]);
7
- const KEYWORDS = new Set(["whisper"]);
8
- function strings(value) {
9
- if (typeof value === "string")
10
- return [value];
11
- if (Array.isArray(value))
12
- return value.filter((v) => typeof v === "string");
13
- return [];
14
- }
15
- export function assertArgPaths(args) {
16
- const visit = (node) => {
17
- if (Array.isArray(node)) {
18
- node.forEach(visit);
19
- return;
20
- }
21
- if (!node || typeof node !== "object")
22
- return;
23
- for (const [key, value] of Object.entries(node)) {
24
- if (INPUT_KEYS.has(key)) {
25
- for (const s of strings(value)) {
26
- if (s.trim().length > 0 && !KEYWORDS.has(s))
27
- assertInputAllowed(s, `Input "${key}"`);
28
- }
29
- }
30
- else if (LOCAL_ONLY_KEYS.has(key)) {
31
- for (const s of strings(value))
32
- assertLocalPath(s, `"${key}"`);
33
- }
34
- if (value && typeof value === "object")
35
- visit(value);
36
- }
37
- };
38
- visit(args);
39
- }
@@ -1,113 +0,0 @@
1
- import { extname } from "node:path";
2
- import { ScreencastError } from "./errors.js";
3
- import { isAudioOnlyPath } from "./media.js";
4
- export const LOUDNESS_PRESETS = {
5
- youtube: { i: -14, tp: -1, lra: 11 },
6
- podcast: { i: -16, tp: -1.5, lra: 11 },
7
- broadcast: { i: -23, tp: -1, lra: 7 },
8
- };
9
- export function loudnessTarget(target) {
10
- if (target === undefined)
11
- return LOUDNESS_PRESETS.youtube;
12
- if (typeof target === "number") {
13
- if (!Number.isFinite(target) || target < -70 || target > -5) {
14
- throw new ScreencastError("target LUFS must be between -70 and -5 (e.g. -14).");
15
- }
16
- return { i: target, tp: -1, lra: 11 };
17
- }
18
- const p = LOUDNESS_PRESETS[target];
19
- if (!p)
20
- throw new ScreencastError(`Unknown loudness target "${target}".`);
21
- return p;
22
- }
23
- const filterTarget = (t) => `I=${t.i}:TP=${t.tp}:LRA=${t.lra}`;
24
- export function buildLoudnessMeasureArgs(input, t) {
25
- return ["-hide_banner", "-nostats", "-i", input, "-vn", "-af", `loudnorm=${filterTarget(t)}:print_format=json`, "-f", "null", "-"];
26
- }
27
- export function parseLoudnorm(stderr) {
28
- const blocks = stderr.match(/\{[^{}]*"input_i"[^{}]*\}/g);
29
- const lastBlock = blocks?.at(-1);
30
- if (lastBlock === undefined)
31
- throw new ScreencastError("Could not measure loudness (no loudnorm report). Does the file have audio?");
32
- const raw = JSON.parse(lastBlock);
33
- const num = (k) => Number(raw[k]);
34
- const m = {
35
- input_i: num("input_i"),
36
- input_tp: num("input_tp"),
37
- input_lra: num("input_lra"),
38
- input_thresh: num("input_thresh"),
39
- target_offset: num("target_offset"),
40
- ...(raw.output_i !== undefined ? { output_i: num("output_i") } : {}),
41
- };
42
- if (!Number.isFinite(m.input_i)) {
43
- throw new ScreencastError("The audio is silent (loudness is -inf), so there is nothing to normalize.");
44
- }
45
- return m;
46
- }
47
- function keepVideoArgs(output) {
48
- return isAudioOnlyPath(output)
49
- ? ["-map", "0:a:0", "-vn"]
50
- : ["-map", "0:v?", "-map", "0:a:0", "-c:v", "copy"];
51
- }
52
- export function audioCodecFor(output) {
53
- switch (extname(output).toLowerCase()) {
54
- case ".wav":
55
- return ["-c:a", "pcm_s16le"];
56
- case ".mp3":
57
- return ["-c:a", "libmp3lame", "-b:a", "192k"];
58
- default:
59
- return ["-c:a", "aac", "-b:a", "192k"];
60
- }
61
- }
62
- export function loudnormFilter(t, m) {
63
- if (!m)
64
- return `loudnorm=${filterTarget(t)}`;
65
- const measured = `measured_I=${m.input_i}:measured_TP=${m.input_tp}:measured_LRA=${m.input_lra}:` +
66
- `measured_thresh=${m.input_thresh}:offset=${m.target_offset}`;
67
- return `loudnorm=${filterTarget(t)}:${measured}:linear=true`;
68
- }
69
- export function buildLoudnessApplyArgs(input, output, t, m) {
70
- return [
71
- "-y", "-hide_banner", "-i", input,
72
- ...keepVideoArgs(output),
73
- "-af", `${loudnormFilter(t, m)}:print_format=json`,
74
- "-ar", "48000",
75
- ...audioCodecFor(output),
76
- output,
77
- ];
78
- }
79
- export const DENOISE_NR = { light: 6, medium: 12, strong: 20 };
80
- export function buildNoiseFloorArgs(input) {
81
- return [
82
- "-hide_banner", "-nostats", "-i", input, "-vn",
83
- "-af", "aresample=48000,asetnsamples=4800,astats=metadata=1:reset=1,ametadata=print:key=lavfi.astats.Overall.RMS_level:file=-",
84
- "-f", "null", "-",
85
- ];
86
- }
87
- export function parseNoiseFloor(stdout) {
88
- const levels = [...stdout.matchAll(/RMS_level=(-?[\d.]+)/g)].map((m) => Number(m[1])).filter(Number.isFinite);
89
- if (levels.length === 0)
90
- return null;
91
- levels.sort((a, b) => a - b);
92
- return levels[Math.floor(levels.length * 0.1)] ?? null;
93
- }
94
- export function noiseFloorSetting(floorDb) {
95
- if (floorDb === null)
96
- return -50;
97
- return Math.max(-80, Math.min(-20, Math.round(floorDb + 5)));
98
- }
99
- export function denoiseFilter(strength, noiseFloorDb) {
100
- const nr = DENOISE_NR[strength];
101
- if (nr === undefined)
102
- throw new ScreencastError(`Unknown denoise strength "${strength}".`);
103
- return `afftdn=nr=${nr}:nf=${noiseFloorSetting(noiseFloorDb)}`;
104
- }
105
- export function buildDenoiseArgs(input, output, strength = "medium", noiseFloorDb = null) {
106
- return [
107
- "-y", "-i", input,
108
- ...keepVideoArgs(output),
109
- "-af", denoiseFilter(strength, noiseFloorDb),
110
- ...audioCodecFor(output),
111
- output,
112
- ];
113
- }