@tmhs/screencast-mcp 0.49.1 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +15 -9
  2. package/dist/index.js +551 -106
  3. package/dist/wgcRecorder.js +15 -139
  4. package/package.json +9 -5
  5. package/assets/.gitkeep +0 -0
  6. package/assets/icon.png +0 -0
  7. package/dist/cli.js +0 -516
  8. package/dist/context.js +0 -50
  9. package/dist/prompts.js +0 -95
  10. package/dist/resources.js +0 -93
  11. package/dist/server.js +0 -174
  12. package/dist/setup.js +0 -438
  13. package/dist/tools/addMarker.js +0 -93
  14. package/dist/tools/assembleHighlights.js +0 -69
  15. package/dist/tools/backdrop.js +0 -79
  16. package/dist/tools/bugReport.js +0 -243
  17. package/dist/tools/burnSubtitles.js +0 -56
  18. package/dist/tools/callout.js +0 -62
  19. package/dist/tools/chapters.js +0 -156
  20. package/dist/tools/clip.js +0 -52
  21. package/dist/tools/compress.js +0 -51
  22. package/dist/tools/concat.js +0 -67
  23. package/dist/tools/contactSheet.js +0 -113
  24. package/dist/tools/convert.js +0 -46
  25. package/dist/tools/crop.js +0 -43
  26. package/dist/tools/cursor.js +0 -67
  27. package/dist/tools/cutByTranscript.js +0 -86
  28. package/dist/tools/cutIdle.js +0 -84
  29. package/dist/tools/deleteRecording.js +0 -119
  30. package/dist/tools/denoise.js +0 -60
  31. package/dist/tools/doctor.js +0 -146
  32. package/dist/tools/exportGif.js +0 -57
  33. package/dist/tools/exportPreset.js +0 -48
  34. package/dist/tools/extractAudio.js +0 -65
  35. package/dist/tools/findText.js +0 -194
  36. package/dist/tools/getMediaInfo.js +0 -36
  37. package/dist/tools/getSession.js +0 -40
  38. package/dist/tools/indexRecording.js +0 -195
  39. package/dist/tools/keystrokeOverlay.js +0 -90
  40. package/dist/tools/listAudioDevices.js +0 -35
  41. package/dist/tools/listSessions.js +0 -28
  42. package/dist/tools/listTargets.js +0 -76
  43. package/dist/tools/listVideoDevices.js +0 -26
  44. package/dist/tools/musicBed.js +0 -55
  45. package/dist/tools/narrate.js +0 -86
  46. package/dist/tools/normalizeAudio.js +0 -59
  47. package/dist/tools/overlay.js +0 -62
  48. package/dist/tools/pauseRecording.js +0 -44
  49. package/dist/tools/pipeline.js +0 -397
  50. package/dist/tools/readEvents.js +0 -98
  51. package/dist/tools/redactRegion.js +0 -62
  52. package/dist/tools/reframe.js +0 -46
  53. package/dist/tools/resumeRecording.js +0 -46
  54. package/dist/tools/reviewRecording.js +0 -163
  55. package/dist/tools/sampleFrames.js +0 -200
  56. package/dist/tools/saveReplay.js +0 -90
  57. package/dist/tools/scale.js +0 -44
  58. package/dist/tools/screenDiff.js +0 -86
  59. package/dist/tools/screenshot.js +0 -76
  60. package/dist/tools/searchRecording.js +0 -79
  61. package/dist/tools/speed.js +0 -46
  62. package/dist/tools/startRecording.js +0 -398
  63. package/dist/tools/stepGuide.js +0 -249
  64. package/dist/tools/stopRecording.js +0 -132
  65. package/dist/tools/titleCard.js +0 -67
  66. package/dist/tools/transcribe.js +0 -66
  67. package/dist/tools/trim.js +0 -57
  68. package/dist/tools/waitForChange.js +0 -142
  69. package/dist/tools/xfadeTransition.js +0 -58
  70. package/dist/tools/zoom.js +0 -134
  71. package/dist/utils/anim.js +0 -54
  72. package/dist/utils/animExport.js +0 -56
  73. package/dist/utils/argPaths.js +0 -39
  74. package/dist/utils/audio.js +0 -117
  75. package/dist/utils/audioDevices.js +0 -107
  76. package/dist/utils/backdrop.js +0 -162
  77. package/dist/utils/bugReport.js +0 -195
  78. package/dist/utils/callout.js +0 -132
  79. package/dist/utils/calloutAssets.js +0 -42
  80. package/dist/utils/capabilities.js +0 -96
  81. package/dist/utils/captions.js +0 -104
  82. package/dist/utils/chapters.js +0 -227
  83. package/dist/utils/consent.js +0 -29
  84. package/dist/utils/cursor.js +0 -338
  85. package/dist/utils/diff.js +0 -186
  86. package/dist/utils/errors.js +0 -29
  87. package/dist/utils/events.js +0 -403
  88. package/dist/utils/expr.js +0 -11
  89. package/dist/utils/ffmpeg.js +0 -285
  90. package/dist/utils/fontCoverage.js +0 -177
  91. package/dist/utils/fonts.js +0 -154
  92. package/dist/utils/frameQueue.js +0 -50
  93. package/dist/utils/gpu.js +0 -219
  94. package/dist/utils/idle.js +0 -91
  95. package/dist/utils/images.js +0 -38
  96. package/dist/utils/jobs.js +0 -129
  97. package/dist/utils/keystrokes.js +0 -198
  98. package/dist/utils/lifecycle.js +0 -233
  99. package/dist/utils/logging.js +0 -75
  100. package/dist/utils/media.js +0 -584
  101. package/dist/utils/monitors.js +0 -124
  102. package/dist/utils/narrate.js +0 -233
  103. package/dist/utils/ocr.js +0 -222
  104. package/dist/utils/ocrScan.js +0 -93
  105. package/dist/utils/paths.js +0 -155
  106. package/dist/utils/pause.js +0 -190
  107. package/dist/utils/pipeline.js +0 -361
  108. package/dist/utils/player.js +0 -85
  109. package/dist/utils/pool.js +0 -29
  110. package/dist/utils/produce.js +0 -300
  111. package/dist/utils/recipes.js +0 -71
  112. package/dist/utils/recorder.js +0 -173
  113. package/dist/utils/recordingFiles.js +0 -32
  114. package/dist/utils/recordingIndex.js +0 -312
  115. package/dist/utils/replay.js +0 -283
  116. package/dist/utils/resolveTarget.js +0 -25
  117. package/dist/utils/retention.js +0 -48
  118. package/dist/utils/roots.js +0 -43
  119. package/dist/utils/sessions.js +0 -499
  120. package/dist/utils/sheet.js +0 -82
  121. package/dist/utils/stepGuide.js +0 -231
  122. package/dist/utils/steps.js +0 -88
  123. package/dist/utils/still.js +0 -38
  124. package/dist/utils/targetList.js +0 -64
  125. package/dist/utils/targets.js +0 -265
  126. package/dist/utils/timeline.js +0 -85
  127. package/dist/utils/toolSpec.js +0 -31
  128. package/dist/utils/toolsets.js +0 -134
  129. package/dist/utils/transcriptCut.js +0 -149
  130. package/dist/utils/validate.js +0 -23
  131. package/dist/utils/waitLoop.js +0 -50
  132. package/dist/utils/wgc.js +0 -84
  133. package/dist/utils/windows.js +0 -192
  134. package/dist/utils/zoom.js +0 -252
@@ -1,584 +0,0 @@
1
- import { extname } from "node:path";
2
- import { ScreencastError } from "./errors.js";
3
- import { resolveQuality } from "./targets.js";
4
- import { validateColor, validateEvenDimension } from "./validate.js";
5
- import { isStillImage, stillOutput } from "./paths.js";
6
- import { z } from "zod";
7
- const DEFAULT_EDIT_QUALITY = "standard";
8
- function numberOrNull(v) {
9
- if (v === undefined)
10
- return null;
11
- const n = Number(v);
12
- return Number.isFinite(n) ? n : null;
13
- }
14
- export function parseFrameRate(value) {
15
- if (!value)
16
- return null;
17
- const [num, den] = value.split("/");
18
- const n = Number(num);
19
- const d = den === undefined ? 1 : Number(den);
20
- if (!Number.isFinite(n) || !Number.isFinite(d) || d === 0)
21
- return null;
22
- if (n === 0)
23
- return null;
24
- return Math.round((n / d) * 1000) / 1000;
25
- }
26
- function streamRotation(video) {
27
- const side = video?.side_data_list?.find((d) => d.rotation !== undefined)?.rotation;
28
- const raw = side ?? video?.tags?.rotate;
29
- const n = raw === undefined ? NaN : Number(raw);
30
- return Number.isFinite(n) ? Math.round(n) % 360 : null;
31
- }
32
- export function parseMediaInfo(probe) {
33
- const streams = probe.streams ?? [];
34
- const video = streams.find((s) => s.codec_type === "video");
35
- const audio = streams.find((s) => s.codec_type === "audio");
36
- const duration = probe.format?.duration;
37
- const size = probe.format?.size;
38
- const durationSec = duration !== undefined ? Number(duration) : null;
39
- const rotation = streamRotation(video);
40
- const turned = rotation !== null && Math.abs(rotation) % 180 === 90;
41
- return {
42
- durationSec,
43
- videoDurationSec: video ? (numberOrNull(video.duration) ?? durationSec) : null,
44
- width: (turned ? video?.height : video?.width) ?? null,
45
- height: (turned ? video?.width : video?.height) ?? null,
46
- ...(rotation ? { rotation } : {}),
47
- fps: parseFrameRate(video?.avg_frame_rate) ?? parseFrameRate(video?.r_frame_rate),
48
- videoCodec: video?.codec_name ?? null,
49
- audioCodec: audio?.codec_name ?? null,
50
- format: probe.format?.format_name ?? null,
51
- sizeBytes: size !== undefined ? Number(size) : null,
52
- pixFmt: video?.pix_fmt ?? null,
53
- videoFrames: numberOrNull(video?.nb_frames),
54
- sampleRate: numberOrNull(audio?.sample_rate),
55
- channels: audio?.channels ?? null,
56
- };
57
- }
58
- export function buildProbeArgs(input) {
59
- return [
60
- "-v", "quiet",
61
- "-print_format", "json",
62
- "-show_format",
63
- "-show_streams",
64
- input,
65
- ];
66
- }
67
- function validatePositive(value, label) {
68
- if (!Number.isFinite(value) || value <= 0) {
69
- throw new ScreencastError(`${label} must be a positive number.`);
70
- }
71
- return value;
72
- }
73
- export const DEFAULT_MAX_FRAMES = 100;
74
- export const MAX_FRAMES_CEILING = 1000;
75
- export function planFpsSampling(durationSec, fps, maxFrames) {
76
- validatePositive(fps, "fps");
77
- if (durationSec === null || !(durationSec > 0)) {
78
- return { fps, requestedFrames: null, clamped: false };
79
- }
80
- const requested = Math.ceil(durationSec * fps);
81
- if (requested <= maxFrames)
82
- return { fps, requestedFrames: requested, clamped: false };
83
- const clampedFps = Math.max(1e-4, Math.floor((maxFrames / durationSec) * 10_000) / 10_000);
84
- return { fps: clampedFps, requestedFrames: requested, clamped: true };
85
- }
86
- export function pickFramePrefix(existing, unique) {
87
- for (const f of existing)
88
- if (/^frame_\d+\.png$/i.test(f))
89
- return `frame_${unique}_`;
90
- return "frame_";
91
- }
92
- export function buildSampleByFpsArgs(input, fps, outputPattern, maxFrames = DEFAULT_MAX_FRAMES, dedupe = false, range) {
93
- validatePositive(fps, "fps");
94
- const vf = dedupe ? `fps=${fps},mpdecimate` : `fps=${fps}`;
95
- const seek = range
96
- ? ["-ss", String(range.start), ...(range.duration !== undefined ? ["-t", String(range.duration)] : [])]
97
- : [];
98
- return [
99
- "-y", ...seek, "-i", input, "-vf", vf,
100
- ...(dedupe ? ["-fps_mode", "vfr"] : []),
101
- "-frames:v", String(maxFrames), outputPattern,
102
- ];
103
- }
104
- export const DEFAULT_SCENE_THRESHOLD = 0.1;
105
- export function buildSceneScanArgs(input, threshold = DEFAULT_SCENE_THRESHOLD) {
106
- if (!Number.isFinite(threshold) || threshold <= 0 || threshold >= 1) {
107
- throw new ScreencastError("sceneThreshold must be between 0 and 1 (exclusive).");
108
- }
109
- return [
110
- "-v", "error", "-i", input, "-an",
111
- "-vf", `scale=320:-2,select='gt(scene\\,${threshold})',metadata=print:file=-`,
112
- "-f", "null", "-",
113
- ];
114
- }
115
- export function parseSceneScan(stdout) {
116
- const out = [];
117
- let time = null;
118
- for (const line of stdout.split(/\r?\n/)) {
119
- const t = line.match(/pts_time:\s*(-?[\d.]+)/);
120
- if (t) {
121
- time = Number(t[1]);
122
- continue;
123
- }
124
- const s = line.match(/lavfi\.scene_score=([\d.]+)/);
125
- if (s && time !== null) {
126
- out.push({ timeSec: time, score: Number(s[1]) });
127
- time = null;
128
- }
129
- }
130
- return out;
131
- }
132
- export function pickSceneFrames(changes, maxFrames) {
133
- const strongest = [...changes]
134
- .filter((c) => c.timeSec > 0)
135
- .sort((a, b) => b.score - a.score)
136
- .slice(0, Math.max(0, maxFrames - 1))
137
- .map((c) => c.timeSec);
138
- return [0, ...strongest].sort((a, b) => a - b);
139
- }
140
- export function buildSampleAtTimestampArgs(input, timestampSec, output) {
141
- if (!Number.isFinite(timestampSec) || timestampSec < 0) {
142
- throw new ScreencastError("timestamp must be a non-negative number.");
143
- }
144
- return ["-y", "-ss", String(timestampSec), "-i", input, "-frames:v", "1", ...stillOutput(output)];
145
- }
146
- export function editOutputExt(input, opts = {}) {
147
- const ext = extname(input).toLowerCase();
148
- if (ext === ".mp4" || ext === ".mkv" || ext === ".mov")
149
- return ext;
150
- if (opts.audio && AUDIO_ONLY_EXTS.has(ext))
151
- return ext;
152
- return ".mp4";
153
- }
154
- const AUDIO_ONLY_EXTS = new Set([".wav", ".mp3", ".m4a"]);
155
- export function isAudioOnlyPath(path) {
156
- return AUDIO_ONLY_EXTS.has(extname(path).toLowerCase());
157
- }
158
- export function assertEditContainer(output) {
159
- if (output === undefined)
160
- return;
161
- const ext = extname(output).toLowerCase();
162
- if (ext === ".webm" || ext === ".gif") {
163
- throw new ScreencastError(`This tool writes H.264/AAC, which a ${ext} file cannot hold. Use an .mp4, .mkv or .mov ` +
164
- `output, then convert (format: "webm") or export_gif the result.`);
165
- }
166
- }
167
- export function buildTrimArgs(input, output, opts) {
168
- const start = opts.start;
169
- if (!Number.isFinite(start) || start < 0) {
170
- throw new ScreencastError("start must be a non-negative number.");
171
- }
172
- if (opts.end === undefined && opts.duration === undefined) {
173
- throw new ScreencastError("trim requires either end or duration.");
174
- }
175
- if (opts.end !== undefined && opts.duration !== undefined) {
176
- throw new ScreencastError("trim takes end OR duration, not both.");
177
- }
178
- const args = ["-y", "-ss", String(start), "-i", input];
179
- if (opts.end !== undefined) {
180
- if (opts.end <= start) {
181
- throw new ScreencastError("end must be greater than start.");
182
- }
183
- args.push("-t", String(Math.round((opts.end - start) * 1000) / 1000));
184
- }
185
- else {
186
- args.push("-t", String(validatePositive(opts.duration, "duration")));
187
- }
188
- if (opts.exact === false)
189
- args.push("-c", "copy", output);
190
- else
191
- args.push(...resolveQuality(DEFAULT_EDIT_QUALITY), "-c:a", "aac", output);
192
- return args;
193
- }
194
- export function concatListContent(files) {
195
- return files.map((p) => `file '${p.replace(/'/g, "'\\''")}'`).join("\n") + "\n";
196
- }
197
- export function buildConcatListContent(inputs) {
198
- if (inputs.length < 2) {
199
- throw new ScreencastError("concat requires at least two input files.");
200
- }
201
- return concatListContent(inputs);
202
- }
203
- export function buildConcatArgs(listFile, output, opts = {}) {
204
- return ["-y", ...(opts.quiet ? ["-v", "error"] : []), "-f", "concat", "-safe", "0", "-i", listFile, "-c", "copy", output];
205
- }
206
- export function hasHiddenFrames(info) {
207
- const { videoFrames: n, videoDurationSec: d, fps } = info;
208
- if (n === null || d === null || fps === null)
209
- return false;
210
- return n > d * fps * 1.05 + 2;
211
- }
212
- export function concatCopyBlocker(paths, infos) {
213
- const fields = [
214
- ["videoCodec", "video codec"],
215
- ["width", "width"],
216
- ["height", "height"],
217
- ["pixFmt", "pixel format"],
218
- ["fps", "frame rate"],
219
- ["audioCodec", "audio codec"],
220
- ["sampleRate", "audio sample rate"],
221
- ["channels", "audio channels"],
222
- ];
223
- const first = infos[0];
224
- for (const [i, info] of infos.entries()) {
225
- if (hasHiddenFrames(info))
226
- return `${paths[i]} holds hidden frames behind an edit list`;
227
- if (i === 0 || !first)
228
- continue;
229
- for (const [key, label] of fields) {
230
- if (info[key] !== first[key]) {
231
- return `${label} differs: ${paths[0]} has ${first[key] ?? "none"}, ${paths[i]} has ${info[key] ?? "none"}`;
232
- }
233
- }
234
- }
235
- return null;
236
- }
237
- export function buildConvertArgs(input, output, format, opts = {}) {
238
- switch (format) {
239
- case "gif": {
240
- const fps = opts.fps ?? 12;
241
- const width = opts.width ?? 720;
242
- const filter = `fps=${fps},scale='min(${width},iw)':-1:flags=lanczos,split[s0][s1];` +
243
- `[s0]palettegen[p];[s1][p]paletteuse`;
244
- return ["-y", "-i", input, "-vf", filter, output];
245
- }
246
- case "webm":
247
- return [
248
- "-y", "-i", input,
249
- "-c:v", "libvpx-vp9", "-b:v", "0", "-crf", "30",
250
- "-deadline", "good", "-cpu-used", "4", "-row-mt", "1",
251
- output,
252
- ];
253
- case "mp4":
254
- return [
255
- "-y", "-i", input,
256
- "-c:v", "libx264", "-preset", "veryfast", "-crf", "23",
257
- "-pix_fmt", "yuv420p",
258
- "-movflags", "+faststart",
259
- output,
260
- ];
261
- default:
262
- throw new ScreencastError(`Unsupported convert format "${format}".`);
263
- }
264
- }
265
- function requireNonNegativeInt(value, label) {
266
- if (!Number.isInteger(value) || value < 0) {
267
- throw new ScreencastError(`${label} must be a non-negative integer.`);
268
- }
269
- return value;
270
- }
271
- function requirePositiveInt(value, label) {
272
- if (!Number.isInteger(value) || value <= 0) {
273
- throw new ScreencastError(`${label} must be a positive integer.`);
274
- }
275
- return value;
276
- }
277
- export function enableExpr(start, end) {
278
- if (start !== undefined && end !== undefined) {
279
- if (end <= start)
280
- throw new ScreencastError("end must be greater than start.");
281
- return `between(t,${start},${end})`;
282
- }
283
- if (start !== undefined)
284
- return `gte(t,${start})`;
285
- if (end !== undefined)
286
- return `lte(t,${end})`;
287
- return "";
288
- }
289
- export function cropFilter(rect, dims) {
290
- const x = requireNonNegativeInt(rect.x, "crop x");
291
- const y = requireNonNegativeInt(rect.y, "crop y");
292
- const w = validateEvenDimension(requirePositiveInt(rect.width, "crop width"), "crop width");
293
- const h = validateEvenDimension(requirePositiveInt(rect.height, "crop height"), "crop height");
294
- if (dims && dims.width != null && dims.height != null) {
295
- if (x + w > dims.width || y + h > dims.height) {
296
- throw new ScreencastError(`crop region ${w}x${h}+${x}+${y} falls outside the ` +
297
- `${dims.width}x${dims.height} frame.`);
298
- }
299
- }
300
- return `crop=${w}:${h}:${x}:${y}`;
301
- }
302
- export function buildCropArgs(input, output, rect, dims, quality = DEFAULT_EDIT_QUALITY) {
303
- return [
304
- "-y", "-i", input,
305
- "-vf", cropFilter(rect, dims),
306
- ...resolveQuality(quality),
307
- "-c:a", "copy",
308
- output,
309
- ];
310
- }
311
- export function scaleFilter(opts) {
312
- if (opts.width === undefined && opts.height === undefined) {
313
- throw new ScreencastError("scale requires width or height (or both).");
314
- }
315
- if (opts.width !== undefined) {
316
- validateEvenDimension(requirePositiveInt(opts.width, "scale width"), "scale width");
317
- }
318
- if (opts.height !== undefined) {
319
- validateEvenDimension(requirePositiveInt(opts.height, "scale height"), "scale height");
320
- }
321
- return `scale=${opts.width ?? -2}:${opts.height ?? -2}`;
322
- }
323
- export function scaledSize(W, H, opts) {
324
- const even = (v) => Math.max(2, Math.round(v / 2) * 2);
325
- if (opts.width !== undefined && opts.height !== undefined)
326
- return { width: opts.width, height: opts.height };
327
- if (opts.width !== undefined)
328
- return { width: opts.width, height: even((H * opts.width) / W) };
329
- return { width: even((W * opts.height) / H), height: opts.height };
330
- }
331
- export function buildScaleArgs(input, output, opts, quality = DEFAULT_EDIT_QUALITY) {
332
- return [
333
- "-y", "-i", input,
334
- "-vf", scaleFilter(opts),
335
- ...resolveQuality(quality),
336
- "-c:a", "copy",
337
- output,
338
- ];
339
- }
340
- export function atempoChain(factor) {
341
- let remaining = factor;
342
- const parts = [];
343
- while (remaining > 2.0) {
344
- parts.push("atempo=2.0");
345
- remaining /= 2.0;
346
- }
347
- while (remaining < 0.5) {
348
- parts.push("atempo=0.5");
349
- remaining /= 0.5;
350
- }
351
- parts.push(`atempo=${Number(remaining.toFixed(6))}`);
352
- return parts.join(",");
353
- }
354
- export function buildSpeedArgs(input, output, factor, hasAudio, quality = DEFAULT_EDIT_QUALITY) {
355
- if (!Number.isFinite(factor) || factor <= 0) {
356
- throw new ScreencastError("speed factor must be a positive number.");
357
- }
358
- const args = ["-y", "-i", input, "-filter:v", `setpts=PTS/${factor}`];
359
- if (hasAudio)
360
- args.push("-filter:a", atempoChain(factor));
361
- args.push(...resolveQuality(quality));
362
- if (hasAudio) {
363
- args.push("-c:a", "aac");
364
- }
365
- else {
366
- args.push("-an");
367
- }
368
- args.push(output);
369
- return args;
370
- }
371
- export const CIRCLE_MASK = "crop='min(iw,ih)':'min(iw,ih)',format=yuva420p," +
372
- "geq=lum='p(X,Y)':cb='p(X,Y)':cr='p(X,Y)':a='if(lte(hypot(X-W/2,Y-H/2),W/2),255,0)'";
373
- export function buildOverlayArgs(input, overlay, output, opts, quality = DEFAULT_EDIT_QUALITY) {
374
- const x = requireNonNegativeInt(opts.x, "overlay x");
375
- const y = requireNonNegativeInt(opts.y, "overlay y");
376
- const expr = enableExpr(opts.start, opts.end);
377
- const enable = expr ? `:enable='${expr}'` : "";
378
- const shift = `setpts=PTS-STARTPTS+${opts.start ?? 0}/TB`;
379
- let ovl = `[1:v]${shift}`;
380
- if (opts.scale && (opts.scale.width !== undefined || opts.scale.height !== undefined)) {
381
- if (opts.scale.width !== undefined)
382
- requirePositiveInt(opts.scale.width, "overlay scale width");
383
- if (opts.scale.height !== undefined)
384
- requirePositiveInt(opts.scale.height, "overlay scale height");
385
- const sw = opts.scale.width ?? -1;
386
- const sh = opts.scale.height ?? -1;
387
- ovl += `,scale=${sw}:${sh}`;
388
- }
389
- if (opts.shape === "circle")
390
- ovl += `,${CIRCLE_MASK}`;
391
- const filter = `${ovl}[ovl];[0:v][ovl]overlay=${x}:${y}${enable}[v]`;
392
- const dur = opts.durationSec;
393
- return [
394
- "-y", "-i", input, "-i", overlay,
395
- "-filter_complex", filter,
396
- "-map", "[v]", "-map", "0:a?",
397
- ...resolveQuality(quality),
398
- "-c:a", "copy",
399
- ...(dur != null && dur > 0 ? ["-t", String(dur)] : []),
400
- output,
401
- ];
402
- }
403
- const COMPRESS_CRF = {
404
- light: 23,
405
- medium: 28,
406
- heavy: 32,
407
- };
408
- export function buildCompressArgs(input, output, opts = {}) {
409
- const level = opts.level ?? "medium";
410
- const crf = COMPRESS_CRF[level];
411
- if (crf === undefined)
412
- throw new ScreencastError(`Unknown compress level "${level}".`);
413
- const args = ["-y", "-i", input];
414
- if (opts.maxWidth !== undefined) {
415
- requirePositiveInt(opts.maxWidth, "maxWidth");
416
- args.push("-vf", `scale='trunc(min(${opts.maxWidth},iw)/2)*2':-2`);
417
- }
418
- args.push("-c:v", "libx264", "-preset", "slow", "-crf", String(crf), "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", output);
419
- return args;
420
- }
421
- const AUDIO_CODEC = {
422
- mp3: ["-c:a", "libmp3lame", "-q:a", "2"],
423
- aac: ["-c:a", "aac", "-b:a", "192k"],
424
- wav: ["-c:a", "pcm_s16le"],
425
- copy: ["-c:a", "copy"],
426
- };
427
- export function copyAudioExtension(codec) {
428
- switch (codec) {
429
- case "aac":
430
- case "alac":
431
- return "m4a";
432
- case "mp3":
433
- return "mp3";
434
- case "opus":
435
- case "vorbis":
436
- return "ogg";
437
- case "flac":
438
- return "flac";
439
- default:
440
- if (codec && codec.startsWith("pcm_"))
441
- return "wav";
442
- return "mka";
443
- }
444
- }
445
- export function buildExtractAudioArgs(input, output, format) {
446
- const codec = AUDIO_CODEC[format];
447
- if (!codec)
448
- throw new ScreencastError(`Unknown audio format "${format}".`);
449
- return ["-y", "-i", input, "-vn", ...codec, output];
450
- }
451
- export function buildClipArgs(input, output, seg, quality = DEFAULT_EDIT_QUALITY) {
452
- if (!Number.isFinite(seg.start) || seg.start < 0) {
453
- throw new ScreencastError("clip start must be a non-negative number.");
454
- }
455
- if (!Number.isFinite(seg.end) || seg.end <= seg.start) {
456
- throw new ScreencastError("clip end must be greater than start.");
457
- }
458
- return [
459
- "-y", "-i", input,
460
- "-ss", String(seg.start),
461
- "-t", String(seg.end - seg.start),
462
- ...resolveQuality(quality),
463
- "-c:a", "aac",
464
- output,
465
- ];
466
- }
467
- export const REDACT_STYLES = ["box", "blur", "pixelate"];
468
- function normalizeRegions(regions, pad, dims) {
469
- return regions.map((r, i) => {
470
- const x0 = requireNonNegativeInt(r.x, `region[${i}] x`);
471
- const y0 = requireNonNegativeInt(r.y, `region[${i}] y`);
472
- const w0 = requirePositiveInt(r.width, `region[${i}] width`);
473
- const h0 = requirePositiveInt(r.height, `region[${i}] height`);
474
- if (dims && dims.width != null && dims.height != null) {
475
- if (x0 + w0 > dims.width || y0 + h0 > dims.height) {
476
- throw new ScreencastError(`region[${i}] ${w0}x${h0}+${x0}+${y0} falls outside the ` +
477
- `${dims.width}x${dims.height} frame.`);
478
- }
479
- }
480
- const x = Math.max(0, x0 - pad);
481
- const y = Math.max(0, y0 - pad);
482
- let right = x0 + w0 + pad;
483
- let bottom = y0 + h0 + pad;
484
- if (dims && dims.width != null)
485
- right = Math.min(right, dims.width);
486
- if (dims && dims.height != null)
487
- bottom = Math.min(bottom, dims.height);
488
- return { x, y, w: right - x, h: bottom - y, enable: enableExpr(r.start, r.end) };
489
- });
490
- }
491
- export const MIN_BLUR_RADIUS = 8;
492
- export const BLUR_PASSES = 3;
493
- export const MIN_PIXEL_BLOCK = 16;
494
- export function blurRadius(r) {
495
- const m = Math.min(r.w, r.h);
496
- const maxRadius = (side) => Math.max(0, Math.floor((side - 1) / 2));
497
- const lr = Math.min(maxRadius(m), Math.max(MIN_BLUR_RADIUS, Math.min(20, Math.floor(m / 4))));
498
- const cr = Math.min(lr, maxRadius(Math.ceil(m / 2)));
499
- return `lr=${lr}:lp=${BLUR_PASSES}:cr=${cr}:cp=${BLUR_PASSES}`;
500
- }
501
- export function pixelateFilter(r) {
502
- const block = Math.max(MIN_PIXEL_BLOCK, Math.ceil(Math.max(r.w, r.h) / 16));
503
- const cols = Math.max(1, Math.round(r.w / block));
504
- const rows = Math.max(1, Math.round(r.h / block));
505
- return `scale=${cols}:${rows}:flags=area,scale=${r.w}:${r.h}:flags=neighbor`;
506
- }
507
- export function redactSteps(regions, opts, dims, input, tag) {
508
- if (regions.length === 0) {
509
- throw new ScreencastError("redact_region requires at least one region.");
510
- }
511
- const style = opts.style ?? "box";
512
- const pad = opts.pad ?? 0;
513
- if (!Number.isInteger(pad) || pad < 0) {
514
- throw new ScreencastError("pad must be a non-negative integer.");
515
- }
516
- const color = validateColor(opts.color ?? "black", "color");
517
- const rs = normalizeRegions(regions, pad, dims);
518
- if (style === "box") {
519
- const boxes = rs
520
- .map((r) => {
521
- const en = r.enable ? `:enable='${r.enable}'` : "";
522
- return `drawbox=x=${r.x}:y=${r.y}:w=${r.w}:h=${r.h}:color=${color}:t=fill${en}`;
523
- })
524
- .join(",");
525
- return { steps: [`${input}${boxes}[${tag}out]`], out: `[${tag}out]` };
526
- }
527
- const n = rs.length;
528
- const steps = [];
529
- const splitOuts = [`${tag}base`, ...rs.map((_, i) => `${tag}s${i}`)];
530
- steps.push(`${input}split=${n + 1}[${splitOuts.join("][")}]`);
531
- rs.forEach((r, i) => {
532
- const crop = `crop=${r.w}:${r.h}:${r.x}:${r.y}`;
533
- const soften = style === "blur"
534
- ? `boxblur=${blurRadius(r)}`
535
- : pixelateFilter(r);
536
- steps.push(`[${tag}s${i}]${crop},${soften}[${tag}b${i}]`);
537
- });
538
- let prev = `${tag}base`;
539
- rs.forEach((r, i) => {
540
- const en = r.enable ? `:enable='${r.enable}'` : "";
541
- const out = i === n - 1 ? `${tag}out` : `${tag}c${i}`;
542
- steps.push(`[${prev}][${tag}b${i}]overlay=${r.x}:${r.y}${en}[${out}]`);
543
- prev = `${tag}c${i}`;
544
- });
545
- return { steps, out: `[${tag}out]` };
546
- }
547
- export function stillEdit(input, output) {
548
- if (!isStillImage(input)) {
549
- assertEditContainer(output);
550
- return { still: false, ext: editOutputExt(input) };
551
- }
552
- if (output && !isStillImage(output)) {
553
- throw new ScreencastError("An image input writes an image: give the output a .png or .jpg extension.");
554
- }
555
- return { still: true, ext: /\.jpe?g$/i.test(input) ? extname(input).toLowerCase() : ".png" };
556
- }
557
- export function buildRedactArgs(input, output, regions, opts = {}, dims, still = false) {
558
- const rs = still ? regions.map(({ start: _s, end: _e, ...r }) => r) : regions;
559
- const { steps, out } = redactSteps(rs, opts, dims, "[0:v]", "");
560
- if (still) {
561
- return ["-y", "-i", input, "-filter_complex", steps.join(";"), "-map", out, "-frames:v", "1", ...stillOutput(output)];
562
- }
563
- const [chain] = steps;
564
- if ((opts.style ?? "box") === "box" && chain !== undefined) {
565
- const vf = chain.slice("[0:v]".length, -out.length);
566
- return ["-y", "-i", input, "-vf", vf, ...resolveQuality("high"), "-c:a", "copy", output];
567
- }
568
- return [
569
- "-y", "-i", input,
570
- "-filter_complex", steps.join(";"),
571
- "-map", out, "-map", "0:a?",
572
- ...resolveQuality("high"),
573
- "-c:a", "copy",
574
- output,
575
- ];
576
- }
577
- export const redactRegionSchema = z.object({
578
- x: z.number().int().nonnegative(),
579
- y: z.number().int().nonnegative(),
580
- width: z.number().int().positive(),
581
- height: z.number().int().positive(),
582
- start: z.number().nonnegative().optional(),
583
- end: z.number().positive().optional(),
584
- });