@tmhs/screencast-mcp 0.46.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.
@@ -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
+ `;
@@ -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
+ }
@@ -10,6 +10,7 @@ import { cutFilters, cutsFor, DEFAULT_KEEP_SEC, DEFAULT_MIN_IDLE_SEC } from "./i
10
10
  import { denoiseFilter, loudnessTarget, loudnormFilter } from "./audio.js";
11
11
  import { subtitlesFilter } from "./captions.js";
12
12
  import { mapSpans, mapTime } from "./timeline.js";
13
+ import { cursorSteps, transformCursor } from "./cursor.js";
13
14
  export const MAX_PIPELINE_STEPS = 30;
14
15
  const r3 = (v) => Math.round(v * 1000) / 1000;
15
16
  export function probeArgs(args, p) {
@@ -55,6 +56,7 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
55
56
  const summary = [];
56
57
  const timeOps = [];
57
58
  const pending = [];
59
+ const files = [];
58
60
  let geo = { sx: 1, sy: 1, ox: 0, oy: 0 };
59
61
  const trimRange = (s, at) => {
60
62
  if (!Number.isFinite(s.start) || s.start < 0)
@@ -283,6 +285,27 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
283
285
  summary.push(`keystroke_overlay ${badges.length} badge(s)`);
284
286
  break;
285
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
+ }
286
309
  case "export_preset": {
287
310
  const p = exportPresetParts(s.platform, s.fit ?? "pad", tag);
288
311
  geo = null;
@@ -330,5 +353,5 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
330
353
  if (chaptersInput !== -1)
331
354
  args.push("-map_chapters", String(chaptersInput));
332
355
  args.push(output);
333
- return { args, width: W, height: H, fps, durationSec: dur === null ? null : r3(dur), gif, summary, timeOps, pending };
356
+ return { args, width: W, height: H, fps, durationSec: dur === null ? null : r3(dur), gif, summary, timeOps, pending, files };
334
357
  }