@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,300 +0,0 @@
1
- import { ScreencastError } from "./errors.js";
2
- import { resolveQuality } from "./targets.js";
3
- import { escapeFilterPath } from "./fonts.js";
4
- import { validateTransition, validateColor, validateEvenDimension, } from "./validate.js";
5
- export const DEFAULT_PRODUCE_WIDTH = 1920;
6
- export const DEFAULT_PRODUCE_HEIGHT = 1080;
7
- export const DEFAULT_PRODUCE_FPS = 30;
8
- export const DEFAULT_AUDIO_RATE = 48000;
9
- export const DEFAULT_TRANSITION_DUR = 1;
10
- const DEFAULT_QUALITY = "standard";
11
- function round3(n) {
12
- return Math.round(n * 1000) / 1000;
13
- }
14
- function producedDims(opts) {
15
- if (opts.width !== undefined)
16
- validateEvenDimension(opts.width, "width");
17
- if (opts.height !== undefined)
18
- validateEvenDimension(opts.height, "height");
19
- return {
20
- w: opts.width ?? DEFAULT_PRODUCE_WIDTH,
21
- h: opts.height ?? DEFAULT_PRODUCE_HEIGHT,
22
- };
23
- }
24
- export function videoNormalizeChain(w, h, fps) {
25
- return (`scale=${w}:${h}:force_original_aspect_ratio=decrease,` +
26
- `pad=${w}:${h}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=${fps},format=yuv420p`);
27
- }
28
- export function audioNormalizeChain(rate) {
29
- return `aresample=${rate},aformat=sample_fmts=fltp:channel_layouts=stereo`;
30
- }
31
- function encodeArgs(quality) {
32
- return resolveQuality(quality);
33
- }
34
- export function xfadeOffsets(durations, transitionDur) {
35
- const offsets = [];
36
- let running = 0;
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)));
40
- }
41
- return offsets;
42
- }
43
- export function clipLength(info) {
44
- return info.videoDurationSec ?? info.durationSec;
45
- }
46
- export function buildXfadeArgs(inputA, inputB, durations, output, opts = {}, clipHasAudio = [false, false]) {
47
- const transition = validateTransition(opts.transition ?? "fade");
48
- const d = opts.duration ?? DEFAULT_TRANSITION_DUR;
49
- if (!Number.isFinite(d) || d <= 0) {
50
- throw new ScreencastError("transition duration must be a positive number.");
51
- }
52
- if (!Number.isFinite(durations[0]) || durations[0] <= d) {
53
- throw new ScreencastError(`first clip (${durations[0]}s) must be longer than the transition (${d}s).`);
54
- }
55
- return buildAssembleArgs([inputA, inputB], durations, output, { ...opts, transition }, clipHasAudio);
56
- }
57
- export function buildAssembleArgs(inputs, durations, output, opts = {}, clipHasAudio = []) {
58
- if (inputs.length < 2) {
59
- throw new ScreencastError("assemble_highlights requires at least two clips.");
60
- }
61
- const { w, h } = producedDims(opts);
62
- const fps = opts.fps ?? DEFAULT_PRODUCE_FPS;
63
- const rate = opts.audioRate ?? DEFAULT_AUDIO_RATE;
64
- const transition = opts.transition ?? "cut";
65
- const d = opts.duration ?? DEFAULT_TRANSITION_DUR;
66
- const n = inputs.length;
67
- const vf = videoNormalizeChain(w, h, fps);
68
- const af = audioNormalizeChain(rate);
69
- const anyAudio = clipHasAudio.some(Boolean);
70
- const parts = [];
71
- for (let i = 0; i < n; i++) {
72
- parts.push(`[${i}:v]${vf}[v${i}]`);
73
- if (!anyAudio)
74
- continue;
75
- if (clipHasAudio[i]) {
76
- const dur = durations[i] ?? Number.NaN;
77
- const fit = Number.isFinite(dur) && dur > 0 ? `,apad,atrim=duration=${round3(dur)}` : "";
78
- parts.push(`[${i}:a]${af}${fit}[a${i}]`);
79
- }
80
- else {
81
- const dur = durations[i] ?? Number.NaN;
82
- if (!Number.isFinite(dur) || dur <= 0) {
83
- throw new ScreencastError(`clip ${i} has no audio track and its duration is unknown, so a ` +
84
- `matching silent track cannot be generated.`);
85
- }
86
- parts.push(`anullsrc=channel_layout=stereo:sample_rate=${rate}:d=${dur}[a${i}]`);
87
- }
88
- }
89
- const maps = [];
90
- if (transition === "cut") {
91
- if (anyAudio) {
92
- const labels = inputs.map((_, i) => `[v${i}][a${i}]`).join("");
93
- parts.push(`${labels}concat=n=${n}:v=1:a=1[vout][aout]`);
94
- maps.push("-map", "[vout]", "-map", "[aout]");
95
- }
96
- else {
97
- const labels = inputs.map((_, i) => `[v${i}]`).join("");
98
- parts.push(`${labels}concat=n=${n}:v=1:a=0[vout]`);
99
- maps.push("-map", "[vout]");
100
- }
101
- }
102
- else {
103
- validateTransition(transition);
104
- if (durations.length !== n) {
105
- throw new ScreencastError(`a ${transition} transition needs a duration for each of the ${n} clips.`);
106
- }
107
- if (!Number.isFinite(d) || d <= 0) {
108
- throw new ScreencastError("transition duration must be a positive number.");
109
- }
110
- const badClip = durations.findIndex((dur) => !Number.isFinite(dur) || dur <= d);
111
- if (badClip !== -1) {
112
- throw new ScreencastError(`clip ${badClip} (${durations[badClip]}s) must be longer than the ` +
113
- `${d}s ${transition} transition. Use a shorter transition or trim fewer frames.`);
114
- }
115
- const offsets = xfadeOffsets(durations, d);
116
- let vPrev = "v0";
117
- for (let m = 1; m < n; m++) {
118
- const out = m === n - 1 ? "vout" : `vx${m}`;
119
- parts.push(`[${vPrev}][v${m}]xfade=transition=${transition}:duration=${d}:offset=${offsets[m - 1]}[${out}]`);
120
- vPrev = out;
121
- }
122
- maps.push("-map", "[vout]");
123
- if (anyAudio) {
124
- let aPrev = "a0";
125
- for (let m = 1; m < n; m++) {
126
- const out = m === n - 1 ? "aout" : `ax${m}`;
127
- parts.push(`[${aPrev}][a${m}]acrossfade=d=${d}[${out}]`);
128
- aPrev = out;
129
- }
130
- maps.push("-map", "[aout]");
131
- }
132
- }
133
- return [
134
- "-y",
135
- ...inputs.flatMap((f) => ["-i", f]),
136
- "-filter_complex", parts.join(";"),
137
- ...maps,
138
- ...encodeArgs(opts.quality ?? DEFAULT_QUALITY),
139
- ...(anyAudio ? ["-c:a", "aac", "-b:a", "160k"] : ["-an"]),
140
- "-movflags", "+faststart",
141
- output,
142
- ];
143
- }
144
- export const DEFAULT_TITLE_DURATION = 3;
145
- export function buildTitleCardArgs(textFile, fontFile, output, opts = {}) {
146
- const { w, h } = producedDims(opts);
147
- const dur = opts.duration ?? DEFAULT_TITLE_DURATION;
148
- const fps = opts.fps ?? DEFAULT_PRODUCE_FPS;
149
- const bg = validateColor(opts.bg ?? "black", "bg");
150
- const fontColor = validateColor(opts.fontColor ?? "white", "fontColor");
151
- const fontSize = opts.fontSize ?? 96;
152
- if (!Number.isFinite(dur) || dur <= 0) {
153
- throw new ScreencastError("title duration must be a positive number.");
154
- }
155
- if (!Number.isInteger(fontSize) || fontSize <= 0) {
156
- throw new ScreencastError("fontSize must be a positive integer.");
157
- }
158
- const draw = `drawtext=fontfile=${escapeFilterPath(fontFile)}:` +
159
- `textfile=${escapeFilterPath(textFile)}:expansion=none:` +
160
- `fontcolor=${fontColor}:fontsize=${fontSize}:` +
161
- `x=(w-text_w)/2:y=(h-text_h)/2:` +
162
- `shadowcolor=black@0.5:shadowx=2:shadowy=2`;
163
- return [
164
- "-y",
165
- "-f", "lavfi", "-i", `color=c=${bg}:s=${w}x${h}:d=${dur}:r=${fps}`,
166
- "-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=48000",
167
- "-vf", draw,
168
- "-shortest",
169
- ...encodeArgs(opts.quality ?? DEFAULT_QUALITY),
170
- "-c:a", "aac", "-b:a", "160k",
171
- "-movflags", "+faststart",
172
- output,
173
- ];
174
- }
175
- export function buildMusicBedArgs(video, music, output, videoDuration, hasVideoAudio, opts = {}) {
176
- if (!Number.isFinite(videoDuration) || videoDuration <= 0) {
177
- throw new ScreencastError("video duration must be known and positive.");
178
- }
179
- const vol = opts.musicVolume ?? (hasVideoAudio ? 0.25 : 0.8);
180
- const fin = opts.fadeIn ?? 1;
181
- const fout = opts.fadeOut ?? 2;
182
- for (const [v, label] of [[vol, "musicVolume"], [fin, "fadeIn"], [fout, "fadeOut"]]) {
183
- if (!Number.isFinite(v) || v < 0) {
184
- throw new ScreencastError(`${label} must be a non-negative number.`);
185
- }
186
- }
187
- const duck = opts.duck ?? false;
188
- const fadeOutStart = Math.max(0, round3(videoDuration - fout));
189
- const musicChain = `[1:a]afade=t=in:st=0:d=${fin},afade=t=out:st=${fadeOutStart}:d=${fout},volume=${vol}`;
190
- const mix = "amix=inputs=2:duration=first:dropout_transition=0:normalize=0";
191
- const parts = [];
192
- if (hasVideoAudio) {
193
- parts.push(`${musicChain}[music]`);
194
- if (duck) {
195
- parts.push("[music][0:a]sidechaincompress=threshold=0.03:ratio=8:attack=20:release=300[ducked]");
196
- parts.push(`[0:a][ducked]${mix}[aout]`);
197
- }
198
- else {
199
- parts.push(`[0:a][music]${mix}[aout]`);
200
- }
201
- }
202
- else {
203
- parts.push(`${musicChain}[aout]`);
204
- }
205
- return [
206
- "-y",
207
- "-i", video,
208
- "-stream_loop", "-1", "-i", music,
209
- "-filter_complex", parts.join(";"),
210
- "-map", "0:v", "-map", "[aout]",
211
- "-t", String(videoDuration),
212
- "-c:v", "copy",
213
- "-c:a", "aac", "-b:a", "192k",
214
- "-movflags", "+faststart",
215
- output,
216
- ];
217
- }
218
- export const ASPECTS = ["16:9", "9:16", "1:1", "4:5"];
219
- export const REFRAME_FITS = ["pad", "crop"];
220
- export const ASPECT_DIMS = {
221
- "16:9": { w: 1920, h: 1080 },
222
- "9:16": { w: 1080, h: 1920 },
223
- "1:1": { w: 1080, h: 1080 },
224
- "4:5": { w: 1080, h: 1350 },
225
- };
226
- export function reframeFilter(w, h, fit) {
227
- if (fit === "crop") {
228
- return `scale=${w}:${h}:force_original_aspect_ratio=increase,crop=${w}:${h},setsar=1`;
229
- }
230
- return (`scale=${w}:${h}:force_original_aspect_ratio=decrease,` +
231
- `pad=${w}:${h}:(ow-iw)/2:(oh-ih)/2,setsar=1`);
232
- }
233
- export function buildReframeArgs(input, output, aspect, fit = "pad", quality = DEFAULT_QUALITY) {
234
- const dim = ASPECT_DIMS[aspect];
235
- if (!dim)
236
- throw new ScreencastError(`Unknown aspect "${aspect}".`);
237
- return [
238
- "-y", "-i", input,
239
- "-vf", `${reframeFilter(dim.w, dim.h, fit)},format=yuv420p`,
240
- ...encodeArgs(quality),
241
- "-c:a", "copy",
242
- "-movflags", "+faststart",
243
- output,
244
- ];
245
- }
246
- export const PLATFORMS = ["youtube", "instagram_reel", "tiktok", "x", "square", "steam_trailer", "vertical_reel"];
247
- export const PLATFORM_PRESETS = {
248
- youtube: { aspect: "16:9", fps: 30, videoBitrate: "8M", bufsize: "16M", audioBitrate: "192k" },
249
- instagram_reel: { aspect: "9:16", fps: 30, videoBitrate: "6M", bufsize: "12M", audioBitrate: "160k" },
250
- tiktok: { aspect: "9:16", fps: 30, videoBitrate: "6M", bufsize: "12M", audioBitrate: "160k" },
251
- x: { aspect: "16:9", fps: 30, videoBitrate: "5M", bufsize: "10M", audioBitrate: "128k" },
252
- square: { aspect: "1:1", fps: 30, videoBitrate: "6M", bufsize: "12M", audioBitrate: "160k" },
253
- steam_trailer: {
254
- aspect: "16:9", fps: 30, videoBitrate: "5.5M", bufsize: "11M", audioBitrate: "192k",
255
- cbr: true, loudness: { sampleRate: 48000 },
256
- },
257
- vertical_reel: {
258
- aspect: "9:16", fps: 30, videoBitrate: "6M", bufsize: "12M", audioBitrate: "160k",
259
- blurFill: true, loudness: {},
260
- },
261
- };
262
- export function blurFillFilter(w, h, tag = "") {
263
- return (`split=2[${tag}bg][${tag}fg];` +
264
- `[${tag}bg]scale=${w}:${h}:force_original_aspect_ratio=increase,crop=${w}:${h},boxblur=20:2,eq=brightness=-0.08[${tag}b];` +
265
- `[${tag}fg]scale=${w}:${w}:force_original_aspect_ratio=decrease:force_divisible_by=2[${tag}f];` +
266
- `[${tag}b][${tag}f]overlay=(W-w)/2:(H-h)/2,setsar=1`);
267
- }
268
- export function exportPresetParts(platform, fit = "pad", tag = "") {
269
- const p = PLATFORM_PRESETS[platform];
270
- if (!p)
271
- throw new ScreencastError(`Unknown platform "${platform}".`);
272
- const dim = ASPECT_DIMS[p.aspect];
273
- const frame = p.blurFill ? blurFillFilter(dim.w, dim.h, tag) : reframeFilter(dim.w, dim.h, fit);
274
- const af = p.loudness
275
- ?
276
- `loudnorm=I=-14:TP=-1:LRA=11,aresample=${p.loudness.sampleRate ?? DEFAULT_AUDIO_RATE}`
277
- : undefined;
278
- return {
279
- vf: `${frame},fps=${p.fps},format=yuv420p`,
280
- ...(af ? { af } : {}),
281
- encode: [
282
- "-c:v", "libx264", "-preset", "medium",
283
- ...(p.cbr ? ["-profile:v", "high"] : []),
284
- "-b:v", p.videoBitrate,
285
- ...(p.cbr ? ["-minrate", p.videoBitrate, "-x264-params", "nal-hrd=cbr"] : []),
286
- "-maxrate", p.videoBitrate, "-bufsize", p.bufsize,
287
- "-pix_fmt", "yuv420p",
288
- "-c:a", "aac", "-b:a", p.audioBitrate,
289
- ...(p.loudness?.sampleRate ? ["-ar", String(p.loudness.sampleRate), "-ac", "2"] : []),
290
- "-r", String(p.fps),
291
- "-movflags", "+faststart",
292
- ],
293
- width: dim.w,
294
- height: dim.h,
295
- };
296
- }
297
- export function buildExportPresetArgs(input, output, platform, fit = "pad") {
298
- const { vf, af, encode } = exportPresetParts(platform, fit);
299
- return ["-y", "-i", input, "-vf", vf, ...(af ? ["-af", af] : []), ...encode, output];
300
- }
@@ -1,71 +0,0 @@
1
- import { ScreencastError } from "./errors.js";
2
- export const RECIPES = ["pr_demo", "tutorial", "social_reel"];
3
- export const PR_DEMO_MAX_BYTES = 10_000_000;
4
- const EXPORTS = new Set(["export_preset", "export_gif"]);
5
- export function recipeSteps(recipe, ctx) {
6
- const notes = [];
7
- const steps = [{ op: "cut_idle" }];
8
- if (ctx.hasClicks)
9
- steps.push({ op: "zoom", follow: "clicks" });
10
- else
11
- notes.push("zoom left out: no event log with clicks (record with start_recording events: true).");
12
- const captions = (style) => {
13
- if (!ctx.hasAudio)
14
- return;
15
- if (ctx.transcribeBlocker)
16
- notes.push(`captions left out: ${ctx.transcribeBlocker}`);
17
- else
18
- steps.push({ op: "burn_subtitles", transcribe: true, style });
19
- };
20
- if (!ctx.hasAudio && recipe !== "pr_demo")
21
- notes.push("audio and captions left out: the input has no audio.");
22
- switch (recipe) {
23
- case "pr_demo":
24
- steps.push({ op: "export_gif", maxBytes: PR_DEMO_MAX_BYTES });
25
- break;
26
- case "tutorial":
27
- if (ctx.hasAudio)
28
- steps.push({ op: "audio", denoise: "light", normalize: "youtube" });
29
- captions("clean");
30
- steps.push({ op: "export_preset", platform: "youtube" });
31
- break;
32
- case "social_reel":
33
- if (ctx.hasAudio)
34
- steps.push({ op: "audio", normalize: "youtube" });
35
- steps.push({ op: "reframe", aspect: "9:16" });
36
- captions("social");
37
- steps.push({ op: "export_preset", platform: "instagram_reel" });
38
- break;
39
- default:
40
- throw new ScreencastError(`Unknown recipe "${String(recipe)}".`);
41
- }
42
- return { steps, notes };
43
- }
44
- const SOURCE_OPS = new Set(["redact", "crop", "cursor"]);
45
- export function applyOverrides(base, overrides) {
46
- const out = [...base];
47
- const tail = out.at(-1) && EXPORTS.has(out.at(-1).op) ? out.pop() : null;
48
- let exportStep = tail;
49
- const recipeLen = out.length;
50
- const replaced = new Set();
51
- const trims = [];
52
- const front = [];
53
- for (const o of overrides) {
54
- if (EXPORTS.has(o.op)) {
55
- exportStep = o;
56
- continue;
57
- }
58
- const i = out.findIndex((s, j) => j < recipeLen && !replaced.has(j) && s.op === o.op);
59
- if (i === -1 && o.op === "trim")
60
- trims.push(o);
61
- else if (i === -1 && SOURCE_OPS.has(o.op))
62
- front.push(o);
63
- else if (i === -1)
64
- out.push(o);
65
- else {
66
- out[i] = o;
67
- replaced.add(i);
68
- }
69
- }
70
- return [...trims, ...front, ...out, ...(exportStep ? [exportStep] : [])];
71
- }
@@ -1,173 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { mkdirSync, rmSync } from "node:fs";
3
- import { errorMessage, ScreencastError } from "./errors.js";
4
- import { logMessage, StderrWatch } from "./logging.js";
5
- import { parseCaptureStart, whenFinalized } from "./events.js";
6
- import { buildCaptureArgs } from "./targets.js";
7
- import { probeDuration, requireFfmpeg } from "./ffmpeg.js";
8
- import { joinSegments, withSessionOp } from "./lifecycle.js";
9
- import { endSession, isPausing, partPath, partsDir, recordedSec, remainingCapSec, resumeBlocker, webcamPartPath, } from "./pause.js";
10
- import { classifyUnrequestedExit, killPid } from "./sessions.js";
11
- export function watchStderr(child, sessionId) {
12
- let head = "";
13
- let tail = "";
14
- let outputAt = null;
15
- const watch = new StderrWatch(() => ({ sessionId }));
16
- child.stderr?.on("data", (d) => {
17
- const text = d.toString();
18
- tail = (tail + text).slice(-2000);
19
- if (head.length < 8000)
20
- head += text;
21
- if (outputAt === null && /Output #0/.test(head))
22
- outputAt = Date.now();
23
- watch.feed(text);
24
- });
25
- child.on("error", (err) => {
26
- tail += `\n${err.message}`;
27
- });
28
- return { head: () => head, tail: () => tail, outputAt: () => outputAt };
29
- }
30
- export function tailLines(watch, n = 6) {
31
- return watch.tail().trim().split("\n").slice(-n).join("\n");
32
- }
33
- export function settleCapture(child, watch, backend) {
34
- return new Promise((resolve) => {
35
- const timer = setTimeout(() => resolve("running"), backend === "wgc" ? 15_000 : backend === "ddagrab" ? 2000 : 1200);
36
- if (backend === "wgc") {
37
- child.stderr?.on("data", () => {
38
- if (parseCaptureStart(watch.head()) !== null) {
39
- clearTimeout(timer);
40
- resolve("running");
41
- }
42
- });
43
- }
44
- child.on("error", () => {
45
- clearTimeout(timer);
46
- resolve("exited");
47
- });
48
- child.on("exit", () => {
49
- clearTimeout(timer);
50
- resolve("exited");
51
- });
52
- });
53
- }
54
- export function captureStartMs(watch, backend, spawnedAt) {
55
- const banner = parseCaptureStart(watch.head());
56
- if (banner !== null)
57
- return banner;
58
- return backend === "ddagrab" ? (watch.outputAt() ?? spawnedAt) : spawnedAt;
59
- }
60
- export function attachExitHandler(store, id, child, opts) {
61
- child.on("exit", (code) => {
62
- const attached = store.getChild(id);
63
- if (attached && attached !== child)
64
- return;
65
- store.detachChild(id, child);
66
- if (!isPausing(id))
67
- endSession(id);
68
- const cur = store.get(id);
69
- if (!cur || cur.status !== "recording" || store.isStopping(id))
70
- return;
71
- const verdict = classifyUnrequestedExit({
72
- code,
73
- backend: opts.backend,
74
- maxDurationSec: opts.maxDurationSec,
75
- elapsedMs: Date.now() - opts.spawnedAt,
76
- });
77
- logMessage(verdict.status === "failed" ? "error" : "notice", verdict.status === "failed"
78
- ? `Recording ${id} failed: the recorder exited with code ${code}.`
79
- : `Recording ${id} ended on its own (${verdict.endReason}).`, { sessionId: id, ...verdict });
80
- store.tryUpdate(id, {
81
- ...verdict,
82
- stoppedAt: new Date().toISOString(),
83
- ...(verdict.status === "failed"
84
- ? { error: `${opts.backend === "wgc" ? "The window recorder" : "ffmpeg"} exited with code ${code}:\n${tailLines(opts.watch)}` }
85
- : {}),
86
- });
87
- if (cur.segments && (cur.segments.parts.length > 0 || cur.webcam)) {
88
- void finalizeSegments(store, cur).catch((err) => {
89
- process.stderr.write(`Joining ${id}'s segments failed: ${errorMessage(err)}\n`);
90
- });
91
- }
92
- });
93
- }
94
- async function finalizeSegments(store, record) {
95
- const tools = requireFfmpeg();
96
- await whenFinalized(record.id);
97
- const { patch, error } = await joinSegments(record, tools);
98
- const durationSec = await probeDuration(record.outputPath, { ffprobe: tools.ffprobe });
99
- store.tryUpdate(record.id, { ...patch, durationSec: durationSec ?? undefined, ...(error ? { error } : {}) });
100
- }
101
- export function resumeSession(store, record, ffmpeg) {
102
- return withSessionOp(store, record.id, "resume", () => runResume(store, store.get(record.id) ?? record, ffmpeg));
103
- }
104
- async function runResume(store, record, ffmpeg) {
105
- const blocker = resumeBlocker(record, store.ownsPaused(record.id));
106
- if (blocker)
107
- throw new ScreencastError(`Cannot resume ${record.id}: ${blocker}.`);
108
- const seg = record.segments;
109
- const capture = record.capture;
110
- const backend = record.backend ?? "gdigrab";
111
- const done = recordedSec(seg.parts);
112
- const capSec = remainingCapSec(record.maxDurationSec, done);
113
- const index = seg.parts.length;
114
- const path = partPath(record.outputPath, index);
115
- const webcamPath = capture.webcam ? webcamPartPath(record.outputPath, index) : undefined;
116
- if (index > 0 || webcamPath)
117
- mkdirSync(partsDir(record.outputPath), { recursive: true });
118
- const args = buildCaptureArgs(capture.target, {
119
- ...capture.opts,
120
- output: path,
121
- maxDurationSec: capSec,
122
- ...(capture.webcam && webcamPath ? { webcam: { ...capture.webcam, output: webcamPath } } : {}),
123
- });
124
- const spawnedAt = Date.now();
125
- const child = spawn(ffmpeg, args, { stdio: ["pipe", "ignore", "pipe"], windowsHide: true });
126
- const watch = watchStderr(child, record.id);
127
- const cleanup = () => {
128
- const other = store.getChild(record.id);
129
- if (other && other !== child)
130
- return;
131
- if (index > 0)
132
- rmSync(path, { force: true });
133
- if (webcamPath)
134
- rmSync(webcamPath, { force: true });
135
- };
136
- if ((await settleCapture(child, watch, backend)) === "exited") {
137
- cleanup();
138
- throw new ScreencastError(`Resume failed (ffmpeg exited immediately); the recording stays paused:\n${tailLines(watch)}`);
139
- }
140
- const startMs = captureStartMs(watch, backend, spawnedAt);
141
- const camStart = webcamPath ? parseCaptureStart(watch.head(), capture.opts.audio ? 2 : 1) : null;
142
- store.attachChild(record.id, child);
143
- const abandon = () => {
144
- store.detachChild(record.id, child);
145
- if (child.pid !== undefined)
146
- killPid(child.pid);
147
- cleanup();
148
- };
149
- let updated;
150
- try {
151
- updated = store.update(record.id, {
152
- status: "recording",
153
- pid: child.pid ?? null,
154
- pidSpawnedAt: spawnedAt,
155
- videoStartMs: startMs - done * 1000,
156
- segments: {
157
- parts: seg.parts,
158
- current: { path, startMs, ...(webcamPath ? { webcamPath, ...(camStart !== null ? { webcamStartMs: camStart } : {}) } : {}) },
159
- },
160
- });
161
- }
162
- catch (err) {
163
- abandon();
164
- throw new ScreencastError(`Resume stopped: the session registry could not be written (${errorMessage(err)}).`);
165
- }
166
- if (!updated) {
167
- abandon();
168
- throw new ScreencastError(`No session with id "${record.id}".`);
169
- }
170
- store.clearPaused(record.id);
171
- attachExitHandler(store, record.id, child, { backend, maxDurationSec: capSec, spawnedAt, watch });
172
- return { record: updated, recordedSec: done, capSec };
173
- }
@@ -1,32 +0,0 @@
1
- import { basename } from "node:path";
2
- import { markersPath } from "./chapters.js";
3
- import { eventPaths } from "./events.js";
4
- import { partsDir, webcamOutputPath } from "./pause.js";
5
- import { allowedOutputDirs, assertLocalPath, homeRoot, isWithin } from "./paths.js";
6
- import { ScreencastError } from "./errors.js";
7
- import { defaultTranscriptPath, fallbackIndexPath, indexSidecarPath } from "./recordingIndex.js";
8
- import { wgcStopFile } from "./wgc.js";
9
- export function recordingSidecars(video, siblings, editsDir) {
10
- const events = eventPaths(video);
11
- const transcript = defaultTranscriptPath(video, siblings);
12
- const files = [
13
- events.jsonl,
14
- events.raw,
15
- `${events.raw}.stop`,
16
- webcamOutputPath(video),
17
- indexSidecarPath(video),
18
- fallbackIndexPath(video, editsDir),
19
- markersPath(video),
20
- wgcStopFile(video),
21
- ...(transcript.path && !transcript.ambiguous ? [transcript.path] : []),
22
- ];
23
- return { files: [...new Set(files)].filter((f) => basename(f) !== basename(video)), dirs: [partsDir(video)] };
24
- }
25
- export function assertDeleteAllowed(path) {
26
- assertLocalPath(path, "Recording");
27
- const dirs = [homeRoot(), ...(allowedOutputDirs() ?? [])];
28
- if (dirs.some((d) => isWithin(path, d)))
29
- return;
30
- throw new ScreencastError(`Recording ${path} is outside SCREENCAST_HOME and the allowed directories, so it is not deleted. ` +
31
- "Add its folder to SCREENCAST_ALLOWED_DIRS or the client's workspace roots, or delete it yourself.");
32
- }