@phil65/demoreel 0.5.1 → 0.6.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/dist/voice.js ADDED
@@ -0,0 +1,316 @@
1
+ /**
2
+ * Voiceover synthesis (backed by `@phil65/anyvoice`), WebVTT subtitle generation,
3
+ * ffmpeg AAC audio muxing, and automated audio/sync linting for agent review.
4
+ */
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { VoiceClient } from "@phil65/anyvoice";
8
+ import { DemoreelError, ffmpegBin, run } from "./env.js";
9
+ import { sourceToOutputMs } from "./idle.js";
10
+ export const DEFAULT_VOICE_GAP_MS = 250;
11
+ export const DEFAULT_VOICE_PAD_MS = 220;
12
+ /** Creates a cached `@phil65/anyvoice` synthesizer from a `VoiceConfig`. */
13
+ export function createVoiceSynthesizer(config = {}, defaultCacheDir = path.resolve(".demoreel/voice-cache")) {
14
+ const provider = config.provider ?? "edge";
15
+ let client;
16
+ try {
17
+ if (provider === "edge") {
18
+ client = VoiceClient.edge(config.voice);
19
+ }
20
+ else if (provider === "openai") {
21
+ client = VoiceClient.openai({
22
+ apiKey: config.apiKey,
23
+ baseUrl: config.baseUrl,
24
+ model: config.model,
25
+ voice: config.voice,
26
+ });
27
+ }
28
+ else if (provider === "elevenlabs") {
29
+ client = VoiceClient.elevenlabs({
30
+ apiKey: config.apiKey,
31
+ baseUrl: config.baseUrl,
32
+ model: config.model,
33
+ voice: config.voice,
34
+ });
35
+ }
36
+ else {
37
+ throw new DemoreelError(`unknown voice provider: ${String(provider)}`, "use edge, openai, or elevenlabs");
38
+ }
39
+ }
40
+ catch (e) {
41
+ if (e instanceof DemoreelError)
42
+ throw e;
43
+ throw new DemoreelError(`failed to initialise voice provider "${provider}": ${e.message}`, provider === "openai"
44
+ ? "set OPENAI_API_KEY or switch to provider: 'edge' (free)"
45
+ : provider === "elevenlabs"
46
+ ? "set ELEVENLABS_API_KEY or switch to provider: 'edge' (free)"
47
+ : undefined);
48
+ }
49
+ const cacheDir = path.resolve(config.cacheDir ?? defaultCacheDir);
50
+ const cached = client.withCache(cacheDir);
51
+ return {
52
+ async synthesize(text, opts = {}) {
53
+ const res = await cached.synthesize(text, {
54
+ voice: opts.voice ?? config.voice,
55
+ speed: opts.speed ?? config.speed,
56
+ pitch: opts.pitch ?? config.pitch,
57
+ volume: opts.volume ?? config.volume,
58
+ instructions: opts.instructions ?? config.instructions,
59
+ });
60
+ return {
61
+ wav: Buffer.from(res.wav),
62
+ durationMs: Math.round(res.durationMs),
63
+ sampleRate: res.sampleRate,
64
+ channels: res.channels,
65
+ timings: res.timings.map((t) => ({
66
+ text: t.text,
67
+ offsetMs: Math.round(t.offsetMs),
68
+ durationMs: Math.round(t.durationMs),
69
+ estimated: Boolean(t.estimated),
70
+ })),
71
+ };
72
+ },
73
+ };
74
+ }
75
+ /** Matches a word in `timings` (case-insensitive, stripping outer punctuation) starting at `fromIndex`. */
76
+ export function findWordTiming(timings, query, fromIndex = 0) {
77
+ const norm = (s) => s.toLowerCase().replace(/^[^a-z0-9]+|[^a-z0-9]+$/gi, "");
78
+ const needle = typeof query === "string" ? norm(query) : null;
79
+ const searchFrom = (start) => {
80
+ for (let i = start; i < timings.length; i++) {
81
+ const t = timings[i];
82
+ const matched = typeof query === "string"
83
+ ? norm(t.text) === needle || t.text.toLowerCase().includes(needle)
84
+ : query.test(t.text);
85
+ if (matched)
86
+ return { timing: t, index: i };
87
+ }
88
+ return null;
89
+ };
90
+ return searchFrom(fromIndex) ?? (fromIndex > 0 ? searchFrom(0) : null);
91
+ }
92
+ function formatVttTimestamp(ms) {
93
+ const clamped = Math.max(0, Math.round(ms));
94
+ const h = Math.floor(clamped / 3_600_000);
95
+ const m = Math.floor((clamped % 3_600_000) / 60_000);
96
+ const s = Math.floor((clamped % 60_000) / 1000);
97
+ const frac = clamped % 1000;
98
+ const pad2 = (n) => String(n).padStart(2, "0");
99
+ const pad3 = (n) => String(n).padStart(3, "0");
100
+ return `${pad2(h)}:${pad2(m)}:${pad2(s)}.${pad3(frac)}`;
101
+ }
102
+ /** Builds a WebVTT subtitle file from voice cues, mapped onto rendered output timestamps. */
103
+ export function buildVoiceVtt(cues, trims = [], speeds = [], wordsPerCue = 8) {
104
+ const lines = ["WEBVTT", ""];
105
+ const chunkSize = Math.max(1, wordsPerCue);
106
+ for (const cue of cues) {
107
+ const outStart = Math.max(0, Math.round(sourceToOutputMs(cue.startMs, trims, speeds)));
108
+ if (cue.timings.length === 0) {
109
+ lines.push(`${formatVttTimestamp(outStart)} --> ${formatVttTimestamp(outStart + cue.durationMs)}`);
110
+ lines.push(cue.text.trim());
111
+ lines.push("");
112
+ continue;
113
+ }
114
+ for (let i = 0; i < cue.timings.length; i += chunkSize) {
115
+ const group = cue.timings.slice(i, i + chunkSize);
116
+ const first = group[0];
117
+ const last = group[group.length - 1];
118
+ const start = outStart + first.offsetMs;
119
+ const end = Math.max(start + 150, outStart + last.offsetMs + last.durationMs);
120
+ lines.push(`${formatVttTimestamp(start)} --> ${formatVttTimestamp(end)}`);
121
+ lines.push(group.map((w) => w.text).join(" "));
122
+ lines.push("");
123
+ }
124
+ }
125
+ return lines.join("\n");
126
+ }
127
+ /**
128
+ * Mixes all voice cue `.wav` files into an AAC audio track at their post-trim output timestamps
129
+ * and stream-copies the video (`-c:v copy`) so OpenScreen's H.264 output is never re-encoded.
130
+ */
131
+ export async function muxVoiceTrack(videoPath, cues, baseDir, opts = {}) {
132
+ if (cues.length === 0)
133
+ return { audioMuxed: false };
134
+ const trims = opts.trims ?? [];
135
+ const speeds = opts.speeds ?? [];
136
+ const resolved = cues
137
+ .map((cue) => ({
138
+ cue,
139
+ wavPath: path.isAbsolute(cue.audioFile) ? cue.audioFile : path.resolve(baseDir, cue.audioFile),
140
+ delayMs: Math.max(0, Math.round(sourceToOutputMs(cue.startMs, trims, speeds))),
141
+ }))
142
+ .filter((entry) => fs.existsSync(entry.wavPath));
143
+ if (resolved.length === 0)
144
+ return { audioMuxed: false };
145
+ const args = ["-y", "-loglevel", "error", "-i", videoPath];
146
+ for (const entry of resolved)
147
+ args.push("-i", entry.wavPath);
148
+ const filterParts = [];
149
+ const labels = [];
150
+ for (let i = 0; i < resolved.length; i++) {
151
+ const idx = i + 1;
152
+ const delay = resolved[i].delayMs;
153
+ const label = `a${idx}`;
154
+ filterParts.push(`[${idx}:a]aresample=48000,aformat=channel_layouts=stereo,adelay=${delay}|${delay}[${label}]`);
155
+ labels.push(`[${label}]`);
156
+ }
157
+ if (resolved.length === 1) {
158
+ filterParts.push(`${labels[0]}anull[aout]`);
159
+ }
160
+ else {
161
+ // normalize=0 preserves each voice clip's full loudness instead of dividing by N.
162
+ filterParts.push(`${labels.join("")}amix=inputs=${resolved.length}:duration=longest:dropout_transition=0:normalize=0[aout]`);
163
+ }
164
+ const tmpOut = videoPath.replace(/\.mp4$/i, ".voiced.tmp.mp4");
165
+ args.push("-filter_complex", filterParts.join(";"), "-map", "0:v:0", "-map", "[aout]", "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", tmpOut);
166
+ await run(ffmpegBin(), args);
167
+ fs.renameSync(tmpOut, videoPath);
168
+ let vttPath;
169
+ if (opts.writeVtt !== false) {
170
+ vttPath = videoPath.replace(/\.mp4$/i, ".vtt");
171
+ fs.writeFileSync(vttPath, buildVoiceVtt(cues, trims, speeds));
172
+ }
173
+ return { audioMuxed: true, vttPath };
174
+ }
175
+ /**
176
+ * Automated audio/sync checks so an agent (which cannot listen to the MP4) gets deterministic
177
+ * feedback on overlaps, clipping, trim collisions, and speech↔action pacing mismatches.
178
+ */
179
+ export function lintVoiceCues(cues, outputDurationMs, trims = [], speeds = []) {
180
+ if (cues.length === 0)
181
+ return [];
182
+ const findings = [];
183
+ const mapped = cues
184
+ .map((cue) => {
185
+ const outStart = Math.round(sourceToOutputMs(cue.startMs, trims, speeds));
186
+ return { cue, outStart, outEnd: outStart + cue.durationMs };
187
+ })
188
+ .sort((a, b) => a.outStart - b.outStart);
189
+ for (let i = 0; i < mapped.length; i++) {
190
+ const { cue, outStart, outEnd } = mapped[i];
191
+ if (i > 0) {
192
+ const prev = mapped[i - 1];
193
+ if (outStart < prev.outEnd - 20) {
194
+ findings.push({
195
+ severity: "error",
196
+ code: "voice-overlap",
197
+ cueId: cue.id,
198
+ message: `${cue.id} overlaps ${prev.cue.id} by ${prev.outEnd - outStart}ms`,
199
+ });
200
+ }
201
+ }
202
+ if (outEnd > outputDurationMs + 150) {
203
+ findings.push({
204
+ severity: "error",
205
+ code: "voice-clipped-end",
206
+ cueId: cue.id,
207
+ message: `${cue.id} ends at ${(outEnd / 1000).toFixed(2)}s, past video end ${(outputDurationMs / 1000).toFixed(2)}s`,
208
+ });
209
+ }
210
+ for (const t of trims) {
211
+ if (t.startMs < cue.endMs && t.endMs > cue.startMs) {
212
+ findings.push({
213
+ severity: "error",
214
+ code: "voice-trim-collision",
215
+ cueId: cue.id,
216
+ message: `${cue.id} intersects trim region ${t.id} (${t.startMs}-${t.endMs}ms)`,
217
+ });
218
+ }
219
+ }
220
+ for (const s of speeds) {
221
+ if (s.startMs < cue.endMs && s.endMs > cue.startMs) {
222
+ findings.push({
223
+ severity: "error",
224
+ code: "voice-speed-collision",
225
+ cueId: cue.id,
226
+ message: `${cue.id} intersects speed region ${s.id} (${s.startMs}-${s.endMs}ms)`,
227
+ });
228
+ }
229
+ }
230
+ const words = cue.text.trim().split(/\s+/).filter(Boolean).length;
231
+ if (words > 28) {
232
+ findings.push({
233
+ severity: "warning",
234
+ code: "voice-long-cue",
235
+ cueId: cue.id,
236
+ message: `${cue.id} has ${words} words (${(cue.durationMs / 1000).toFixed(1)}s) — consider splitting into two shorter beats`,
237
+ });
238
+ }
239
+ if (cue.actionDurationMs !== undefined) {
240
+ const excessSpeech = cue.durationMs - cue.actionDurationMs;
241
+ const excessAction = cue.actionDurationMs - cue.durationMs;
242
+ if (excessSpeech > 3000) {
243
+ findings.push({
244
+ severity: "warning",
245
+ code: "voice-longer-than-action",
246
+ cueId: cue.id,
247
+ message: `${cue.id} held static for ${(excessSpeech / 1000).toFixed(1)}s after its UI actions finished — trim the wording or add a highlight`,
248
+ });
249
+ }
250
+ else if (excessAction > 3500) {
251
+ findings.push({
252
+ severity: "warning",
253
+ code: "action-longer-than-voice",
254
+ cueId: cue.id,
255
+ message: `${cue.id} actions ran ${(excessAction / 1000).toFixed(1)}s after narration ended — consider a follow-up beat`,
256
+ });
257
+ }
258
+ }
259
+ }
260
+ const totalSpokenMs = cues.reduce((sum, c) => sum + c.durationMs, 0);
261
+ if (cues.length >= 3 && outputDurationMs > 0 && totalSpokenMs / outputDurationMs > 0.9) {
262
+ findings.push({
263
+ severity: "warning",
264
+ code: "voice-dense",
265
+ message: `Narration fills ${Math.round((totalSpokenMs / outputDurationMs) * 100)}% of the video — add a short breath between sections`,
266
+ });
267
+ }
268
+ return findings;
269
+ }
270
+ /** Dry-run voice summary (reports exact synthesized durations & word counts without false wall-clock overlap checks). */
271
+ export function formatDryRunVoiceSummary(cues) {
272
+ if (cues.length === 0)
273
+ return "";
274
+ const totalSpokenMs = cues.reduce((s, c) => s + c.durationMs, 0);
275
+ const lines = [
276
+ `Voiceover (dry-run, cache warmed): ${cues.length} cues, ${(totalSpokenMs / 1000).toFixed(1)}s spoken`,
277
+ ];
278
+ let longCues = 0;
279
+ for (const cue of cues) {
280
+ const words = cue.text.trim().split(/\s+/).filter(Boolean).length;
281
+ if (words > 28)
282
+ longCues++;
283
+ lines.push(` ${cue.id} (${(cue.durationMs / 1000).toFixed(1)}s, ${words} words): "${cue.text}"`);
284
+ }
285
+ if (longCues > 0) {
286
+ lines.push(` [warning] ${longCues} cue(s) exceed 28 words — consider splitting into shorter beats`);
287
+ }
288
+ return lines.join("\n");
289
+ }
290
+ /** Human- and agent-readable summary of voice cues and sync lint findings. */
291
+ export function formatVoiceSummary(cues, outputDurationMs, trims = [], speeds = []) {
292
+ if (cues.length === 0)
293
+ return "";
294
+ const findings = lintVoiceCues(cues, outputDurationMs, trims, speeds);
295
+ const totalSpokenMs = cues.reduce((s, c) => s + c.durationMs, 0);
296
+ const pct = outputDurationMs > 0 ? Math.round((totalSpokenMs / outputDurationMs) * 100) : 0;
297
+ const lines = [
298
+ `Voiceover: ${cues.length} cues, ${(totalSpokenMs / 1000).toFixed(1)}s spoken / ${(outputDurationMs / 1000).toFixed(1)}s video (${pct}%)`,
299
+ ];
300
+ for (const cue of cues) {
301
+ const outStart = Math.max(0, Math.round(sourceToOutputMs(cue.startMs, trims, speeds)));
302
+ const act = cue.actionDurationMs !== undefined ? ` [actions ${(cue.actionDurationMs / 1000).toFixed(1)}s]` : "";
303
+ lines.push(` ${cue.id} ${(outStart / 1000).toFixed(1)}s–${((outStart + cue.durationMs) / 1000).toFixed(1)}s (${(cue.durationMs / 1000).toFixed(1)}s)${act}: "${cue.text}"`);
304
+ }
305
+ if (findings.length === 0) {
306
+ lines.push(" voice lint: 0 errors, 0 warnings");
307
+ }
308
+ else {
309
+ const errs = findings.filter((f) => f.severity === "error").length;
310
+ const warns = findings.length - errs;
311
+ lines.push(` voice lint: ${errs} error(s), ${warns} warning(s)`);
312
+ for (const f of findings)
313
+ lines.push(` [${f.severity}] ${f.code}: ${f.message}`);
314
+ }
315
+ return lines.join("\n");
316
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@phil65/demoreel",
3
3
  "mcpName": "io.github.phil65/demoreel",
4
- "version": "0.5.1",
4
+ "version": "0.6.0",
5
5
  "private": false,
6
6
  "description": "Scripted product demo videos (videos as code): Playwright scenarios with auto cursor + auto zoom, rendered headless by OpenScreen's exporter.",
7
7
  "keywords": [
@@ -79,6 +79,7 @@
79
79
  },
80
80
  "dependencies": {
81
81
  "@modelcontextprotocol/server": "^2.4.0",
82
+ "@phil65/anyvoice": "^0.2.0",
82
83
  "zod": "^4.6.7"
83
84
  }
84
85
  }
@@ -76,6 +76,11 @@ export default defineScenario({
76
76
  - **Dark UIs**: set `colorScheme: "dark"` and pair with a deep slate/indigo `look.wallpaper`
77
77
  gradient (e.g. `linear-gradient(135deg, #0b1022 0%, #1d2d5c 52%, #3a2368 100%)`) rather than
78
78
  bright default gradients.
79
+ - **Voiceover narration (`scene.say`)**: backed by `@phil65/anyvoice` (defaults to free `edge` TTS with SHA-256 disk caching; also supports `openai` with `instructions` and `elevenlabs`).
80
+ - Set `voice: { provider: "edge", voice: "en-US-AndrewMultilingualNeural", speed: 1.05 }` on the scenario.
81
+ - Chain short beats (`await scene.say("Welcome.")`) or narrate *while* acting (`await scene.say("Pick Bracket and orbit.", async (cue) => { await scene.click(...); await cue.at("orbit", -150); await scene.drag(...); })`) — `demoreel` automatically holds if actions finish faster than speech, prevents overlapping cues, protects voice cues from `trimIdle`, muxes AAC audio into the rendered MP4, and writes `<name>.vtt` subtitles (opt-in `captions: "burned"` to also draw on-video).
82
+ - Always run `--dry-run` first so the SHA-256 voice cache is warmed (<1ms hits during real recording), and check the printed **voice lint** findings (`voice-overlap`, `voice-clipped-end`, `voice-longer-than-action`, `voice-long-cue`) alongside `framesheet` — that's how you verify audio pacing without listening to the MP4.
83
+ - Override on the CLI/MCP without editing the scenario: `--voice-provider openai --voice nova` for studio final cuts, or `--no-voice` to test visuals silently.
79
84
  - **AI / streaming apps**: mock only the LLM fetch/SSE boundary via `scene.page.evaluate(...)`
80
85
  or `page.route(...)` while keeping real client-side/WASM tools live — deterministic, fast,
81
86
  zero API cost, and authentic tool results.