@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,173 @@
1
+ import { ScreencastError } from "./errors.js";
2
+ import { runCapture } from "./ffmpeg.js";
3
+ import { runPowerShell } from "./monitors.js";
4
+ import { QUALITY_PRESETS, resolveQuality } from "./targets.js";
5
+ export const HW_ENCODERS = ["nvenc", "qsv", "amf"];
6
+ export const ENCODER_CODECS = {
7
+ x264: "libx264",
8
+ nvenc: "h264_nvenc",
9
+ qsv: "h264_qsv",
10
+ amf: "h264_amf",
11
+ };
12
+ export const HW_QUALITY = {
13
+ nvenc: { draft: { preset: "p1", q: 30 }, standard: { preset: "p4", q: 25 }, high: { preset: "p6", q: 20 } },
14
+ qsv: { draft: { preset: "veryfast", q: 30 }, standard: { preset: "medium", q: 25 }, high: { preset: "slower", q: 20 } },
15
+ amf: { draft: { preset: "speed", q: 30 }, standard: { preset: "balanced", q: 25 }, high: { preset: "quality", q: 20 } },
16
+ };
17
+ export function encoderArgs(encoder, quality, opts = {}) {
18
+ if (!QUALITY_PRESETS[quality])
19
+ throw new ScreencastError(`Unknown quality preset "${quality}".`);
20
+ if (encoder === "x264")
21
+ return resolveQuality(quality);
22
+ const { preset, q } = HW_QUALITY[encoder][quality];
23
+ const codec = ["-c:v", ENCODER_CODECS[encoder]];
24
+ const rate = encoder === "nvenc"
25
+ ? ["-preset", preset, "-rc", "vbr", "-cq", String(q), "-b:v", "0"]
26
+ : encoder === "qsv"
27
+ ? ["-preset", preset, "-global_quality", String(q)]
28
+ : ["-quality", preset, "-rc", "cqp", "-qp_i", String(q), "-qp_p", String(q)];
29
+ return [...codec, ...rate, ...(opts.gpuFrames ? [] : ["-pix_fmt", "nv12"])];
30
+ }
31
+ export function buildEncoderProbeArgs(encoder) {
32
+ return [
33
+ "-hide_banner", "-v", "error",
34
+ "-f", "lavfi", "-i", "color=c=black:s=256x256:r=30",
35
+ "-frames:v", "3",
36
+ ...encoderArgs(encoder, "draft"),
37
+ "-f", "null", "-",
38
+ ];
39
+ }
40
+ export function buildDdaProbeArgs(encoder) {
41
+ return [
42
+ "-hide_banner", "-v", "error",
43
+ "-f", "lavfi", "-i", `ddagrab=framerate=10${encoder ? "" : ",hwdownload,format=bgra"}`,
44
+ "-frames:v", "2",
45
+ ...(encoder ? encoderArgs(encoder, "draft", { gpuFrames: true }) : []),
46
+ "-f", "null", "-",
47
+ ];
48
+ }
49
+ const PROBE_TIMEOUT_MS = 20_000;
50
+ export function ffmpegRunner(ffmpeg) {
51
+ return async (args) => {
52
+ try {
53
+ const res = await runCapture(ffmpeg, args, PROBE_TIMEOUT_MS, { closeStdin: true });
54
+ return res.code === 0;
55
+ }
56
+ catch {
57
+ return false;
58
+ }
59
+ };
60
+ }
61
+ const probes = new Map();
62
+ function cachedProbe(ffmpeg, key, args, run) {
63
+ const k = `${ffmpeg}\u0000${key}`;
64
+ let p = probes.get(k);
65
+ if (!p) {
66
+ p = run(args);
67
+ probes.set(k, p);
68
+ }
69
+ return p;
70
+ }
71
+ export function clearGpuProbeCache() {
72
+ probes.clear();
73
+ dxgiCache = null;
74
+ }
75
+ export async function probeHwEncoders(ffmpeg, run = ffmpegRunner(ffmpeg)) {
76
+ const results = await Promise.all(HW_ENCODERS.map((e) => cachedProbe(ffmpeg, `enc:${e}`, buildEncoderProbeArgs(e), run)));
77
+ return Object.fromEntries(HW_ENCODERS.map((e, i) => [e, results[i]]));
78
+ }
79
+ export async function resolveEncoder(choice, backend, ffmpeg, run = ffmpegRunner(ffmpeg)) {
80
+ if (choice === "x264")
81
+ return { encoder: "x264", gpuFrames: false };
82
+ const available = await probeHwEncoders(ffmpeg, run);
83
+ const pick = choice === "auto" ? HW_ENCODERS.find((e) => available[e]) : available[choice] ? choice : undefined;
84
+ if (!pick) {
85
+ if (choice === "auto")
86
+ return { encoder: "x264", gpuFrames: false, note: "No hardware encoder passed a trial encode; using libx264." };
87
+ throw new ScreencastError(`The ${choice} encoder (${ENCODER_CODECS[choice]}) failed a trial encode on this machine.`, 'Use encoder: "auto" (falls back to libx264) or "x264"; doctor lists the encoders that work here.');
88
+ }
89
+ const gpuFrames = backend === "ddagrab" && (await cachedProbe(ffmpeg, `dda:${pick}`, buildDdaProbeArgs(pick), run));
90
+ return { encoder: pick, gpuFrames };
91
+ }
92
+ export function ddagrabWorks(ffmpeg, run = ffmpegRunner(ffmpeg)) {
93
+ return cachedProbe(ffmpeg, "dda", buildDdaProbeArgs(), run);
94
+ }
95
+ export function parseDxgiOutputs(stdout) {
96
+ const out = [];
97
+ for (const line of stdout.split(/\r?\n/)) {
98
+ const parts = line.trim().split(",");
99
+ if (parts.length < 7)
100
+ continue;
101
+ const n = parts.slice(0, 6).map(Number);
102
+ if (n.some((v) => !Number.isInteger(v)))
103
+ continue;
104
+ const [adapter = 0, output = 0, x = 0, y = 0, w = 0, h = 0] = n;
105
+ if (w <= 0 || h <= 0)
106
+ continue;
107
+ out.push({ adapter, output, x, y, w, h, name: parts.slice(6).join(",") });
108
+ }
109
+ return out;
110
+ }
111
+ const PS_DXGI = `
112
+ Add-Type -TypeDefinition @"
113
+ using System; using System.Runtime.InteropServices; using System.Text;
114
+ public static class ScDxgi {
115
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
116
+ public struct DESC { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string Name; public int L, T, R, B; public int Attached; public int Rot; public IntPtr Mon; }
117
+ [ComImport, Guid("770aae78-f26f-4dba-a829-253c83d1b387"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
118
+ interface IF1 { void a(); void b(); void c(); void d(); void e(); void f(); void g(); void h(); void i();
119
+ [PreserveSig] int EnumAdapters1(uint i, [MarshalAs(UnmanagedType.Interface)] out IA1 a); }
120
+ [ComImport, Guid("29038f61-3839-4626-91fd-086879011a05"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
121
+ interface IA1 { void a(); void b(); void c(); void d();
122
+ [PreserveSig] int EnumOutputs(uint i, [MarshalAs(UnmanagedType.Interface)] out IO o); }
123
+ [ComImport, Guid("ae02eedb-c735-4690-8d52-5a8dc20213aa"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
124
+ interface IO { void a(); void b(); void c(); void d(); [PreserveSig] int GetDesc(out DESC d); }
125
+ [DllImport("dxgi.dll")] static extern int CreateDXGIFactory1(ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IF1 f);
126
+ public static string List() {
127
+ Guid g = new Guid("770aae78-f26f-4dba-a829-253c83d1b387"); IF1 f;
128
+ if (CreateDXGIFactory1(ref g, out f) != 0) return "";
129
+ StringBuilder sb = new StringBuilder(); IA1 a;
130
+ for (uint ai = 0; f.EnumAdapters1(ai, out a) == 0; ai++) { IO o;
131
+ for (uint oi = 0; a.EnumOutputs(oi, out o) == 0; oi++) { DESC d;
132
+ if (o.GetDesc(out d) == 0) sb.AppendFormat("{0},{1},{2},{3},{4},{5},{6}\\n", ai, oi, d.L, d.T, d.R - d.L, d.B - d.T, d.Name); } }
133
+ return sb.ToString(); } }
134
+ "@
135
+ [ScDxgi]::List()
136
+ `;
137
+ const DXGI_CACHE_MS = 5_000;
138
+ let dxgiCache = null;
139
+ export function getDxgiOutputs() {
140
+ if (dxgiCache && Date.now() - dxgiCache.at < DXGI_CACHE_MS)
141
+ return dxgiCache.outputs;
142
+ const outputs = runPowerShell(PS_DXGI, "DXGI outputs").then(parseDxgiOutputs);
143
+ dxgiCache = { at: Date.now(), outputs };
144
+ outputs.catch(() => {
145
+ dxgiCache = null;
146
+ });
147
+ return outputs;
148
+ }
149
+ const evenDown = (n) => n - (n % 2);
150
+ export function planDdaSource(rect, outputs) {
151
+ const holds = (o) => rect.x >= o.x && rect.y >= o.y && rect.x + rect.w <= o.x + o.w && rect.y + rect.h <= o.y + o.h;
152
+ const host = outputs.find(holds);
153
+ if (!host) {
154
+ throw new ScreencastError(`backend "ddagrab" captures one display, and ${rect.x},${rect.y} ${rect.w}x${rect.h} is not inside a single one.`, 'Use a monitor:<i> target, a region inside one display, or backend "gdigrab".');
155
+ }
156
+ if (host.adapter !== 0) {
157
+ throw new ScreencastError(`That display (${host.name || `adapter ${host.adapter} output ${host.output}`}) is driven by a second GPU, which ddagrab cannot reach.`, 'Use backend "gdigrab" for it.');
158
+ }
159
+ const w = evenDown(rect.w);
160
+ const h = evenDown(rect.h);
161
+ if (w <= 0 || h <= 0)
162
+ throw new ScreencastError("The capture rectangle is too small to record (needs at least 2x2 px).");
163
+ const whole = rect.x === host.x && rect.y === host.y && w === host.w && h === host.h;
164
+ return whole ? { output: host.output } : { output: host.output, crop: { x: rect.x - host.x, y: rect.y - host.y, w, h } };
165
+ }
166
+ export function buildDdaInputArgs(src, fps, opts) {
167
+ const crop = src.crop
168
+ ? `:offset_x=${src.crop.x}:offset_y=${src.crop.y}:video_size=${src.crop.w}x${src.crop.h}`
169
+ : "";
170
+ const mouse = opts.drawMouse === false ? 0 : 1;
171
+ const graph = `ddagrab=output_idx=${src.output}:framerate=${fps}:draw_mouse=${mouse}${crop}${opts.download ? ",hwdownload,format=bgra" : ""}`;
172
+ return ["-f", "lavfi", "-i", graph];
173
+ }
@@ -66,17 +66,24 @@ export function cutsFor(idle, minIdleSec, keep) {
66
66
  .filter((r) => r.end - r.start > 0.05)
67
67
  .map((r) => ({ start: Number(r.start.toFixed(3)), end: Number(r.end.toFixed(3)) }));
68
68
  }
69
- export function buildCutIdleArgs(input, output, cuts, withAudio, quality = "standard") {
69
+ export function cutFilters(cuts) {
70
70
  if (cuts.length === 0)
71
71
  throw new ScreencastError("Nothing to cut.");
72
72
  if (cuts.length > MAX_CUTS)
73
73
  throw new ScreencastError(`Too many idle stretches (${cuts.length}); raise minIdleSec.`);
74
74
  const drop = sumExpr(cuts.map((c) => `between(t,${c.start},${c.end})`));
75
75
  const removed = sumExpr(cuts.map((c) => `clip(T-${c.start},0,${Number((c.end - c.start).toFixed(3))})`));
76
+ return {
77
+ video: `select='not(${drop})',setpts='(T-(${removed}))/TB'`,
78
+ audio: `asetnsamples=n=256:p=0,aselect='not(${drop})',asetpts=N/SR/TB`,
79
+ };
80
+ }
81
+ export function buildCutIdleArgs(input, output, cuts, withAudio, quality = "standard") {
82
+ const f = cutFilters(cuts);
76
83
  return [
77
84
  "-y", "-i", input,
78
- "-vf", `select='not(${drop})',setpts='(T-(${removed}))/TB'`,
79
- ...(withAudio ? ["-af", `aselect='not(${drop})',asetpts=N/SR/TB`] : ["-an"]),
85
+ "-vf", f.video,
86
+ ...(withAudio ? ["-af", f.audio] : ["-an"]),
80
87
  ...resolveQuality(quality),
81
88
  ...(withAudio ? ["-c:a", "aac", "-b:a", "160k"] : []),
82
89
  output,
@@ -3,6 +3,7 @@ import { escapeFilterPath } from "./fonts.js";
3
3
  import { sumExpr } from "./expr.js";
4
4
  import { resolveQuality } from "./targets.js";
5
5
  import { validateColor } from "./validate.js";
6
+ import { mapWindow } from "./timeline.js";
6
7
  export const BADGE_POSITIONS = ["bottom", "bottom-left", "bottom-right", "top", "top-left", "top-right"];
7
8
  export const DEFAULT_LINGER_SEC = 1.2;
8
9
  export const DOUBLE_CLICK_SEC = 0.5;
@@ -106,23 +107,7 @@ export function mapBadges(badges, map) {
106
107
  });
107
108
  }
108
109
  export function retimeBadges(badges, ops) {
109
- return mapBadges(badges, (from, to) => {
110
- let a = from;
111
- let b = to;
112
- for (const op of ops) {
113
- if (op.op === "trim") {
114
- a = Math.max(a, op.start) - op.start;
115
- b = Math.min(b, op.end) - op.start;
116
- if (b <= a)
117
- return null;
118
- }
119
- else {
120
- a /= op.factor;
121
- b /= op.factor;
122
- }
123
- }
124
- return [a, b];
125
- });
110
+ return mapBadges(badges, (from, to) => mapWindow(from, to, ops));
126
111
  }
127
112
  export function badgeSize(frameH, size) {
128
113
  if (size !== undefined) {
@@ -5,6 +5,8 @@ import { whenFinalized } from "./events.js";
5
5
  import { buildProbeArgs, parseMediaInfo } from "./media.js";
6
6
  import { ScreencastError } from "./errors.js";
7
7
  import { wgcStopFile } from "./wgc.js";
8
+ import { encoderArgs } from "./gpu.js";
9
+ import { clearPausing, endSession, finishSegments, markPausing, pauseBlocker, recordedSec, webcamOutputPath, } from "./pause.js";
8
10
  import { expectedImage, isAlive, isRecorderProcess, killPid, } from "./sessions.js";
9
11
  async function waitForPidExit(pid, ms) {
10
12
  const deadline = Date.now() + ms;
@@ -36,6 +38,75 @@ export async function probeDuration(ffprobe, path) {
36
38
  return null;
37
39
  }
38
40
  }
41
+ async function quitChild(child, pid, gracefulMs) {
42
+ if (!child.stdin || !child.stdin.writable)
43
+ return false;
44
+ child.stdin.write("q\n");
45
+ child.stdin.end();
46
+ const graceful = await waitForExit(child, gracefulMs);
47
+ if (!graceful && pid !== null) {
48
+ killPid(pid);
49
+ await waitForPidExit(pid, 2000);
50
+ await waitForExit(child, 2000);
51
+ }
52
+ return graceful;
53
+ }
54
+ export async function finalParts(record, ffprobe) {
55
+ const seg = record.segments;
56
+ if (!seg)
57
+ return [];
58
+ const parts = [...seg.parts];
59
+ if (seg.current) {
60
+ const durationSec = (await probeDuration(ffprobe, seg.current.path)) ?? 0;
61
+ parts.push({ ...seg.current, durationSec });
62
+ }
63
+ return parts;
64
+ }
65
+ export function needsJoin(record) {
66
+ const seg = record.segments;
67
+ return !!seg && (seg.parts.length > 0 || !!record.webcam);
68
+ }
69
+ export async function joinSegments(record, tools) {
70
+ const parts = await finalParts(record, tools.ffprobe);
71
+ const res = await finishSegments(record.outputPath, parts, {
72
+ ffmpeg: tools.ffmpeg,
73
+ webcamOutput: record.webcam ? webcamOutputPath(record.outputPath) : undefined,
74
+ webcamCodec: encoderArgs(record.encoder ?? "x264", record.quality, { gpuFrames: false }),
75
+ });
76
+ return {
77
+ patch: {
78
+ segments: { parts },
79
+ ...(record.webcam ? { webcam: { ...record.webcam, error: res.webcamError } } : {}),
80
+ },
81
+ count: parts.length,
82
+ error: res.error,
83
+ };
84
+ }
85
+ export async function pauseSession(store, record, opts) {
86
+ const child = store.getChild(record.id);
87
+ const blocker = pauseBlocker(record, !!child);
88
+ if (blocker)
89
+ throw new ScreencastError(`Cannot pause ${record.id}: ${blocker}.`);
90
+ markPausing(record.id);
91
+ store.markStopping(record.id);
92
+ try {
93
+ const graceful = await quitChild(child, record.pid, opts.gracefulMs ?? 8000);
94
+ store.detachChild(record.id);
95
+ const cur = record.segments.current;
96
+ const segmentSec = (await opts.probe(cur.path)) ?? 0;
97
+ const parts = record.segments.parts;
98
+ const next = segmentSec > 0 ? [...parts, { ...cur, durationSec: segmentSec }] : parts;
99
+ if (segmentSec <= 0 && cur.path !== record.outputPath)
100
+ rmSync(cur.path, { force: true });
101
+ store.markPaused(record.id);
102
+ const updated = store.update(record.id, { status: "paused", pid: null, segments: { parts: next } });
103
+ return { record: updated, recordedSec: recordedSec(next), segmentSec, graceful };
104
+ }
105
+ finally {
106
+ clearPausing(record.id);
107
+ store.clearStopping(record.id);
108
+ }
109
+ }
39
110
  export async function stopAll(store, probe, capMs = 10_000) {
40
111
  const ids = store.activeIds();
41
112
  const stops = ids.map(async (id) => {
@@ -101,7 +172,18 @@ async function runStop(store, record, opts) {
101
172
  }
102
173
  }
103
174
  store.detachChild(record.id);
175
+ if (record.status === "paused")
176
+ graceful = true;
177
+ endSession(record.id);
178
+ store.clearPaused(record.id);
104
179
  await whenFinalized(record.id);
180
+ let segments;
181
+ let segmentPatch = {};
182
+ if (needsJoin(record)) {
183
+ const join = await joinSegments(record, requireFfmpeg());
184
+ segmentPatch = join.patch;
185
+ segments = { count: join.count, ...(join.error ? { error: join.error } : {}) };
186
+ }
105
187
  const replay = record.replay
106
188
  ? await finishReplay(record.replay, {
107
189
  save: opts.saveReplay ?? false,
@@ -112,13 +194,14 @@ async function runStop(store, record, opts) {
112
194
  : undefined;
113
195
  const durationSec = await opts.probe(record.outputPath);
114
196
  const updated = store.update(record.id, {
197
+ ...segmentPatch,
115
198
  status: "stopped",
116
199
  stoppedAt: new Date().toISOString(),
117
200
  durationSec: durationSec ?? undefined,
118
201
  endReason: opts.reason,
119
- error: undefined,
202
+ error: segments?.error,
120
203
  });
121
- return { record: updated, graceful, durationSec, ...(replay ? { replay } : {}) };
204
+ return { record: updated, graceful, durationSec, ...(replay ? { replay } : {}), ...(segments ? { segments } : {}) };
122
205
  }
123
206
  finally {
124
207
  if (stopFile)
@@ -360,6 +360,8 @@ export function buildSpeedArgs(input, output, factor, hasAudio, quality = DEFAUL
360
360
  args.push(output);
361
361
  return args;
362
362
  }
363
+ export const CIRCLE_MASK = "crop='min(iw,ih)':'min(iw,ih)',format=yuva420p," +
364
+ "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)'";
363
365
  export function buildOverlayArgs(input, overlay, output, opts, quality = DEFAULT_EDIT_QUALITY) {
364
366
  const x = requireNonNegativeInt(opts.x, "overlay x");
365
367
  const y = requireNonNegativeInt(opts.y, "overlay y");
@@ -376,6 +378,8 @@ export function buildOverlayArgs(input, overlay, output, opts, quality = DEFAULT
376
378
  const sh = opts.scale.height ?? -1;
377
379
  ovl += `,scale=${sw}:${sh}`;
378
380
  }
381
+ if (opts.shape === "circle")
382
+ ovl += `,${CIRCLE_MASK}`;
379
383
  const filter = `${ovl}[ovl];[0:v][ovl]overlay=${x}:${y}${enable}[v]`;
380
384
  const dur = opts.durationSec;
381
385
  return [
@@ -49,8 +49,11 @@ export function runPowerShell(script, what, opts = {}) {
49
49
  const file = opts.command?.file ?? "powershell";
50
50
  const args = opts.command?.args ?? ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded];
51
51
  return new Promise((resolve, reject) => {
52
- execFile(file, args, { encoding: "utf8", windowsHide: true, maxBuffer: 8 * 1024 * 1024, timeout, killSignal: "SIGKILL" }, (err, stdout, stderr) => {
53
- if (err && err.killed) {
52
+ execFile(file, args, { encoding: "utf8", windowsHide: true, maxBuffer: 8 * 1024 * 1024, timeout, killSignal: "SIGKILL", signal: opts.signal }, (err, stdout, stderr) => {
53
+ if (opts.signal?.aborted) {
54
+ reject(new ScreencastError(`Cancelled while reading ${what}.`));
55
+ }
56
+ else if (err && err.killed) {
54
57
  reject(new ScreencastError(`Timed out reading ${what} after ${timeout / 1000} s (PowerShell did not answer).`, `Retry; if it keeps happening, restart the app being captured or raise ${PS_TIMEOUT_ENV}.`));
55
58
  }
56
59
  else if (err || !stdout) {
@@ -0,0 +1,224 @@
1
+ import { ScreencastError } from "./errors.js";
2
+ import { runPowerShell, psTimeoutMs } from "./monitors.js";
3
+ import { audioCodecFor } from "./audio.js";
4
+ import { isAudioOnlyPath } from "./media.js";
5
+ export const MAX_LINES = 200;
6
+ export const MAX_LINE_CHARS = 1_000;
7
+ export const MIN_RATE = 0.5;
8
+ export const MAX_RATE = 3;
9
+ const r3 = (v) => Math.round(v * 1000) / 1000;
10
+ export function resolveLines(lines, markers) {
11
+ if (lines.length === 0)
12
+ throw new ScreencastError("lines is empty: give at least one { t | marker, text }.");
13
+ if (lines.length > MAX_LINES)
14
+ throw new ScreencastError(`At most ${MAX_LINES} lines are allowed (got ${lines.length}).`);
15
+ const out = lines.map((line, i) => {
16
+ const text = line.text.replace(/\s+/g, " ").trim();
17
+ if (!text)
18
+ throw new ScreencastError(`lines[${i}] has no text.`);
19
+ if (text.length > MAX_LINE_CHARS) {
20
+ throw new ScreencastError(`lines[${i}] is ${text.length} characters; at most ${MAX_LINE_CHARS} are allowed. Split it.`);
21
+ }
22
+ if (line.t !== undefined && line.marker !== undefined) {
23
+ throw new ScreencastError(`lines[${i}] has both t and marker; give one.`);
24
+ }
25
+ if (line.t !== undefined) {
26
+ if (!Number.isFinite(line.t) || line.t < 0)
27
+ throw new ScreencastError(`lines[${i}].t must be a non-negative number.`);
28
+ return { t: r3(line.t), text };
29
+ }
30
+ if (line.marker !== undefined) {
31
+ const want = line.marker.trim().toLowerCase();
32
+ const m = markers.find((k) => k.label.trim().toLowerCase() === want);
33
+ if (!m) {
34
+ const known = markers.map((k) => `"${k.label}"`).join(", ");
35
+ throw new ScreencastError(`lines[${i}]: no marker labelled "${line.marker}".`, known ? `Markers on this video: ${known}.` : "This video has no markers; add_marker stamps one, or give t.");
36
+ }
37
+ return { t: r3(m.t), text };
38
+ }
39
+ throw new ScreencastError(`lines[${i}] needs t (seconds) or marker (a marker label).`);
40
+ });
41
+ return out.sort((a, b) => a.t - b.t);
42
+ }
43
+ export function placementWarnings(placed, videoDurationSec) {
44
+ const warnings = [];
45
+ placed.forEach((p, i) => {
46
+ const end = p.t + p.durationSec;
47
+ const next = placed[i + 1];
48
+ const quote = `"${p.text.length > 40 ? `${p.text.slice(0, 40)}...` : p.text}"`;
49
+ if (p.t >= videoDurationSec) {
50
+ warnings.push(`Line at ${p.t}s ${quote} starts after the video ends (${r3(videoDurationSec)}s) and is not heard.`);
51
+ }
52
+ else if (next && end > next.t + 0.05) {
53
+ warnings.push(`Line at ${p.t}s ${quote} runs ${r3(end - next.t)}s past the next line (${next.t}s); they overlap. Move the next line, shorten this one, or raise rate.`);
54
+ }
55
+ else if (end > videoDurationSec + 0.05) {
56
+ warnings.push(`Line at ${p.t}s ${quote} runs ${r3(end - videoDurationSec)}s past the end of the video and is cut off.`);
57
+ }
58
+ });
59
+ return warnings;
60
+ }
61
+ export function narrationCues(placed, videoDurationSec) {
62
+ return placed
63
+ .map((p, i) => {
64
+ const next = placed[i + 1];
65
+ const end = Math.min(p.t + p.durationSec, next ? next.t : Infinity, videoDurationSec);
66
+ return { start: p.t, end: r3(end), text: p.text };
67
+ })
68
+ .filter((c) => c.end > c.start);
69
+ }
70
+ export function wavDurationSec(buf) {
71
+ if (buf.length < 12 || buf.toString("ascii", 0, 4) !== "RIFF" || buf.toString("ascii", 8, 12) !== "WAVE") {
72
+ throw new ScreencastError("The speech engine did not return a WAV file.");
73
+ }
74
+ let byteRate = 0;
75
+ for (let off = 12; off + 8 <= buf.length;) {
76
+ const id = buf.toString("ascii", off, off + 4);
77
+ const size = buf.readUInt32LE(off + 4);
78
+ if (id === "fmt " && off + 16 <= buf.length)
79
+ byteRate = buf.readUInt32LE(off + 16);
80
+ if (id === "data") {
81
+ if (byteRate <= 0)
82
+ break;
83
+ const available = buf.length - (off + 8);
84
+ const bytes = size === 0 || size === 0xffffffff || size > available ? available : size;
85
+ return bytes / byteRate;
86
+ }
87
+ off += 8 + size + (size % 2);
88
+ }
89
+ throw new ScreencastError("Could not read the WAV header the speech engine wrote.");
90
+ }
91
+ export function buildNarrateArgs(video, wavs, output, placed, videoDurationSec, opts) {
92
+ if (!Number.isFinite(videoDurationSec) || videoDurationSec <= 0) {
93
+ throw new ScreencastError("video duration must be known and positive.");
94
+ }
95
+ if (wavs.length === 0 || wavs.length !== placed.length) {
96
+ throw new ScreencastError("Every placed line needs its WAV.");
97
+ }
98
+ const D = r3(videoDurationSec);
99
+ const mix = (n) => `amix=inputs=${n}:duration=longest:dropout_transition=0:normalize=0`;
100
+ const parts = placed.map((p, i) => {
101
+ const ms = Math.round(p.t * 1000);
102
+ return `[${i + 1}:a]aresample=48000,aformat=channel_layouts=mono,adelay=${ms}[l${i}]`;
103
+ });
104
+ const lines = placed.map((_, i) => `[l${i}]`).join("");
105
+ const stereo = !(opts.hasAudio && opts.channels === 1);
106
+ const bus = `apad,atrim=end=${D}${stereo ? ",pan=stereo|c0=c0|c1=c0" : ""}`;
107
+ const voice = opts.hasAudio ? "voice" : "aout";
108
+ parts.push(placed.length > 1 ? `${lines}${mix(placed.length)},${bus}[${voice}]` : `[l0]${bus}[${voice}]`);
109
+ if (opts.hasAudio) {
110
+ parts.push(`[0:a]aresample=48000,aformat=channel_layouts=${stereo ? "stereo" : "mono"}[orig]`);
111
+ if (opts.duck ?? true) {
112
+ parts.push("[voice]asplit=2[vo][key]");
113
+ parts.push("[orig][key]sidechaincompress=threshold=0.02:ratio=8:attack=20:release=400[bed]");
114
+ parts.push(`[bed][vo]${mix(2)}[aout]`);
115
+ }
116
+ else {
117
+ parts.push(`[orig][voice]${mix(2)}[aout]`);
118
+ }
119
+ }
120
+ const audioOnly = isAudioOnlyPath(output);
121
+ return [
122
+ "-y",
123
+ "-i", video,
124
+ ...wavs.flatMap((w) => ["-i", w]),
125
+ "-filter_complex", parts.join(";"),
126
+ ...(audioOnly ? [] : ["-map", "0:v?", "-c:v", "copy"]),
127
+ "-map", "[aout]",
128
+ "-t", String(D),
129
+ ...audioCodecFor(output),
130
+ ...(/\.(mp4|mov|m4a)$/i.test(output) ? ["-movflags", "+faststart"] : []),
131
+ output,
132
+ ];
133
+ }
134
+ export const TTS_TIMEOUT_MS = 30_000;
135
+ export const TTS_PER_LINE_MS = 10_000;
136
+ export const TTS_STEP_TIMEOUT_MS = 30_000;
137
+ const asArray = (v) => (Array.isArray(v) ? v : v === undefined || v === null ? [] : [v]);
138
+ export function parseVoices(raw) {
139
+ return asArray(raw.voices).map((v) => ({ name: String(v.name ?? ""), language: String(v.language ?? ""), gender: String(v.gender ?? "") }));
140
+ }
141
+ async function runTts(request, timeoutMs, signal) {
142
+ if (process.platform !== "win32") {
143
+ throw new ScreencastError("narrate uses the speech engine built into Windows and runs on Windows only.");
144
+ }
145
+ const req = Buffer.from(JSON.stringify(request), "utf8").toString("base64");
146
+ const stdout = await runPowerShell(PS_TTS.replace("__REQ__", req), "speech voices", { timeoutMs, signal });
147
+ try {
148
+ return JSON.parse(stdout);
149
+ }
150
+ catch (err) {
151
+ throw new ScreencastError(`Could not parse the speech engine's output: ${err.message}`);
152
+ }
153
+ }
154
+ export async function listVoices(signal) {
155
+ const raw = await runTts({ list: true }, psTimeoutMs(15_000), signal);
156
+ if (raw.error)
157
+ throw new ScreencastError(`Windows speech is unavailable: ${raw.error}`);
158
+ return parseVoices(raw);
159
+ }
160
+ export async function ttsStatus() {
161
+ if (process.platform !== "win32")
162
+ return { available: false, voices: [], error: "Windows speech is available on Windows only." };
163
+ try {
164
+ const voices = (await listVoices()).map((v) => `${v.name} (${v.language})`);
165
+ return { available: voices.length > 0, voices, ...(voices.length ? {} : { error: "No speech voices are installed." }) };
166
+ }
167
+ catch (err) {
168
+ return { available: false, voices: [], error: err.message };
169
+ }
170
+ }
171
+ export async function synthesize(items, opts) {
172
+ const rate = opts.rate ?? 1;
173
+ if (!Number.isFinite(rate) || rate < MIN_RATE || rate > MAX_RATE) {
174
+ throw new ScreencastError(`rate must be between ${MIN_RATE} and ${MAX_RATE} (1 is normal speed).`);
175
+ }
176
+ const raw = await runTts({ voice: opts.voice ?? null, rate, items }, psTimeoutMs(TTS_TIMEOUT_MS + items.length * TTS_PER_LINE_MS), opts.signal);
177
+ if (raw.error) {
178
+ const voices = parseVoices(raw);
179
+ if (raw.error === "unknown voice") {
180
+ throw new ScreencastError(`No installed voice matches "${opts.voice}".`, voices.length ? `Installed voices: ${voices.map((v) => `${v.name} (${v.language})`).join(", ")}.` : "No voices are installed.");
181
+ }
182
+ throw new ScreencastError(`Windows speech is unavailable: ${raw.error}`, "Install a voice: Settings > Time & language > Speech > Manage voices.");
183
+ }
184
+ asArray(raw.results).forEach((r, i) => {
185
+ if (r.error)
186
+ throw new ScreencastError(`Could not synthesize line ${i + 1}: ${r.error}`);
187
+ });
188
+ return String(raw.voice ?? "");
189
+ }
190
+ const PS_TTS = `
191
+ $ErrorActionPreference = 'Stop'
192
+ function Out($o) { ConvertTo-Json -InputObject $o -Depth 5 -Compress }
193
+ try {
194
+ Add-Type -AssemblyName System.Runtime.WindowsRuntime
195
+ $null = [Windows.Media.SpeechSynthesis.SpeechSynthesizer, Windows.Media, ContentType = WindowsRuntime]
196
+ $req = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__REQ__')) | ConvertFrom-Json
197
+ $all = @([Windows.Media.SpeechSynthesis.SpeechSynthesizer]::AllVoices)
198
+ $voices = @($all | ForEach-Object { [pscustomobject]@{ name = $_.DisplayName; language = $_.Language; gender = [string]$_.Gender } })
199
+ if ($req.list) { Out ([pscustomobject]@{ voices = $voices }); return }
200
+ if ($all.Count -eq 0) { Out ([pscustomobject]@{ error = 'No speech voices are installed.'; voices = $voices }); return }
201
+ $synth = New-Object Windows.Media.SpeechSynthesis.SpeechSynthesizer
202
+ if ($req.voice) {
203
+ $want = [string]$req.voice
204
+ $v = $all | Where-Object { $_.DisplayName -eq $want -or $_.Id -eq $want } | Select-Object -First 1
205
+ if (-not $v) { $v = $all | Where-Object { $_.DisplayName.IndexOf($want, [StringComparison]::OrdinalIgnoreCase) -ge 0 } | Select-Object -First 1 }
206
+ if (-not $v) { Out ([pscustomobject]@{ error = 'unknown voice'; voices = $voices }); return }
207
+ $synth.Voice = $v
208
+ }
209
+ $synth.Options.SpeakingRate = [double]$req.rate
210
+ $asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation\`1' })[0]
211
+ $results = foreach ($item in @($req.items)) {
212
+ try {
213
+ $task = $asTask.MakeGenericMethod([Windows.Media.SpeechSynthesis.SpeechSynthesisStream]).Invoke($null, @($synth.SynthesizeTextToStreamAsync([string]$item.text)))
214
+ if (-not $task.Wait(${TTS_STEP_TIMEOUT_MS})) { throw "The speech engine did not answer within ${TTS_STEP_TIMEOUT_MS / 1000} s." }
215
+ $stream = $task.Result
216
+ $in = [System.IO.WindowsRuntimeStreamExtensions]::AsStreamForRead($stream)
217
+ $fs = [System.IO.File]::Create([string]$item.path)
218
+ try { $in.CopyTo($fs) } finally { $fs.Dispose(); $in.Dispose(); $stream.Dispose() }
219
+ [pscustomobject]@{ ok = $true }
220
+ } catch { [pscustomobject]@{ error = $_.Exception.Message } }
221
+ }
222
+ Out ([pscustomobject]@{ voice = $synth.Voice.DisplayName; results = @($results) })
223
+ } catch { Out ([pscustomobject]@{ error = $_.Exception.Message }) }
224
+ `;