@tmhs/screencast-mcp 0.45.0 → 0.47.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 (56) hide show
  1. package/README.md +138 -82
  2. package/assets/cursor/arrow.png +0 -0
  3. package/dist/cli.js +360 -0
  4. package/dist/index.js +10 -2
  5. package/dist/prompts.js +16 -3
  6. package/dist/server.js +18 -0
  7. package/dist/tools/addMarker.js +6 -2
  8. package/dist/tools/bugReport.js +2 -2
  9. package/dist/tools/chapters.js +1 -1
  10. package/dist/tools/cursor.js +87 -0
  11. package/dist/tools/cutByTranscript.js +86 -0
  12. package/dist/tools/doctor.js +14 -1
  13. package/dist/tools/indexRecording.js +173 -0
  14. package/dist/tools/listVideoDevices.js +26 -0
  15. package/dist/tools/narrate.js +84 -0
  16. package/dist/tools/overlay.js +2 -0
  17. package/dist/tools/pauseRecording.js +44 -0
  18. package/dist/tools/pipeline.js +215 -19
  19. package/dist/tools/readEvents.js +1 -1
  20. package/dist/tools/resumeRecording.js +46 -0
  21. package/dist/tools/reviewRecording.js +1 -1
  22. package/dist/tools/searchRecording.js +73 -0
  23. package/dist/tools/startRecording.js +106 -67
  24. package/dist/tools/stepGuide.js +193 -0
  25. package/dist/tools/stopRecording.js +38 -3
  26. package/dist/tools/transcribe.js +4 -3
  27. package/dist/tools/zoom.js +1 -1
  28. package/dist/utils/audio.js +12 -4
  29. package/dist/utils/audioDevices.js +34 -4
  30. package/dist/utils/bugReport.js +1 -75
  31. package/dist/utils/captions.js +19 -6
  32. package/dist/utils/chapters.js +5 -0
  33. package/dist/utils/cursor.js +317 -0
  34. package/dist/utils/events.js +22 -4
  35. package/dist/utils/gpu.js +173 -0
  36. package/dist/utils/idle.js +10 -3
  37. package/dist/utils/keystrokes.js +2 -17
  38. package/dist/utils/lifecycle.js +85 -2
  39. package/dist/utils/media.js +4 -0
  40. package/dist/utils/monitors.js +5 -2
  41. package/dist/utils/narrate.js +224 -0
  42. package/dist/utils/pause.js +176 -0
  43. package/dist/utils/pipeline.js +154 -14
  44. package/dist/utils/recipes.js +67 -0
  45. package/dist/utils/recorder.js +163 -0
  46. package/dist/utils/recordingIndex.js +266 -0
  47. package/dist/utils/sessions.js +29 -5
  48. package/dist/utils/stepGuide.js +205 -0
  49. package/dist/utils/steps.js +88 -0
  50. package/dist/utils/targets.js +31 -7
  51. package/dist/utils/timeline.js +85 -0
  52. package/dist/utils/toolsets.js +17 -6
  53. package/dist/utils/transcriptCut.js +134 -0
  54. package/dist/utils/wgc.js +2 -2
  55. package/dist/wgcRecorder.js +1 -1
  56. package/package.json +3 -1
@@ -0,0 +1,176 @@
1
+ import { existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { basename, dirname, extname, join } from "node:path";
3
+ import { ScreencastError } from "./errors.js";
4
+ import { runCapture } from "./ffmpeg.js";
5
+ import { jobTimeoutMs } from "./jobs.js";
6
+ import { concatList, buildReplayJoinArgs } from "./replay.js";
7
+ export const DEFAULT_WEBCAM_SIZE = 0.25;
8
+ export function partsDir(output) {
9
+ return `${output}.parts`;
10
+ }
11
+ export function partPath(output, index) {
12
+ return index === 0 ? output : join(partsDir(output), `part-${String(index).padStart(3, "0")}.mp4`);
13
+ }
14
+ export function webcamPartPath(output, index) {
15
+ return join(partsDir(output), `webcam-${String(index).padStart(3, "0")}.mp4`);
16
+ }
17
+ export function webcamOutputPath(output) {
18
+ const ext = extname(output);
19
+ return join(dirname(output), `${basename(output, ext)}.webcam.mp4`);
20
+ }
21
+ export function recordedSec(parts) {
22
+ return parts.reduce((s, p) => s + p.durationSec, 0);
23
+ }
24
+ export function clockSpans(state) {
25
+ const spans = [];
26
+ let offset = 0;
27
+ for (const p of state.parts) {
28
+ spans.push({ startMs: p.startMs, offsetSec: offset, durationSec: p.durationSec });
29
+ offset += p.durationSec;
30
+ }
31
+ if (state.current)
32
+ spans.push({ startMs: state.current.startMs, offsetSec: offset });
33
+ return spans;
34
+ }
35
+ export function eventClock(state, fallbackStartMs, nowMs) {
36
+ if (!state || (state.parts.length === 0 && !state.current)) {
37
+ return { startMs: fallbackStartMs, endSec: (nowMs - fallbackStartMs) / 1000 };
38
+ }
39
+ const spans = clockSpans(state);
40
+ const live = state.current ? Math.max(0, (nowMs - state.current.startMs) / 1000) : 0;
41
+ return { startMs: spans[0].startMs, endSec: recordedSec(state.parts) + live, spans };
42
+ }
43
+ export function remainingCapSec(maxDurationSec, recorded) {
44
+ if (!maxDurationSec)
45
+ return 0;
46
+ const left = Math.floor(maxDurationSec - recorded);
47
+ if (left < 1) {
48
+ throw new ScreencastError(`The recording already used its maxDurationSec cap (${maxDurationSec}s); nothing is left to resume.`, "Call stop_recording to finalize it.");
49
+ }
50
+ return left;
51
+ }
52
+ export function pauseBlocker(record, ownsChild) {
53
+ if (record.status === "paused")
54
+ return "it is already paused";
55
+ if (record.status !== "recording")
56
+ return `it is ${record.status}`;
57
+ if (record.backend === "wgc")
58
+ return 'backend "wgc" cannot pause yet';
59
+ if (record.replay)
60
+ return "a replay buffer cannot pause";
61
+ if (!record.capture || !record.segments?.current)
62
+ return "it was started before pause was supported";
63
+ if (!ownsChild)
64
+ return "another server instance owns it";
65
+ return null;
66
+ }
67
+ export function resumeBlocker(record, owns) {
68
+ if (record.status === "recording")
69
+ return "it is already recording";
70
+ if (record.status !== "paused")
71
+ return `it is ${record.status}`;
72
+ if (!record.capture || !record.segments)
73
+ return "its capture settings are missing";
74
+ if (!owns)
75
+ return "it was paused by another server instance";
76
+ return null;
77
+ }
78
+ const pausing = new Set();
79
+ export function markPausing(id) {
80
+ pausing.add(id);
81
+ }
82
+ export function isPausing(id) {
83
+ return pausing.has(id);
84
+ }
85
+ export function clearPausing(id) {
86
+ pausing.delete(id);
87
+ }
88
+ const ends = new Map();
89
+ function endEntry(id) {
90
+ let e = ends.get(id);
91
+ if (!e) {
92
+ let resolve;
93
+ const promise = new Promise((r) => (resolve = r));
94
+ e = { promise, resolve };
95
+ ends.set(id, e);
96
+ }
97
+ return e;
98
+ }
99
+ export function sessionEnded(id) {
100
+ return endEntry(id).promise;
101
+ }
102
+ export function endSession(id) {
103
+ endEntry(id).resolve();
104
+ setTimeout(() => ends.delete(id), 60_000).unref?.();
105
+ }
106
+ const r3 = (n) => Math.round(n * 1000) / 1000;
107
+ export function buildWebcamAlignArgs(parts, output, codec) {
108
+ if (parts.length === 0)
109
+ throw new ScreencastError("No webcam parts to join.");
110
+ const chains = parts.map((p, i) => {
111
+ const d = r3(Math.max(0.001, p.durationSec));
112
+ const lead = r3(p.leadSec);
113
+ const head = lead > 0 ? `tpad=start_duration=${lead}:start_mode=clone,` : lead < 0 ? `trim=start=${-lead},setpts=PTS-STARTPTS,` : "";
114
+ return `[${i}:v]${head}tpad=stop_duration=${d}:stop_mode=clone,trim=duration=${d},setpts=PTS-STARTPTS,format=yuv420p,setsar=1[w${i}]`;
115
+ });
116
+ const join = `${parts.map((_, i) => `[w${i}]`).join("")}concat=n=${parts.length}:v=1:a=0[v]`;
117
+ return [
118
+ "-y", "-v", "error",
119
+ ...parts.flatMap((p) => ["-i", p.path]),
120
+ "-filter_complex", `${chains.join(";")};${join}`,
121
+ "-map", "[v]",
122
+ ...codec,
123
+ "-movflags", "+faststart",
124
+ output,
125
+ ];
126
+ }
127
+ export async function finishSegments(output, parts, opts) {
128
+ const dir = partsDir(output);
129
+ const result = { joined: false };
130
+ const video = parts.filter((p) => existsSync(p.path) && p.durationSec > 0);
131
+ const total = recordedSec(video);
132
+ let keepDir = false;
133
+ if (video.length > 1 || (video.length === 1 && video[0].path !== output)) {
134
+ mkdirSync(dir, { recursive: true });
135
+ const list = join(dir, "segments.txt");
136
+ const tmp = join(dir, `joined${extname(output) || ".mp4"}`);
137
+ writeFileSync(list, concatList(video.map((p) => p.path)));
138
+ const res = await runCapture(opts.ffmpeg, buildReplayJoinArgs(list, tmp), jobTimeoutMs(total));
139
+ if (res.code === 0 && existsSync(tmp)) {
140
+ renameSync(tmp, output);
141
+ result.joined = true;
142
+ }
143
+ else {
144
+ keepDir = true;
145
+ result.error = `Joining the ${video.length} segments failed; they are kept in ${dir}: ${res.stderr.trim().split("\n").slice(-3).join(" ")}`;
146
+ }
147
+ }
148
+ const cams = video.filter((p) => p.webcamPath && existsSync(p.webcamPath));
149
+ if (opts.webcamOutput && cams.length > 0) {
150
+ const args = buildWebcamAlignArgs(cams.map((p) => ({
151
+ path: p.webcamPath,
152
+ leadSec: p.webcamStartMs !== undefined ? (p.webcamStartMs - p.startMs) / 1000 : 0,
153
+ durationSec: p.durationSec,
154
+ })), opts.webcamOutput, opts.webcamCodec);
155
+ const res = await runCapture(opts.ffmpeg, args, jobTimeoutMs(total));
156
+ if (res.code === 0 && existsSync(opts.webcamOutput)) {
157
+ result.webcamPath = opts.webcamOutput;
158
+ }
159
+ else {
160
+ keepDir = true;
161
+ result.webcamError = `Aligning the webcam failed; its raw parts are kept in ${dir}: ${res.stderr.trim().split("\n").slice(-3).join(" ")}`;
162
+ }
163
+ }
164
+ if (!keepDir)
165
+ rmSync(dir, { recursive: true, force: true });
166
+ return result;
167
+ }
168
+ export function webcamPlacement(screen, cam, corner, size) {
169
+ const even = (n) => Math.max(2, Math.round(n / 2) * 2);
170
+ const width = even(screen.width * size);
171
+ const height = even((width * cam.height) / Math.max(1, cam.width));
172
+ const m = Math.round(screen.width * 0.02);
173
+ const x = corner.endsWith("left") ? m : Math.max(0, screen.width - width - m);
174
+ const y = corner.startsWith("top") ? m : Math.max(0, screen.height - height - m);
175
+ return { x, y, width, height };
176
+ }
@@ -2,12 +2,25 @@ import { ScreencastError } from "./errors.js";
2
2
  import { atempoChain, cropFilter, redactSteps, scaleFilter, scaledSize } from "./media.js";
3
3
  import { calloutSteps } from "./callout.js";
4
4
  import { ASPECT_DIMS, exportPresetParts, reframeFilter } from "./produce.js";
5
- import { keyframesToViews, zoomFilter, DEFAULT_TRANSITION_SEC } from "./zoom.js";
5
+ import { keyframesToViews, planClickZoom, zoomFilter, DEFAULT_TRANSITION_SEC } from "./zoom.js";
6
6
  import { resolveQuality } from "./targets.js";
7
7
  import { backdropSteps } from "./backdrop.js";
8
8
  import { groupBadges, keystrokeSteps, retimeBadges } from "./keystrokes.js";
9
+ import { cutFilters, cutsFor, DEFAULT_KEEP_SEC, DEFAULT_MIN_IDLE_SEC } from "./idle.js";
10
+ import { denoiseFilter, loudnessTarget, loudnormFilter } from "./audio.js";
11
+ import { subtitlesFilter } from "./captions.js";
12
+ import { mapSpans, mapTime } from "./timeline.js";
13
+ import { cursorSteps, transformCursor } from "./cursor.js";
9
14
  export const MAX_PIPELINE_STEPS = 30;
10
15
  const r3 = (v) => Math.round(v * 1000) / 1000;
16
+ export function probeArgs(args, p) {
17
+ const out = [...args];
18
+ const af = out.indexOf("-af");
19
+ if (af !== -1 && p.audio.length > 0)
20
+ out[af + 1] = `${p.audio.join(",")},${out[af + 1]}`;
21
+ out.splice(out.indexOf("-i"), 0, ...p.seek);
22
+ return out;
23
+ }
11
24
  export function planPipeline(input, output, steps, src, assets = {}, quality = "standard", opts = {}) {
12
25
  if (steps.length === 0)
13
26
  throw new ScreencastError("Give at least one step.");
@@ -25,6 +38,8 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
25
38
  "Put redact before zoom, in the source's coordinates.");
26
39
  }
27
40
  const redacts = steps.some((s) => s.op === "redact");
41
+ if (steps.filter((s) => s.op === "cut_idle").length > 1)
42
+ throw new ScreencastError("Use at most one cut_idle step.");
28
43
  let W = src.width;
29
44
  let H = src.height;
30
45
  let fps = src.fps;
@@ -40,6 +55,9 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
40
55
  let gif;
41
56
  const summary = [];
42
57
  const timeOps = [];
58
+ const pending = [];
59
+ const files = [];
60
+ let geo = { sx: 1, sy: 1, ox: 0, oy: 0 };
43
61
  const trimRange = (s, at) => {
44
62
  if (!Number.isFinite(s.start) || s.start < 0)
45
63
  throw new ScreencastError(`step ${at}: trim start must be a non-negative number.`);
@@ -62,6 +80,7 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
62
80
  graph.push(`${cur}${filter}${out}`);
63
81
  cur = out;
64
82
  };
83
+ const pend = (kind) => pending.push({ step: i, kind, seek: [...inputArgs], audio: [...audio], ops: [...timeOps] });
65
84
  switch (s.op) {
66
85
  case "trim": {
67
86
  const { start, end } = trimRange(s, at);
@@ -81,13 +100,18 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
81
100
  }
82
101
  case "crop":
83
102
  chain(cropFilter(s, { width: W, height: H }));
103
+ if (geo)
104
+ geo = { ...geo, ox: geo.ox - s.x, oy: geo.oy - s.y };
84
105
  W = s.width;
85
106
  H = s.height;
86
107
  summary.push(`crop to ${W}x${H}`);
87
108
  break;
88
109
  case "scale": {
89
110
  const f = scaleFilter(s);
111
+ const [w0, h0] = [W, H];
90
112
  ({ width: W, height: H } = scaledSize(W, H, s));
113
+ if (geo)
114
+ geo = { sx: (geo.sx * W) / w0, sy: (geo.sy * H) / h0, ox: (geo.ox * W) / w0, oy: (geo.oy * H) / h0 };
91
115
  chain(f);
92
116
  summary.push(`scale to ${W}x${H}`);
93
117
  break;
@@ -127,20 +151,116 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
127
151
  if (!dim)
128
152
  throw new ScreencastError(`step ${at}: unknown aspect "${s.aspect}".`);
129
153
  chain(`${reframeFilter(dim.w, dim.h, s.fit ?? "pad")},format=yuv420p`);
154
+ geo = null;
130
155
  W = dim.w;
131
156
  H = dim.h;
132
157
  summary.push(`reframe to ${s.aspect} (${s.fit ?? "pad"})`);
133
158
  break;
134
159
  }
135
160
  case "zoom": {
136
- const views = keyframesToViews(s.keyframes, W, H);
137
- chain(zoomFilter(views, { width: W, height: H, fps }, s.transitionSec ?? DEFAULT_TRANSITION_SEC));
138
- summary.push(`zoom ${s.keyframes.length} keyframe(s)`);
161
+ const transition = s.transitionSec ?? DEFAULT_TRANSITION_SEC;
162
+ let kfs = s.keyframes;
163
+ let from = "";
164
+ if (s.follow === "clicks") {
165
+ if (kfs)
166
+ throw new ScreencastError(`step ${at}: zoom takes keyframes or follow, not both.`);
167
+ if (!geo) {
168
+ throw new ScreencastError(`step ${at}: zoom follow "clicks" must come before reframe, backdrop or another zoom; the logged click positions no longer match the frame.`);
169
+ }
170
+ const g = geo;
171
+ const logged = opts.clicks?.[i];
172
+ if (!logged)
173
+ throw new ScreencastError(`Internal: missing clicks for step ${at}.`);
174
+ const clicks = logged.flatMap((c) => {
175
+ const t = mapTime(c.t, timeOps);
176
+ const x = c.x * g.sx + g.ox;
177
+ const y = c.y * g.sy + g.oy;
178
+ return t !== null && x >= 0 && x < W && y >= 0 && y < H ? [{ t, x, y }] : [];
179
+ });
180
+ kfs = planClickZoom(clicks, W, H, { holdSec: s.holdSec, maxZoom: s.maxZoom, transition });
181
+ from = ` from ${clicks.length} click(s)`;
182
+ }
183
+ else if (!kfs || kfs.length === 0) {
184
+ throw new ScreencastError(`step ${at}: zoom needs keyframes, or follow: "clicks".`);
185
+ }
186
+ if (kfs.length === 0) {
187
+ summary.push("zoom: no clicks in this part of the video; skipped");
188
+ break;
189
+ }
190
+ chain(zoomFilter(keyframesToViews(kfs, W, H), { width: W, height: H, fps }, transition));
191
+ geo = null;
192
+ summary.push(`zoom ${kfs.length} keyframe(s)${from}`);
193
+ break;
194
+ }
195
+ case "cut_idle": {
196
+ if (!opts.idle)
197
+ throw new ScreencastError(`Internal: missing idle scan for step ${at}.`);
198
+ const cuts = cutsFor(mapSpans(opts.idle, timeOps), s.minIdleSec ?? DEFAULT_MIN_IDLE_SEC, s.keepSec ?? DEFAULT_KEEP_SEC);
199
+ if (cuts.length === 0) {
200
+ summary.push("cut_idle: no idle stretches here; nothing cut");
201
+ break;
202
+ }
203
+ const f = cutFilters(cuts);
204
+ chain(f.video);
205
+ audio.push(f.audio);
206
+ audioReencode = true;
207
+ const removed = cuts.reduce((sum, c) => sum + (c.end - c.start), 0);
208
+ if (dur !== null)
209
+ dur -= removed;
210
+ timeOps.push({ op: "cut", spans: cuts });
211
+ summary.push(`cut_idle ${cuts.length} stretch(es), ${r3(removed)}s removed`);
212
+ break;
213
+ }
214
+ case "audio": {
215
+ if (s.normalize === undefined && s.denoise === undefined)
216
+ throw new ScreencastError(`step ${at}: audio needs normalize and/or denoise.`);
217
+ if (!src.hasAudio) {
218
+ summary.push("audio: the input has no audio; skipped");
219
+ break;
220
+ }
221
+ const m = opts.audio?.[i];
222
+ const did = [];
223
+ if (s.denoise !== undefined) {
224
+ if (m?.floorDb === undefined)
225
+ pend("noisefloor");
226
+ audio.push(denoiseFilter(s.denoise, m?.floorDb ?? null));
227
+ did.push(`denoise ${s.denoise}`);
228
+ }
229
+ if (s.normalize !== undefined && m?.silent)
230
+ did.push("silent, not normalized");
231
+ else if (s.normalize !== undefined) {
232
+ const t = loudnessTarget(s.normalize);
233
+ if (!m?.loudness)
234
+ pend("loudness");
235
+ audio.push(loudnormFilter(t, m?.loudness), "aresample=48000");
236
+ did.push(`normalize to ${t.i} LUFS${m?.loudness ? ` (measured ${m.loudness.input_i})` : ""}`);
237
+ }
238
+ audioReencode = true;
239
+ summary.push(`audio: ${did.join(", ")}`);
240
+ break;
241
+ }
242
+ case "burn_subtitles": {
243
+ if (!s.subtitles === !s.transcribe)
244
+ throw new ScreencastError(`step ${at}: burn_subtitles takes subtitles (a path) or transcribe: true.`);
245
+ if (s.transcribe && !src.hasAudio)
246
+ throw new ScreencastError(`step ${at}: transcribe needs audio, and the input has none.`);
247
+ const file = opts.subtitles?.[i];
248
+ if (file === "") {
249
+ summary.push("burn_subtitles: no cues in this part of the video; skipped");
250
+ break;
251
+ }
252
+ if (file === undefined)
253
+ pend(s.transcribe ? "transcribe" : "subtitles");
254
+ const ass = !!s.subtitles && /\.(ass|ssa)$/i.test(s.subtitles);
255
+ const style = s.style ?? (ass ? null : "clean");
256
+ chain(subtitlesFilter(file ?? "<subtitles.srt>", opts.fontsDir ?? "<fonts>", style));
257
+ summary.push(`burn_subtitles ${s.transcribe ? "from a transcript" : "from a file"}, ${style ?? "file"} style`);
139
258
  break;
140
259
  }
141
260
  case "backdrop": {
142
261
  const { op: _op, ...bo } = s;
143
262
  const { steps: st, out: o, extraInputs: ex, layout } = backdropSteps(bo, { width: W, height: H }, cur, nextInput, tag);
263
+ geo = null;
144
264
  graph.push(...st);
145
265
  extraInputs.push(...ex);
146
266
  nextInput += ex.length / 2;
@@ -165,8 +285,30 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
165
285
  summary.push(`keystroke_overlay ${badges.length} badge(s)`);
166
286
  break;
167
287
  }
288
+ case "cursor": {
289
+ if (!geo) {
290
+ throw new ScreencastError(`step ${at}: cursor must come before zoom, reframe or backdrop; the logged positions no longer match the frame after them.`);
291
+ }
292
+ const c = opts.cursor?.[i];
293
+ if (!c)
294
+ throw new ScreencastError(`Internal: missing cursor plan for step ${at}.`);
295
+ const moved = transformCursor(c.plan, timeOps, geo);
296
+ if (moved.path.length === 0 || moved.visible.length === 0) {
297
+ summary.push("cursor: no cursor movement in this part of the video");
298
+ break;
299
+ }
300
+ const { steps: st, out: o, extraInputs: ex, commands } = cursorSteps(moved, s, { width: W, height: H }, cur, nextInput, tag, c.sprite, c.commandsFile);
301
+ graph.push(...st);
302
+ extraInputs.push(...ex);
303
+ nextInput += ex.length / 2;
304
+ cur = o;
305
+ files.push({ path: c.commandsFile, content: commands });
306
+ summary.push(`cursor ${moved.path.length} segment(s), ${moved.clicks.length} click(s)${s.spotlight ? ", spotlight" : ""}`);
307
+ break;
308
+ }
168
309
  case "export_preset": {
169
310
  const p = exportPresetParts(s.platform, s.fit ?? "pad", tag);
311
+ geo = null;
170
312
  chain(p.vf);
171
313
  if (p.af)
172
314
  audio.push(p.af);
@@ -190,16 +332,14 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
190
332
  const chaptersInput = opts.chaptersFile ? args.filter((a) => a === "-i").length : -1;
191
333
  if (opts.chaptersFile)
192
334
  args.push("-f", "ffmetadata", "-i", opts.chaptersFile);
193
- if (graph.length > 0) {
194
- if (src.hasAudio && audio.length > 0)
195
- graph.push(`[0:a]${audio.join(",")}[aout]`);
196
- args.push("-filter_complex", graph.join(";"), "-map", cur);
197
- }
198
- else {
199
- args.push("-map", "0:v");
200
- }
335
+ const audioGraph = src.hasAudio && audio.length > 0;
336
+ if (audioGraph)
337
+ graph.push(`[0:a]${audio.join(",")}[aout]`);
338
+ if (graph.length > 0)
339
+ args.push("-filter_complex", graph.join(";"));
340
+ args.push("-map", cur === "[0:v]" ? "0:v" : cur);
201
341
  if (src.hasAudio)
202
- args.push("-map", audio.length > 0 && graph.length > 0 ? "[aout]" : "0:a");
342
+ args.push("-map", audioGraph ? "[aout]" : "0:a");
203
343
  const finalEncode = encode;
204
344
  if (finalEncode) {
205
345
  args.push(...finalEncode);
@@ -213,5 +353,5 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
213
353
  if (chaptersInput !== -1)
214
354
  args.push("-map_chapters", String(chaptersInput));
215
355
  args.push(output);
216
- return { args, width: W, height: H, fps, durationSec: dur === null ? null : r3(dur), gif, summary, timeOps };
356
+ return { args, width: W, height: H, fps, durationSec: dur === null ? null : r3(dur), gif, summary, timeOps, pending, files };
217
357
  }
@@ -0,0 +1,67 @@
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
+ export function applyOverrides(base, overrides) {
45
+ const out = [...base];
46
+ const tail = out.at(-1) && EXPORTS.has(out.at(-1).op) ? out.pop() : null;
47
+ let exportStep = tail;
48
+ const recipeLen = out.length;
49
+ const replaced = new Set();
50
+ const first = [];
51
+ for (const o of overrides) {
52
+ if (EXPORTS.has(o.op)) {
53
+ exportStep = o;
54
+ continue;
55
+ }
56
+ const i = out.findIndex((s, j) => j < recipeLen && !replaced.has(j) && s.op === o.op);
57
+ if (i === -1 && o.op === "trim")
58
+ first.push(o);
59
+ else if (i === -1)
60
+ out.push(o);
61
+ else {
62
+ out[i] = o;
63
+ replaced.add(i);
64
+ }
65
+ }
66
+ return [...first, ...out, ...(exportStep ? [exportStep] : [])];
67
+ }
@@ -0,0 +1,163 @@
1
+ import { spawn } from "node:child_process";
2
+ import { mkdirSync, rmSync } from "node:fs";
3
+ import { 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 { requireFfmpeg } from "./ffmpeg.js";
8
+ import { joinSegments, probeDuration } 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
+ store.detachChild(id);
63
+ if (!isPausing(id))
64
+ endSession(id);
65
+ const cur = store.get(id);
66
+ if (!cur || cur.status !== "recording" || store.isStopping(id))
67
+ return;
68
+ const verdict = classifyUnrequestedExit({
69
+ code,
70
+ backend: opts.backend,
71
+ maxDurationSec: opts.maxDurationSec,
72
+ elapsedMs: Date.now() - opts.spawnedAt,
73
+ });
74
+ logMessage(verdict.status === "failed" ? "error" : "notice", verdict.status === "failed"
75
+ ? `Recording ${id} failed: the recorder exited with code ${code}.`
76
+ : `Recording ${id} ended on its own (${verdict.endReason}).`, { sessionId: id, ...verdict });
77
+ store.tryUpdate(id, {
78
+ ...verdict,
79
+ stoppedAt: new Date().toISOString(),
80
+ ...(verdict.status === "failed"
81
+ ? { error: `${opts.backend === "wgc" ? "The window recorder" : "ffmpeg"} exited with code ${code}:\n${tailLines(opts.watch)}` }
82
+ : {}),
83
+ });
84
+ if (cur.segments && (cur.segments.parts.length > 0 || cur.webcam)) {
85
+ void finalizeSegments(store, cur).catch((err) => {
86
+ process.stderr.write(`Joining ${id}'s segments failed: ${err instanceof Error ? err.message : String(err)}\n`);
87
+ });
88
+ }
89
+ });
90
+ }
91
+ async function finalizeSegments(store, record) {
92
+ const tools = requireFfmpeg();
93
+ await whenFinalized(record.id);
94
+ const { patch, error } = await joinSegments(record, tools);
95
+ const durationSec = await probeDuration(tools.ffprobe, record.outputPath);
96
+ store.tryUpdate(record.id, { ...patch, durationSec: durationSec ?? undefined, ...(error ? { error } : {}) });
97
+ }
98
+ export async function resumeSession(store, record, ffmpeg) {
99
+ const blocker = resumeBlocker(record, store.ownsPaused(record.id));
100
+ if (blocker)
101
+ throw new ScreencastError(`Cannot resume ${record.id}: ${blocker}.`);
102
+ const seg = record.segments;
103
+ const capture = record.capture;
104
+ const backend = record.backend ?? "gdigrab";
105
+ const done = recordedSec(seg.parts);
106
+ const capSec = remainingCapSec(record.maxDurationSec, done);
107
+ const index = seg.parts.length;
108
+ const path = partPath(record.outputPath, index);
109
+ const webcamPath = capture.webcam ? webcamPartPath(record.outputPath, index) : undefined;
110
+ if (index > 0 || webcamPath)
111
+ mkdirSync(partsDir(record.outputPath), { recursive: true });
112
+ const args = buildCaptureArgs(capture.target, {
113
+ ...capture.opts,
114
+ output: path,
115
+ maxDurationSec: capSec,
116
+ ...(capture.webcam && webcamPath ? { webcam: { ...capture.webcam, output: webcamPath } } : {}),
117
+ });
118
+ const spawnedAt = Date.now();
119
+ const child = spawn(ffmpeg, args, { stdio: ["pipe", "ignore", "pipe"], windowsHide: true });
120
+ const watch = watchStderr(child, record.id);
121
+ const cleanup = () => {
122
+ if (index > 0)
123
+ rmSync(path, { force: true });
124
+ if (webcamPath)
125
+ rmSync(webcamPath, { force: true });
126
+ };
127
+ if ((await settleCapture(child, watch, backend)) === "exited") {
128
+ cleanup();
129
+ throw new ScreencastError(`Resume failed (ffmpeg exited immediately); the recording stays paused:\n${tailLines(watch)}`);
130
+ }
131
+ const startMs = captureStartMs(watch, backend, spawnedAt);
132
+ const camStart = webcamPath ? parseCaptureStart(watch.head(), capture.opts.audio ? 2 : 1) : null;
133
+ store.attachChild(record.id, child);
134
+ let updated;
135
+ try {
136
+ updated = store.update(record.id, {
137
+ status: "recording",
138
+ pid: child.pid ?? null,
139
+ videoStartMs: startMs - done * 1000,
140
+ segments: {
141
+ parts: seg.parts,
142
+ current: { path, startMs, ...(webcamPath ? { webcamPath, ...(camStart !== null ? { webcamStartMs: camStart } : {}) } : {}) },
143
+ },
144
+ });
145
+ }
146
+ catch (err) {
147
+ store.detachChild(record.id);
148
+ if (child.pid !== undefined)
149
+ killPid(child.pid);
150
+ cleanup();
151
+ throw new ScreencastError(`Resume stopped: the session registry could not be written (${err.message}).`);
152
+ }
153
+ if (!updated) {
154
+ store.detachChild(record.id);
155
+ if (child.pid !== undefined)
156
+ killPid(child.pid);
157
+ cleanup();
158
+ throw new ScreencastError(`No session with id "${record.id}".`);
159
+ }
160
+ store.clearPaused(record.id);
161
+ attachExitHandler(store, record.id, child, { backend, maxDurationSec: capSec, spawnedAt, watch });
162
+ return { record: updated, recordedSec: done, capSec };
163
+ }