@phil65/demoreel 0.7.2 → 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.
- package/README.md +20 -1
- package/dist/args.js +8 -0
- package/dist/cli.js +43 -1
- package/dist/compose.d.ts +3 -0
- package/dist/compose.js +12 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/mcp.js +35 -0
- package/dist/music.d.ts +81 -0
- package/dist/music.js +344 -0
- package/dist/record.d.ts +3 -0
- package/dist/record.js +1 -0
- package/dist/render.d.ts +4 -0
- package/dist/render.js +52 -15
- package/package.json +1 -1
- package/skills/demoreel/SKILL.md +1 -0
package/README.md
CHANGED
|
@@ -128,7 +128,8 @@ JSON, relative to the scenario file), `colorScheme`, `seed`, `pacing`
|
|
|
128
128
|
(`wallpaper`, `padding`, `borderRadius`, `shadowIntensity`, `showBlur`, `crop`, `aspectRatio`,
|
|
129
129
|
`captionPosition`, `captionFontSize`, `captionAnimation`, `showKeys`, `watermark`), `cursor` (`size`, `clickBounce`, `smoothing`, `motionBlur`,
|
|
130
130
|
`show`), `clickRipple`, `trimIdle` (`true` or `{ minMs, keepMs, mode, speed, ignoreFrames }`),
|
|
131
|
-
`voice` (`{ provider: "edge" | "openai" | "elevenlabs" | "gemini" | "cartesia" | "deepgram", voice, model, language, speed, pitch, volume, instructions, gapMs, padMs, captions: "vtt" | "burned" | "off", cacheDir }`)
|
|
131
|
+
`voice` (`{ provider: "edge" | "openai" | "elevenlabs" | "gemini" | "cartesia" | "deepgram", voice, model, language, speed, pitch, volume, instructions, gapMs, padMs, captions: "vtt" | "burned" | "off", cacheDir }`),
|
|
132
|
+
`music` (`"./bed.mp3"`, `"https://..."`, or `{ src?, provider?: "elevenlabs" | "gemini", prompt?, model?, instrumental?, volume?, duck?, fadeInMs?, fadeOutMs?, loop?, startOffsetMs?, cacheDir? }`).
|
|
132
133
|
|
|
133
134
|
### Voiceover narration (`scene.say`)
|
|
134
135
|
|
|
@@ -158,6 +159,24 @@ export default defineScenario({
|
|
|
158
159
|
- `demoreel render` / `demoreel rezoom --render` stream-copy the OpenScreen H.264 video (`-c:v copy`), mux all cues into AAC audio at post-trim timestamps, and write `<name>.vtt`.
|
|
159
160
|
- Override provider or voice at run time without editing the scenario: `--voice-provider openai --voice nova` or `--no-voice`.
|
|
160
161
|
|
|
162
|
+
### Background music (`music`)
|
|
163
|
+
|
|
164
|
+
Layer a local track, cached HTTP(S) URL, or AI-generated instrumental bed (ElevenLabs Music via `ELEVENLABS_API_KEY` or Google Lyria via `GEMINI_API_KEY`). Tracks automatically loop/trim to the rendered duration, fade in/out cleanly, and **auto-duck smoothly under `scene.say()` voiceover cues** in the same `-c:v copy` ffmpeg pass:
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
export default defineScenario({
|
|
168
|
+
name: "launch",
|
|
169
|
+
// Static file or URL (cached on disk):
|
|
170
|
+
music: { src: "./bed.mp3", volume: 0.18, duck: 0.3, fadeInMs: 800, fadeOutMs: 1500 },
|
|
171
|
+
// Or AI-generated (SHA-256 cached by prompt + 5s duration bucket):
|
|
172
|
+
// music: { provider: "elevenlabs", prompt: "minimal upbeat lo-fi synth, instrumental" },
|
|
173
|
+
// music: { provider: "gemini", prompt: "warm clean acoustic tech background" },
|
|
174
|
+
async run(scene) { /* ... */ },
|
|
175
|
+
});
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
Override on the CLI or MCP without editing the scenario: `--music ./bed.mp3`, `--music-provider elevenlabs --music-prompt "..."`, or `--no-music` (works on both `run` and `render`).
|
|
179
|
+
|
|
161
180
|
Library: `recordScenario`, `dryRunScenario`, `resolveStorageState`, `deriveZoomRegions`,
|
|
162
181
|
`deriveIdleRegions`, `buildProject`, `buildCursorData`, `buildMarks`, `renderProject`,
|
|
163
182
|
`validateProject`, `rezoom`, `reviewSheet`, `extractFrame`, `exportGif`, `createMcpServer`,
|
package/dist/args.js
CHANGED
|
@@ -27,6 +27,10 @@ export const COMMANDS = {
|
|
|
27
27
|
"voice-provider": { type: "string", value: "NAME", description: "override voiceover TTS provider: edge (free) | openai | elevenlabs | gemini | cartesia | deepgram" },
|
|
28
28
|
voice: { type: "string", value: "ID", description: "override voiceover voice ID" },
|
|
29
29
|
"no-voice": { type: "boolean", description: "skip voiceover TTS synthesis for this run" },
|
|
30
|
+
music: { type: "string", value: "PATH|URL", description: "background music bed (local audio file or HTTP(S) URL)" },
|
|
31
|
+
"music-provider": { type: "string", value: "NAME", description: "AI background music provider: elevenlabs | gemini (Lyria)" },
|
|
32
|
+
"music-prompt": { type: "string", value: "TEXT", description: "prompt for AI background music generation" },
|
|
33
|
+
"no-music": { type: "boolean", description: "disable background music for this run" },
|
|
30
34
|
headed: { type: "boolean", description: "show the browser while recording" },
|
|
31
35
|
frames,
|
|
32
36
|
framesheet,
|
|
@@ -39,6 +43,10 @@ export const COMMANDS = {
|
|
|
39
43
|
positionals: { min: 1, max: 1 },
|
|
40
44
|
flags: {
|
|
41
45
|
out: { type: "string", alias: "o", value: "FILE", description: "output MP4 (default: next to the project)" },
|
|
46
|
+
music: { type: "string", value: "PATH|URL", description: "override background music bed (local audio file or HTTP(S) URL)" },
|
|
47
|
+
"music-provider": { type: "string", value: "NAME", description: "AI background music provider: elevenlabs | gemini (Lyria)" },
|
|
48
|
+
"music-prompt": { type: "string", value: "TEXT", description: "prompt for AI background music generation" },
|
|
49
|
+
"no-music": { type: "boolean", description: "disable background music for this render" },
|
|
42
50
|
gpu,
|
|
43
51
|
fps,
|
|
44
52
|
quality,
|
package/dist/cli.js
CHANGED
|
@@ -9,6 +9,7 @@ import { checkFfmpeg, DemoreelError, detectGpu, launchChromium } from "./env.js"
|
|
|
9
9
|
import { exportGif } from "./gif.js";
|
|
10
10
|
import { initProject } from "./init.js";
|
|
11
11
|
import { loadScenario } from "./load.js";
|
|
12
|
+
import { MUSIC_PROVIDERS, normalizeMusicConfig } from "./music.js";
|
|
12
13
|
import { PACKAGE_ROOT } from "./openscreen.js";
|
|
13
14
|
import { dryRunScenario, recordScenario, resolveStorageState } from "./record.js";
|
|
14
15
|
import { renderProject, validateProject } from "./render.js";
|
|
@@ -32,12 +33,42 @@ function progressPrinter(enabled) {
|
|
|
32
33
|
};
|
|
33
34
|
}
|
|
34
35
|
function printRender(r) {
|
|
35
|
-
|
|
36
|
+
const audioNote = r.audioMuxed ? (r.musicMuxed ? " + audio/music" : " + audio") : "";
|
|
37
|
+
log(` rendered ${r.width}x${r.height} ${(r.bytes / 1e6).toFixed(1)} MB in ${fmt(r.renderMs)} (${r.gpu ? "GPU" : "software"}, setup ${fmt(r.setupMs)})${audioNote} -> ${r.outputPath}`);
|
|
36
38
|
if (r.vttPath)
|
|
37
39
|
log(` subtitles: ${r.vttPath}`);
|
|
38
40
|
if (r.warnings.length)
|
|
39
41
|
log(` warnings: ${r.warnings.join("; ")}`);
|
|
40
42
|
}
|
|
43
|
+
function musicFlagOverride(flags, base) {
|
|
44
|
+
if (flags.music === undefined && flags["music-provider"] === undefined && flags["music-prompt"] === undefined && !flags["no-music"]) {
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
const m = { ...base };
|
|
48
|
+
if (flags["no-music"])
|
|
49
|
+
m.enabled = false;
|
|
50
|
+
if (typeof flags.music === "string") {
|
|
51
|
+
m.src = /^https?:\/\//i.test(flags.music) ? flags.music : path.resolve(flags.music);
|
|
52
|
+
delete m.provider;
|
|
53
|
+
delete m.prompt;
|
|
54
|
+
m.enabled = true;
|
|
55
|
+
}
|
|
56
|
+
if (flags["music-provider"] !== undefined) {
|
|
57
|
+
const p = String(flags["music-provider"]);
|
|
58
|
+
if (!MUSIC_PROVIDERS.includes(p)) {
|
|
59
|
+
throw new UsageError(`--music-provider must be ${MUSIC_PROVIDERS.join(", ")}`);
|
|
60
|
+
}
|
|
61
|
+
m.provider = p;
|
|
62
|
+
delete m.src;
|
|
63
|
+
m.enabled = true;
|
|
64
|
+
}
|
|
65
|
+
if (typeof flags["music-prompt"] === "string") {
|
|
66
|
+
m.prompt = flags["music-prompt"];
|
|
67
|
+
delete m.src;
|
|
68
|
+
m.enabled = true;
|
|
69
|
+
}
|
|
70
|
+
return m;
|
|
71
|
+
}
|
|
41
72
|
function renderFlags(flags) {
|
|
42
73
|
const q = flags.quality;
|
|
43
74
|
if (q && !["medium", "good", "source"].includes(q))
|
|
@@ -80,6 +111,9 @@ async function cmdRun({ positionals, flags }) {
|
|
|
80
111
|
voice.voice = flags.voice;
|
|
81
112
|
overrides.voice = voice;
|
|
82
113
|
}
|
|
114
|
+
const musicOverride = musicFlagOverride(flags, normalizeMusicConfig(scenario.music));
|
|
115
|
+
if (musicOverride)
|
|
116
|
+
overrides.music = musicOverride;
|
|
83
117
|
const storageState = flags.state ? String(flags.state) : undefined;
|
|
84
118
|
if (flags["dry-run"]) {
|
|
85
119
|
const res = await dryRunScenario(scenario, {
|
|
@@ -122,11 +156,17 @@ async function cmdRun({ positionals, flags }) {
|
|
|
122
156
|
log(` marks: ${rec.marksPath}`);
|
|
123
157
|
if (flags.render === false)
|
|
124
158
|
return;
|
|
159
|
+
const baseMusic = normalizeMusicConfig(scenario.music);
|
|
160
|
+
const resolvedScenarioMusic = baseMusic?.src && !/^https?:\/\//i.test(baseMusic.src) && !path.isAbsolute(baseMusic.src)
|
|
161
|
+
? { ...baseMusic, src: path.resolve(path.dirname(file), baseMusic.src) }
|
|
162
|
+
: baseMusic;
|
|
163
|
+
const effectiveMusic = musicOverride ?? resolvedScenarioMusic;
|
|
125
164
|
const mp4 = path.join(out, `${scenario.name}.mp4`);
|
|
126
165
|
const r = await renderProject({
|
|
127
166
|
projectPath: rec.projectPath,
|
|
128
167
|
outputPath: mp4,
|
|
129
168
|
cursor: scenario.cursor,
|
|
169
|
+
...(effectiveMusic ? { music: effectiveMusic } : {}),
|
|
130
170
|
...renderFlags(flags),
|
|
131
171
|
log,
|
|
132
172
|
onProgress: progressPrinter(true),
|
|
@@ -154,9 +194,11 @@ async function cmdRun({ positionals, flags }) {
|
|
|
154
194
|
}
|
|
155
195
|
async function cmdRender({ positionals, flags }) {
|
|
156
196
|
const projectPath = path.resolve(positionals[0]);
|
|
197
|
+
const music = musicFlagOverride(flags);
|
|
157
198
|
const r = await renderProject({
|
|
158
199
|
projectPath,
|
|
159
200
|
outputPath: flags.out ? path.resolve(String(flags.out)) : undefined,
|
|
201
|
+
...(music ? { music } : {}),
|
|
160
202
|
...renderFlags(flags),
|
|
161
203
|
log,
|
|
162
204
|
onProgress: progressPrinter(true),
|
package/dist/compose.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type IdleOptions } from "./idle.ts";
|
|
2
2
|
import { type Marks } from "./marks.ts";
|
|
3
|
+
import { type MusicConfig, type MusicInput } from "./music.ts";
|
|
3
4
|
import { buildProject, type LookOptions } from "./project.ts";
|
|
4
5
|
import type { CursorStyle } from "./render.ts";
|
|
5
6
|
import type { ActionRecord, ArrowAnnotation, BlurAnnotation, Caption, CursorSample, ImageAnnotation, SpeedRegion, TrimRegion, Viewport, VoiceCue, ZoomRegion } from "./types.ts";
|
|
@@ -23,6 +24,7 @@ export interface Timeline {
|
|
|
23
24
|
trimIdle: Partial<IdleOptions> | false;
|
|
24
25
|
cursor?: CursorStyle;
|
|
25
26
|
voice?: Omit<VoiceConfig, "apiKey">;
|
|
27
|
+
music?: Omit<MusicConfig, "apiKey">;
|
|
26
28
|
};
|
|
27
29
|
actions: ActionRecord[];
|
|
28
30
|
zoomRegions: ZoomRegion[];
|
|
@@ -69,6 +71,7 @@ export interface ComposeInput {
|
|
|
69
71
|
trimIdle?: Partial<IdleOptions> | boolean;
|
|
70
72
|
cursor?: CursorStyle;
|
|
71
73
|
voice?: VoiceConfig;
|
|
74
|
+
music?: MusicInput;
|
|
72
75
|
}
|
|
73
76
|
export interface ComposeResult {
|
|
74
77
|
timeline: Timeline;
|
package/dist/compose.js
CHANGED
|
@@ -8,6 +8,7 @@ import path from "node:path";
|
|
|
8
8
|
import { deriveIdleRegions, sourceToOutputMs } from "./idle.js";
|
|
9
9
|
import { stageLayout } from "./layout.js";
|
|
10
10
|
import { buildMarks, placeCaptions, targetRects } from "./marks.js";
|
|
11
|
+
import { normalizeMusicConfig } from "./music.js";
|
|
11
12
|
import { buildCursorData, buildProject, DEFAULT_LOOK } from "./project.js";
|
|
12
13
|
import { deriveZoomRegions } from "./zoom.js";
|
|
13
14
|
export const TIMELINE_VERSION = 1;
|
|
@@ -90,6 +91,15 @@ export function compose(input, opts = {}) {
|
|
|
90
91
|
fs.writeFileSync(marksPath, JSON.stringify(marks, null, 1));
|
|
91
92
|
// Never persist secret apiKey into timeline.json.
|
|
92
93
|
const safeVoice = input.voice ? (({ apiKey: _k, ...rest }) => rest)(input.voice) : undefined;
|
|
94
|
+
const normMusic = normalizeMusicConfig(input.music);
|
|
95
|
+
const safeMusic = normMusic
|
|
96
|
+
? (({ apiKey: _k, ...rest }) => ({
|
|
97
|
+
...rest,
|
|
98
|
+
...(rest.src && !/^https?:\/\//i.test(rest.src) && !path.isAbsolute(rest.src)
|
|
99
|
+
? { src: path.resolve(input.baseDir ?? process.cwd(), rest.src) }
|
|
100
|
+
: {}),
|
|
101
|
+
}))(normMusic)
|
|
102
|
+
: undefined;
|
|
93
103
|
const timeline = {
|
|
94
104
|
version: TIMELINE_VERSION,
|
|
95
105
|
scenario: input.name,
|
|
@@ -110,6 +120,7 @@ export function compose(input, opts = {}) {
|
|
|
110
120
|
trimIdle: idleOpts ?? false,
|
|
111
121
|
...(input.cursor ? { cursor: input.cursor } : {}),
|
|
112
122
|
...(safeVoice ? { voice: safeVoice } : {}),
|
|
123
|
+
...(safeMusic ? { music: safeMusic } : {}),
|
|
113
124
|
},
|
|
114
125
|
actions: input.actions.map(roundAction),
|
|
115
126
|
zoomRegions,
|
|
@@ -191,5 +202,6 @@ export function rezoom(dir, overrides = {}) {
|
|
|
191
202
|
trimIdle: trimIdle ?? false,
|
|
192
203
|
cursor,
|
|
193
204
|
voice: tl.options?.voice,
|
|
205
|
+
music: tl.options?.music,
|
|
194
206
|
}, { keepProjectFrom: overrides.look ? undefined : projectPath });
|
|
195
207
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
export { type DryRunError, type DryRunOptions, type DryRunResult, type RecordOptions, type RecordResult, type Scenario, type ScenarioContext, defineScenario, dryRunScenario, recordScenario, resolveStorageState, } from "./record.ts";
|
|
3
3
|
export { type ActionOptions, applyZoomAnchor, type ArrowOptions, type BlurOptions, type ClickRippleOptions, DEFAULT_PACING, describeTarget, type HighlightOptions, type ImageOptions, type PacingOptions, type PressOptions, resolveTarget, type SayOptions, Scene, type SceneClock, type Target, type TargetSpec, type VoiceCueHandle, ZOOM_ATTRIBUTE, type ZoomOptions as SceneZoomOptions, } from "./scene.ts";
|
|
4
4
|
export { buildVoiceVtt, chunkVoiceCaptions, createVoiceSynthesizer, DEFAULT_VOICE_GAP_MS, DEFAULT_VOICE_PAD_MS, findWordTiming, formatDryRunVoiceSummary, formatVoiceSummary, lintVoiceCues, muxVoiceTrack, type SayDeliveryOptions, type SynthesizedCue, type VoiceConfig, type VoiceFinding, VOICE_PROVIDERS, type VoiceProviderName, type VoiceSynthesizer, } from "./voice.ts";
|
|
5
|
+
export { bucketMusicDurationMs, buildDuckingVolumeExpr, defaultMusicCacheDir, extractLyriaAudio, MUSIC_PROVIDERS, type MusicConfig, type MusicInput, type MusicProviderName, muxAudioTracks, type MuxAudioOptions, normalizeMusicConfig, type ResolvedMusicTrack, resolveMusicTrack, } from "./music.ts";
|
|
5
6
|
export { DEFAULT_ZOOM_OPTIONS, DEPTH_SCALES, deriveZoomRegions, depthForBox, normalizeDepth, type ZoomOptions } from "./zoom.ts";
|
|
6
7
|
export { DEFAULT_IDLE_OPTIONS, deriveIdleRegions, idleIntervals, type IdleOptions, sourceToOutputMs } from "./idle.ts";
|
|
7
8
|
export { arrowAnnotations, blurAnnotations, buildCursorData, buildProject, type BuildProjectOptions, captionAnnotations, DEFAULT_LOOK, formatKeycap, imageAnnotations, keycapAnnotations, type KeyHudOptions, type KeyHudPosition, keycapRect, type LookOptions, normalizeSamples, type OpenScreenProject, resolveImageDataUrl, type WatermarkOptions, type WatermarkPosition, writeProject, } from "./project.ts";
|
package/dist/index.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
export { defineScenario, dryRunScenario, recordScenario, resolveStorageState, } from "./record.js";
|
|
3
3
|
export { applyZoomAnchor, DEFAULT_PACING, describeTarget, resolveTarget, Scene, ZOOM_ATTRIBUTE, } from "./scene.js";
|
|
4
4
|
export { buildVoiceVtt, chunkVoiceCaptions, createVoiceSynthesizer, DEFAULT_VOICE_GAP_MS, DEFAULT_VOICE_PAD_MS, findWordTiming, formatDryRunVoiceSummary, formatVoiceSummary, lintVoiceCues, muxVoiceTrack, VOICE_PROVIDERS, } from "./voice.js";
|
|
5
|
+
export { bucketMusicDurationMs, buildDuckingVolumeExpr, defaultMusicCacheDir, extractLyriaAudio, MUSIC_PROVIDERS, muxAudioTracks, normalizeMusicConfig, resolveMusicTrack, } from "./music.js";
|
|
5
6
|
export { DEFAULT_ZOOM_OPTIONS, DEPTH_SCALES, deriveZoomRegions, depthForBox, normalizeDepth } from "./zoom.js";
|
|
6
7
|
export { DEFAULT_IDLE_OPTIONS, deriveIdleRegions, idleIntervals, sourceToOutputMs } from "./idle.js";
|
|
7
8
|
export { arrowAnnotations, blurAnnotations, buildCursorData, buildProject, captionAnnotations, DEFAULT_LOOK, formatKeycap, imageAnnotations, keycapAnnotations, keycapRect, normalizeSamples, resolveImageDataUrl, writeProject, } from "./project.js";
|
package/dist/mcp.js
CHANGED
|
@@ -15,6 +15,7 @@ import { readTimeline, rezoom } from "./compose.js";
|
|
|
15
15
|
import { checkFfmpeg, detectGpu, launchChromium } from "./env.js";
|
|
16
16
|
import { exportGif } from "./gif.js";
|
|
17
17
|
import { loadScenario } from "./load.js";
|
|
18
|
+
import { normalizeMusicConfig } from "./music.js";
|
|
18
19
|
import { dryRunScenario, recordScenario, resolveStorageState } from "./record.js";
|
|
19
20
|
import { renderProject, validateProject } from "./render.js";
|
|
20
21
|
import { extractFrame, findFramesheet, reviewSheet } from "./sheet.js";
|
|
@@ -248,6 +249,10 @@ export function createMcpServer() {
|
|
|
248
249
|
voiceProvider: z.enum(["edge", "openai", "elevenlabs", "gemini", "cartesia", "deepgram"]).optional().describe("Override voiceover TTS provider."),
|
|
249
250
|
voice: z.string().optional().describe("Override voiceover voice ID."),
|
|
250
251
|
noVoice: z.boolean().optional().describe("Disable voiceover synthesis for this run."),
|
|
252
|
+
music: z.string().optional().describe("Background music file path or HTTP(S) URL."),
|
|
253
|
+
musicProvider: z.enum(["elevenlabs", "gemini"]).optional().describe("AI background music provider (ElevenLabs Music or Google Lyria)."),
|
|
254
|
+
musicPrompt: z.string().optional().describe("Natural-language prompt for AI background music."),
|
|
255
|
+
noMusic: z.boolean().optional().describe("Disable background music for this run."),
|
|
251
256
|
}),
|
|
252
257
|
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
|
|
253
258
|
}, async (args, ctx) => {
|
|
@@ -271,6 +276,33 @@ export function createMcpServer() {
|
|
|
271
276
|
vc.enabled = false;
|
|
272
277
|
overrides.voice = vc;
|
|
273
278
|
}
|
|
279
|
+
const baseMusic = normalizeMusicConfig(scenario.music);
|
|
280
|
+
let effectiveMusic = baseMusic?.src && !/^https?:\/\//i.test(baseMusic.src) && !path.isAbsolute(baseMusic.src)
|
|
281
|
+
? { ...baseMusic, src: path.resolve(path.dirname(file), baseMusic.src) }
|
|
282
|
+
: baseMusic;
|
|
283
|
+
if (args.music || args.musicProvider || args.musicPrompt || args.noMusic) {
|
|
284
|
+
const mc = { ...effectiveMusic };
|
|
285
|
+
if (args.noMusic)
|
|
286
|
+
mc.enabled = false;
|
|
287
|
+
if (args.music) {
|
|
288
|
+
mc.src = /^https?:\/\//i.test(args.music) ? args.music : path.resolve(args.music);
|
|
289
|
+
delete mc.provider;
|
|
290
|
+
delete mc.prompt;
|
|
291
|
+
mc.enabled = true;
|
|
292
|
+
}
|
|
293
|
+
if (args.musicProvider) {
|
|
294
|
+
mc.provider = args.musicProvider;
|
|
295
|
+
delete mc.src;
|
|
296
|
+
mc.enabled = true;
|
|
297
|
+
}
|
|
298
|
+
if (args.musicPrompt) {
|
|
299
|
+
mc.prompt = args.musicPrompt;
|
|
300
|
+
delete mc.src;
|
|
301
|
+
mc.enabled = true;
|
|
302
|
+
}
|
|
303
|
+
effectiveMusic = mc;
|
|
304
|
+
overrides.music = mc;
|
|
305
|
+
}
|
|
274
306
|
const outDir = path.resolve(args.outDir ?? path.join("out", scenario.name));
|
|
275
307
|
progress(5, `Recording "${scenario.name}"...`);
|
|
276
308
|
const rec = await recordScenario(scenario, {
|
|
@@ -303,6 +335,7 @@ export function createMcpServer() {
|
|
|
303
335
|
frameRate: args.fps,
|
|
304
336
|
quality: args.quality,
|
|
305
337
|
cursor: scenario.cursor,
|
|
338
|
+
...(effectiveMusic ? { music: effectiveMusic } : {}),
|
|
306
339
|
log: logStderr,
|
|
307
340
|
onProgress: (p) => progress(15 + p * 0.75, `Rendering ${Math.round(p)}%`),
|
|
308
341
|
});
|
|
@@ -314,6 +347,8 @@ export function createMcpServer() {
|
|
|
314
347
|
summary.renderMs = rendered.renderMs;
|
|
315
348
|
if (rendered.audioMuxed)
|
|
316
349
|
summary.audioMuxed = true;
|
|
350
|
+
if (rendered.musicMuxed)
|
|
351
|
+
summary.musicMuxed = true;
|
|
317
352
|
if (rendered.vttPath)
|
|
318
353
|
summary.vttPath = rendered.vttPath;
|
|
319
354
|
if (rec.timeline.voiceCues?.length) {
|
package/dist/music.d.ts
ADDED
|
@@ -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/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
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). */
|
package/dist/render.js
CHANGED
|
@@ -7,9 +7,11 @@
|
|
|
7
7
|
import fs from "node:fs";
|
|
8
8
|
import path from "node:path";
|
|
9
9
|
import { DemoreelError, launchChromium, renderArgs } from "./env.js";
|
|
10
|
+
import { muxAudioTracks, normalizeMusicConfig, resolveMusicTrack } from "./music.js";
|
|
10
11
|
import { openscreenProjectApi, rendererDir } from "./openscreen.js";
|
|
11
12
|
import { sendFile, serveStatic } from "./server.js";
|
|
12
|
-
import {
|
|
13
|
+
import { probeDuration } from "./sheet.js";
|
|
14
|
+
import { lintVoiceCues } from "./voice.js";
|
|
13
15
|
function readProject(projectPath) {
|
|
14
16
|
if (!fs.existsSync(projectPath))
|
|
15
17
|
throw new DemoreelError(`project not found: ${projectPath}`);
|
|
@@ -101,31 +103,65 @@ export async function renderProject(opts) {
|
|
|
101
103
|
const warnings = [...(result.warnings ?? [])];
|
|
102
104
|
let bytes = result.bytes;
|
|
103
105
|
let audioMuxed = false;
|
|
106
|
+
let musicMuxed = false;
|
|
104
107
|
let vttPath;
|
|
105
|
-
//
|
|
108
|
+
// Mux voiceCues and/or background music into the MP4 (stream-copying video via `-c:v copy`).
|
|
106
109
|
const projectDir = path.dirname(projectPath);
|
|
107
110
|
const timelinePath = path.join(projectDir, "timeline.json");
|
|
111
|
+
let tl = null;
|
|
108
112
|
if (fs.existsSync(timelinePath)) {
|
|
109
113
|
try {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
114
|
+
tl = JSON.parse(fs.readFileSync(timelinePath, "utf8"));
|
|
115
|
+
}
|
|
116
|
+
catch (e) {
|
|
117
|
+
warnings.push(`timeline.json parse skipped: ${e.message}`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
const voiceCues = tl?.voiceCues ?? [];
|
|
121
|
+
const baseMusic = normalizeMusicConfig(tl?.options?.music);
|
|
122
|
+
const overrideMusic = normalizeMusicConfig(opts.music);
|
|
123
|
+
const effectiveMusic = overrideMusic || baseMusic ? { ...baseMusic, ...overrideMusic } : undefined;
|
|
124
|
+
const wantsMusic = Boolean(effectiveMusic &&
|
|
125
|
+
effectiveMusic.enabled !== false &&
|
|
126
|
+
(effectiveMusic.src || (effectiveMusic.provider && effectiveMusic.prompt)));
|
|
127
|
+
if (voiceCues.length > 0 || wantsMusic) {
|
|
128
|
+
try {
|
|
129
|
+
const outDurMs = tl?.outputDurationMs && tl.outputDurationMs > 0
|
|
130
|
+
? tl.outputDurationMs
|
|
131
|
+
: Math.round((await probeDuration(outputPath)) * 1000);
|
|
132
|
+
let musicPath;
|
|
133
|
+
if (wantsMusic && effectiveMusic) {
|
|
134
|
+
const resolved = await resolveMusicTrack(effectiveMusic, {
|
|
135
|
+
durationMs: outDurMs,
|
|
136
|
+
baseDir: projectDir,
|
|
137
|
+
log,
|
|
116
138
|
});
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
139
|
+
musicPath = resolved.filePath;
|
|
140
|
+
}
|
|
141
|
+
const mux = await muxAudioTracks(outputPath, {
|
|
142
|
+
voiceCues,
|
|
143
|
+
musicPath,
|
|
144
|
+
music: effectiveMusic,
|
|
145
|
+
outputDurationMs: outDurMs,
|
|
146
|
+
baseDir: projectDir,
|
|
147
|
+
trims: tl?.trimRegions,
|
|
148
|
+
speeds: tl?.speedRegions,
|
|
149
|
+
writeVtt: tl?.options?.voice?.captions !== "off",
|
|
150
|
+
});
|
|
151
|
+
audioMuxed = mux.audioMuxed;
|
|
152
|
+
musicMuxed = mux.musicMuxed;
|
|
153
|
+
vttPath = mux.vttPath;
|
|
154
|
+
if (audioMuxed && fs.existsSync(outputPath)) {
|
|
155
|
+
bytes = fs.statSync(outputPath).size;
|
|
156
|
+
}
|
|
157
|
+
if (voiceCues.length > 0) {
|
|
158
|
+
const voiceFindings = lintVoiceCues(voiceCues, outDurMs, tl?.trimRegions, tl?.speedRegions);
|
|
123
159
|
for (const f of voiceFindings)
|
|
124
160
|
warnings.push(`[voice:${f.severity}] ${f.message}`);
|
|
125
161
|
}
|
|
126
162
|
}
|
|
127
163
|
catch (e) {
|
|
128
|
-
warnings.push(`
|
|
164
|
+
warnings.push(`audio mux skipped: ${e.message}`);
|
|
129
165
|
}
|
|
130
166
|
}
|
|
131
167
|
return {
|
|
@@ -140,6 +176,7 @@ export async function renderProject(opts) {
|
|
|
140
176
|
setupMs: tReady - t0,
|
|
141
177
|
totalMs: Date.now() - t0,
|
|
142
178
|
...(audioMuxed ? { audioMuxed } : {}),
|
|
179
|
+
...(musicMuxed ? { musicMuxed } : {}),
|
|
143
180
|
...(vttPath ? { vttPath } : {}),
|
|
144
181
|
};
|
|
145
182
|
}
|
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.
|
|
4
|
+
"version": "0.8.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": [
|
package/skills/demoreel/SKILL.md
CHANGED
|
@@ -85,6 +85,7 @@ export default defineScenario({
|
|
|
85
85
|
- 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"` draws balanced word-chunked captions on-video).
|
|
86
86
|
- 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.
|
|
87
87
|
- 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.
|
|
88
|
+
- **Background music (`music`)**: accepts a local audio file (`"./bed.mp3"`), cached `https://` URL, or AI-generated instrumental track (`{ provider: "elevenlabs" | "gemini", prompt: "minimal upbeat lo-fi tech bed", volume: 0.18, duck: 0.3, fadeInMs: 800, fadeOutMs: 1500 }`, SHA-256 cached on disk). Automatically loops/trims to the rendered video length, fades in/out, and smoothly auto-ducks under `scene.say()` voiceover cues via `-c:v copy` (CLI/MCP overrides: `--music`, `--music-provider`, `--music-prompt`, `--no-music`).
|
|
88
89
|
- **AI / streaming apps**: mock only the LLM fetch/SSE boundary via `scene.page.evaluate(...)`
|
|
89
90
|
or `page.route(...)` while keeping real client-side/WASM tools live — deterministic, fast,
|
|
90
91
|
zero API cost, and authentic tool results.
|