@tmhs/screencast-mcp 0.46.0 → 0.48.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.
- package/README.md +127 -303
- package/assets/cursor/arrow.png +0 -0
- package/assets/fonts/Inter-Bold.ttf +0 -0
- package/assets/fonts/Inter-Regular.ttf +0 -0
- package/dist/cli.js +515 -0
- package/dist/index.js +10 -2
- package/dist/server.js +23 -0
- package/dist/setup.js +437 -0
- package/dist/tools/addMarker.js +6 -2
- package/dist/tools/bugReport.js +1 -1
- package/dist/tools/chapters.js +1 -1
- package/dist/tools/cursor.js +87 -0
- package/dist/tools/cutByTranscript.js +3 -3
- package/dist/tools/doctor.js +14 -1
- package/dist/tools/indexRecording.js +37 -15
- package/dist/tools/listVideoDevices.js +26 -0
- package/dist/tools/narrate.js +86 -0
- package/dist/tools/overlay.js +2 -0
- package/dist/tools/pauseRecording.js +44 -0
- package/dist/tools/pipeline.js +37 -13
- package/dist/tools/readEvents.js +1 -1
- package/dist/tools/resumeRecording.js +46 -0
- package/dist/tools/reviewRecording.js +1 -1
- package/dist/tools/searchRecording.js +9 -3
- package/dist/tools/startRecording.js +155 -86
- package/dist/tools/stepGuide.js +57 -4
- package/dist/tools/stopRecording.js +38 -3
- package/dist/utils/argPaths.js +39 -0
- package/dist/utils/audioDevices.js +34 -4
- package/dist/utils/captions.js +5 -3
- package/dist/utils/cursor.js +317 -0
- package/dist/utils/events.js +62 -12
- package/dist/utils/gpu.js +219 -0
- package/dist/utils/lifecycle.js +136 -13
- package/dist/utils/media.js +7 -2
- package/dist/utils/monitors.js +39 -5
- package/dist/utils/narrate.js +233 -0
- package/dist/utils/ocr.js +8 -3
- package/dist/utils/paths.js +41 -3
- package/dist/utils/pause.js +190 -0
- package/dist/utils/pipeline.js +29 -2
- package/dist/utils/recipes.js +7 -3
- package/dist/utils/recorder.js +172 -0
- package/dist/utils/recordingIndex.js +55 -9
- package/dist/utils/replay.js +20 -2
- package/dist/utils/retention.js +4 -1
- package/dist/utils/roots.js +1 -1
- package/dist/utils/sessions.js +32 -6
- package/dist/utils/stepGuide.js +26 -0
- package/dist/utils/targets.js +31 -7
- package/dist/utils/toolsets.js +8 -3
- package/dist/utils/transcriptCut.js +20 -5
- package/dist/utils/wgc.js +2 -2
- package/dist/wgcRecorder.js +1 -1
- package/package.json +5 -1
|
@@ -0,0 +1,233 @@
|
|
|
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
|
+
export function ttsCall(request) {
|
|
142
|
+
return { script: PS_TTS, payload: JSON.stringify(request) };
|
|
143
|
+
}
|
|
144
|
+
async function runTts(request, timeoutMs, signal) {
|
|
145
|
+
if (process.platform !== "win32") {
|
|
146
|
+
throw new ScreencastError("narrate uses the speech engine built into Windows and runs on Windows only.");
|
|
147
|
+
}
|
|
148
|
+
const { script, payload } = ttsCall(request);
|
|
149
|
+
const list = "list" in request;
|
|
150
|
+
const stdout = await runPowerShell(script, list ? "speech voices" : "the speech engine", {
|
|
151
|
+
timeoutMs,
|
|
152
|
+
signal,
|
|
153
|
+
payload,
|
|
154
|
+
failure: list ? "Could not list speech voices" : "Could not synthesize speech",
|
|
155
|
+
});
|
|
156
|
+
try {
|
|
157
|
+
return JSON.parse(stdout);
|
|
158
|
+
}
|
|
159
|
+
catch (err) {
|
|
160
|
+
throw new ScreencastError(`Could not parse the speech engine's output: ${err.message}`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
export async function listVoices(signal) {
|
|
164
|
+
const raw = await runTts({ list: true }, psTimeoutMs(15_000), signal);
|
|
165
|
+
if (raw.error)
|
|
166
|
+
throw new ScreencastError(`Windows speech is unavailable: ${raw.error}`);
|
|
167
|
+
return parseVoices(raw);
|
|
168
|
+
}
|
|
169
|
+
export async function ttsStatus() {
|
|
170
|
+
if (process.platform !== "win32")
|
|
171
|
+
return { available: false, voices: [], error: "Windows speech is available on Windows only." };
|
|
172
|
+
try {
|
|
173
|
+
const voices = (await listVoices()).map((v) => `${v.name} (${v.language})`);
|
|
174
|
+
return { available: voices.length > 0, voices, ...(voices.length ? {} : { error: "No speech voices are installed." }) };
|
|
175
|
+
}
|
|
176
|
+
catch (err) {
|
|
177
|
+
return { available: false, voices: [], error: err.message };
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
export async function synthesize(items, opts) {
|
|
181
|
+
const rate = opts.rate ?? 1;
|
|
182
|
+
if (!Number.isFinite(rate) || rate < MIN_RATE || rate > MAX_RATE) {
|
|
183
|
+
throw new ScreencastError(`rate must be between ${MIN_RATE} and ${MAX_RATE} (1 is normal speed).`);
|
|
184
|
+
}
|
|
185
|
+
const raw = await runTts({ voice: opts.voice ?? null, rate, items }, psTimeoutMs(TTS_TIMEOUT_MS + items.length * TTS_PER_LINE_MS), opts.signal);
|
|
186
|
+
if (raw.error) {
|
|
187
|
+
const voices = parseVoices(raw);
|
|
188
|
+
if (raw.error === "unknown voice") {
|
|
189
|
+
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.");
|
|
190
|
+
}
|
|
191
|
+
throw new ScreencastError(`Windows speech is unavailable: ${raw.error}`, "Install a voice: Settings > Time & language > Speech > Manage voices.");
|
|
192
|
+
}
|
|
193
|
+
asArray(raw.results).forEach((r, i) => {
|
|
194
|
+
if (r.error)
|
|
195
|
+
throw new ScreencastError(`Could not synthesize line ${i + 1}: ${r.error}`);
|
|
196
|
+
});
|
|
197
|
+
return String(raw.voice ?? "");
|
|
198
|
+
}
|
|
199
|
+
const PS_TTS = `
|
|
200
|
+
$ErrorActionPreference = 'Stop'
|
|
201
|
+
function Out($o) { ConvertTo-Json -InputObject $o -Depth 5 -Compress }
|
|
202
|
+
try {
|
|
203
|
+
Add-Type -AssemblyName System.Runtime.WindowsRuntime
|
|
204
|
+
$null = [Windows.Media.SpeechSynthesis.SpeechSynthesizer, Windows.Media, ContentType = WindowsRuntime]
|
|
205
|
+
$req = $Payload | ConvertFrom-Json
|
|
206
|
+
$all = @([Windows.Media.SpeechSynthesis.SpeechSynthesizer]::AllVoices)
|
|
207
|
+
$voices = @($all | ForEach-Object { [pscustomobject]@{ name = $_.DisplayName; language = $_.Language; gender = [string]$_.Gender } })
|
|
208
|
+
if ($req.list) { Out ([pscustomobject]@{ voices = $voices }); return }
|
|
209
|
+
if ($all.Count -eq 0) { Out ([pscustomobject]@{ error = 'No speech voices are installed.'; voices = $voices }); return }
|
|
210
|
+
$synth = New-Object Windows.Media.SpeechSynthesis.SpeechSynthesizer
|
|
211
|
+
if ($req.voice) {
|
|
212
|
+
$want = [string]$req.voice
|
|
213
|
+
$v = $all | Where-Object { $_.DisplayName -eq $want -or $_.Id -eq $want } | Select-Object -First 1
|
|
214
|
+
if (-not $v) { $v = $all | Where-Object { $_.DisplayName.IndexOf($want, [StringComparison]::OrdinalIgnoreCase) -ge 0 } | Select-Object -First 1 }
|
|
215
|
+
if (-not $v) { Out ([pscustomobject]@{ error = 'unknown voice'; voices = $voices }); return }
|
|
216
|
+
$synth.Voice = $v
|
|
217
|
+
}
|
|
218
|
+
$synth.Options.SpeakingRate = [double]$req.rate
|
|
219
|
+
$asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation\`1' })[0]
|
|
220
|
+
$results = foreach ($item in @($req.items)) {
|
|
221
|
+
try {
|
|
222
|
+
$task = $asTask.MakeGenericMethod([Windows.Media.SpeechSynthesis.SpeechSynthesisStream]).Invoke($null, @($synth.SynthesizeTextToStreamAsync([string]$item.text)))
|
|
223
|
+
if (-not $task.Wait(${TTS_STEP_TIMEOUT_MS})) { throw "The speech engine did not answer within ${TTS_STEP_TIMEOUT_MS / 1000} s." }
|
|
224
|
+
$stream = $task.Result
|
|
225
|
+
$in = [System.IO.WindowsRuntimeStreamExtensions]::AsStreamForRead($stream)
|
|
226
|
+
$fs = [System.IO.File]::Create([string]$item.path)
|
|
227
|
+
try { $in.CopyTo($fs) } finally { $fs.Dispose(); $in.Dispose(); $stream.Dispose() }
|
|
228
|
+
[pscustomobject]@{ ok = $true }
|
|
229
|
+
} catch { [pscustomobject]@{ error = $_.Exception.Message } }
|
|
230
|
+
}
|
|
231
|
+
Out ([pscustomobject]@{ voice = $synth.Voice.DisplayName; results = @($results) })
|
|
232
|
+
} catch { Out ([pscustomobject]@{ error = $_.Exception.Message }) }
|
|
233
|
+
`;
|
package/dist/utils/ocr.js
CHANGED
|
@@ -3,13 +3,18 @@ import { ScreencastError } from "./errors.js";
|
|
|
3
3
|
import { runPowerShell, psTimeoutMs } from "./monitors.js";
|
|
4
4
|
export const OCR_SCALES = [2, 4];
|
|
5
5
|
export const OCR_MAX_DIMENSION = 10_000;
|
|
6
|
+
export function ocrCall(paths) {
|
|
7
|
+
return { script: PS_OCR, payload: JSON.stringify(paths) };
|
|
8
|
+
}
|
|
6
9
|
export async function recognize(paths, scales) {
|
|
7
10
|
if (process.platform !== "win32") {
|
|
8
11
|
throw new ScreencastError("find_text uses the Windows OCR engine and runs on Windows only.");
|
|
9
12
|
}
|
|
10
|
-
const
|
|
11
|
-
const stdout = await runPowerShell(
|
|
13
|
+
const { script, payload } = ocrCall(paths);
|
|
14
|
+
const stdout = await runPowerShell(script, "text (OCR)", {
|
|
12
15
|
timeoutMs: psTimeoutMs(OCR_TIMEOUT_MS + Math.max(0, paths.length - 2) * OCR_PER_IMAGE_MS),
|
|
16
|
+
payload,
|
|
17
|
+
failure: "Could not run OCR",
|
|
13
18
|
});
|
|
14
19
|
let raw;
|
|
15
20
|
try {
|
|
@@ -197,7 +202,7 @@ $null = [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsR
|
|
|
197
202
|
$null = [Windows.Graphics.Imaging.BitmapDecoder, Windows.Foundation, ContentType = WindowsRuntime]
|
|
198
203
|
$asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation\`1' })[0]
|
|
199
204
|
function Await($op, [Type]$t) { $task = $asTask.MakeGenericMethod($t).Invoke($null, @($op)); if (-not $task.Wait(${OCR_STEP_TIMEOUT_MS})) { throw "The OCR engine did not answer within ${OCR_STEP_TIMEOUT_MS / 1000} s." }; $task.Result }
|
|
200
|
-
$paths =
|
|
205
|
+
$paths = $Payload | ConvertFrom-Json
|
|
201
206
|
$engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages()
|
|
202
207
|
$out = foreach ($p in $paths) {
|
|
203
208
|
try {
|
package/dist/utils/paths.js
CHANGED
|
@@ -81,7 +81,33 @@ export function isWithin(path, dir) {
|
|
|
81
81
|
const rel = relative(realish(dir), realish(path));
|
|
82
82
|
return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
|
|
83
83
|
}
|
|
84
|
+
export function isNetworkPath(path) {
|
|
85
|
+
const p = path.trim();
|
|
86
|
+
if (!/^[\\/]{2}/.test(p))
|
|
87
|
+
return false;
|
|
88
|
+
return !/^[\\/]{2}\?[\\/][A-Za-z]:[\\/]/.test(p);
|
|
89
|
+
}
|
|
90
|
+
export function assertLocalPath(path, label = "Path") {
|
|
91
|
+
if (isNetworkPath(path)) {
|
|
92
|
+
throw new ScreencastError(`${label} ${path} is a network or device path; only local files are allowed. ` +
|
|
93
|
+
"Copy the file to a local folder first.");
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
export function assertInputAllowed(path, label = "Input") {
|
|
97
|
+
assertLocalPath(path, label);
|
|
98
|
+
const full = resolve(path);
|
|
99
|
+
if (clientRoots === "pending" && envAllowedDirs().length === 0 && !isWithin(full, homeRoot())) {
|
|
100
|
+
throw new ScreencastError(`${label} ${full} is outside SCREENCAST_HOME and the client's workspace roots have not loaded yet. ` +
|
|
101
|
+
"Retry the call in a moment.");
|
|
102
|
+
}
|
|
103
|
+
const allowed = allowedOutputDirs();
|
|
104
|
+
if (allowed === null || allowed.some((dir) => isWithin(full, dir)))
|
|
105
|
+
return;
|
|
106
|
+
throw new ScreencastError(`${label} ${full} is outside the allowed directories: ${allowed.join(", ")}. ` +
|
|
107
|
+
`Move it under one of them, or add its folder to ${ALLOWED_DIRS_ENV} or the client's workspace roots.`);
|
|
108
|
+
}
|
|
84
109
|
export function assertOutputAllowed(path) {
|
|
110
|
+
assertLocalPath(path, "Output");
|
|
85
111
|
if (clientRoots === "pending" && envAllowedDirs().length === 0 && !isWithin(path, homeRoot())) {
|
|
86
112
|
throw new ScreencastError(`Output ${path} is outside SCREENCAST_HOME and the client's workspace roots have not loaded yet. ` +
|
|
87
113
|
"Retry the call in a moment, or omit the path to write under SCREENCAST_HOME.");
|
|
@@ -93,13 +119,24 @@ export function assertOutputAllowed(path) {
|
|
|
93
119
|
`Write under one of them (a relative path lands in SCREENCAST_HOME), or add the folder to ` +
|
|
94
120
|
`${ALLOWED_DIRS_ENV} or the client's workspace roots.`);
|
|
95
121
|
}
|
|
122
|
+
export function assertOverwriteAllowed(path) {
|
|
123
|
+
if (allowedOutputDirs() !== null || isWithin(path, homeRoot()))
|
|
124
|
+
return;
|
|
125
|
+
throw new ScreencastError(`Refusing to replace ${path}: it is outside SCREENCAST_HOME and no allowed directories are set. ` +
|
|
126
|
+
`Add its folder to ${ALLOWED_DIRS_ENV} (or the client's workspace roots) to allow overwriting there, ` +
|
|
127
|
+
"or write to a new path.");
|
|
128
|
+
}
|
|
96
129
|
export function resolveOutput(provided, defaultDir, defaultName, overwrite = false) {
|
|
97
130
|
if (provided && provided.trim().length > 0) {
|
|
131
|
+
assertLocalPath(provided, "Output");
|
|
98
132
|
const path = resolve(defaultDir, provided);
|
|
99
133
|
assertOutputAllowed(path);
|
|
100
|
-
if (
|
|
101
|
-
|
|
102
|
-
`
|
|
134
|
+
if (existsSync(path)) {
|
|
135
|
+
if (!overwrite) {
|
|
136
|
+
throw new ScreencastError(`Output already exists: ${path}. Pass overwrite: true to replace it, ` +
|
|
137
|
+
`or choose a different path.`);
|
|
138
|
+
}
|
|
139
|
+
assertOverwriteAllowed(path);
|
|
103
140
|
}
|
|
104
141
|
return path;
|
|
105
142
|
}
|
|
@@ -108,6 +145,7 @@ export function resolveOutput(provided, defaultDir, defaultName, overwrite = fal
|
|
|
108
145
|
export function resolveOutputDir(provided, defaultParent) {
|
|
109
146
|
if (!provided || provided.trim().length === 0)
|
|
110
147
|
return undefined;
|
|
148
|
+
assertLocalPath(provided, "Output directory");
|
|
111
149
|
const dir = resolve(defaultParent, provided);
|
|
112
150
|
assertOutputAllowed(dir);
|
|
113
151
|
return dir;
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, renameSync, rmSync, statSync, 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 segmentDurationSec(path, probed, startMs, endMs) {
|
|
22
|
+
if (probed !== null && probed > 0)
|
|
23
|
+
return probed;
|
|
24
|
+
let size;
|
|
25
|
+
try {
|
|
26
|
+
size = statSync(path).size;
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
if (size <= 0)
|
|
32
|
+
return null;
|
|
33
|
+
return Math.max(0.001, Math.round(endMs - startMs) / 1000);
|
|
34
|
+
}
|
|
35
|
+
export function recordedSec(parts) {
|
|
36
|
+
return parts.reduce((s, p) => s + p.durationSec, 0);
|
|
37
|
+
}
|
|
38
|
+
export function clockSpans(state) {
|
|
39
|
+
const spans = [];
|
|
40
|
+
let offset = 0;
|
|
41
|
+
for (const p of state.parts) {
|
|
42
|
+
spans.push({ startMs: p.startMs, offsetSec: offset, durationSec: p.durationSec });
|
|
43
|
+
offset += p.durationSec;
|
|
44
|
+
}
|
|
45
|
+
if (state.current)
|
|
46
|
+
spans.push({ startMs: state.current.startMs, offsetSec: offset });
|
|
47
|
+
return spans;
|
|
48
|
+
}
|
|
49
|
+
export function eventClock(state, fallbackStartMs, nowMs) {
|
|
50
|
+
if (!state || (state.parts.length === 0 && !state.current)) {
|
|
51
|
+
return { startMs: fallbackStartMs, endSec: (nowMs - fallbackStartMs) / 1000 };
|
|
52
|
+
}
|
|
53
|
+
const spans = clockSpans(state);
|
|
54
|
+
const live = state.current ? Math.max(0, (nowMs - state.current.startMs) / 1000) : 0;
|
|
55
|
+
return { startMs: spans[0].startMs, endSec: recordedSec(state.parts) + live, spans };
|
|
56
|
+
}
|
|
57
|
+
export function remainingCapSec(maxDurationSec, recorded) {
|
|
58
|
+
if (!maxDurationSec)
|
|
59
|
+
return 0;
|
|
60
|
+
const left = Math.floor(maxDurationSec - recorded);
|
|
61
|
+
if (left < 1) {
|
|
62
|
+
throw new ScreencastError(`The recording already used its maxDurationSec cap (${maxDurationSec}s); nothing is left to resume.`, "Call stop_recording to finalize it.");
|
|
63
|
+
}
|
|
64
|
+
return left;
|
|
65
|
+
}
|
|
66
|
+
export function pauseBlocker(record, ownsChild) {
|
|
67
|
+
if (record.status === "paused")
|
|
68
|
+
return "it is already paused";
|
|
69
|
+
if (record.status !== "recording")
|
|
70
|
+
return `it is ${record.status}`;
|
|
71
|
+
if (record.backend === "wgc")
|
|
72
|
+
return 'backend "wgc" cannot pause yet';
|
|
73
|
+
if (record.replay)
|
|
74
|
+
return "a replay buffer cannot pause";
|
|
75
|
+
if (!record.capture || !record.segments?.current)
|
|
76
|
+
return "it was started before pause was supported";
|
|
77
|
+
if (!ownsChild)
|
|
78
|
+
return "another server instance owns it";
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
export function resumeBlocker(record, owns) {
|
|
82
|
+
if (record.status === "recording")
|
|
83
|
+
return "it is already recording";
|
|
84
|
+
if (record.status !== "paused")
|
|
85
|
+
return `it is ${record.status}`;
|
|
86
|
+
if (!record.capture || !record.segments)
|
|
87
|
+
return "its capture settings are missing";
|
|
88
|
+
if (!owns)
|
|
89
|
+
return "it was paused by another server instance";
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
const pausing = new Set();
|
|
93
|
+
export function markPausing(id) {
|
|
94
|
+
pausing.add(id);
|
|
95
|
+
}
|
|
96
|
+
export function isPausing(id) {
|
|
97
|
+
return pausing.has(id);
|
|
98
|
+
}
|
|
99
|
+
export function clearPausing(id) {
|
|
100
|
+
pausing.delete(id);
|
|
101
|
+
}
|
|
102
|
+
const ends = new Map();
|
|
103
|
+
function endEntry(id) {
|
|
104
|
+
let e = ends.get(id);
|
|
105
|
+
if (!e) {
|
|
106
|
+
let resolve;
|
|
107
|
+
const promise = new Promise((r) => (resolve = r));
|
|
108
|
+
e = { promise, resolve };
|
|
109
|
+
ends.set(id, e);
|
|
110
|
+
}
|
|
111
|
+
return e;
|
|
112
|
+
}
|
|
113
|
+
export function sessionEnded(id) {
|
|
114
|
+
return endEntry(id).promise;
|
|
115
|
+
}
|
|
116
|
+
export function endSession(id) {
|
|
117
|
+
endEntry(id).resolve();
|
|
118
|
+
setTimeout(() => ends.delete(id), 60_000).unref?.();
|
|
119
|
+
}
|
|
120
|
+
const r3 = (n) => Math.round(n * 1000) / 1000;
|
|
121
|
+
export function buildWebcamAlignArgs(parts, output, codec) {
|
|
122
|
+
if (parts.length === 0)
|
|
123
|
+
throw new ScreencastError("No webcam parts to join.");
|
|
124
|
+
const chains = parts.map((p, i) => {
|
|
125
|
+
const d = r3(Math.max(0.001, p.durationSec));
|
|
126
|
+
const lead = r3(p.leadSec);
|
|
127
|
+
const head = lead > 0 ? `tpad=start_duration=${lead}:start_mode=clone,` : lead < 0 ? `trim=start=${-lead},setpts=PTS-STARTPTS,` : "";
|
|
128
|
+
return `[${i}:v]${head}tpad=stop_duration=${d}:stop_mode=clone,trim=duration=${d},setpts=PTS-STARTPTS,format=yuv420p,setsar=1[w${i}]`;
|
|
129
|
+
});
|
|
130
|
+
const join = `${parts.map((_, i) => `[w${i}]`).join("")}concat=n=${parts.length}:v=1:a=0[v]`;
|
|
131
|
+
return [
|
|
132
|
+
"-y", "-v", "error",
|
|
133
|
+
...parts.flatMap((p) => ["-i", p.path]),
|
|
134
|
+
"-filter_complex", `${chains.join(";")};${join}`,
|
|
135
|
+
"-map", "[v]",
|
|
136
|
+
...codec,
|
|
137
|
+
"-movflags", "+faststart",
|
|
138
|
+
output,
|
|
139
|
+
];
|
|
140
|
+
}
|
|
141
|
+
export async function finishSegments(output, parts, opts) {
|
|
142
|
+
const dir = partsDir(output);
|
|
143
|
+
const result = { joined: false };
|
|
144
|
+
const video = parts.filter((p) => existsSync(p.path) && p.durationSec > 0);
|
|
145
|
+
const total = recordedSec(video);
|
|
146
|
+
let keepDir = false;
|
|
147
|
+
if (video.length > 1 || (video.length === 1 && video[0].path !== output)) {
|
|
148
|
+
mkdirSync(dir, { recursive: true });
|
|
149
|
+
const list = join(dir, "segments.txt");
|
|
150
|
+
const tmp = join(dir, `joined${extname(output) || ".mp4"}`);
|
|
151
|
+
writeFileSync(list, concatList(video.map((p) => p.path)));
|
|
152
|
+
const res = await runCapture(opts.ffmpeg, buildReplayJoinArgs(list, tmp), jobTimeoutMs(total));
|
|
153
|
+
if (res.code === 0 && existsSync(tmp)) {
|
|
154
|
+
renameSync(tmp, output);
|
|
155
|
+
result.joined = true;
|
|
156
|
+
}
|
|
157
|
+
else {
|
|
158
|
+
keepDir = true;
|
|
159
|
+
result.error = `Joining the ${video.length} segments failed; they are kept in ${dir}: ${res.stderr.trim().split("\n").slice(-3).join(" ")}`;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const cams = video.filter((p) => p.webcamPath && existsSync(p.webcamPath));
|
|
163
|
+
if (opts.webcamOutput && cams.length > 0) {
|
|
164
|
+
const args = buildWebcamAlignArgs(cams.map((p) => ({
|
|
165
|
+
path: p.webcamPath,
|
|
166
|
+
leadSec: p.webcamStartMs !== undefined ? (p.webcamStartMs - p.startMs) / 1000 : 0,
|
|
167
|
+
durationSec: p.durationSec,
|
|
168
|
+
})), opts.webcamOutput, opts.webcamCodec);
|
|
169
|
+
const res = await runCapture(opts.ffmpeg, args, jobTimeoutMs(total));
|
|
170
|
+
if (res.code === 0 && existsSync(opts.webcamOutput)) {
|
|
171
|
+
result.webcamPath = opts.webcamOutput;
|
|
172
|
+
}
|
|
173
|
+
else {
|
|
174
|
+
keepDir = true;
|
|
175
|
+
result.webcamError = `Aligning the webcam failed; its raw parts are kept in ${dir}: ${res.stderr.trim().split("\n").slice(-3).join(" ")}`;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
if (!keepDir)
|
|
179
|
+
rmSync(dir, { recursive: true, force: true });
|
|
180
|
+
return result;
|
|
181
|
+
}
|
|
182
|
+
export function webcamPlacement(screen, cam, corner, size) {
|
|
183
|
+
const even = (n) => Math.max(2, Math.round(n / 2) * 2);
|
|
184
|
+
const width = even(screen.width * size);
|
|
185
|
+
const height = even((width * cam.height) / Math.max(1, cam.width));
|
|
186
|
+
const m = Math.round(screen.width * 0.02);
|
|
187
|
+
const x = corner.endsWith("left") ? m : Math.max(0, screen.width - width - m);
|
|
188
|
+
const y = corner.startsWith("top") ? m : Math.max(0, screen.height - height - m);
|
|
189
|
+
return { x, y, width, height };
|
|
190
|
+
}
|
package/dist/utils/pipeline.js
CHANGED
|
@@ -9,7 +9,8 @@ import { groupBadges, keystrokeSteps, retimeBadges } from "./keystrokes.js";
|
|
|
9
9
|
import { cutFilters, cutsFor, DEFAULT_KEEP_SEC, DEFAULT_MIN_IDLE_SEC } from "./idle.js";
|
|
10
10
|
import { denoiseFilter, loudnessTarget, loudnormFilter } from "./audio.js";
|
|
11
11
|
import { subtitlesFilter } from "./captions.js";
|
|
12
|
-
import { mapSpans, mapTime } from "./timeline.js";
|
|
12
|
+
import { mapSpans, mapTime, retimeCues } 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) {
|
|
@@ -20,6 +21,10 @@ export function probeArgs(args, p) {
|
|
|
20
21
|
out.splice(out.indexOf("-i"), 0, ...p.seek);
|
|
21
22
|
return out;
|
|
22
23
|
}
|
|
24
|
+
export function sidecarCues(cues, timeOps, opsBefore) {
|
|
25
|
+
const later = timeOps.slice(opsBefore);
|
|
26
|
+
return later.length > 0 ? retimeCues(cues, later) : [...cues];
|
|
27
|
+
}
|
|
23
28
|
export function planPipeline(input, output, steps, src, assets = {}, quality = "standard", opts = {}) {
|
|
24
29
|
if (steps.length === 0)
|
|
25
30
|
throw new ScreencastError("Give at least one step.");
|
|
@@ -55,6 +60,7 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
|
|
|
55
60
|
const summary = [];
|
|
56
61
|
const timeOps = [];
|
|
57
62
|
const pending = [];
|
|
63
|
+
const files = [];
|
|
58
64
|
let geo = { sx: 1, sy: 1, ox: 0, oy: 0 };
|
|
59
65
|
const trimRange = (s, at) => {
|
|
60
66
|
if (!Number.isFinite(s.start) || s.start < 0)
|
|
@@ -283,6 +289,27 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
|
|
|
283
289
|
summary.push(`keystroke_overlay ${badges.length} badge(s)`);
|
|
284
290
|
break;
|
|
285
291
|
}
|
|
292
|
+
case "cursor": {
|
|
293
|
+
if (!geo) {
|
|
294
|
+
throw new ScreencastError(`step ${at}: cursor must come before zoom, reframe or backdrop; the logged positions no longer match the frame after them.`);
|
|
295
|
+
}
|
|
296
|
+
const c = opts.cursor?.[i];
|
|
297
|
+
if (!c)
|
|
298
|
+
throw new ScreencastError(`Internal: missing cursor plan for step ${at}.`);
|
|
299
|
+
const moved = transformCursor(c.plan, timeOps, geo);
|
|
300
|
+
if (moved.path.length === 0 || moved.visible.length === 0) {
|
|
301
|
+
summary.push("cursor: no cursor movement in this part of the video");
|
|
302
|
+
break;
|
|
303
|
+
}
|
|
304
|
+
const { steps: st, out: o, extraInputs: ex, commands } = cursorSteps(moved, s, { width: W, height: H }, cur, nextInput, tag, c.sprite, c.commandsFile);
|
|
305
|
+
graph.push(...st);
|
|
306
|
+
extraInputs.push(...ex);
|
|
307
|
+
nextInput += ex.length / 2;
|
|
308
|
+
cur = o;
|
|
309
|
+
files.push({ path: c.commandsFile, content: commands });
|
|
310
|
+
summary.push(`cursor ${moved.path.length} segment(s), ${moved.clicks.length} click(s)${s.spotlight ? ", spotlight" : ""}`);
|
|
311
|
+
break;
|
|
312
|
+
}
|
|
286
313
|
case "export_preset": {
|
|
287
314
|
const p = exportPresetParts(s.platform, s.fit ?? "pad", tag);
|
|
288
315
|
geo = null;
|
|
@@ -330,5 +357,5 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
|
|
|
330
357
|
if (chaptersInput !== -1)
|
|
331
358
|
args.push("-map_chapters", String(chaptersInput));
|
|
332
359
|
args.push(output);
|
|
333
|
-
return { args, width: W, height: H, fps, durationSec: dur === null ? null : r3(dur), gif, summary, timeOps, pending };
|
|
360
|
+
return { args, width: W, height: H, fps, durationSec: dur === null ? null : r3(dur), gif, summary, timeOps, pending, files };
|
|
334
361
|
}
|
package/dist/utils/recipes.js
CHANGED
|
@@ -41,13 +41,15 @@ export function recipeSteps(recipe, ctx) {
|
|
|
41
41
|
}
|
|
42
42
|
return { steps, notes };
|
|
43
43
|
}
|
|
44
|
+
const SOURCE_OPS = new Set(["redact", "crop", "cursor"]);
|
|
44
45
|
export function applyOverrides(base, overrides) {
|
|
45
46
|
const out = [...base];
|
|
46
47
|
const tail = out.at(-1) && EXPORTS.has(out.at(-1).op) ? out.pop() : null;
|
|
47
48
|
let exportStep = tail;
|
|
48
49
|
const recipeLen = out.length;
|
|
49
50
|
const replaced = new Set();
|
|
50
|
-
const
|
|
51
|
+
const trims = [];
|
|
52
|
+
const front = [];
|
|
51
53
|
for (const o of overrides) {
|
|
52
54
|
if (EXPORTS.has(o.op)) {
|
|
53
55
|
exportStep = o;
|
|
@@ -55,7 +57,9 @@ export function applyOverrides(base, overrides) {
|
|
|
55
57
|
}
|
|
56
58
|
const i = out.findIndex((s, j) => j < recipeLen && !replaced.has(j) && s.op === o.op);
|
|
57
59
|
if (i === -1 && o.op === "trim")
|
|
58
|
-
|
|
60
|
+
trims.push(o);
|
|
61
|
+
else if (i === -1 && SOURCE_OPS.has(o.op))
|
|
62
|
+
front.push(o);
|
|
59
63
|
else if (i === -1)
|
|
60
64
|
out.push(o);
|
|
61
65
|
else {
|
|
@@ -63,5 +67,5 @@ export function applyOverrides(base, overrides) {
|
|
|
63
67
|
replaced.add(i);
|
|
64
68
|
}
|
|
65
69
|
}
|
|
66
|
-
return [...
|
|
70
|
+
return [...trims, ...front, ...out, ...(exportStep ? [exportStep] : [])];
|
|
67
71
|
}
|