@canvakit/showreel 0.0.0-stage → 0.2.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/LICENSE +105 -0
- package/README.md +131 -2
- package/dist/index.d.ts +998 -0
- package/dist/index.mjs +1844 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +69 -3
- package/showreel.config.example.jsonc +78 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1844 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { defaultRegistry, designkitExtension, DesignSourceRegistry } from '@canvakit/designkit';
|
|
3
|
+
export { DesignSourceRegistry, createDefaultRegistry, defaultRegistry } from '@canvakit/designkit';
|
|
4
|
+
import { promises, existsSync, readdirSync, mkdtempSync, writeFileSync, readFileSync, mkdirSync } from 'fs';
|
|
5
|
+
import * as path from 'path';
|
|
6
|
+
import { join, isAbsolute, resolve } from 'path';
|
|
7
|
+
import { readText, parseTemplate, extractTopLevelReferences, render } from '@canvakit/core';
|
|
8
|
+
import { designFrontmatterSchema } from '@designkit-sh/core';
|
|
9
|
+
import { spawn } from 'child_process';
|
|
10
|
+
import { homedir, tmpdir } from 'os';
|
|
11
|
+
import { performance } from 'perf_hooks';
|
|
12
|
+
import puppeteer from 'puppeteer-core';
|
|
13
|
+
import { createHash, randomUUID } from 'crypto';
|
|
14
|
+
import { stat, mkdtemp, copyFile, mkdir, rename } from 'fs/promises';
|
|
15
|
+
import { exportHtml, localChromeRenderer } from '@canvakit/export';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @canvakit/showreel v0.1.0
|
|
19
|
+
* Generate a pitch showreel from a live web app — capture, promo scenes,
|
|
20
|
+
* narration, music, ffmpeg assembly + PDF deck. Scaffold; pipeline stubs.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
var ViewportSchema = z.object({
|
|
24
|
+
width: z.number().int().positive().default(1920),
|
|
25
|
+
height: z.number().int().positive().default(1080),
|
|
26
|
+
/** device pixel ratio — 2 for retina-crisp capture */
|
|
27
|
+
dpr: z.number().positive().default(2)
|
|
28
|
+
});
|
|
29
|
+
var TargetSchema = z.object({
|
|
30
|
+
/** base URL of the running app, e.g. http://localhost:5173 */
|
|
31
|
+
url: z.string().url(),
|
|
32
|
+
viewport: ViewportSchema.default({ width: 1920, height: 1080, dpr: 2 }),
|
|
33
|
+
/**
|
|
34
|
+
* Path to a Chrome/Chromium executable, or an `env:VAR` reference
|
|
35
|
+
* resolved at runtime. puppeteer-core does not ship a browser.
|
|
36
|
+
*/
|
|
37
|
+
chromePath: z.string().default("env:CHROME_PATH"),
|
|
38
|
+
/**
|
|
39
|
+
* A CSS selector that becomes true once the app is interactive.
|
|
40
|
+
* Used as the hard fallback for every `waitFor` (readiness gate),
|
|
41
|
+
* so captures never start against a half-mounted DOM.
|
|
42
|
+
*/
|
|
43
|
+
readyFlag: z.string().default("body[data-ready=true]")
|
|
44
|
+
});
|
|
45
|
+
var BrandFontSchema = z.object({
|
|
46
|
+
family: z.string().min(1),
|
|
47
|
+
weights: z.array(z.number().int().positive()).optional(),
|
|
48
|
+
href: z.string().optional()
|
|
49
|
+
});
|
|
50
|
+
var BrandSchema = z.object({
|
|
51
|
+
/** a named designkit preset (e.g. "naia") */
|
|
52
|
+
preset: z.string().optional(),
|
|
53
|
+
/** token overrides merged over the preset (accent color, etc.) */
|
|
54
|
+
tokens: z.record(z.string(), z.string()).default({}),
|
|
55
|
+
/**
|
|
56
|
+
* Explicit font faces the brand prescribes — shape aligned with
|
|
57
|
+
* `@canvakit/designkit`'s `DesignArtifact.fonts`. When present, both the
|
|
58
|
+
* agentic brief and the html-still renderer treat these as the fonts to
|
|
59
|
+
* use (see `renderPrompt` in showreel-agentic and `renderSceneHtml`
|
|
60
|
+
* below) instead of leaving font choice to the scene author.
|
|
61
|
+
*/
|
|
62
|
+
fonts: z.array(BrandFontSchema).optional()
|
|
63
|
+
});
|
|
64
|
+
var NavigateStepSchema = z.object({
|
|
65
|
+
action: z.literal("navigate"),
|
|
66
|
+
/** path appended to target.url (e.g. "/chat") */
|
|
67
|
+
path: z.string()
|
|
68
|
+
});
|
|
69
|
+
var TypeStepSchema = z.object({
|
|
70
|
+
action: z.literal("type"),
|
|
71
|
+
selector: z.string(),
|
|
72
|
+
text: z.string(),
|
|
73
|
+
/** ms between keystrokes — humanizes the demo, defaults to instant */
|
|
74
|
+
delay: z.number().int().nonnegative().default(0)
|
|
75
|
+
});
|
|
76
|
+
var ClickStepSchema = z.object({
|
|
77
|
+
action: z.literal("click"),
|
|
78
|
+
selector: z.string()
|
|
79
|
+
});
|
|
80
|
+
var WaitForStepSchema = z.object({
|
|
81
|
+
action: z.literal("waitFor"),
|
|
82
|
+
/** selector to await; resolution timestamp becomes the item's endMs */
|
|
83
|
+
selector: z.string(),
|
|
84
|
+
/** hard cap in ms — on expiry the step fails loudly, never silently */
|
|
85
|
+
timeout: z.number().int().positive().default(15e3)
|
|
86
|
+
});
|
|
87
|
+
var CaptureStepSchema = z.discriminatedUnion("action", [
|
|
88
|
+
NavigateStepSchema,
|
|
89
|
+
TypeStepSchema,
|
|
90
|
+
ClickStepSchema,
|
|
91
|
+
WaitForStepSchema
|
|
92
|
+
]);
|
|
93
|
+
var narrationField = z.string().optional();
|
|
94
|
+
var SceneItemSchema = z.object({
|
|
95
|
+
kind: z.literal("scene"),
|
|
96
|
+
id: z.string().min(1),
|
|
97
|
+
/**
|
|
98
|
+
* A scene template ref, resolved via `SceneTemplateRegistry` /
|
|
99
|
+
* `resolveSceneTemplate` (`../templates/registry.js`) into a canvakit-core
|
|
100
|
+
* canva rendered by `renderCanva`. Accepts a scheme-prefixed ref
|
|
101
|
+
* (`"builtin:hero-split"`, `"ws:_scenes/foo.md"`) or a bare name
|
|
102
|
+
* (`"hero-split"`), which falls back to `builtin:<name>` — back-compat
|
|
103
|
+
* with configs authored before the registry existed.
|
|
104
|
+
*/
|
|
105
|
+
template: z.string().min(1),
|
|
106
|
+
/** template data (title, subtitle, …) */
|
|
107
|
+
data: z.record(z.string(), z.unknown()).default({}),
|
|
108
|
+
/** declared duration in ms — a scene lasts exactly this long */
|
|
109
|
+
duration: z.number().int().positive(),
|
|
110
|
+
narration: narrationField
|
|
111
|
+
});
|
|
112
|
+
var RecordSchema = z.object({
|
|
113
|
+
/** target capture framerate; assembly rescales to CFR */
|
|
114
|
+
fps: z.number().int().positive().default(30),
|
|
115
|
+
/** safety ceiling in ms — capture stops even if waitFor never resolves */
|
|
116
|
+
maxDuration: z.number().int().positive().default(2e4)
|
|
117
|
+
});
|
|
118
|
+
var ScreenshotSchema = z.object({
|
|
119
|
+
/** capture a still the moment these selectors/step-ids resolve */
|
|
120
|
+
at: z.array(z.string()).default([])
|
|
121
|
+
});
|
|
122
|
+
var CaptureItemSchema = z.object({
|
|
123
|
+
kind: z.literal("capture"),
|
|
124
|
+
id: z.string().min(1),
|
|
125
|
+
record: RecordSchema.default({ fps: 30, maxDuration: 2e4 }),
|
|
126
|
+
/** scripted steps; the item's endMs is when the last waitFor resolves */
|
|
127
|
+
steps: z.array(CaptureStepSchema).min(1),
|
|
128
|
+
screenshot: ScreenshotSchema.optional(),
|
|
129
|
+
narration: narrationField
|
|
130
|
+
});
|
|
131
|
+
var ClipItemSchema = z.object({
|
|
132
|
+
kind: z.literal("clip"),
|
|
133
|
+
id: z.string().min(1),
|
|
134
|
+
/** source video, absolute or relative to the config file's directory */
|
|
135
|
+
src: z.string().min(1),
|
|
136
|
+
/** optional window within `src`; each bound defaults to the full measured span */
|
|
137
|
+
trim: z.object({
|
|
138
|
+
startMs: z.number().int().nonnegative().optional(),
|
|
139
|
+
endMs: z.number().int().positive().optional()
|
|
140
|
+
}).optional(),
|
|
141
|
+
fit: z.enum(["cover", "contain"]).default("cover"),
|
|
142
|
+
narration: narrationField
|
|
143
|
+
});
|
|
144
|
+
var TimelineItemSchema = z.discriminatedUnion("kind", [
|
|
145
|
+
SceneItemSchema,
|
|
146
|
+
CaptureItemSchema,
|
|
147
|
+
ClipItemSchema
|
|
148
|
+
]);
|
|
149
|
+
var VoiceSchema = z.object({
|
|
150
|
+
provider: z.literal("elevenlabs").default("elevenlabs"),
|
|
151
|
+
voiceId: z.string().min(1),
|
|
152
|
+
model: z.string().default("eleven_multilingual_v2")
|
|
153
|
+
});
|
|
154
|
+
var MusicSchema = z.object({
|
|
155
|
+
/** ElevenLabs Music API prompt */
|
|
156
|
+
prompt: z.string().min(1),
|
|
157
|
+
/** ducking depth in dB while narration plays (negative = quieter) */
|
|
158
|
+
duckDb: z.number().default(-14),
|
|
159
|
+
/** fade in/out in ms */
|
|
160
|
+
fade: z.number().int().nonnegative().default(2e3)
|
|
161
|
+
});
|
|
162
|
+
var OutputSchema = z.object({
|
|
163
|
+
dir: z.string().default("./out"),
|
|
164
|
+
video: z.string().default("showreel.mp4"),
|
|
165
|
+
deck: z.string().default("deck.pdf"),
|
|
166
|
+
/** output resolution label, e.g. "1080p" */
|
|
167
|
+
res: z.string().default("1080p"),
|
|
168
|
+
/** seed for any stochastic step — reproducibility knob */
|
|
169
|
+
seed: z.number().int().nonnegative().default(42)
|
|
170
|
+
});
|
|
171
|
+
var ShowreelConfigSchema = z.object({
|
|
172
|
+
$schema: z.string().optional(),
|
|
173
|
+
target: TargetSchema,
|
|
174
|
+
/**
|
|
175
|
+
* Either an inline `Brand` object, or a design ref string (`"dk:heritage"`,
|
|
176
|
+
* `"kit:naia"`, `"ws:_design/foo.md"`) resolved via
|
|
177
|
+
* `@canvakit/designkit`'s `DesignSourceRegistry` — see `resolveBrand`
|
|
178
|
+
* in `../brand/resolve.js`. `runShowreelWith` resolves this once,
|
|
179
|
+
* up front, before any stage consumes it.
|
|
180
|
+
*/
|
|
181
|
+
brand: z.union([BrandSchema, z.string().min(1)]).default({ tokens: {} }),
|
|
182
|
+
timeline: z.array(TimelineItemSchema).min(1),
|
|
183
|
+
voice: VoiceSchema,
|
|
184
|
+
music: MusicSchema,
|
|
185
|
+
output: OutputSchema.default({
|
|
186
|
+
dir: "./out",
|
|
187
|
+
video: "showreel.mp4",
|
|
188
|
+
deck: "deck.pdf",
|
|
189
|
+
res: "1080p",
|
|
190
|
+
seed: 42
|
|
191
|
+
})
|
|
192
|
+
}).superRefine((cfg, ctx) => {
|
|
193
|
+
const seen = /* @__PURE__ */ new Set();
|
|
194
|
+
for (const [i, item] of cfg.timeline.entries()) {
|
|
195
|
+
if (seen.has(item.id)) {
|
|
196
|
+
ctx.addIssue({
|
|
197
|
+
code: "custom",
|
|
198
|
+
message: `duplicate timeline id "${item.id}" \u2014 ids must be unique (they key narration + the measured timeline)`,
|
|
199
|
+
path: ["timeline", i, "id"]
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
seen.add(item.id);
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
var ShowreelConfigError = class extends Error {
|
|
206
|
+
constructor(message, issues) {
|
|
207
|
+
super(message);
|
|
208
|
+
this.issues = issues;
|
|
209
|
+
this.name = "ShowreelConfigError";
|
|
210
|
+
}
|
|
211
|
+
issues;
|
|
212
|
+
};
|
|
213
|
+
function validateConfig(input) {
|
|
214
|
+
const result = ShowreelConfigSchema.safeParse(input);
|
|
215
|
+
if (!result.success) {
|
|
216
|
+
const lines = result.error.issues.map((issue) => {
|
|
217
|
+
const path2 = issue.path.length ? issue.path.join(".") : "(root)";
|
|
218
|
+
return ` \u2022 ${path2}: ${issue.message}`;
|
|
219
|
+
});
|
|
220
|
+
throw new ShowreelConfigError(
|
|
221
|
+
`invalid showreel config:
|
|
222
|
+
${lines.join("\n")}`,
|
|
223
|
+
result.error.issues
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
return result.data;
|
|
227
|
+
}
|
|
228
|
+
async function resolveBrand(input, ctx) {
|
|
229
|
+
if (typeof input !== "string") return input;
|
|
230
|
+
const artifact = await defaultRegistry.resolve(input, ctx);
|
|
231
|
+
if (!artifact) {
|
|
232
|
+
throw new Error(
|
|
233
|
+
`brand ref "${input}" unresolved \u2014 no design source matched, or resolution failed (see prior console.warn for the reason). Use a scheme prefix (dk:/ws:/kit:) that resolves, or pass an inline Brand object instead.`
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
const brand = { preset: input, tokens: artifact.tokens.colors };
|
|
237
|
+
if (artifact.fonts) brand.fonts = artifact.fonts;
|
|
238
|
+
return brand;
|
|
239
|
+
}
|
|
240
|
+
function entryType(isDirectory) {
|
|
241
|
+
return isDirectory ? "directory" : "file";
|
|
242
|
+
}
|
|
243
|
+
function createLocalFs(baseDir) {
|
|
244
|
+
const abs = path.resolve(baseDir);
|
|
245
|
+
const resolve3 = (p) => path.resolve(abs, p.replace(/^\/+/, ""));
|
|
246
|
+
return {
|
|
247
|
+
async readFile(p) {
|
|
248
|
+
return promises.readFile(resolve3(p));
|
|
249
|
+
},
|
|
250
|
+
async writeFile(p, contents) {
|
|
251
|
+
const full = resolve3(p);
|
|
252
|
+
await promises.mkdir(path.dirname(full), { recursive: true });
|
|
253
|
+
await promises.writeFile(full, contents);
|
|
254
|
+
},
|
|
255
|
+
async exists(p) {
|
|
256
|
+
try {
|
|
257
|
+
await promises.access(resolve3(p));
|
|
258
|
+
return true;
|
|
259
|
+
} catch {
|
|
260
|
+
return false;
|
|
261
|
+
}
|
|
262
|
+
},
|
|
263
|
+
async readdir(p, opts) {
|
|
264
|
+
const root = resolve3(p);
|
|
265
|
+
try {
|
|
266
|
+
const found = await promises.readdir(root, {
|
|
267
|
+
recursive: opts?.recursive === true,
|
|
268
|
+
withFileTypes: true
|
|
269
|
+
});
|
|
270
|
+
return found.map((e) => ({
|
|
271
|
+
name: opts?.recursive === true ? path.relative(root, path.join(e.parentPath, e.name)).split(path.sep).join("/") : e.name,
|
|
272
|
+
type: entryType(e.isDirectory())
|
|
273
|
+
}));
|
|
274
|
+
} catch {
|
|
275
|
+
return [];
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// src/templates/builtin-scenes.generated.ts
|
|
282
|
+
var BUILTIN_SCENES = {
|
|
283
|
+
"bullets": { source: '---\ntemplate: true\n---\n<!doctype html>\n<html>\n <head>\n <meta charset="utf-8" />\n <style>\n * { box-sizing: border-box; }\n html, body {\n margin: 0;\n padding: 0;\n width: 100vw;\n height: 100vh;\n overflow: hidden;\n font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;\n background: #0a0a0f;\n color: #e6e6f0;\n }\n .bullets { width: 100%; height: 100%; display: flex; flex-direction: column; justify-content: center; padding: 6vw; }\n .bullets h1 { font-size: 3.6vw; font-weight: 700; margin: 0 0 3vw; color: {{$design.colors.accent}}; }\n .bullets ul { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 1.6vw; }\n .bullets li { font-size: 2.2vw; font-weight: 500; padding-left: 2vw; position: relative; }\n .bullets li::before { content: "\u2014"; position: absolute; left: 0; color: {{$design.colors.accent}}; }\n </style>\n </head>\n <body>\n <div class="bullets">\n <h1>{{title}}</h1>\n <ul>\n {{#bullets}}<li>{{.}}</li>{{/bullets}}\n </ul>\n </div>\n </body>\n</html>\n', slots: ["title", "bullets"] },
|
|
284
|
+
"chapter": { source: '---\ntemplate: true\n---\n<!doctype html>\n<html>\n <head>\n <meta charset="utf-8" />\n <style>\n * { box-sizing: border-box; }\n html, body {\n margin: 0;\n padding: 0;\n width: 100vw;\n height: 100vh;\n overflow: hidden;\n font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;\n background: #0a0a0f;\n color: #e6e6f0;\n }\n .chapter { width: 100%; height: 100%; display: flex; flex-direction: column; align-items: flex-start; justify-content: center; padding: 6vw; }\n .chapter__index { font-size: 2vw; font-weight: 700; color: {{$design.colors.accent}}; margin: 0 0 1vw; letter-spacing: 0.1em; }\n .chapter__kicker { font-size: 1.6vw; font-weight: 600; opacity: 0.7; margin: 0 0 0.6vw; text-transform: uppercase; letter-spacing: 0.08em; }\n .chapter__title { font-size: 5vw; font-weight: 800; margin: 0; }\n </style>\n </head>\n <body>\n <div class="chapter">\n <p class="chapter__index">{{index}}</p>\n {{#kicker}}<p class="chapter__kicker">{{kicker}}</p>{{/kicker}}\n <h1 class="chapter__title">{{title}}</h1>\n </div>\n </body>\n</html>\n', slots: ["index", "kicker", "title"] },
|
|
285
|
+
"code": { source: '---\ntemplate: true\n---\n<!doctype html>\n<html>\n <head>\n <meta charset="utf-8" />\n <style>\n * { box-sizing: border-box; }\n html, body {\n margin: 0;\n padding: 0;\n width: 100vw;\n height: 100vh;\n overflow: hidden;\n font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;\n background: #0a0a0f;\n color: #e6e6f0;\n }\n .code { width: 100%; height: 100%; display: flex; flex-direction: column; justify-content: center; padding: 5vw; gap: 2vw; }\n .code__header { display: flex; align-items: baseline; gap: 1.2vw; }\n .code__title { font-size: 2.4vw; font-weight: 700; margin: 0; }\n .code__lang { font-size: 1.3vw; font-weight: 600; color: {{$design.colors.accent}}; text-transform: uppercase; letter-spacing: 0.08em; }\n .code__card { background: #14141c; border: 1px solid rgba(230, 230, 240, 0.12); border-radius: 1vw; padding: 2.4vw; overflow: hidden; }\n .code__card pre { margin: 0; font-family: "SFMono-Regular", Menlo, Consolas, monospace; font-size: 1.6vw; line-height: 1.5; white-space: pre-wrap; word-break: break-word; }\n </style>\n </head>\n <body>\n <div class="code">\n <div class="code__header">\n <h1 class="code__title">{{title}}</h1>\n {{#lang}}<span class="code__lang">{{lang}}</span>{{/lang}}\n </div>\n <div class="code__card"><pre>{{code}}</pre></div>\n </div>\n </body>\n</html>\n', slots: ["title", "lang", "code"] },
|
|
286
|
+
"comparison": { source: '---\ntemplate: true\n---\n<!doctype html>\n<html>\n <head>\n <meta charset="utf-8" />\n <style>\n * { box-sizing: border-box; }\n html, body {\n margin: 0;\n padding: 0;\n width: 100vw;\n height: 100vh;\n overflow: hidden;\n font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;\n background: #0a0a0f;\n color: #e6e6f0;\n }\n .comparison { width: 100%; height: 100%; display: flex; flex-direction: column; padding: 4vw; gap: 2vw; }\n .comparison h1 { font-size: 3vw; font-weight: 700; margin: 0; text-align: center; }\n .comparison__row { flex: 1; display: flex; gap: 2vw; }\n .comparison__col { flex: 1; display: flex; flex-direction: column; padding: 2.4vw; border-radius: 1vw; background: #14141c; }\n .comparison__col--right { border: 1px solid {{$design.colors.accent}}; }\n .comparison__col h2 { font-size: 1.8vw; font-weight: 700; margin: 0 0 1.4vw; opacity: 0.8; }\n .comparison__col p { font-size: 1.8vw; font-weight: 500; line-height: 1.4; margin: 0; }\n </style>\n </head>\n <body>\n <div class="comparison">\n <h1>{{title}}</h1>\n <div class="comparison__row">\n <div class="comparison__col">\n <h2>{{leftTitle}}</h2>\n <p>{{left}}</p>\n </div>\n <div class="comparison__col comparison__col--right">\n <h2>{{rightTitle}}</h2>\n <p>{{right}}</p>\n </div>\n </div>\n </div>\n </body>\n</html>\n', slots: ["title", "leftTitle", "left", "rightTitle", "right"] },
|
|
287
|
+
"cta-card": { source: '---\ntemplate: true\naliases: [cta]\n---\n<!doctype html>\n<html>\n <head>\n <meta charset="utf-8" />\n <style>\n * { box-sizing: border-box; }\n html, body {\n margin: 0;\n padding: 0;\n width: 100vw;\n height: 100vh;\n overflow: hidden;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;\n }\n .cta-card { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; background: #0a0a0f; }\n .cta-card__box { text-align: center; color: #ffffff; }\n .cta-card h1 { font-size: 5vw; font-weight: 700; margin: 0 0 1.5vw; }\n .cta-card__cta { display: inline-block; padding: 1vw 3vw; border-radius: 999px; background: {{$design.colors.accent}}; font-size: 2vw; font-weight: 600; }\n </style>\n </head>\n <body>\n <div class="cta-card">\n <div class="cta-card__box">\n <h1>{{title}}</h1>\n {{#cta}}<div class="cta-card__cta">{{cta}}</div>{{/cta}}\n </div>\n </div>\n </body>\n</html>\n', slots: ["title", "cta"], aliases: ["cta"] },
|
|
288
|
+
"hero-split": { source: '---\ntemplate: true\naliases: [hero]\n---\n<!doctype html>\n<html>\n <head>\n <meta charset="utf-8" />\n <style>\n * { box-sizing: border-box; }\n html, body {\n margin: 0;\n padding: 0;\n width: 100vw;\n height: 100vh;\n overflow: hidden;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;\n }\n .hero-split { display: flex; width: 100%; height: 100%; }\n .hero-split__panel { flex: 1; display: flex; align-items: center; justify-content: center; padding: 4vw; }\n .hero-split__panel--accent { background: {{$design.colors.accent}}; color: #ffffff; }\n .hero-split__panel--dark { background: #0a0a0f; color: #e6e6f0; }\n .hero-split h1 { font-size: 4vw; font-weight: 700; margin: 0; }\n .hero-split p { font-size: 2vw; margin: 0; }\n </style>\n </head>\n <body>\n <div class="hero-split">\n <div class="hero-split__panel hero-split__panel--accent"><h1>{{title}}</h1></div>\n <div class="hero-split__panel hero-split__panel--dark"><p>{{subtitle}}</p></div>\n </div>\n </body>\n</html>\n', slots: ["title", "subtitle"], aliases: ["hero"] },
|
|
289
|
+
"quote": { source: '---\ntemplate: true\n---\n<!doctype html>\n<html>\n <head>\n <meta charset="utf-8" />\n <style>\n * { box-sizing: border-box; }\n html, body {\n margin: 0;\n padding: 0;\n width: 100vw;\n height: 100vh;\n overflow: hidden;\n font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;\n background: #0a0a0f;\n color: #e6e6f0;\n }\n .quote { width: 100%; height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; padding: 6vw; }\n .quote__mark { font-size: 6vw; color: {{$design.colors.accent}}; line-height: 1; margin: 0 0 1vw; }\n .quote__text { font-size: 3.2vw; font-weight: 600; line-height: 1.3; margin: 0; max-width: 70vw; }\n .quote__author { font-size: 1.8vw; font-weight: 700; margin: 2.5vw 0 0; }\n .quote__role { font-size: 1.4vw; opacity: 0.7; margin: 0.4vw 0 0; }\n </style>\n </head>\n <body>\n <div class="quote">\n <p class="quote__mark">“</p>\n <p class="quote__text">{{quote}}</p>\n <p class="quote__author">{{author}}</p>\n {{#role}}<p class="quote__role">{{role}}</p>{{/role}}\n </div>\n </body>\n</html>\n', slots: ["quote", "author", "role"] },
|
|
290
|
+
"stat": { source: '---\ntemplate: true\n---\n<!doctype html>\n<html>\n <head>\n <meta charset="utf-8" />\n <style>\n * { box-sizing: border-box; }\n html, body {\n margin: 0;\n padding: 0;\n width: 100vw;\n height: 100vh;\n overflow: hidden;\n font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;\n background: #0a0a0f;\n color: #e6e6f0;\n }\n .stat { width: 100%; height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; }\n .stat__value { font-size: 12vw; font-weight: 800; line-height: 1; margin: 0; color: {{$design.colors.accent}}; }\n .stat__label { font-size: 2.4vw; font-weight: 600; margin: 1.5vw 0 0; letter-spacing: 0.02em; }\n .stat__caption { font-size: 1.4vw; opacity: 0.7; margin: 1vw 0 0; }\n </style>\n </head>\n <body>\n <div class="stat">\n <p class="stat__value">{{value}}</p>\n <p class="stat__label">{{label}}</p>\n {{#caption}}<p class="stat__caption">{{caption}}</p>{{/caption}}\n </div>\n </body>\n</html>\n', slots: ["value", "label", "caption"] }
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
// src/templates/registry.ts
|
|
294
|
+
var SceneTemplateRegistry = class {
|
|
295
|
+
#sources = /* @__PURE__ */ new Map();
|
|
296
|
+
#listers = /* @__PURE__ */ new Map();
|
|
297
|
+
register(source) {
|
|
298
|
+
this.#sources.set(source.scheme, source.resolve);
|
|
299
|
+
if (source.list) {
|
|
300
|
+
this.#listers.set(source.scheme, source.list);
|
|
301
|
+
} else {
|
|
302
|
+
this.#listers.delete(source.scheme);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
has(scheme) {
|
|
306
|
+
return this.#sources.has(scheme);
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Resolve a ref to a `SceneTemplate`. Splits on the first colon to
|
|
310
|
+
* extract the scheme. A ref with no scheme (no colon, or a leading
|
|
311
|
+
* colon) is sugar for `builtin:<ref>` — never throws; an unknown
|
|
312
|
+
* scheme or unknown id warns once and returns `null`.
|
|
313
|
+
*/
|
|
314
|
+
async resolve(ref, ctx) {
|
|
315
|
+
if (!ref) {
|
|
316
|
+
console.warn("[canvakit-showreel] Empty scene template ref.");
|
|
317
|
+
return null;
|
|
318
|
+
}
|
|
319
|
+
const colonIdx = ref.indexOf(":");
|
|
320
|
+
if (colonIdx <= 0) {
|
|
321
|
+
return this.resolve(`builtin:${ref}`, ctx);
|
|
322
|
+
}
|
|
323
|
+
const scheme = ref.slice(0, colonIdx);
|
|
324
|
+
const id = ref.slice(colonIdx + 1);
|
|
325
|
+
const handler = this.#sources.get(scheme);
|
|
326
|
+
if (!handler) {
|
|
327
|
+
console.warn(
|
|
328
|
+
`[canvakit-showreel] No resolver matched scene template ref "${ref}". Register a scheme via SceneTemplateRegistry.register() or use a built-in (builtin:/ws:).`
|
|
329
|
+
);
|
|
330
|
+
return null;
|
|
331
|
+
}
|
|
332
|
+
return handler(id, ctx);
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Enumerate every scene template discoverable across schemes that expose
|
|
336
|
+
* a `list`. Aggregated result is sorted by `(scheme, ref)` and
|
|
337
|
+
* de-duplicated by `ref`. Per-lister isolation matches `resolve()`'s
|
|
338
|
+
* never-throw contract — a misbehaving lister is warned about and
|
|
339
|
+
* skipped rather than crashing the aggregate.
|
|
340
|
+
*/
|
|
341
|
+
async list(ctx) {
|
|
342
|
+
const seen = /* @__PURE__ */ new Set();
|
|
343
|
+
const out = [];
|
|
344
|
+
for (const [scheme, lister] of this.#listers.entries()) {
|
|
345
|
+
let entries;
|
|
346
|
+
try {
|
|
347
|
+
entries = await lister(ctx);
|
|
348
|
+
} catch (err) {
|
|
349
|
+
console.warn(
|
|
350
|
+
`[canvakit-showreel] list() lister for scheme "${scheme}:" threw \u2014 skipping: ${err instanceof Error ? err.message : String(err)}`
|
|
351
|
+
);
|
|
352
|
+
continue;
|
|
353
|
+
}
|
|
354
|
+
for (const entry of entries) {
|
|
355
|
+
if (seen.has(entry.ref)) continue;
|
|
356
|
+
seen.add(entry.ref);
|
|
357
|
+
out.push(entry);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
return out.sort((a, b) => {
|
|
361
|
+
if (a.scheme !== b.scheme) return a.scheme.localeCompare(b.scheme);
|
|
362
|
+
return a.ref.localeCompare(b.ref);
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
function findBuiltinScene(id) {
|
|
367
|
+
const direct = BUILTIN_SCENES[id];
|
|
368
|
+
if (direct) return direct;
|
|
369
|
+
for (const scene of Object.values(BUILTIN_SCENES)) {
|
|
370
|
+
if (scene.aliases?.includes(id)) return scene;
|
|
371
|
+
}
|
|
372
|
+
return null;
|
|
373
|
+
}
|
|
374
|
+
function builtinRefs() {
|
|
375
|
+
const refs = [];
|
|
376
|
+
for (const [id, scene] of Object.entries(BUILTIN_SCENES)) {
|
|
377
|
+
refs.push(id);
|
|
378
|
+
if (scene.aliases) refs.push(...scene.aliases);
|
|
379
|
+
}
|
|
380
|
+
return refs;
|
|
381
|
+
}
|
|
382
|
+
var builtinResolver = async (id) => {
|
|
383
|
+
const scene = findBuiltinScene(id);
|
|
384
|
+
if (!scene) {
|
|
385
|
+
console.warn(
|
|
386
|
+
`[canvakit-showreel] Unknown builtin scene template "builtin:${id}" \u2014 available: ${builtinRefs().join(", ")}.`
|
|
387
|
+
);
|
|
388
|
+
return null;
|
|
389
|
+
}
|
|
390
|
+
return { id: `builtin:${id}`, source: scene.source, slots: scene.slots, defaults: scene.defaults ?? {} };
|
|
391
|
+
};
|
|
392
|
+
var builtinLister = async () => {
|
|
393
|
+
return builtinRefs().map((ref) => ({ ref: `builtin:${ref}`, scheme: "builtin" }));
|
|
394
|
+
};
|
|
395
|
+
function builtinSceneSource(id) {
|
|
396
|
+
return findBuiltinScene(id)?.source ?? null;
|
|
397
|
+
}
|
|
398
|
+
var wsResolver = async (id, { fs: fs2 }) => {
|
|
399
|
+
const path2 = id.replace(/^\/+/, "");
|
|
400
|
+
if (!path2) {
|
|
401
|
+
console.warn("[canvakit-showreel] Empty ws: scene template path.");
|
|
402
|
+
return null;
|
|
403
|
+
}
|
|
404
|
+
if (path2.split("/").some((segment) => segment === "..")) {
|
|
405
|
+
console.warn(`[canvakit-showreel] ws: path "${path2}" escapes the workspace \u2014 refused.`);
|
|
406
|
+
return null;
|
|
407
|
+
}
|
|
408
|
+
try {
|
|
409
|
+
if (!await fs2.exists(path2)) {
|
|
410
|
+
console.warn(`[canvakit-showreel] ws:${path2} not found in workspace.`);
|
|
411
|
+
return null;
|
|
412
|
+
}
|
|
413
|
+
const source = await readText(fs2, path2);
|
|
414
|
+
const { template } = parseTemplate(source, path2);
|
|
415
|
+
const slots = template ? extractTopLevelReferences(template.body).filter((name) => !name.startsWith("$")) : [];
|
|
416
|
+
return { id: `ws:${path2}`, source, slots, defaults: {} };
|
|
417
|
+
} catch (err) {
|
|
418
|
+
console.warn(
|
|
419
|
+
`[canvakit-showreel] Failed to load ws:${path2}: ${err instanceof Error ? err.message : String(err)}`
|
|
420
|
+
);
|
|
421
|
+
return null;
|
|
422
|
+
}
|
|
423
|
+
};
|
|
424
|
+
function createDefaultSceneTemplateRegistry() {
|
|
425
|
+
const registry = new SceneTemplateRegistry();
|
|
426
|
+
registry.register({ scheme: "builtin", resolve: builtinResolver, list: builtinLister });
|
|
427
|
+
registry.register({ scheme: "ws", resolve: wsResolver });
|
|
428
|
+
return registry;
|
|
429
|
+
}
|
|
430
|
+
var defaultSceneTemplateRegistry = createDefaultSceneTemplateRegistry();
|
|
431
|
+
function resolveSceneTemplate(ref, ctx) {
|
|
432
|
+
return defaultSceneTemplateRegistry.resolve(ref, ctx);
|
|
433
|
+
}
|
|
434
|
+
var DEFAULT_ACCENT = "#5B8CFF";
|
|
435
|
+
var BRAND_SCHEME = "brand";
|
|
436
|
+
var BRAND_REF = `${BRAND_SCHEME}:resolved`;
|
|
437
|
+
var noopFilesystem = {
|
|
438
|
+
readFile() {
|
|
439
|
+
return Promise.reject(
|
|
440
|
+
new Error("renderCanva: a scene canva must not declare file sources")
|
|
441
|
+
);
|
|
442
|
+
},
|
|
443
|
+
readdir() {
|
|
444
|
+
return Promise.resolve([]);
|
|
445
|
+
},
|
|
446
|
+
exists() {
|
|
447
|
+
return Promise.resolve(false);
|
|
448
|
+
},
|
|
449
|
+
writeFile() {
|
|
450
|
+
return Promise.reject(
|
|
451
|
+
new Error("renderCanva: a scene canva must not write files")
|
|
452
|
+
);
|
|
453
|
+
}
|
|
454
|
+
};
|
|
455
|
+
function buildBrandRegistry(brand) {
|
|
456
|
+
const registry = new DesignSourceRegistry();
|
|
457
|
+
registry.register({
|
|
458
|
+
scheme: BRAND_SCHEME,
|
|
459
|
+
resolve: async () => ({
|
|
460
|
+
tokens: designFrontmatterSchema.parse({
|
|
461
|
+
colors: { accent: DEFAULT_ACCENT, ...brand.tokens }
|
|
462
|
+
}),
|
|
463
|
+
fonts: brand.fonts
|
|
464
|
+
})
|
|
465
|
+
});
|
|
466
|
+
return registry;
|
|
467
|
+
}
|
|
468
|
+
async function renderCanva(template, data, brand) {
|
|
469
|
+
const variables = { ...template.defaults, ...data };
|
|
470
|
+
const result = await render({
|
|
471
|
+
template: template.source,
|
|
472
|
+
templatePath: template.id,
|
|
473
|
+
filesystem: noopFilesystem,
|
|
474
|
+
variables,
|
|
475
|
+
extensions: [
|
|
476
|
+
designkitExtension({
|
|
477
|
+
skipStylePrepend: true,
|
|
478
|
+
registry: buildBrandRegistry(brand),
|
|
479
|
+
overrideDesign: BRAND_REF
|
|
480
|
+
})
|
|
481
|
+
]
|
|
482
|
+
});
|
|
483
|
+
return injectFontFaces(result.body, brand.fonts);
|
|
484
|
+
}
|
|
485
|
+
function fontFaceFormat(href) {
|
|
486
|
+
const clean = href.split(/[?#]/)[0] ?? href;
|
|
487
|
+
const ext = clean.slice(clean.lastIndexOf(".") + 1).toLowerCase();
|
|
488
|
+
switch (ext) {
|
|
489
|
+
case "woff2":
|
|
490
|
+
return "woff2";
|
|
491
|
+
case "woff":
|
|
492
|
+
return "woff";
|
|
493
|
+
case "ttf":
|
|
494
|
+
return "truetype";
|
|
495
|
+
case "otf":
|
|
496
|
+
return "opentype";
|
|
497
|
+
default:
|
|
498
|
+
return null;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
function cssEscape(value) {
|
|
502
|
+
return value.replace(/[\\'\n\r<>]/g, (ch) => {
|
|
503
|
+
switch (ch) {
|
|
504
|
+
case "\\":
|
|
505
|
+
return "\\\\";
|
|
506
|
+
case "'":
|
|
507
|
+
return "\\'";
|
|
508
|
+
case "\n":
|
|
509
|
+
return "\\A ";
|
|
510
|
+
case "\r":
|
|
511
|
+
return "\\D ";
|
|
512
|
+
case "<":
|
|
513
|
+
return "\\3C ";
|
|
514
|
+
default:
|
|
515
|
+
return "\\3E ";
|
|
516
|
+
}
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
function escapeHtmlAttr(value) {
|
|
520
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
521
|
+
}
|
|
522
|
+
function renderFontFacesHead(fonts) {
|
|
523
|
+
if (!fonts || fonts.length === 0) return "";
|
|
524
|
+
const faceBlocks = [];
|
|
525
|
+
const linkTags = [];
|
|
526
|
+
for (const font of fonts) {
|
|
527
|
+
if (!font.href) continue;
|
|
528
|
+
const isDataUri = font.href.startsWith("data:");
|
|
529
|
+
const format = isDataUri ? null : fontFaceFormat(font.href);
|
|
530
|
+
if (!isDataUri && !format) {
|
|
531
|
+
linkTags.push(
|
|
532
|
+
`<link rel="stylesheet" href="${escapeHtmlAttr(font.href)}">`
|
|
533
|
+
);
|
|
534
|
+
continue;
|
|
535
|
+
}
|
|
536
|
+
const urlLiteral = `url('${cssEscape(font.href)}')`;
|
|
537
|
+
const src = format ? `${urlLiteral} format('${format}')` : urlLiteral;
|
|
538
|
+
const family = cssEscape(font.family);
|
|
539
|
+
const weights = font.weights && font.weights.length > 0 ? font.weights : [400];
|
|
540
|
+
for (const weight of weights) {
|
|
541
|
+
faceBlocks.push(
|
|
542
|
+
`@font-face { font-family: '${family}'; font-weight: ${weight}; font-style: normal; font-display: swap; src: ${src}; }`
|
|
543
|
+
);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
const styleBlock = faceBlocks.length > 0 ? `<style>${faceBlocks.join("\n")}</style>` : "";
|
|
547
|
+
return [...linkTags, styleBlock].filter(Boolean).join("\n");
|
|
548
|
+
}
|
|
549
|
+
function injectFontFaces(html, fonts) {
|
|
550
|
+
const head = renderFontFacesHead(fonts);
|
|
551
|
+
if (!head) return html;
|
|
552
|
+
const closeHead = html.search(/<\/head\s*>/i);
|
|
553
|
+
if (closeHead >= 0) {
|
|
554
|
+
return `${html.slice(0, closeHead)}${head}
|
|
555
|
+
${html.slice(closeHead)}`;
|
|
556
|
+
}
|
|
557
|
+
return `${head}
|
|
558
|
+
${html}`;
|
|
559
|
+
}
|
|
560
|
+
function findChrome(spec = "env:CHROME_PATH") {
|
|
561
|
+
let candidate = spec;
|
|
562
|
+
if (candidate.startsWith("env:")) {
|
|
563
|
+
candidate = process.env[candidate.slice(4)] ?? "";
|
|
564
|
+
}
|
|
565
|
+
if (candidate && existsSync(candidate)) return candidate;
|
|
566
|
+
const fallbacks = [
|
|
567
|
+
...cachedPuppeteerChrome(),
|
|
568
|
+
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
569
|
+
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
|
570
|
+
"/usr/bin/google-chrome",
|
|
571
|
+
"/usr/bin/chromium",
|
|
572
|
+
"/usr/bin/chromium-browser"
|
|
573
|
+
];
|
|
574
|
+
for (const path2 of fallbacks) {
|
|
575
|
+
if (existsSync(path2)) return path2;
|
|
576
|
+
}
|
|
577
|
+
return null;
|
|
578
|
+
}
|
|
579
|
+
function cachedPuppeteerChrome() {
|
|
580
|
+
const root = join(homedir(), ".cache", "puppeteer", "chrome");
|
|
581
|
+
if (!existsSync(root)) return [];
|
|
582
|
+
const out = [];
|
|
583
|
+
for (const dir of readdirSync(root)) {
|
|
584
|
+
for (const inner of [
|
|
585
|
+
join(
|
|
586
|
+
root,
|
|
587
|
+
dir,
|
|
588
|
+
"chrome-mac-arm64",
|
|
589
|
+
"Google Chrome for Testing.app",
|
|
590
|
+
"Contents",
|
|
591
|
+
"MacOS",
|
|
592
|
+
"Google Chrome for Testing"
|
|
593
|
+
),
|
|
594
|
+
join(
|
|
595
|
+
root,
|
|
596
|
+
dir,
|
|
597
|
+
"chrome-mac-x64",
|
|
598
|
+
"Google Chrome for Testing.app",
|
|
599
|
+
"Contents",
|
|
600
|
+
"MacOS",
|
|
601
|
+
"Google Chrome for Testing"
|
|
602
|
+
),
|
|
603
|
+
join(root, dir, "chrome-linux64", "chrome")
|
|
604
|
+
]) {
|
|
605
|
+
if (existsSync(inner)) out.push(inner);
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
return out;
|
|
609
|
+
}
|
|
610
|
+
async function runCapture(target, items, startOffsetMs) {
|
|
611
|
+
const executablePath = findChrome(target.chromePath);
|
|
612
|
+
if (!executablePath) {
|
|
613
|
+
throw new Error(
|
|
614
|
+
"runCapture: no Chrome executable found. Set target.chromePath or the CHROME_PATH env var to a Chrome/Chromium binary."
|
|
615
|
+
);
|
|
616
|
+
}
|
|
617
|
+
const outDir = mkdtempSync(join(tmpdir(), "showreel-"));
|
|
618
|
+
const screencastPath = join(outDir, "capture.mp4");
|
|
619
|
+
const fps = items[0]?.record.fps ?? 30;
|
|
620
|
+
const browser = await puppeteer.launch({
|
|
621
|
+
executablePath,
|
|
622
|
+
headless: true,
|
|
623
|
+
args: ["--no-sandbox", "--disable-setuid-sandbox"],
|
|
624
|
+
defaultViewport: {
|
|
625
|
+
width: target.viewport.width,
|
|
626
|
+
height: target.viewport.height,
|
|
627
|
+
deviceScaleFactor: target.viewport.dpr
|
|
628
|
+
}
|
|
629
|
+
});
|
|
630
|
+
try {
|
|
631
|
+
const page = await browser.newPage();
|
|
632
|
+
await page.goto(target.url, { waitUntil: "load" });
|
|
633
|
+
await page.waitForSelector(target.readyFlag, { timeout: 15e3 });
|
|
634
|
+
const client = await page.createCDPSession();
|
|
635
|
+
const frames = [];
|
|
636
|
+
client.on("Page.screencastFrame", (event) => {
|
|
637
|
+
frames.push(Buffer.from(event.data, "base64"));
|
|
638
|
+
void client.send("Page.screencastFrameAck", { sessionId: event.sessionId }).catch(() => {
|
|
639
|
+
});
|
|
640
|
+
});
|
|
641
|
+
await client.send("Page.startScreencast", {
|
|
642
|
+
format: "jpeg",
|
|
643
|
+
quality: 80,
|
|
644
|
+
everyNthFrame: 1
|
|
645
|
+
});
|
|
646
|
+
const origin = performance.now();
|
|
647
|
+
const toMaster = (t) => Math.round(startOffsetMs + (t - origin));
|
|
648
|
+
const timeline = [];
|
|
649
|
+
const screenshots = [];
|
|
650
|
+
for (const item of items) {
|
|
651
|
+
const itemStart = performance.now();
|
|
652
|
+
let lastWaitEnd = itemStart;
|
|
653
|
+
const deadline = itemStart + item.record.maxDuration;
|
|
654
|
+
const shotSelectors = new Set(item.screenshot?.at ?? []);
|
|
655
|
+
for (const step of item.steps) {
|
|
656
|
+
if (performance.now() > deadline) {
|
|
657
|
+
throw new Error(
|
|
658
|
+
`runCapture: capture "${item.id}" exceeded maxDuration ${item.record.maxDuration}ms before completing its steps.`
|
|
659
|
+
);
|
|
660
|
+
}
|
|
661
|
+
switch (step.action) {
|
|
662
|
+
case "navigate":
|
|
663
|
+
await page.goto(target.url + step.path, { waitUntil: "load" });
|
|
664
|
+
break;
|
|
665
|
+
case "type":
|
|
666
|
+
await page.type(step.selector, step.text, { delay: step.delay });
|
|
667
|
+
break;
|
|
668
|
+
case "click":
|
|
669
|
+
await page.click(step.selector);
|
|
670
|
+
break;
|
|
671
|
+
case "waitFor": {
|
|
672
|
+
const budget = Math.max(
|
|
673
|
+
1,
|
|
674
|
+
Math.min(step.timeout, deadline - performance.now())
|
|
675
|
+
);
|
|
676
|
+
await page.waitForSelector(step.selector, { timeout: budget });
|
|
677
|
+
lastWaitEnd = performance.now();
|
|
678
|
+
if (shotSelectors.has(step.selector)) {
|
|
679
|
+
const shot = join(outDir, `${item.id}-${screenshots.length}.png`);
|
|
680
|
+
const png = await page.screenshot();
|
|
681
|
+
writeFileSync(shot, png);
|
|
682
|
+
screenshots.push(shot);
|
|
683
|
+
}
|
|
684
|
+
break;
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
timeline.push({
|
|
689
|
+
id: item.id,
|
|
690
|
+
kind: "capture",
|
|
691
|
+
startMs: toMaster(itemStart),
|
|
692
|
+
endMs: toMaster(lastWaitEnd)
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
await client.send("Page.stopScreencast");
|
|
696
|
+
await encodeFramesToMp4(frames, fps, screencastPath);
|
|
697
|
+
return { timeline, screenshots, screencastPath };
|
|
698
|
+
} finally {
|
|
699
|
+
await browser.close();
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
function encodeFramesToMp4(frames, fps, outPath) {
|
|
703
|
+
return new Promise((resolve3, reject) => {
|
|
704
|
+
if (frames.length === 0) {
|
|
705
|
+
reject(new Error("encodeFramesToMp4: no frames captured"));
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
const ff = spawn(
|
|
709
|
+
"ffmpeg",
|
|
710
|
+
[
|
|
711
|
+
"-y",
|
|
712
|
+
"-f",
|
|
713
|
+
"image2pipe",
|
|
714
|
+
"-framerate",
|
|
715
|
+
String(fps),
|
|
716
|
+
"-i",
|
|
717
|
+
"-",
|
|
718
|
+
"-pix_fmt",
|
|
719
|
+
"yuv420p",
|
|
720
|
+
// even dimensions — yuv420p requires width/height divisible by 2
|
|
721
|
+
"-vf",
|
|
722
|
+
"scale=trunc(iw/2)*2:trunc(ih/2)*2",
|
|
723
|
+
outPath
|
|
724
|
+
],
|
|
725
|
+
{ stdio: ["pipe", "ignore", "pipe"] }
|
|
726
|
+
);
|
|
727
|
+
let stderr = "";
|
|
728
|
+
ff.stderr.on("data", (chunk) => {
|
|
729
|
+
stderr += chunk.toString();
|
|
730
|
+
});
|
|
731
|
+
ff.on("error", reject);
|
|
732
|
+
ff.on("close", (code) => {
|
|
733
|
+
if (code === 0) resolve3();
|
|
734
|
+
else
|
|
735
|
+
reject(
|
|
736
|
+
new Error(
|
|
737
|
+
`encodeFramesToMp4: ffmpeg exited ${String(code)}: ` + stderr.slice(-500)
|
|
738
|
+
)
|
|
739
|
+
);
|
|
740
|
+
});
|
|
741
|
+
for (const frame of frames) ff.stdin.write(frame);
|
|
742
|
+
ff.stdin.end();
|
|
743
|
+
});
|
|
744
|
+
}
|
|
745
|
+
function cachingVisualRenderer(inner, opts = {}) {
|
|
746
|
+
const enabled = opts.enabled ?? true;
|
|
747
|
+
const dir = opts.dir ?? join(process.cwd(), ".canvakit", "scene-cache");
|
|
748
|
+
const salt = opts.salt ?? "";
|
|
749
|
+
return {
|
|
750
|
+
async renderScene(item, brand) {
|
|
751
|
+
if (!enabled) {
|
|
752
|
+
return inner.renderScene(item, brand);
|
|
753
|
+
}
|
|
754
|
+
const hash = hashCacheKey({
|
|
755
|
+
template: item.template,
|
|
756
|
+
data: item.data ?? null,
|
|
757
|
+
duration: item.duration,
|
|
758
|
+
brand,
|
|
759
|
+
salt
|
|
760
|
+
});
|
|
761
|
+
const cachePath = join(dir, `${hash}.mp4`);
|
|
762
|
+
const cachedSize = await fileSizeSafe(cachePath);
|
|
763
|
+
if (cachedSize !== null && cachedSize > 0) {
|
|
764
|
+
return { clipPath: await copyToFreshOutPath(cachePath, item.id), durationMs: item.duration };
|
|
765
|
+
}
|
|
766
|
+
const clip = await inner.renderScene(item, brand);
|
|
767
|
+
await storeInCache(dir, hash, clip.clipPath);
|
|
768
|
+
return clip;
|
|
769
|
+
},
|
|
770
|
+
async dispose() {
|
|
771
|
+
await inner.dispose?.();
|
|
772
|
+
}
|
|
773
|
+
};
|
|
774
|
+
}
|
|
775
|
+
function hashCacheKey(value) {
|
|
776
|
+
return createHash("sha256").update(stableStringify(value)).digest("hex");
|
|
777
|
+
}
|
|
778
|
+
function stableStringify(value) {
|
|
779
|
+
return JSON.stringify(
|
|
780
|
+
value,
|
|
781
|
+
(_key, val) => val !== null && typeof val === "object" && !Array.isArray(val) ? Object.fromEntries(Object.keys(val).sort().map((key) => [key, val[key]])) : val
|
|
782
|
+
);
|
|
783
|
+
}
|
|
784
|
+
async function fileSizeSafe(path2) {
|
|
785
|
+
try {
|
|
786
|
+
const info = await stat(path2);
|
|
787
|
+
return info.size;
|
|
788
|
+
} catch {
|
|
789
|
+
return null;
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
async function copyToFreshOutPath(cachePath, sceneId) {
|
|
793
|
+
const freshDir = await mkdtemp(join(tmpdir(), "showreel-cache-hit-"));
|
|
794
|
+
const outPath = join(freshDir, `${sceneId}.mp4`);
|
|
795
|
+
await copyFile(cachePath, outPath);
|
|
796
|
+
return outPath;
|
|
797
|
+
}
|
|
798
|
+
async function storeInCache(dir, hash, clipPath) {
|
|
799
|
+
await mkdir(dir, { recursive: true });
|
|
800
|
+
const tmpPath = join(dir, `${hash}.${randomUUID()}.tmp`);
|
|
801
|
+
await copyFile(clipPath, tmpPath);
|
|
802
|
+
await rename(tmpPath, join(dir, `${hash}.mp4`));
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
// src/renderer/index.ts
|
|
806
|
+
function resolveVisualRenderer(opts = {}) {
|
|
807
|
+
const base = opts.renderer ?? createHtmlStillVisualRenderer();
|
|
808
|
+
return opts.cache ? cachingVisualRenderer(base, opts.cache) : base;
|
|
809
|
+
}
|
|
810
|
+
var SCENE_VIEWPORT = { width: 1920, height: 1080, dpr: 2 };
|
|
811
|
+
var SCENE_FPS = 30;
|
|
812
|
+
function createHtmlStillVisualRenderer() {
|
|
813
|
+
let browserPromise = null;
|
|
814
|
+
function acquireBrowser() {
|
|
815
|
+
if (!browserPromise) {
|
|
816
|
+
const executablePath = findChrome();
|
|
817
|
+
if (!executablePath) {
|
|
818
|
+
throw new Error(
|
|
819
|
+
"htmlStillVisualRenderer: no Chrome executable found. Set the CHROME_PATH env var to a Chrome/Chromium binary."
|
|
820
|
+
);
|
|
821
|
+
}
|
|
822
|
+
browserPromise = puppeteer.launch({
|
|
823
|
+
executablePath,
|
|
824
|
+
headless: true,
|
|
825
|
+
args: ["--no-sandbox", "--disable-setuid-sandbox"],
|
|
826
|
+
defaultViewport: {
|
|
827
|
+
width: SCENE_VIEWPORT.width,
|
|
828
|
+
height: SCENE_VIEWPORT.height,
|
|
829
|
+
deviceScaleFactor: SCENE_VIEWPORT.dpr
|
|
830
|
+
}
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
return browserPromise;
|
|
834
|
+
}
|
|
835
|
+
return {
|
|
836
|
+
async renderScene(item, brand) {
|
|
837
|
+
const outDir = mkdtempSync(join(tmpdir(), "showreel-scenes-"));
|
|
838
|
+
const browser = await acquireBrowser();
|
|
839
|
+
const clipPath = await recordScene(browser, item, brand, outDir);
|
|
840
|
+
return { clipPath, durationMs: item.duration };
|
|
841
|
+
},
|
|
842
|
+
async dispose() {
|
|
843
|
+
const pending = browserPromise;
|
|
844
|
+
browserPromise = null;
|
|
845
|
+
if (pending) {
|
|
846
|
+
await (await pending).close();
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
var htmlStillVisualRenderer = createHtmlStillVisualRenderer();
|
|
852
|
+
async function recordScene(browser, item, brand, outDir) {
|
|
853
|
+
const page = await browser.newPage();
|
|
854
|
+
try {
|
|
855
|
+
const html = await renderSceneHtml(item, brand);
|
|
856
|
+
await page.setContent(html, { waitUntil: "load" });
|
|
857
|
+
return await captureScenePage(page, item, outDir);
|
|
858
|
+
} finally {
|
|
859
|
+
await page.close();
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
async function captureScenePage(page, item, outDir) {
|
|
863
|
+
const stillPath = join(outDir, `${item.id}-still.png`);
|
|
864
|
+
const png = await page.screenshot();
|
|
865
|
+
writeFileSync(stillPath, png);
|
|
866
|
+
const clipPath = join(outDir, `${item.id}.mp4`);
|
|
867
|
+
await encodeStillToMp4(stillPath, item.duration, SCENE_FPS, clipPath);
|
|
868
|
+
return clipPath;
|
|
869
|
+
}
|
|
870
|
+
function encodeStillToMp4(stillPath, durationMs, fps, outPath) {
|
|
871
|
+
return new Promise((resolvePromise, reject) => {
|
|
872
|
+
const ff = spawn(
|
|
873
|
+
"ffmpeg",
|
|
874
|
+
[
|
|
875
|
+
"-y",
|
|
876
|
+
"-loop",
|
|
877
|
+
"1",
|
|
878
|
+
"-i",
|
|
879
|
+
stillPath,
|
|
880
|
+
"-t",
|
|
881
|
+
String(durationMs / 1e3),
|
|
882
|
+
"-r",
|
|
883
|
+
String(fps),
|
|
884
|
+
"-pix_fmt",
|
|
885
|
+
"yuv420p",
|
|
886
|
+
// even dimensions — a screenshot PNG's size may be odd, and
|
|
887
|
+
// yuv420p requires width/height divisible by 2
|
|
888
|
+
"-vf",
|
|
889
|
+
"scale=trunc(iw/2)*2:trunc(ih/2)*2",
|
|
890
|
+
outPath
|
|
891
|
+
],
|
|
892
|
+
{ stdio: ["ignore", "ignore", "pipe"] }
|
|
893
|
+
);
|
|
894
|
+
let stderr = "";
|
|
895
|
+
ff.stderr.on("data", (chunk) => {
|
|
896
|
+
stderr += chunk.toString();
|
|
897
|
+
});
|
|
898
|
+
ff.on("error", reject);
|
|
899
|
+
ff.on("close", (code) => {
|
|
900
|
+
if (code === 0) resolvePromise();
|
|
901
|
+
else
|
|
902
|
+
reject(
|
|
903
|
+
new Error(`encodeStillToMp4: ffmpeg exited ${String(code)}: ${stderr.slice(-500)}`)
|
|
904
|
+
);
|
|
905
|
+
});
|
|
906
|
+
});
|
|
907
|
+
}
|
|
908
|
+
async function renderSceneHtml(item, brand, fs2 = createLocalFs(process.cwd())) {
|
|
909
|
+
const template = await resolveSceneTemplate(item.template, { fs: fs2 });
|
|
910
|
+
if (!template) {
|
|
911
|
+
throw new Error(
|
|
912
|
+
`renderSceneHtml: no scene template resolved for "${item.template}" (see prior console.warn for the reason). Register it via SceneTemplateRegistry.register(), author it at the ws: path, or use a known builtin (builtin:hero-split, builtin:cta-card, \u2026).`
|
|
913
|
+
);
|
|
914
|
+
}
|
|
915
|
+
return renderCanva(template, item.data, brand);
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
// src/scenes/index.ts
|
|
919
|
+
async function renderScenesWith(renderer, items, brand, startOffsetMs) {
|
|
920
|
+
const timeline = [];
|
|
921
|
+
const clipPaths = [];
|
|
922
|
+
let cursorMs = startOffsetMs;
|
|
923
|
+
try {
|
|
924
|
+
for (const item of items) {
|
|
925
|
+
const { clipPath } = await renderer.renderScene(item, brand);
|
|
926
|
+
clipPaths.push(clipPath);
|
|
927
|
+
const startMs = cursorMs;
|
|
928
|
+
const endMs = startMs + item.duration;
|
|
929
|
+
timeline.push({ id: item.id, kind: "scene", startMs, endMs });
|
|
930
|
+
cursorMs = endMs;
|
|
931
|
+
}
|
|
932
|
+
} finally {
|
|
933
|
+
await renderer.dispose?.();
|
|
934
|
+
}
|
|
935
|
+
return { timeline, clipPaths };
|
|
936
|
+
}
|
|
937
|
+
function renderScenes(items, brand, startOffsetMs) {
|
|
938
|
+
return renderScenesWith(resolveVisualRenderer(), items, brand, startOffsetMs);
|
|
939
|
+
}
|
|
940
|
+
function resolveClipSrc(src, configDir) {
|
|
941
|
+
return isAbsolute(src) ? src : resolve(configDir, src);
|
|
942
|
+
}
|
|
943
|
+
function computeTrimWindow(item, durationMs, resolvedPath) {
|
|
944
|
+
const startMs = item.trim?.startMs ?? 0;
|
|
945
|
+
const endMs = item.trim?.endMs ?? durationMs;
|
|
946
|
+
if (startMs < 0 || startMs >= durationMs) {
|
|
947
|
+
throw new Error(
|
|
948
|
+
`clip "${item.id}": trim.startMs (${String(startMs)}) is outside its measured duration (${String(durationMs)}ms) at "${resolvedPath}"`
|
|
949
|
+
);
|
|
950
|
+
}
|
|
951
|
+
if (endMs <= startMs || endMs > durationMs) {
|
|
952
|
+
throw new Error(
|
|
953
|
+
`clip "${item.id}": trim.endMs (${String(endMs)}) is outside its measured duration (${String(durationMs)}ms), or not after trim.startMs (${String(startMs)}), at "${resolvedPath}"`
|
|
954
|
+
);
|
|
955
|
+
}
|
|
956
|
+
return { startMs, endMs };
|
|
957
|
+
}
|
|
958
|
+
function ffprobeDurationMs(path2) {
|
|
959
|
+
return new Promise((resolveP, reject) => {
|
|
960
|
+
const proc = spawn(
|
|
961
|
+
"ffprobe",
|
|
962
|
+
[
|
|
963
|
+
"-v",
|
|
964
|
+
"error",
|
|
965
|
+
"-show_entries",
|
|
966
|
+
"format=duration",
|
|
967
|
+
"-of",
|
|
968
|
+
"default=noprint_wrappers=1:nokey=1",
|
|
969
|
+
path2
|
|
970
|
+
],
|
|
971
|
+
{ stdio: ["ignore", "pipe", "pipe"] }
|
|
972
|
+
);
|
|
973
|
+
let stdout = "";
|
|
974
|
+
let stderr = "";
|
|
975
|
+
proc.stdout.on("data", (chunk) => {
|
|
976
|
+
stdout += chunk.toString();
|
|
977
|
+
});
|
|
978
|
+
proc.stderr.on("data", (chunk) => {
|
|
979
|
+
stderr += chunk.toString();
|
|
980
|
+
});
|
|
981
|
+
proc.on("error", reject);
|
|
982
|
+
proc.on("close", (code) => {
|
|
983
|
+
if (code !== 0) {
|
|
984
|
+
reject(new Error(`ffprobe exited ${String(code)}: ${stderr.slice(-500)}`));
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
const seconds = Number.parseFloat(stdout.trim());
|
|
988
|
+
if (!Number.isFinite(seconds)) {
|
|
989
|
+
reject(new Error(`could not parse ffprobe output: "${stdout.trim()}"`));
|
|
990
|
+
return;
|
|
991
|
+
}
|
|
992
|
+
resolveP(Math.round(seconds * 1e3));
|
|
993
|
+
});
|
|
994
|
+
});
|
|
995
|
+
}
|
|
996
|
+
async function measureClip(item, startOffsetMs, configDir) {
|
|
997
|
+
const path2 = resolveClipSrc(item.src, configDir);
|
|
998
|
+
if (!existsSync(path2)) {
|
|
999
|
+
throw new Error(
|
|
1000
|
+
`clip "${item.id}": source not found at "${path2}" (declared src "${item.src}")`
|
|
1001
|
+
);
|
|
1002
|
+
}
|
|
1003
|
+
let durationMs;
|
|
1004
|
+
try {
|
|
1005
|
+
durationMs = await ffprobeDurationMs(path2);
|
|
1006
|
+
} catch (err) {
|
|
1007
|
+
throw new Error(
|
|
1008
|
+
`clip "${item.id}": could not read/probe "${path2}": ${err instanceof Error ? err.message : String(err)}`
|
|
1009
|
+
);
|
|
1010
|
+
}
|
|
1011
|
+
const trim = computeTrimWindow(item, durationMs, path2);
|
|
1012
|
+
const slot = {
|
|
1013
|
+
id: item.id,
|
|
1014
|
+
kind: "clip",
|
|
1015
|
+
startMs: startOffsetMs,
|
|
1016
|
+
endMs: startOffsetMs + (trim.endMs - trim.startMs)
|
|
1017
|
+
};
|
|
1018
|
+
return { slot, result: { id: item.id, path: path2, trim, fit: item.fit } };
|
|
1019
|
+
}
|
|
1020
|
+
async function synthesizeAudioWith(deps, items, measured, voice, music) {
|
|
1021
|
+
const measuredById = new Map(measured.map((slot) => [slot.id, slot]));
|
|
1022
|
+
const outDir = mkdtempSync(join(tmpdir(), "showreel-audio-"));
|
|
1023
|
+
const narration = [];
|
|
1024
|
+
for (const item of items) {
|
|
1025
|
+
if (!item.narration) continue;
|
|
1026
|
+
const slot = measuredById.get(item.id);
|
|
1027
|
+
if (!slot) {
|
|
1028
|
+
console.warn(
|
|
1029
|
+
`synthesizeAudio: skipping narration for "${item.id}" \u2014 no measured timeline entry for that id.`
|
|
1030
|
+
);
|
|
1031
|
+
continue;
|
|
1032
|
+
}
|
|
1033
|
+
const buffer = await deps.tts(item.narration, voice);
|
|
1034
|
+
const path2 = join(outDir, `narration-${item.id}.mp3`);
|
|
1035
|
+
writeFileSync(path2, buffer);
|
|
1036
|
+
const durationMs = await ffprobeDurationMs2(path2);
|
|
1037
|
+
narration.push({ id: item.id, path: path2, startMs: slot.startMs, durationMs });
|
|
1038
|
+
}
|
|
1039
|
+
const totalMs = measured.length > 0 ? Math.max(...measured.map((slot) => slot.endMs)) : 1e3;
|
|
1040
|
+
const musicBuffer = await deps.makeMusic(music.prompt, totalMs);
|
|
1041
|
+
const musicPath = join(outDir, "music-bed.mp3");
|
|
1042
|
+
writeFileSync(musicPath, musicBuffer);
|
|
1043
|
+
return { narration, musicPath };
|
|
1044
|
+
}
|
|
1045
|
+
async function synthesizeAudio(items, measured, voice, music) {
|
|
1046
|
+
return synthesizeAudioWith(
|
|
1047
|
+
{ tts: elevenLabsTts, makeMusic: elevenLabsMusic },
|
|
1048
|
+
items,
|
|
1049
|
+
measured,
|
|
1050
|
+
voice,
|
|
1051
|
+
music
|
|
1052
|
+
);
|
|
1053
|
+
}
|
|
1054
|
+
async function elevenLabsTts(text, voice) {
|
|
1055
|
+
const apiKey = process.env.ELEVENLABS_API_KEY;
|
|
1056
|
+
if (!apiKey) {
|
|
1057
|
+
throw new Error(
|
|
1058
|
+
"synthesizeAudio: ELEVENLABS_API_KEY is not set \u2014 cannot call the ElevenLabs TTS API."
|
|
1059
|
+
);
|
|
1060
|
+
}
|
|
1061
|
+
const response = await fetch(
|
|
1062
|
+
`https://api.elevenlabs.io/v1/text-to-speech/${voice.voiceId}`,
|
|
1063
|
+
{
|
|
1064
|
+
method: "POST",
|
|
1065
|
+
headers: {
|
|
1066
|
+
"xi-api-key": apiKey,
|
|
1067
|
+
"content-type": "application/json",
|
|
1068
|
+
accept: "audio/mpeg"
|
|
1069
|
+
},
|
|
1070
|
+
body: JSON.stringify({ text, model_id: voice.model })
|
|
1071
|
+
}
|
|
1072
|
+
);
|
|
1073
|
+
if (!response.ok) {
|
|
1074
|
+
const body = await response.text().catch(() => "");
|
|
1075
|
+
throw new Error(
|
|
1076
|
+
`synthesizeAudio: ElevenLabs TTS request failed (${String(response.status)}): ${body.slice(0, 500)}`
|
|
1077
|
+
);
|
|
1078
|
+
}
|
|
1079
|
+
return Buffer.from(await response.arrayBuffer());
|
|
1080
|
+
}
|
|
1081
|
+
async function elevenLabsMusic(prompt, totalMs) {
|
|
1082
|
+
const apiKey = process.env.ELEVENLABS_API_KEY;
|
|
1083
|
+
if (apiKey) {
|
|
1084
|
+
try {
|
|
1085
|
+
const response = await fetch("https://api.elevenlabs.io/v1/music", {
|
|
1086
|
+
method: "POST",
|
|
1087
|
+
headers: {
|
|
1088
|
+
"xi-api-key": apiKey,
|
|
1089
|
+
"content-type": "application/json",
|
|
1090
|
+
accept: "audio/mpeg"
|
|
1091
|
+
},
|
|
1092
|
+
body: JSON.stringify({ prompt, music_length_ms: totalMs })
|
|
1093
|
+
});
|
|
1094
|
+
if (response.ok) return Buffer.from(await response.arrayBuffer());
|
|
1095
|
+
console.warn(
|
|
1096
|
+
`synthesizeAudio: ElevenLabs Music API failed (${String(response.status)}) \u2014 falling back to a silent bed.`
|
|
1097
|
+
);
|
|
1098
|
+
} catch (err) {
|
|
1099
|
+
console.warn(
|
|
1100
|
+
`synthesizeAudio: ElevenLabs Music API request errored (${err instanceof Error ? err.message : String(err)}) \u2014 falling back to a silent bed.`
|
|
1101
|
+
);
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
return silentBed(totalMs);
|
|
1105
|
+
}
|
|
1106
|
+
function silentBed(totalMs) {
|
|
1107
|
+
return new Promise((resolve3, reject) => {
|
|
1108
|
+
const outDir = mkdtempSync(join(tmpdir(), "showreel-audio-bed-"));
|
|
1109
|
+
const outPath = join(outDir, "silence.mp3");
|
|
1110
|
+
const seconds = Math.max(totalMs, 1) / 1e3;
|
|
1111
|
+
const ff = spawn(
|
|
1112
|
+
"ffmpeg",
|
|
1113
|
+
[
|
|
1114
|
+
"-y",
|
|
1115
|
+
"-f",
|
|
1116
|
+
"lavfi",
|
|
1117
|
+
"-i",
|
|
1118
|
+
"anullsrc=r=44100:cl=stereo",
|
|
1119
|
+
"-t",
|
|
1120
|
+
String(seconds),
|
|
1121
|
+
"-q:a",
|
|
1122
|
+
"9",
|
|
1123
|
+
outPath
|
|
1124
|
+
],
|
|
1125
|
+
{ stdio: ["ignore", "ignore", "pipe"] }
|
|
1126
|
+
);
|
|
1127
|
+
let stderr = "";
|
|
1128
|
+
ff.stderr.on("data", (chunk) => {
|
|
1129
|
+
stderr += chunk.toString();
|
|
1130
|
+
});
|
|
1131
|
+
ff.on("error", reject);
|
|
1132
|
+
ff.on("close", (code) => {
|
|
1133
|
+
if (code === 0) resolve3(readFileSync(outPath));
|
|
1134
|
+
else
|
|
1135
|
+
reject(
|
|
1136
|
+
new Error(`silentBed: ffmpeg exited ${String(code)}: ${stderr.slice(-500)}`)
|
|
1137
|
+
);
|
|
1138
|
+
});
|
|
1139
|
+
});
|
|
1140
|
+
}
|
|
1141
|
+
function ffprobeDurationMs2(path2) {
|
|
1142
|
+
return new Promise((resolve3, reject) => {
|
|
1143
|
+
const ff = spawn(
|
|
1144
|
+
"ffprobe",
|
|
1145
|
+
[
|
|
1146
|
+
"-v",
|
|
1147
|
+
"error",
|
|
1148
|
+
"-show_entries",
|
|
1149
|
+
"format=duration",
|
|
1150
|
+
"-of",
|
|
1151
|
+
"default=noprint_wrappers=1:nokey=1",
|
|
1152
|
+
path2
|
|
1153
|
+
],
|
|
1154
|
+
{ stdio: ["ignore", "pipe", "pipe"] }
|
|
1155
|
+
);
|
|
1156
|
+
let stdout = "";
|
|
1157
|
+
let stderr = "";
|
|
1158
|
+
ff.stdout.on("data", (chunk) => {
|
|
1159
|
+
stdout += chunk.toString();
|
|
1160
|
+
});
|
|
1161
|
+
ff.stderr.on("data", (chunk) => {
|
|
1162
|
+
stderr += chunk.toString();
|
|
1163
|
+
});
|
|
1164
|
+
ff.on("error", reject);
|
|
1165
|
+
ff.on("close", (code) => {
|
|
1166
|
+
if (code !== 0) {
|
|
1167
|
+
reject(
|
|
1168
|
+
new Error(
|
|
1169
|
+
`ffprobeDurationMs: ffprobe exited ${String(code)}: ${stderr.slice(-500)}`
|
|
1170
|
+
)
|
|
1171
|
+
);
|
|
1172
|
+
return;
|
|
1173
|
+
}
|
|
1174
|
+
const seconds = Number.parseFloat(stdout.trim());
|
|
1175
|
+
if (!Number.isFinite(seconds)) {
|
|
1176
|
+
reject(
|
|
1177
|
+
new Error(
|
|
1178
|
+
`ffprobeDurationMs: could not parse duration from ffprobe output: "${stdout}"`
|
|
1179
|
+
)
|
|
1180
|
+
);
|
|
1181
|
+
return;
|
|
1182
|
+
}
|
|
1183
|
+
resolve3(Math.round(seconds * 1e3));
|
|
1184
|
+
});
|
|
1185
|
+
});
|
|
1186
|
+
}
|
|
1187
|
+
var FPS = 30;
|
|
1188
|
+
function resolveResolution(res) {
|
|
1189
|
+
switch (res.trim().toLowerCase()) {
|
|
1190
|
+
case "720p":
|
|
1191
|
+
return { width: 1280, height: 720 };
|
|
1192
|
+
case "1080p":
|
|
1193
|
+
return { width: 1920, height: 1080 };
|
|
1194
|
+
case "1440p":
|
|
1195
|
+
return { width: 2560, height: 1440 };
|
|
1196
|
+
case "4k":
|
|
1197
|
+
case "2160p":
|
|
1198
|
+
return { width: 3840, height: 2160 };
|
|
1199
|
+
default:
|
|
1200
|
+
return { width: 1920, height: 1080 };
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
function runFf(bin, args) {
|
|
1204
|
+
return new Promise((resolvePromise, reject) => {
|
|
1205
|
+
const proc = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
1206
|
+
let stdout = "";
|
|
1207
|
+
let stderr = "";
|
|
1208
|
+
proc.stdout.on("data", (chunk) => {
|
|
1209
|
+
stdout += chunk.toString();
|
|
1210
|
+
});
|
|
1211
|
+
proc.stderr.on("data", (chunk) => {
|
|
1212
|
+
stderr += chunk.toString();
|
|
1213
|
+
});
|
|
1214
|
+
proc.on("error", reject);
|
|
1215
|
+
proc.on("close", (code) => {
|
|
1216
|
+
if (code === 0) resolvePromise(stdout);
|
|
1217
|
+
else
|
|
1218
|
+
reject(
|
|
1219
|
+
new Error(`${bin} exited ${String(code)}: ${stderr.slice(-800)}`)
|
|
1220
|
+
);
|
|
1221
|
+
});
|
|
1222
|
+
});
|
|
1223
|
+
}
|
|
1224
|
+
function runFfStderr(args) {
|
|
1225
|
+
return new Promise((resolvePromise) => {
|
|
1226
|
+
const proc = spawn("ffmpeg", args, { stdio: ["ignore", "ignore", "pipe"] });
|
|
1227
|
+
let stderr = "";
|
|
1228
|
+
proc.stderr.on("data", (chunk) => {
|
|
1229
|
+
stderr += chunk.toString();
|
|
1230
|
+
});
|
|
1231
|
+
proc.on("error", () => resolvePromise(""));
|
|
1232
|
+
proc.on("close", () => resolvePromise(stderr));
|
|
1233
|
+
});
|
|
1234
|
+
}
|
|
1235
|
+
function safeJsonParse(text) {
|
|
1236
|
+
try {
|
|
1237
|
+
return JSON.parse(text);
|
|
1238
|
+
} catch {
|
|
1239
|
+
return null;
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
var loudnormMeasurementSchema = z.object({
|
|
1243
|
+
input_i: z.string(),
|
|
1244
|
+
input_tp: z.string(),
|
|
1245
|
+
input_lra: z.string(),
|
|
1246
|
+
input_thresh: z.string(),
|
|
1247
|
+
target_offset: z.string()
|
|
1248
|
+
});
|
|
1249
|
+
async function measuredLoudnormFilter(path2) {
|
|
1250
|
+
const stderr = await runFfStderr([
|
|
1251
|
+
"-hide_banner",
|
|
1252
|
+
"-i",
|
|
1253
|
+
path2,
|
|
1254
|
+
"-af",
|
|
1255
|
+
`${NARRATION_LOUDNORM}:print_format=json`,
|
|
1256
|
+
"-f",
|
|
1257
|
+
"null",
|
|
1258
|
+
"-"
|
|
1259
|
+
]);
|
|
1260
|
+
const match = /\{[^{}]*"input_i"[^{}]*\}/.exec(stderr);
|
|
1261
|
+
if (!match) return NARRATION_LOUDNORM;
|
|
1262
|
+
const parsed = loudnormMeasurementSchema.safeParse(safeJsonParse(match[0]));
|
|
1263
|
+
if (!parsed.success) return NARRATION_LOUDNORM;
|
|
1264
|
+
const stats = parsed.data;
|
|
1265
|
+
const numbers = [
|
|
1266
|
+
stats.input_i,
|
|
1267
|
+
stats.input_tp,
|
|
1268
|
+
stats.input_lra,
|
|
1269
|
+
stats.input_thresh,
|
|
1270
|
+
stats.target_offset
|
|
1271
|
+
];
|
|
1272
|
+
if (numbers.some((v) => !Number.isFinite(Number.parseFloat(v))))
|
|
1273
|
+
return NARRATION_LOUDNORM;
|
|
1274
|
+
return `${NARRATION_LOUDNORM}:measured_I=${stats.input_i}:measured_TP=${stats.input_tp}:measured_LRA=${stats.input_lra}:measured_thresh=${stats.input_thresh}:offset=${stats.target_offset}:linear=true`;
|
|
1275
|
+
}
|
|
1276
|
+
async function ffprobeDurationMs3(path2) {
|
|
1277
|
+
const out = await runFf("ffprobe", [
|
|
1278
|
+
"-v",
|
|
1279
|
+
"error",
|
|
1280
|
+
"-show_entries",
|
|
1281
|
+
"format=duration",
|
|
1282
|
+
"-of",
|
|
1283
|
+
"default=noprint_wrappers=1:nokey=1",
|
|
1284
|
+
path2
|
|
1285
|
+
]);
|
|
1286
|
+
const seconds = Number.parseFloat(out.trim());
|
|
1287
|
+
if (!Number.isFinite(seconds)) {
|
|
1288
|
+
throw new Error(
|
|
1289
|
+
`ffprobeDurationMs: could not parse duration for "${path2}": "${out}"`
|
|
1290
|
+
);
|
|
1291
|
+
}
|
|
1292
|
+
return Math.round(seconds * 1e3);
|
|
1293
|
+
}
|
|
1294
|
+
function buildClipList(measured, captures, scenes, clips) {
|
|
1295
|
+
const sceneClipById = /* @__PURE__ */ new Map();
|
|
1296
|
+
for (const scene of scenes) {
|
|
1297
|
+
scene.timeline.forEach((item, i) => {
|
|
1298
|
+
const clip = scene.clipPaths[i];
|
|
1299
|
+
if (clip) sceneClipById.set(item.id, clip);
|
|
1300
|
+
});
|
|
1301
|
+
}
|
|
1302
|
+
const captureById = /* @__PURE__ */ new Map();
|
|
1303
|
+
for (const capture of captures) {
|
|
1304
|
+
for (const item of capture.timeline) captureById.set(item.id, capture);
|
|
1305
|
+
}
|
|
1306
|
+
const clipById = new Map(clips.map((clip) => [clip.id, clip]));
|
|
1307
|
+
const entries = [];
|
|
1308
|
+
const emittedCaptures = /* @__PURE__ */ new Set();
|
|
1309
|
+
for (const item of measured) {
|
|
1310
|
+
if (item.kind === "scene") {
|
|
1311
|
+
const clip = sceneClipById.get(item.id);
|
|
1312
|
+
if (!clip) {
|
|
1313
|
+
throw new Error(
|
|
1314
|
+
`assemble: no scene clip found for measured item "${item.id}"`
|
|
1315
|
+
);
|
|
1316
|
+
}
|
|
1317
|
+
entries.push({ path: clip, targetMs: item.endMs - item.startMs, fit: "contain" });
|
|
1318
|
+
continue;
|
|
1319
|
+
}
|
|
1320
|
+
if (item.kind === "clip") {
|
|
1321
|
+
const clip = clipById.get(item.id);
|
|
1322
|
+
if (!clip) {
|
|
1323
|
+
throw new Error(
|
|
1324
|
+
`assemble: no resolved clip found for measured item "${item.id}"`
|
|
1325
|
+
);
|
|
1326
|
+
}
|
|
1327
|
+
entries.push({
|
|
1328
|
+
path: clip.path,
|
|
1329
|
+
targetMs: item.endMs - item.startMs,
|
|
1330
|
+
fit: clip.fit,
|
|
1331
|
+
trim: clip.trim
|
|
1332
|
+
});
|
|
1333
|
+
continue;
|
|
1334
|
+
}
|
|
1335
|
+
const capture = captureById.get(item.id);
|
|
1336
|
+
if (!capture) {
|
|
1337
|
+
throw new Error(
|
|
1338
|
+
`assemble: no capture result found for measured item "${item.id}"`
|
|
1339
|
+
);
|
|
1340
|
+
}
|
|
1341
|
+
if (emittedCaptures.has(capture)) continue;
|
|
1342
|
+
emittedCaptures.add(capture);
|
|
1343
|
+
const captureItemIds = new Set(capture.timeline.map((i) => i.id));
|
|
1344
|
+
const span = measured.filter((i) => captureItemIds.has(i.id));
|
|
1345
|
+
const firstStartMs = Math.min(...span.map((i) => i.startMs));
|
|
1346
|
+
const lastEndMs = Math.max(...span.map((i) => i.endMs));
|
|
1347
|
+
entries.push({
|
|
1348
|
+
path: capture.screencastPath,
|
|
1349
|
+
targetMs: lastEndMs - firstStartMs,
|
|
1350
|
+
fit: "contain"
|
|
1351
|
+
});
|
|
1352
|
+
}
|
|
1353
|
+
return entries;
|
|
1354
|
+
}
|
|
1355
|
+
var DURATION_EPSILON_MS = 20;
|
|
1356
|
+
function buildFitFilter(res, fit) {
|
|
1357
|
+
if (fit === "cover") {
|
|
1358
|
+
return [
|
|
1359
|
+
`scale=${res.width}:${res.height}:force_original_aspect_ratio=increase`,
|
|
1360
|
+
`crop=${res.width}:${res.height}`,
|
|
1361
|
+
"setsar=1"
|
|
1362
|
+
];
|
|
1363
|
+
}
|
|
1364
|
+
return [
|
|
1365
|
+
`scale=${res.width}:${res.height}:force_original_aspect_ratio=decrease`,
|
|
1366
|
+
`pad=${res.width}:${res.height}:(ow-iw)/2:(oh-ih)/2`,
|
|
1367
|
+
"setsar=1"
|
|
1368
|
+
];
|
|
1369
|
+
}
|
|
1370
|
+
async function extractClipTrim(inputPath, trim, workDir, index) {
|
|
1371
|
+
const outPath = join(workDir, `clip-trim-${String(index)}.mp4`);
|
|
1372
|
+
await runFf("ffmpeg", [
|
|
1373
|
+
"-y",
|
|
1374
|
+
"-ss",
|
|
1375
|
+
String(trim.startMs / 1e3),
|
|
1376
|
+
"-i",
|
|
1377
|
+
inputPath,
|
|
1378
|
+
"-t",
|
|
1379
|
+
String((trim.endMs - trim.startMs) / 1e3),
|
|
1380
|
+
"-an",
|
|
1381
|
+
"-c:v",
|
|
1382
|
+
"libx264",
|
|
1383
|
+
"-preset",
|
|
1384
|
+
"veryfast",
|
|
1385
|
+
outPath
|
|
1386
|
+
]);
|
|
1387
|
+
return outPath;
|
|
1388
|
+
}
|
|
1389
|
+
async function normalizeClip(inputPath, outPath, res, targetMs, fit) {
|
|
1390
|
+
const actualMs = await ffprobeDurationMs3(inputPath);
|
|
1391
|
+
const deltaMs = targetMs - actualMs;
|
|
1392
|
+
const vf = buildFitFilter(res, fit);
|
|
1393
|
+
const args = ["-y", "-i", inputPath];
|
|
1394
|
+
if (deltaMs > DURATION_EPSILON_MS) {
|
|
1395
|
+
const padSeconds = deltaMs / 1e3;
|
|
1396
|
+
vf.push(`tpad=stop_mode=clone:stop_duration=${String(padSeconds)}`);
|
|
1397
|
+
} else if (deltaMs < -DURATION_EPSILON_MS) {
|
|
1398
|
+
args.push("-t", String(targetMs / 1e3));
|
|
1399
|
+
}
|
|
1400
|
+
args.push(
|
|
1401
|
+
"-vf",
|
|
1402
|
+
vf.join(","),
|
|
1403
|
+
"-r",
|
|
1404
|
+
String(FPS),
|
|
1405
|
+
// -fps_mode replaced -vsync in ffmpeg 5.1; ffmpeg 9 removed -vsync.
|
|
1406
|
+
"-fps_mode",
|
|
1407
|
+
"cfr",
|
|
1408
|
+
"-pix_fmt",
|
|
1409
|
+
"yuv420p",
|
|
1410
|
+
"-an",
|
|
1411
|
+
outPath
|
|
1412
|
+
);
|
|
1413
|
+
await runFf("ffmpeg", args);
|
|
1414
|
+
}
|
|
1415
|
+
async function concatClips(clips, workDir, res) {
|
|
1416
|
+
const normalized = [];
|
|
1417
|
+
for (const [i, clip] of clips.entries()) {
|
|
1418
|
+
const sourcePath = clip.trim ? await extractClipTrim(clip.path, clip.trim, workDir, i) : clip.path;
|
|
1419
|
+
const outPath2 = join(workDir, `norm-${String(i)}.mp4`);
|
|
1420
|
+
await normalizeClip(sourcePath, outPath2, res, clip.targetMs, clip.fit);
|
|
1421
|
+
normalized.push(outPath2);
|
|
1422
|
+
}
|
|
1423
|
+
const listPath = join(workDir, "concat.txt");
|
|
1424
|
+
const listBody = normalized.map((p) => `file '${p.replace(/'/g, "'\\''")}'`).join("\n");
|
|
1425
|
+
writeFileSync(listPath, listBody, "utf8");
|
|
1426
|
+
const outPath = join(workDir, "video-silent.mp4");
|
|
1427
|
+
await runFf("ffmpeg", [
|
|
1428
|
+
"-y",
|
|
1429
|
+
"-f",
|
|
1430
|
+
"concat",
|
|
1431
|
+
"-safe",
|
|
1432
|
+
"0",
|
|
1433
|
+
"-i",
|
|
1434
|
+
listPath,
|
|
1435
|
+
"-c",
|
|
1436
|
+
"copy",
|
|
1437
|
+
outPath
|
|
1438
|
+
]);
|
|
1439
|
+
return outPath;
|
|
1440
|
+
}
|
|
1441
|
+
var NARRATION_LOUDNORM = "loudnorm=I=-16:TP=-1.5:LRA=11";
|
|
1442
|
+
var MUSIC_DYNAUDNORM = "dynaudnorm=g=15";
|
|
1443
|
+
async function buildAudioTrack(audio, music, videoDurationMs, workDir) {
|
|
1444
|
+
const videoDurationSec = videoDurationMs / 1e3;
|
|
1445
|
+
const fadeSec = music.fade / 1e3;
|
|
1446
|
+
const fadeOutStartSec = Math.max(0, videoDurationSec - fadeSec);
|
|
1447
|
+
const musicIndex = audio.narration.length;
|
|
1448
|
+
const filterParts = [];
|
|
1449
|
+
const narrationLabels = [];
|
|
1450
|
+
const narrationLoudnorm = await Promise.all(
|
|
1451
|
+
audio.narration.map((clip) => measuredLoudnormFilter(clip.path))
|
|
1452
|
+
);
|
|
1453
|
+
audio.narration.forEach((clip, i) => {
|
|
1454
|
+
filterParts.push(
|
|
1455
|
+
`[${String(i)}:a]aformat=channel_layouts=stereo,aresample=44100,${narrationLoudnorm[i] ?? NARRATION_LOUDNORM},adelay=delays=${String(clip.startMs)}:all=1[n${String(i)}]`
|
|
1456
|
+
);
|
|
1457
|
+
narrationLabels.push(`[n${String(i)}]`);
|
|
1458
|
+
});
|
|
1459
|
+
filterParts.push(
|
|
1460
|
+
`[${String(musicIndex)}:a]aformat=channel_layouts=stereo,aresample=44100,atrim=0:${String(videoDurationSec)},asetpts=N/SR/TB,${MUSIC_DYNAUDNORM},afade=t=in:st=0:d=${String(fadeSec)},afade=t=out:st=${String(fadeOutStartSec)}:d=${String(fadeSec)},volume=${String(music.duckDb)}dB[duck]`
|
|
1461
|
+
);
|
|
1462
|
+
let mixLabel;
|
|
1463
|
+
if (narrationLabels.length > 0) {
|
|
1464
|
+
filterParts.push(
|
|
1465
|
+
`${narrationLabels.join("")}amix=inputs=${String(narrationLabels.length)}:normalize=0:duration=longest:dropout_transition=0,alimiter=level=false:limit=0.9[narr]`
|
|
1466
|
+
);
|
|
1467
|
+
filterParts.push(
|
|
1468
|
+
`[narr][duck]amix=inputs=2:normalize=0:duration=longest:dropout_transition=0[mix]`
|
|
1469
|
+
);
|
|
1470
|
+
mixLabel = "[mix]";
|
|
1471
|
+
} else {
|
|
1472
|
+
mixLabel = "[duck]";
|
|
1473
|
+
}
|
|
1474
|
+
filterParts.push(
|
|
1475
|
+
`${mixLabel}atrim=0:${String(videoDurationSec)},asetpts=PTS-STARTPTS,apad=whole_dur=${String(videoDurationSec)}[final]`
|
|
1476
|
+
);
|
|
1477
|
+
const outPath = join(workDir, "audio-mix.m4a");
|
|
1478
|
+
const args = ["-y"];
|
|
1479
|
+
for (const clip of audio.narration) args.push("-i", clip.path);
|
|
1480
|
+
args.push("-stream_loop", "-1", "-i", audio.musicPath);
|
|
1481
|
+
args.push(
|
|
1482
|
+
"-filter_complex",
|
|
1483
|
+
filterParts.join(";"),
|
|
1484
|
+
"-map",
|
|
1485
|
+
"[final]",
|
|
1486
|
+
"-c:a",
|
|
1487
|
+
"aac",
|
|
1488
|
+
outPath
|
|
1489
|
+
);
|
|
1490
|
+
await runFf("ffmpeg", args);
|
|
1491
|
+
return outPath;
|
|
1492
|
+
}
|
|
1493
|
+
async function muxFinal(videoPath, audioPath, outPath) {
|
|
1494
|
+
await runFf("ffmpeg", [
|
|
1495
|
+
"-y",
|
|
1496
|
+
"-i",
|
|
1497
|
+
videoPath,
|
|
1498
|
+
"-i",
|
|
1499
|
+
audioPath,
|
|
1500
|
+
"-map",
|
|
1501
|
+
"0:v",
|
|
1502
|
+
"-map",
|
|
1503
|
+
"1:a",
|
|
1504
|
+
"-c:v",
|
|
1505
|
+
"copy",
|
|
1506
|
+
"-c:a",
|
|
1507
|
+
"aac",
|
|
1508
|
+
"-movflags",
|
|
1509
|
+
"+faststart",
|
|
1510
|
+
"-shortest",
|
|
1511
|
+
outPath
|
|
1512
|
+
]);
|
|
1513
|
+
}
|
|
1514
|
+
function escapeHtml(value) {
|
|
1515
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
1516
|
+
}
|
|
1517
|
+
function toDataUri(path2) {
|
|
1518
|
+
const bytes = readFileSync(path2);
|
|
1519
|
+
return `data:image/png;base64,${bytes.toString("base64")}`;
|
|
1520
|
+
}
|
|
1521
|
+
function renderDeckPage(item, sourceItem, screenshotPath, narration) {
|
|
1522
|
+
const durationMs = item.endMs - item.startMs;
|
|
1523
|
+
const image = screenshotPath ? `<img class="deck-page__shot" src="${toDataUri(screenshotPath)}" />` : "";
|
|
1524
|
+
const title = sourceItem?.kind === "scene" ? sourceItem.data.title : void 0;
|
|
1525
|
+
const subtitle = sourceItem?.kind === "scene" ? sourceItem.data.subtitle : void 0;
|
|
1526
|
+
const heading = typeof title === "string" && title.length > 0 ? title : item.id;
|
|
1527
|
+
const subtitleHtml = typeof subtitle === "string" && subtitle.length > 0 ? `<p class="deck-page__subtitle">${escapeHtml(subtitle)}</p>` : "";
|
|
1528
|
+
const narrationText = sourceItem?.narration;
|
|
1529
|
+
const narrationMeta = narration ? ` (${String(narration.durationMs)}ms audio clip)` : "";
|
|
1530
|
+
const narrationHtml = narrationText && narrationText.length > 0 ? `<p class="deck-page__narration">“${escapeHtml(narrationText)}”${escapeHtml(narrationMeta)}</p>` : "";
|
|
1531
|
+
return `<section class="deck-page">
|
|
1532
|
+
<h2>${escapeHtml(heading)}</h2>
|
|
1533
|
+
${subtitleHtml}
|
|
1534
|
+
<p class="deck-page__meta">${escapeHtml(item.kind)} \u2014 ${String(item.startMs)}ms\u2013${String(item.endMs)}ms (${String(durationMs)}ms)</p>
|
|
1535
|
+
${image}
|
|
1536
|
+
${narrationHtml}
|
|
1537
|
+
</section>`;
|
|
1538
|
+
}
|
|
1539
|
+
function renderDeckHtml(pages) {
|
|
1540
|
+
const title = "Showreel";
|
|
1541
|
+
return `<!doctype html>
|
|
1542
|
+
<html>
|
|
1543
|
+
<head>
|
|
1544
|
+
<meta charset="utf-8" />
|
|
1545
|
+
<style>
|
|
1546
|
+
* { box-sizing: border-box; }
|
|
1547
|
+
body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; color: #16181d; }
|
|
1548
|
+
.deck-cover { height: 100vh; display: flex; align-items: center; justify-content: center; background: #0a0a0f; color: #ffffff; page-break-after: always; }
|
|
1549
|
+
.deck-cover h1 { font-size: 42pt; margin: 0; }
|
|
1550
|
+
.deck-page { padding: 24px; page-break-after: always; }
|
|
1551
|
+
.deck-page:last-child { page-break-after: auto; }
|
|
1552
|
+
.deck-page h2 { margin: 0 0 8px; }
|
|
1553
|
+
.deck-page__subtitle { color: #33384a; margin: 0 0 12px; font-size: 14pt; }
|
|
1554
|
+
.deck-page__meta { color: #5b6170; margin: 0 0 16px; }
|
|
1555
|
+
.deck-page__shot { max-width: 100%; border: 1px solid #e2e4ee; border-radius: 8px; }
|
|
1556
|
+
.deck-page__narration { margin-top: 12px; font-style: italic; color: #333333; }
|
|
1557
|
+
</style>
|
|
1558
|
+
</head>
|
|
1559
|
+
<body>
|
|
1560
|
+
<section class="deck-cover"><h1>${escapeHtml(title)}</h1></section>
|
|
1561
|
+
${pages.join("\n")}
|
|
1562
|
+
</body>
|
|
1563
|
+
</html>`;
|
|
1564
|
+
}
|
|
1565
|
+
function buildDeckHtml(measured, captures, audio, timeline) {
|
|
1566
|
+
const captureById = /* @__PURE__ */ new Map();
|
|
1567
|
+
for (const capture of captures) {
|
|
1568
|
+
for (const item of capture.timeline) captureById.set(item.id, capture);
|
|
1569
|
+
}
|
|
1570
|
+
const narrationById = new Map(audio.narration.map((clip) => [clip.id, clip]));
|
|
1571
|
+
const timelineById = new Map(timeline.map((item) => [item.id, item]));
|
|
1572
|
+
const screenshotCursor = /* @__PURE__ */ new Map();
|
|
1573
|
+
const pages = [];
|
|
1574
|
+
for (const item of measured) {
|
|
1575
|
+
const narration = narrationById.get(item.id);
|
|
1576
|
+
const sourceItem = timelineById.get(item.id);
|
|
1577
|
+
if (item.kind === "capture") {
|
|
1578
|
+
const capture = captureById.get(item.id);
|
|
1579
|
+
let screenshotPath;
|
|
1580
|
+
if (capture) {
|
|
1581
|
+
const cursor = screenshotCursor.get(capture) ?? 0;
|
|
1582
|
+
screenshotPath = capture.screenshots[cursor];
|
|
1583
|
+
if (screenshotPath) screenshotCursor.set(capture, cursor + 1);
|
|
1584
|
+
}
|
|
1585
|
+
pages.push(renderDeckPage(item, sourceItem, screenshotPath, narration));
|
|
1586
|
+
} else {
|
|
1587
|
+
pages.push(renderDeckPage(item, sourceItem, void 0, narration));
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
return renderDeckHtml(pages);
|
|
1591
|
+
}
|
|
1592
|
+
async function buildDeck(measured, captures, audio, timeline, deckPath) {
|
|
1593
|
+
const html = buildDeckHtml(measured, captures, audio, timeline);
|
|
1594
|
+
try {
|
|
1595
|
+
const chromePath = findChrome() ?? void 0;
|
|
1596
|
+
const artifact = await exportHtml(html, {
|
|
1597
|
+
format: "pdf",
|
|
1598
|
+
name: "deck",
|
|
1599
|
+
renderer: localChromeRenderer(chromePath)
|
|
1600
|
+
});
|
|
1601
|
+
writeFileSync(deckPath, artifact.bytes);
|
|
1602
|
+
} catch (err) {
|
|
1603
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1604
|
+
writeFileSync(deckPath, `deck export failed: ${message}
|
|
1605
|
+
`, "utf8");
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
async function assemble(input) {
|
|
1609
|
+
const { measured, captures, scenes, clips: clipResults, audio, music, output, timeline } = input;
|
|
1610
|
+
const outDir = resolve(process.cwd(), output.dir);
|
|
1611
|
+
mkdirSync(outDir, { recursive: true });
|
|
1612
|
+
const workDir = mkdtempSync(join(tmpdir(), "showreel-assemble-"));
|
|
1613
|
+
const resolution = resolveResolution(output.res);
|
|
1614
|
+
const clipEntries = buildClipList(measured, captures, scenes, clipResults);
|
|
1615
|
+
if (clipEntries.length === 0) {
|
|
1616
|
+
throw new Error("assemble: measured timeline resolved to zero clips");
|
|
1617
|
+
}
|
|
1618
|
+
const silentVideoPath = await concatClips(clipEntries, workDir, resolution);
|
|
1619
|
+
const videoDurationMs = await ffprobeDurationMs3(silentVideoPath);
|
|
1620
|
+
const audioMixPath = await buildAudioTrack(
|
|
1621
|
+
audio,
|
|
1622
|
+
music,
|
|
1623
|
+
videoDurationMs,
|
|
1624
|
+
workDir
|
|
1625
|
+
);
|
|
1626
|
+
const videoPath = join(outDir, output.video);
|
|
1627
|
+
await muxFinal(silentVideoPath, audioMixPath, videoPath);
|
|
1628
|
+
const deckPath = join(outDir, output.deck);
|
|
1629
|
+
await buildDeck(measured, captures, audio, timeline, deckPath);
|
|
1630
|
+
return { videoPath, deckPath };
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
// src/orchestrate/segment.ts
|
|
1634
|
+
function segmentTimeline(timeline) {
|
|
1635
|
+
const segments = [];
|
|
1636
|
+
let i = 0;
|
|
1637
|
+
while (i < timeline.length) {
|
|
1638
|
+
const item = timeline[i];
|
|
1639
|
+
if (!item) break;
|
|
1640
|
+
if (item.kind === "scene") {
|
|
1641
|
+
segments.push({ kind: "scene", item, index: i });
|
|
1642
|
+
i += 1;
|
|
1643
|
+
continue;
|
|
1644
|
+
}
|
|
1645
|
+
if (item.kind === "clip") {
|
|
1646
|
+
segments.push({ kind: "clip", item, index: i });
|
|
1647
|
+
i += 1;
|
|
1648
|
+
continue;
|
|
1649
|
+
}
|
|
1650
|
+
const items = [];
|
|
1651
|
+
const indices = [];
|
|
1652
|
+
while (i < timeline.length) {
|
|
1653
|
+
const next = timeline[i];
|
|
1654
|
+
if (!next || next.kind !== "capture") break;
|
|
1655
|
+
items.push(next);
|
|
1656
|
+
indices.push(i);
|
|
1657
|
+
i += 1;
|
|
1658
|
+
}
|
|
1659
|
+
segments.push({ kind: "capture", items, indices });
|
|
1660
|
+
}
|
|
1661
|
+
return segments;
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
// src/orchestrate/timeline.ts
|
|
1665
|
+
async function buildMasterTimeline(timeline, measure, measureClip2) {
|
|
1666
|
+
const segments = segmentTimeline(timeline);
|
|
1667
|
+
const measured = [];
|
|
1668
|
+
const captureSegments = [];
|
|
1669
|
+
const sceneSlots = /* @__PURE__ */ new Map();
|
|
1670
|
+
let cursorMs = 0;
|
|
1671
|
+
for (const segment of segments) {
|
|
1672
|
+
if (segment.kind === "scene") {
|
|
1673
|
+
const startMs = cursorMs;
|
|
1674
|
+
const endMs = startMs + segment.item.duration;
|
|
1675
|
+
const slot = {
|
|
1676
|
+
id: segment.item.id,
|
|
1677
|
+
kind: "scene",
|
|
1678
|
+
startMs,
|
|
1679
|
+
endMs
|
|
1680
|
+
};
|
|
1681
|
+
measured.push(slot);
|
|
1682
|
+
sceneSlots.set(segment.item.id, slot);
|
|
1683
|
+
cursorMs = endMs;
|
|
1684
|
+
continue;
|
|
1685
|
+
}
|
|
1686
|
+
if (segment.kind === "clip") {
|
|
1687
|
+
const startMs = cursorMs;
|
|
1688
|
+
if (!measureClip2) {
|
|
1689
|
+
throw new Error(
|
|
1690
|
+
`buildMasterTimeline: timeline includes clip "${segment.item.id}" but no measureClip callback was provided`
|
|
1691
|
+
);
|
|
1692
|
+
}
|
|
1693
|
+
const slot = await measureClip2(segment.item, startMs);
|
|
1694
|
+
if (slot.id !== segment.item.id) {
|
|
1695
|
+
throw new Error(
|
|
1696
|
+
`buildMasterTimeline: measureClip returned a slot for "${slot.id}", expected "${segment.item.id}"`
|
|
1697
|
+
);
|
|
1698
|
+
}
|
|
1699
|
+
if (slot.startMs !== startMs) {
|
|
1700
|
+
throw new Error(
|
|
1701
|
+
`buildMasterTimeline: clip "${segment.item.id}" must start at ${String(startMs)}ms, measureClip returned ${String(slot.startMs)}ms`
|
|
1702
|
+
);
|
|
1703
|
+
}
|
|
1704
|
+
if (slot.endMs < slot.startMs) {
|
|
1705
|
+
throw new Error(
|
|
1706
|
+
`buildMasterTimeline: clip "${segment.item.id}" has endMs (${String(slot.endMs)}) before startMs (${String(slot.startMs)})`
|
|
1707
|
+
);
|
|
1708
|
+
}
|
|
1709
|
+
measured.push(slot);
|
|
1710
|
+
cursorMs = slot.endMs;
|
|
1711
|
+
continue;
|
|
1712
|
+
}
|
|
1713
|
+
const startOffsetMs = cursorMs;
|
|
1714
|
+
const { slots } = await measure(segment.items, startOffsetMs);
|
|
1715
|
+
if (slots.length !== segment.items.length) {
|
|
1716
|
+
throw new Error(
|
|
1717
|
+
`buildMasterTimeline: measure() returned ${String(slots.length)} slot(s) for a ${String(segment.items.length)}-item capture segment starting at ${String(startOffsetMs)}ms`
|
|
1718
|
+
);
|
|
1719
|
+
}
|
|
1720
|
+
let lastEndMs = startOffsetMs;
|
|
1721
|
+
segment.items.forEach((item, i) => {
|
|
1722
|
+
const slot = slots[i];
|
|
1723
|
+
if (!slot) {
|
|
1724
|
+
throw new Error(
|
|
1725
|
+
`buildMasterTimeline: measure() returned no slot at index ${String(i)} for capture segment starting at ${String(startOffsetMs)}ms`
|
|
1726
|
+
);
|
|
1727
|
+
}
|
|
1728
|
+
if (slot.id !== item.id) {
|
|
1729
|
+
throw new Error(
|
|
1730
|
+
`buildMasterTimeline: measure() slot order mismatch at index ${String(i)} \u2014 expected id "${item.id}", got "${slot.id}"`
|
|
1731
|
+
);
|
|
1732
|
+
}
|
|
1733
|
+
if (i === 0 && slot.startMs !== startOffsetMs) {
|
|
1734
|
+
throw new Error(
|
|
1735
|
+
`buildMasterTimeline: capture segment must start at ${String(startOffsetMs)}ms, first slot "${slot.id}" started at ${String(slot.startMs)}ms`
|
|
1736
|
+
);
|
|
1737
|
+
}
|
|
1738
|
+
if (slot.endMs < slot.startMs) {
|
|
1739
|
+
throw new Error(
|
|
1740
|
+
`buildMasterTimeline: capture slot "${slot.id}" has endMs (${String(slot.endMs)}) before startMs (${String(slot.startMs)})`
|
|
1741
|
+
);
|
|
1742
|
+
}
|
|
1743
|
+
measured.push(slot);
|
|
1744
|
+
lastEndMs = slot.endMs;
|
|
1745
|
+
});
|
|
1746
|
+
captureSegments.push({
|
|
1747
|
+
ids: segment.items.map((item) => item.id),
|
|
1748
|
+
startOffsetMs
|
|
1749
|
+
});
|
|
1750
|
+
cursorMs = lastEndMs;
|
|
1751
|
+
}
|
|
1752
|
+
return { measured, captureSegments, sceneSlots };
|
|
1753
|
+
}
|
|
1754
|
+
|
|
1755
|
+
// src/orchestrate/index.ts
|
|
1756
|
+
var DEFAULT_SCENE_CONCURRENCY = 3;
|
|
1757
|
+
async function mapWithConcurrency(items, concurrency, worker) {
|
|
1758
|
+
const results = new Array(items.length);
|
|
1759
|
+
let next = 0;
|
|
1760
|
+
async function lane() {
|
|
1761
|
+
for (; ; ) {
|
|
1762
|
+
const index = next;
|
|
1763
|
+
next += 1;
|
|
1764
|
+
if (index >= items.length) return;
|
|
1765
|
+
const item = items[index];
|
|
1766
|
+
results[index] = await worker(item, index);
|
|
1767
|
+
}
|
|
1768
|
+
}
|
|
1769
|
+
const laneCount = Math.max(1, Math.min(concurrency, items.length));
|
|
1770
|
+
await Promise.all(Array.from({ length: laneCount }, () => lane()));
|
|
1771
|
+
return results;
|
|
1772
|
+
}
|
|
1773
|
+
async function renderSceneAt(deps, built, brand, item) {
|
|
1774
|
+
const slot = built.sceneSlots.get(item.id);
|
|
1775
|
+
if (!slot) {
|
|
1776
|
+
throw new Error(
|
|
1777
|
+
`runShowreel: no measured slot found for scene "${item.id}" \u2014 buildMasterTimeline should have placed every declared scene.`
|
|
1778
|
+
);
|
|
1779
|
+
}
|
|
1780
|
+
return deps.renderScenes([item], brand, slot.startMs);
|
|
1781
|
+
}
|
|
1782
|
+
async function runShowreelWith(deps, config) {
|
|
1783
|
+
const cfg = validateConfig(config);
|
|
1784
|
+
const fs2 = deps.fs ?? createLocalFs(process.cwd());
|
|
1785
|
+
const brand = await resolveBrand(cfg.brand, { fs: fs2 });
|
|
1786
|
+
const captures = [];
|
|
1787
|
+
const measure = async (items, startOffsetMs) => {
|
|
1788
|
+
const result = await deps.runCapture(cfg.target, items, startOffsetMs);
|
|
1789
|
+
captures.push(result);
|
|
1790
|
+
return { slots: result.timeline };
|
|
1791
|
+
};
|
|
1792
|
+
const clips = [];
|
|
1793
|
+
const measureClipDep = deps.measureClip;
|
|
1794
|
+
const measureClipWalk = measureClipDep ? async (item, startOffsetMs) => {
|
|
1795
|
+
const resolved = await measureClipDep(item, startOffsetMs);
|
|
1796
|
+
clips.push(resolved.result);
|
|
1797
|
+
return resolved.slot;
|
|
1798
|
+
} : void 0;
|
|
1799
|
+
const built = await buildMasterTimeline(cfg.timeline, measure, measureClipWalk);
|
|
1800
|
+
const sceneItems = cfg.timeline.filter(
|
|
1801
|
+
(item) => item.kind === "scene"
|
|
1802
|
+
);
|
|
1803
|
+
const sceneConcurrency = deps.sceneConcurrency ?? DEFAULT_SCENE_CONCURRENCY;
|
|
1804
|
+
const scenes = await mapWithConcurrency(
|
|
1805
|
+
sceneItems,
|
|
1806
|
+
sceneConcurrency,
|
|
1807
|
+
(item) => renderSceneAt(deps, built, brand, item)
|
|
1808
|
+
);
|
|
1809
|
+
const audio = await deps.synthesizeAudio(
|
|
1810
|
+
cfg.timeline,
|
|
1811
|
+
built.measured,
|
|
1812
|
+
cfg.voice,
|
|
1813
|
+
cfg.music
|
|
1814
|
+
);
|
|
1815
|
+
const input = {
|
|
1816
|
+
measured: built.measured,
|
|
1817
|
+
captures,
|
|
1818
|
+
scenes,
|
|
1819
|
+
clips,
|
|
1820
|
+
audio,
|
|
1821
|
+
music: cfg.music,
|
|
1822
|
+
output: cfg.output,
|
|
1823
|
+
timeline: cfg.timeline
|
|
1824
|
+
};
|
|
1825
|
+
return deps.assemble(input);
|
|
1826
|
+
}
|
|
1827
|
+
function runShowreel(config, opts = {}) {
|
|
1828
|
+
const configDir = opts.configDir ?? process.cwd();
|
|
1829
|
+
return runShowreelWith(
|
|
1830
|
+
{
|
|
1831
|
+
runCapture,
|
|
1832
|
+
renderScenes,
|
|
1833
|
+
synthesizeAudio,
|
|
1834
|
+
assemble,
|
|
1835
|
+
measureClip: (item, startOffsetMs) => measureClip(item, startOffsetMs, configDir),
|
|
1836
|
+
sceneConcurrency: opts.sceneConcurrency
|
|
1837
|
+
},
|
|
1838
|
+
config
|
|
1839
|
+
);
|
|
1840
|
+
}
|
|
1841
|
+
|
|
1842
|
+
export { BUILTIN_SCENES, BrandFontSchema, BrandSchema, CaptureItemSchema, CaptureStepSchema, ClickStepSchema, ClipItemSchema, MusicSchema, NavigateStepSchema, OutputSchema, RecordSchema, SceneItemSchema, SceneTemplateRegistry, ScreenshotSchema, ShowreelConfigError, ShowreelConfigSchema, TargetSchema, TimelineItemSchema, TypeStepSchema, ViewportSchema, VoiceSchema, WaitForStepSchema, assemble, buildDeckHtml, buildMasterTimeline, builtinSceneSource, cachingVisualRenderer, computeTrimWindow, createDefaultSceneTemplateRegistry, createLocalFs, defaultSceneTemplateRegistry, encodeFramesToMp4, findChrome, htmlStillVisualRenderer, measureClip, renderCanva, renderSceneHtml, renderScenes, renderScenesWith, resolveBrand, resolveClipSrc, resolveSceneTemplate, resolveVisualRenderer, runCapture, runShowreel, runShowreelWith, segmentTimeline, synthesizeAudio, synthesizeAudioWith, validateConfig };
|
|
1843
|
+
//# sourceMappingURL=index.mjs.map
|
|
1844
|
+
//# sourceMappingURL=index.mjs.map
|