@phil65/demoreel 0.7.1 → 0.8.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.
@@ -0,0 +1,81 @@
1
+ import type { SpeedRegion, TrimRegion, VoiceCue } from "./types.ts";
2
+ export type MusicProviderName = "elevenlabs" | "gemini";
3
+ export declare const MUSIC_PROVIDERS: readonly MusicProviderName[];
4
+ export interface MusicConfig {
5
+ /** Local audio file path (`.mp3`/`.wav`/`.m4a`/`.ogg`) OR direct `https://` audio URL. */
6
+ src?: string;
7
+ /** AI music provider (`"elevenlabs"` or `"gemini"` Lyria). Requires `prompt`. */
8
+ provider?: MusicProviderName;
9
+ /** Natural-language music prompt for AI generation (e.g. `"upbeat minimal lo-fi tech bed"`). */
10
+ prompt?: string;
11
+ /** Provider model override (default: ElevenLabs `"music_v2_5"`, Gemini `"lyria-3-clip-preview"` / `"lyria-3.5"`). */
12
+ model?: string;
13
+ /** API key override (defaults to `ELEVENLABS_API_KEY` or `GEMINI_API_KEY`). */
14
+ apiKey?: string;
15
+ /** Guarantee instrumental output without vocals (default `true`). */
16
+ instrumental?: boolean;
17
+ /** Base bed volume (`0..1`, default `0.18` with voiceover, `0.35` without voiceover). */
18
+ volume?: number;
19
+ /** Volume multiplier during `scene.say()` cues (`0..1`, default `0.3`; `1` disables ducking). */
20
+ duck?: number;
21
+ /** Fade-in duration in ms (default `800`). */
22
+ fadeInMs?: number;
23
+ /** Fade-out duration in ms (default `1500`). */
24
+ fadeOutMs?: number;
25
+ /** Loop the track when shorter than the video (default `true`). */
26
+ loop?: boolean;
27
+ /** Start offset into the music track in ms (default `0`). */
28
+ startOffsetMs?: number;
29
+ /** Disable background music without removing config (e.g. CLI `--no-music`). */
30
+ enabled?: boolean;
31
+ /** Disk cache directory for downloaded/generated music (default `~/.cache/demoreel/music`). */
32
+ cacheDir?: string;
33
+ }
34
+ export type MusicInput = string | MusicConfig;
35
+ export interface ResolvedMusicTrack {
36
+ filePath: string;
37
+ cached: boolean;
38
+ source: "file" | "url" | MusicProviderName;
39
+ }
40
+ /** Normalizes shorthand string (`"./bed.mp3"` / `"https://..."`) or `MusicConfig` object. */
41
+ export declare function normalizeMusicConfig(input?: MusicInput): MusicConfig | undefined;
42
+ export declare function defaultMusicCacheDir(): string;
43
+ /** Bucket AI generation duration to 5s increments so minor pacing tweaks still hit cache. */
44
+ export declare function bucketMusicDurationMs(durationMs: number): number;
45
+ /** Extracts inline base64 audio from Gemini Interactions API response shapes. */
46
+ export declare function extractLyriaAudio(json: unknown): {
47
+ data: Buffer;
48
+ mimeType: string;
49
+ } | null;
50
+ /** Resolves a local file, cached HTTP(S) URL, or AI-generated music track to a local audio path. */
51
+ export declare function resolveMusicTrack(config: MusicConfig, opts: {
52
+ durationMs: number;
53
+ baseDir?: string;
54
+ fetchImpl?: typeof fetch;
55
+ log?: (msg: string) => void;
56
+ }): Promise<ResolvedMusicTrack>;
57
+ /**
58
+ * Merges voice speech intervals and builds a smooth piecewise-linear ffmpeg `volume` expression
59
+ * that ducks the music bed during speech (ramping down `rampDownSec` before and back up `rampUpSec` after).
60
+ */
61
+ export declare function buildDuckingVolumeExpr(baseVolume: number, duckFactor: number, voiceSpansSec: Array<[number, number]>, rampDownSec?: number, rampUpSec?: number): string;
62
+ export interface MuxAudioOptions {
63
+ voiceCues?: VoiceCue[];
64
+ musicPath?: string;
65
+ music?: MusicConfig;
66
+ /** Output video duration in ms (used to trim/fade the music bed). */
67
+ outputDurationMs: number;
68
+ baseDir: string;
69
+ trims?: TrimRegion[];
70
+ speeds?: SpeedRegion[];
71
+ writeVtt?: boolean;
72
+ }
73
+ /**
74
+ * Muxes voiceover cues and/or a background music bed into an MP4 in a single ffmpeg pass
75
+ * (`-c:v copy`, never re-encoding video), with smooth music fades and automatic ducking under speech.
76
+ */
77
+ export declare function muxAudioTracks(videoPath: string, opts: MuxAudioOptions): Promise<{
78
+ audioMuxed: boolean;
79
+ musicMuxed: boolean;
80
+ vttPath?: string;
81
+ }>;
package/dist/music.js ADDED
@@ -0,0 +1,344 @@
1
+ /**
2
+ * Background music beds for demoreel: static local files, cached HTTP(S) URLs, or
3
+ * AI-generated instrumental tracks via ElevenLabs Music or Google Lyria (Gemini API),
4
+ * mixed with smooth fade-in/fade-out and deterministic auto-ducking under `scene.say()`.
5
+ */
6
+ import crypto from "node:crypto";
7
+ import fs from "node:fs";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import { DemoreelError, ffmpegBin, run } from "./env.js";
11
+ import { sourceToOutputMs } from "./idle.js";
12
+ import { buildVoiceVtt } from "./voice.js";
13
+ export const MUSIC_PROVIDERS = ["elevenlabs", "gemini"];
14
+ /** Normalizes shorthand string (`"./bed.mp3"` / `"https://..."`) or `MusicConfig` object. */
15
+ export function normalizeMusicConfig(input) {
16
+ if (!input)
17
+ return undefined;
18
+ return typeof input === "string" ? { src: input } : { ...input };
19
+ }
20
+ export function defaultMusicCacheDir() {
21
+ const xdg = process.env.XDG_CACHE_HOME;
22
+ const base = xdg && xdg.length > 0 ? xdg : path.join(os.homedir(), ".cache");
23
+ return path.join(base, "demoreel", "music");
24
+ }
25
+ function sha256(s) {
26
+ return crypto.createHash("sha256").update(s).digest("hex");
27
+ }
28
+ function extFromMimeOrUrl(mime, url) {
29
+ const m = (mime ?? "").toLowerCase();
30
+ if (m.includes("wav"))
31
+ return ".wav";
32
+ if (m.includes("ogg"))
33
+ return ".ogg";
34
+ if (m.includes("mp4") || m.includes("m4a") || m.includes("aac"))
35
+ return ".m4a";
36
+ if (m.includes("flac"))
37
+ return ".flac";
38
+ if (m.includes("mpeg") || m.includes("mp3"))
39
+ return ".mp3";
40
+ if (url) {
41
+ try {
42
+ const ext = path.extname(new URL(url).pathname).toLowerCase();
43
+ if ([".mp3", ".wav", ".m4a", ".ogg", ".flac", ".aac", ".opus"].includes(ext))
44
+ return ext;
45
+ }
46
+ catch {
47
+ // ignore invalid URL
48
+ }
49
+ }
50
+ return ".mp3";
51
+ }
52
+ /** Bucket AI generation duration to 5s increments so minor pacing tweaks still hit cache. */
53
+ export function bucketMusicDurationMs(durationMs) {
54
+ const target = Math.max(10_000, Math.ceil((durationMs + 2000) / 5000) * 5000);
55
+ return Math.min(600_000, target);
56
+ }
57
+ /** Extracts inline base64 audio from Gemini Interactions API response shapes. */
58
+ export function extractLyriaAudio(json) {
59
+ if (!json || typeof json !== "object")
60
+ return null;
61
+ const obj = json;
62
+ const tryBlock = (b) => {
63
+ if (!b || typeof b !== "object")
64
+ return null;
65
+ const rec = b;
66
+ const mime = (rec.mime_type ?? rec.mimeType);
67
+ if (typeof rec.data === "string" && (rec.type === "audio" || (mime && mime.startsWith("audio/")))) {
68
+ return { data: Buffer.from(rec.data, "base64"), mimeType: mime ?? "audio/mp3" };
69
+ }
70
+ if (rec.inlineData && typeof rec.inlineData === "object") {
71
+ const inline = rec.inlineData;
72
+ if (typeof inline.data === "string") {
73
+ return {
74
+ data: Buffer.from(inline.data, "base64"),
75
+ mimeType: String(inline.mimeType ?? inline.mime_type ?? "audio/mp3"),
76
+ };
77
+ }
78
+ }
79
+ return null;
80
+ };
81
+ const direct = tryBlock(obj.output_audio);
82
+ if (direct)
83
+ return direct;
84
+ if (Array.isArray(obj.outputs)) {
85
+ for (const item of obj.outputs) {
86
+ const hit = tryBlock(item);
87
+ if (hit)
88
+ return hit;
89
+ }
90
+ }
91
+ if (Array.isArray(obj.steps)) {
92
+ for (const step of obj.steps) {
93
+ const content = step?.content;
94
+ if (Array.isArray(content)) {
95
+ for (const block of content) {
96
+ const hit = tryBlock(block);
97
+ if (hit)
98
+ return hit;
99
+ }
100
+ }
101
+ }
102
+ }
103
+ return null;
104
+ }
105
+ /** Resolves a local file, cached HTTP(S) URL, or AI-generated music track to a local audio path. */
106
+ export async function resolveMusicTrack(config, opts) {
107
+ const fetchFn = opts.fetchImpl ?? globalThis.fetch;
108
+ const cacheDir = config.cacheDir ?? defaultMusicCacheDir();
109
+ if (config.src) {
110
+ if (/^https?:\/\//i.test(config.src)) {
111
+ fs.mkdirSync(cacheDir, { recursive: true });
112
+ const key = sha256(`url:${config.src}`).slice(0, 24);
113
+ const cachedExisting = findCachedFile(cacheDir, `url-${key}`);
114
+ if (cachedExisting)
115
+ return { filePath: cachedExisting, cached: true, source: "url" };
116
+ opts.log?.(`downloading background music from ${config.src}...`);
117
+ const res = await fetchFn(config.src);
118
+ if (!res.ok)
119
+ throw new DemoreelError(`music URL download failed (${res.status}): ${config.src}`);
120
+ const ext = extFromMimeOrUrl(res.headers.get("content-type"), config.src);
121
+ const dest = path.join(cacheDir, `url-${key}${ext}`);
122
+ fs.writeFileSync(dest, Buffer.from(await res.arrayBuffer()));
123
+ return { filePath: dest, cached: false, source: "url" };
124
+ }
125
+ const resolved = path.isAbsolute(config.src) ? config.src : path.resolve(opts.baseDir ?? process.cwd(), config.src);
126
+ if (!fs.existsSync(resolved)) {
127
+ throw new DemoreelError(`music file not found: ${resolved}`);
128
+ }
129
+ return { filePath: resolved, cached: true, source: "file" };
130
+ }
131
+ if (!config.provider) {
132
+ throw new DemoreelError("music config requires either `src` (file path or URL) or `provider` + `prompt`");
133
+ }
134
+ const prompt = config.prompt?.trim();
135
+ if (!prompt) {
136
+ throw new DemoreelError(`music provider "${config.provider}" requires a non-empty \`prompt\``);
137
+ }
138
+ const instrumental = config.instrumental !== false;
139
+ const bucketedMs = bucketMusicDurationMs(opts.durationMs);
140
+ fs.mkdirSync(cacheDir, { recursive: true });
141
+ if (config.provider === "elevenlabs") {
142
+ const model = config.model ?? "music_v2_5";
143
+ const key = sha256(JSON.stringify({ provider: "elevenlabs", model, prompt, instrumental, bucketedMs })).slice(0, 24);
144
+ const dest = path.join(cacheDir, `el-${key}.mp3`);
145
+ if (fs.existsSync(dest))
146
+ return { filePath: dest, cached: true, source: "elevenlabs" };
147
+ const apiKey = config.apiKey ?? process.env.ELEVENLABS_API_KEY;
148
+ if (!apiKey) {
149
+ throw new DemoreelError("ElevenLabs Music requires ELEVENLABS_API_KEY (or music.apiKey)", "export ELEVENLABS_API_KEY=... or pass a static `music: './bed.mp3'`");
150
+ }
151
+ opts.log?.(`generating ${(bucketedMs / 1000).toFixed(0)}s instrumental bed via ElevenLabs Music...`);
152
+ const res = await fetchFn("https://api.elevenlabs.io/v1/music", {
153
+ method: "POST",
154
+ headers: {
155
+ "xi-api-key": apiKey,
156
+ "content-type": "application/json",
157
+ },
158
+ body: JSON.stringify({
159
+ prompt,
160
+ music_length_ms: bucketedMs,
161
+ force_instrumental: instrumental,
162
+ model_id: model,
163
+ }),
164
+ });
165
+ if (!res.ok) {
166
+ const body = await res.text().catch(() => "");
167
+ throw new DemoreelError(`ElevenLabs Music API error (${res.status}): ${body.slice(0, 300)}`);
168
+ }
169
+ fs.writeFileSync(dest, Buffer.from(await res.arrayBuffer()));
170
+ return { filePath: dest, cached: false, source: "elevenlabs" };
171
+ }
172
+ if (config.provider === "gemini") {
173
+ const model = config.model ?? (bucketedMs <= 35_000 ? "lyria-3-clip-preview" : "lyria-3.5");
174
+ const effectivePrompt = instrumental && !/\binstrumental\b/i.test(prompt) ? `${prompt}, instrumental only, no vocals` : prompt;
175
+ const key = sha256(JSON.stringify({ provider: "gemini", model, prompt: effectivePrompt })).slice(0, 24);
176
+ const cachedExisting = findCachedFile(cacheDir, `lyria-${key}`);
177
+ if (cachedExisting)
178
+ return { filePath: cachedExisting, cached: true, source: "gemini" };
179
+ const apiKey = config.apiKey ?? process.env.GEMINI_API_KEY ?? process.env.GOOGLE_API_KEY;
180
+ if (!apiKey) {
181
+ throw new DemoreelError("Google Lyria music requires GEMINI_API_KEY (or music.apiKey)", "export GEMINI_API_KEY=... or pass a static `music: './bed.mp3'`");
182
+ }
183
+ opts.log?.(`generating background music via Google Lyria (${model})...`);
184
+ const res = await fetchFn("https://generativelanguage.googleapis.com/v1beta/interactions", {
185
+ method: "POST",
186
+ headers: {
187
+ "x-goog-api-key": apiKey,
188
+ "content-type": "application/json",
189
+ },
190
+ body: JSON.stringify({
191
+ model,
192
+ input: effectivePrompt,
193
+ }),
194
+ });
195
+ if (!res.ok) {
196
+ const body = await res.text().catch(() => "");
197
+ throw new DemoreelError(`Google Lyria API error (${res.status}): ${body.slice(0, 300)}`);
198
+ }
199
+ const json = await res.json();
200
+ const audio = extractLyriaAudio(json);
201
+ if (!audio) {
202
+ throw new DemoreelError("Google Lyria response did not contain an audio block");
203
+ }
204
+ const ext = extFromMimeOrUrl(audio.mimeType);
205
+ const dest = path.join(cacheDir, `lyria-${key}${ext}`);
206
+ fs.writeFileSync(dest, audio.data);
207
+ return { filePath: dest, cached: false, source: "gemini" };
208
+ }
209
+ throw new DemoreelError(`unsupported music provider: "${String(config.provider)}" (supported: ${MUSIC_PROVIDERS.join(", ")})`);
210
+ }
211
+ function findCachedFile(dir, stem) {
212
+ if (!fs.existsSync(dir))
213
+ return null;
214
+ for (const f of fs.readdirSync(dir)) {
215
+ if (f.startsWith(`${stem}.`))
216
+ return path.join(dir, f);
217
+ }
218
+ return null;
219
+ }
220
+ /**
221
+ * Merges voice speech intervals and builds a smooth piecewise-linear ffmpeg `volume` expression
222
+ * that ducks the music bed during speech (ramping down `rampDownSec` before and back up `rampUpSec` after).
223
+ */
224
+ export function buildDuckingVolumeExpr(baseVolume, duckFactor, voiceSpansSec, rampDownSec = 0.25, rampUpSec = 0.4) {
225
+ const base = Math.min(2, Math.max(0, baseVolume));
226
+ const duck = Math.min(1, Math.max(0, duckFactor));
227
+ if (voiceSpansSec.length === 0 || duck >= 0.999) {
228
+ return base.toFixed(4);
229
+ }
230
+ const sorted = voiceSpansSec
231
+ .filter(([s, e]) => e > s)
232
+ .map(([s, e]) => [Math.max(0, s), e])
233
+ .sort((a, b) => a[0] - b[0]);
234
+ if (sorted.length === 0)
235
+ return base.toFixed(4);
236
+ // Merge spans separated by less than rampDown + rampUp so consecutive cues stay smoothly ducked.
237
+ const mergeGap = rampDownSec + rampUpSec + 0.05;
238
+ const merged = [sorted[0]];
239
+ for (let i = 1; i < sorted.length; i++) {
240
+ const prev = merged[merged.length - 1];
241
+ if (sorted[i][0] <= prev[1] + mergeGap) {
242
+ prev[1] = Math.max(prev[1], sorted[i][1]);
243
+ }
244
+ else {
245
+ merged.push([...sorted[i]]);
246
+ }
247
+ }
248
+ const terms = merged.map(([s, e]) => {
249
+ const downStart = (s - rampDownSec).toFixed(3);
250
+ const upEnd = (e + rampUpSec).toFixed(3);
251
+ return `clip((t-(${downStart}))/${rampDownSec.toFixed(3)},0,1)*clip(((${upEnd})-t)/${rampUpSec.toFixed(3)},0,1)`;
252
+ });
253
+ const depth = (1 - duck).toFixed(4);
254
+ return `${base.toFixed(4)}*(1-${depth}*(${terms.join("+")}))`;
255
+ }
256
+ /**
257
+ * Muxes voiceover cues and/or a background music bed into an MP4 in a single ffmpeg pass
258
+ * (`-c:v copy`, never re-encoding video), with smooth music fades and automatic ducking under speech.
259
+ */
260
+ export async function muxAudioTracks(videoPath, opts) {
261
+ const trims = opts.trims ?? [];
262
+ const speeds = opts.speeds ?? [];
263
+ const cues = opts.voiceCues ?? [];
264
+ const resolvedVoice = cues
265
+ .map((cue) => ({
266
+ cue,
267
+ wavPath: path.isAbsolute(cue.audioFile) ? cue.audioFile : path.resolve(opts.baseDir, cue.audioFile),
268
+ delayMs: Math.max(0, Math.round(sourceToOutputMs(cue.startMs, trims, speeds))),
269
+ }))
270
+ .filter((entry) => fs.existsSync(entry.wavPath));
271
+ const hasVoice = resolvedVoice.length > 0;
272
+ const hasMusic = Boolean(opts.musicPath && fs.existsSync(opts.musicPath));
273
+ if (!hasVoice && !hasMusic)
274
+ return { audioMuxed: false, musicMuxed: false };
275
+ const args = ["-y", "-loglevel", "error", "-i", videoPath];
276
+ const filterParts = [];
277
+ const voiceLabels = [];
278
+ let nextInputIdx = 1;
279
+ for (const entry of resolvedVoice) {
280
+ args.push("-i", entry.wavPath);
281
+ const idx = nextInputIdx++;
282
+ const label = `v${idx}`;
283
+ filterParts.push(`[${idx}:a]aresample=48000,aformat=channel_layouts=stereo,adelay=${entry.delayMs}|${entry.delayMs}[${label}]`);
284
+ voiceLabels.push(`[${label}]`);
285
+ }
286
+ if (hasVoice) {
287
+ if (voiceLabels.length === 1) {
288
+ filterParts.push(`${voiceLabels[0]}anull[vout]`);
289
+ }
290
+ else {
291
+ filterParts.push(`${voiceLabels.join("")}amix=inputs=${voiceLabels.length}:duration=longest:dropout_transition=0:normalize=0[vout]`);
292
+ }
293
+ }
294
+ if (hasMusic && opts.musicPath) {
295
+ const m = opts.music ?? {};
296
+ if (m.loop !== false)
297
+ args.push("-stream_loop", "-1");
298
+ if (m.startOffsetMs && m.startOffsetMs > 0) {
299
+ args.push("-ss", (m.startOffsetMs / 1000).toFixed(3));
300
+ }
301
+ args.push("-i", opts.musicPath);
302
+ const mIdx = nextInputIdx++;
303
+ const durSec = Math.max(0.2, opts.outputDurationMs / 1000);
304
+ const baseVol = m.volume ?? (hasVoice ? 0.18 : 0.35);
305
+ const duck = m.duck ?? 0.3;
306
+ const voiceSpansSec = resolvedVoice.map((v) => [v.delayMs / 1000, (v.delayMs + v.cue.durationMs) / 1000]);
307
+ const volExpr = buildDuckingVolumeExpr(baseVol, duck, voiceSpansSec);
308
+ const fadeInSec = Math.min(durSec / 2, Math.max(0, (m.fadeInMs ?? 800) / 1000));
309
+ const fadeOutSec = Math.min(durSec / 2, Math.max(0, (m.fadeOutMs ?? 1500) / 1000));
310
+ const chain = [
311
+ `[${mIdx}:a]aresample=48000`,
312
+ "aformat=channel_layouts=stereo",
313
+ `atrim=0:${durSec.toFixed(3)}`,
314
+ "asetpts=PTS-STARTPTS",
315
+ `volume='${volExpr}':eval=frame`,
316
+ ];
317
+ if (fadeInSec > 0.01)
318
+ chain.push(`afade=t=in:st=0:d=${fadeInSec.toFixed(3)}`);
319
+ if (fadeOutSec > 0.01) {
320
+ const fadeOutStart = Math.max(0, durSec - fadeOutSec);
321
+ chain.push(`afade=t=out:st=${fadeOutStart.toFixed(3)}:d=${fadeOutSec.toFixed(3)}`);
322
+ }
323
+ filterParts.push(`${chain.join(",")}[mout]`);
324
+ }
325
+ if (hasVoice && hasMusic) {
326
+ filterParts.push("[vout][mout]amix=inputs=2:duration=longest:dropout_transition=0:normalize=0[aout]");
327
+ }
328
+ else if (hasVoice) {
329
+ filterParts.push("[vout]anull[aout]");
330
+ }
331
+ else {
332
+ filterParts.push("[mout]anull[aout]");
333
+ }
334
+ const tmpOut = videoPath.replace(/\.mp4$/i, ".audio.tmp.mp4");
335
+ args.push("-filter_complex", filterParts.join(";"), "-map", "0:v:0", "-map", "[aout]", "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", tmpOut);
336
+ await run(ffmpegBin(), args);
337
+ fs.renameSync(tmpOut, videoPath);
338
+ let vttPath;
339
+ if (hasVoice && opts.writeVtt !== false) {
340
+ vttPath = videoPath.replace(/\.mp4$/i, ".vtt");
341
+ fs.writeFileSync(vttPath, buildVoiceVtt(cues, trims, speeds));
342
+ }
343
+ return { audioMuxed: true, musicMuxed: hasMusic, vttPath };
344
+ }
package/dist/project.d.ts CHANGED
@@ -125,11 +125,12 @@ export declare function captionAnnotations(captions: Caption[], look?: LookOptio
125
125
  }[];
126
126
  /** Resolves a `data:image/...` URL or reads a local image file and encodes it as a data URL. */
127
127
  export declare function resolveImageDataUrl(src: string, baseDir?: string): string;
128
- /** Converts recorded `BlurAnnotation`s into OpenScreen `type: "blur"` regions. */
128
+ /** Converts recorded `BlurAnnotation`s into OpenScreen `type: "blur"` regions (skipping DOM-blurred elements). */
129
129
  export declare function blurAnnotations(blurs: BlurAnnotation[], opts: {
130
130
  viewport: Viewport;
131
131
  layout: StageLayout;
132
132
  durationMs: number;
133
+ zoomRegions?: ZoomRegion[];
133
134
  startZIndex?: number;
134
135
  }): {
135
136
  id: string;
@@ -169,10 +170,23 @@ export declare function blurAnnotations(blurs: BlurAnnotation[], opts: {
169
170
  }[];
170
171
  };
171
172
  }[];
172
- /** Converts recorded `ArrowAnnotation`s into OpenScreen `type: "figure"` arrow regions. */
173
+ /** Places a directional arrow box just outside a target rect pointing toward it. */
174
+ export declare function arrowRectForTarget(stage: {
175
+ x: number;
176
+ y: number;
177
+ w: number;
178
+ h: number;
179
+ }, dir: ArrowDirection, sizePct: number): {
180
+ x: number;
181
+ y: number;
182
+ width: number;
183
+ height: number;
184
+ };
185
+ /** Converts recorded `ArrowAnnotation`s into OpenScreen `type: "figure"` arrow regions (camera-projected). */
173
186
  export declare function arrowAnnotations(arrows: ArrowAnnotation[], opts: {
174
187
  viewport: Viewport;
175
188
  layout: StageLayout;
189
+ zoomRegions?: ZoomRegion[];
176
190
  startZIndex?: number;
177
191
  }): {
178
192
  id: string;
package/dist/project.js CHANGED
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import fs from "node:fs";
7
7
  import path from "node:path";
8
- import { boxToStage, stageLayout } from "./layout.js";
8
+ import { applyCamera, boxToStage, stageLayout } from "./layout.js";
9
9
  export const PROJECT_VERSION = 2;
10
10
  export const CURSOR_TELEMETRY_VERSION = 2;
11
11
  export const DEFAULT_LOOK = {
@@ -183,10 +183,12 @@ const DEFAULT_BLUR_FREEHAND_POINTS = [
183
183
  { x: 22, y: 84 },
184
184
  { x: 8, y: 58 },
185
185
  ];
186
- /** Converts recorded `BlurAnnotation`s into OpenScreen `type: "blur"` regions. */
186
+ /** Converts recorded `BlurAnnotation`s into OpenScreen `type: "blur"` regions (skipping DOM-blurred elements). */
187
187
  export function blurAnnotations(blurs, opts) {
188
188
  const z0 = opts.startZIndex ?? 1;
189
- return blurs.map((b, i) => {
189
+ const overlayBlurs = blurs.filter((b) => b.mode !== "dom");
190
+ return overlayBlurs.map((b, i) => {
191
+ const endMs = b.endMs === "end" ? Math.max(b.startMs + 100, opts.durationMs) : b.endMs;
190
192
  let x;
191
193
  let y;
192
194
  let width;
@@ -202,7 +204,9 @@ export function blurAnnotations(blurs, opts) {
202
204
  width: b.box.width + pad * 2,
203
205
  height: b.box.height + pad * 2,
204
206
  };
205
- const stage = boxToStage(opts.layout, opts.viewport, padded);
207
+ const rawStage = boxToStage(opts.layout, opts.viewport, padded);
208
+ const sampleT = Math.min(endMs, b.startMs + Math.min(350, (endMs - b.startMs) / 2));
209
+ const stage = opts.zoomRegions?.length ? applyCamera(rawStage, opts.zoomRegions, sampleT) : rawStage;
206
210
  x = stage.x * 100;
207
211
  y = stage.y * 100;
208
212
  width = stage.w * 100;
@@ -214,7 +218,6 @@ export function blurAnnotations(blurs, opts) {
214
218
  width = 20;
215
219
  height = 10;
216
220
  }
217
- const endMs = b.endMs === "end" ? Math.max(b.startMs + 100, opts.durationMs) : b.endMs;
218
221
  return {
219
222
  id: `blur-${i + 1}`,
220
223
  startMs: Math.round(b.startMs),
@@ -237,7 +240,7 @@ export function blurAnnotations(blurs, opts) {
237
240
  });
238
241
  }
239
242
  /** Places a directional arrow box just outside a target rect pointing toward it. */
240
- function arrowRectForTarget(stage, dir, sizePct) {
243
+ export function arrowRectForTarget(stage, dir, sizePct) {
241
244
  const tx = stage.x * 100;
242
245
  const ty = stage.y * 100;
243
246
  const tw = stage.w * 100;
@@ -275,16 +278,24 @@ function arrowRectForTarget(stage, dir, sizePct) {
275
278
  }
276
279
  return { x: clampPct(x, 0, 100 - w), y: clampPct(y, 0, 100 - h), width: w, height: h };
277
280
  }
278
- /** Converts recorded `ArrowAnnotation`s into OpenScreen `type: "figure"` arrow regions. */
281
+ /** Converts recorded `ArrowAnnotation`s into OpenScreen `type: "figure"` arrow regions (camera-projected). */
279
282
  export function arrowAnnotations(arrows, opts) {
280
283
  const z0 = opts.startZIndex ?? 1;
281
284
  return arrows.map((a, i) => {
282
285
  const sizePct = Math.min(40, Math.max(3, a.size ?? 9));
283
- const rect = a.rect
284
- ? a.rect
285
- : a.box
286
- ? arrowRectForTarget(boxToStage(opts.layout, opts.viewport, a.box), a.direction, sizePct)
287
- : { x: 45, y: 45, width: sizePct, height: sizePct };
286
+ let rect;
287
+ if (a.rect) {
288
+ rect = a.rect;
289
+ }
290
+ else if (a.box) {
291
+ const rawStage = boxToStage(opts.layout, opts.viewport, a.box);
292
+ const sampleT = Math.min(a.endMs, a.startMs + Math.min(350, (a.endMs - a.startMs) / 2));
293
+ const stage = opts.zoomRegions?.length ? applyCamera(rawStage, opts.zoomRegions, sampleT) : rawStage;
294
+ rect = arrowRectForTarget(stage, a.direction, sizePct);
295
+ }
296
+ else {
297
+ rect = { x: 45, y: 45, width: sizePct, height: sizePct };
298
+ }
288
299
  return {
289
300
  id: `arrow-${i + 1}`,
290
301
  startMs: Math.round(a.startMs),
@@ -366,11 +377,11 @@ export function buildProject(opts) {
366
377
  const layout = stageLayout(viewport, look);
367
378
  const durationMs = opts.durationMs ?? Math.max(1000, ...opts.captions.map((c) => c.endMs), ...(opts.actions ?? []).map((a) => a.endMs));
368
379
  let z = 1;
369
- const blurs = blurAnnotations(opts.blurs ?? [], { viewport, layout, durationMs, startZIndex: z });
380
+ const blurs = blurAnnotations(opts.blurs ?? [], { viewport, layout, durationMs, zoomRegions: opts.zoomRegions, startZIndex: z });
370
381
  z += blurs.length;
371
382
  const images = imageAnnotations(opts.images ?? [], { durationMs, baseDir: opts.baseDir, watermark: look.watermark, startZIndex: z });
372
383
  z += images.length;
373
- const arrows = arrowAnnotations(opts.arrows ?? [], { viewport, layout, startZIndex: z });
384
+ const arrows = arrowAnnotations(opts.arrows ?? [], { viewport, layout, zoomRegions: opts.zoomRegions, startZIndex: z });
374
385
  z += arrows.length;
375
386
  const captions = captionAnnotations(opts.captions, look, z);
376
387
  z += captions.length;
package/dist/record.d.ts CHANGED
@@ -2,6 +2,7 @@ import type { Page } from "playwright";
2
2
  import { type ComposeResult } from "./compose.ts";
3
3
  import type { IdleOptions } from "./idle.ts";
4
4
  import type { LookOptions } from "./project.ts";
5
+ import type { MusicInput } from "./music.ts";
5
6
  import type { CursorStyle } from "./render.ts";
6
7
  import { type ClickRippleOptions, type PacingOptions, Scene } from "./scene.ts";
7
8
  import type { ActionRecord, RecordingResult, Viewport, VoiceCue } from "./types.ts";
@@ -41,6 +42,8 @@ export interface Scenario {
41
42
  trimIdle?: boolean | Partial<IdleOptions>;
42
43
  /** Voiceover TTS configuration for `scene.say()` (defaults to free Microsoft Edge TTS). */
43
44
  voice?: VoiceConfig;
45
+ /** Background music bed: local path, HTTP(S) URL, or AI-generated config (ElevenLabs Music / Google Lyria). */
46
+ music?: MusicInput;
44
47
  run(scene: Scene, ctx: ScenarioContext): Promise<void>;
45
48
  }
46
49
  /** Identity helper that gives scenario files type checking and editor completion. */
package/dist/record.js CHANGED
@@ -150,6 +150,7 @@ export async function recordScenario(input, opts = {}) {
150
150
  trimIdle: session.scenario.trimIdle,
151
151
  cursor: session.scenario.cursor,
152
152
  voice: session.scenario.voice,
153
+ music: session.scenario.music,
153
154
  });
154
155
  const result = {
155
156
  videoPath,
package/dist/render.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type GpuMode } from "./env.ts";
2
+ import { type MusicInput } from "./music.ts";
2
3
  export interface CursorStyle {
3
4
  /** Cursor scale (OpenScreen default 3). */
4
5
  size?: number;
@@ -15,6 +16,8 @@ export interface RenderOptions {
15
16
  /** OpenScreen export quality: medium (720p), good (1080p), source. Default: the project's. */
16
17
  quality?: "medium" | "good" | "source";
17
18
  cursor?: CursorStyle;
19
+ /** Optional background music override (takes precedence over `timeline.json`). */
20
+ music?: MusicInput;
18
21
  /** `"auto"` (default): use the GPU if one works, else SwiftShader with a warning. */
19
22
  gpu?: GpuMode;
20
23
  /** Print browser console output. */
@@ -37,6 +40,7 @@ export interface RenderResult {
37
40
  setupMs: number;
38
41
  totalMs: number;
39
42
  audioMuxed?: boolean;
43
+ musicMuxed?: boolean;
40
44
  vttPath?: string;
41
45
  }
42
46
  /** Resolves the project's screen video (absolute, or relative to the project file). */