@skilldeck/studio 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,370 @@
1
+ #!/usr/bin/env node
2
+ // studio / render.mjs
3
+ //
4
+ // Render an HTML composition deterministically. Headless Chrome is driven over raw
5
+ // CDP; for every frame the page's clock is seeked with window.__studio.seek(t) and
6
+ // the viewport is captured as PNG. `render` then encodes the frames with ffmpeg if
7
+ // it is on PATH, or prints the exact ffmpeg command to run.
8
+ //
9
+ // node render.mjs snapshot <comp.html> [--at 0,1.5,3] [--out dir] [--json]
10
+ // node render.mjs render <comp.html> [--out clip.mp4] [--from s] [--to s] [--fps n]
11
+ // [--scale n] [--audio file] [--crf n]
12
+ // [--frames dir] [--keep-frames] [--no-encode] [--json]
13
+ //
14
+ // Exit 0 on success, 1 when rendering or encoding fails, 2 on bad usage or a
15
+ // missing environment piece (Chrome, Node 22). Zero dependencies. Node 22+.
16
+
17
+ import { spawnSync } from 'node:child_process'
18
+ import fs from 'node:fs'
19
+ import path from 'node:path'
20
+ import { parseArgs } from 'node:util'
21
+ import { pathToFileURL } from 'node:url'
22
+ import { CDP, findChrome, launchChrome, openPage } from './lib/cdp.mjs'
23
+ import { lintFile } from './lint-comp.mjs'
24
+
25
+ const HELP = `render: snapshot or render an HTML composition with headless Chrome
26
+
27
+ node render.mjs snapshot <comp.html> [--at 0,1.5,3] [--out dir] [--scale n] [--json]
28
+ PNG stills at the given times (default: the middle of every scene)
29
+
30
+ node render.mjs render <comp.html> [options]
31
+ --out <file> output video (default <name>.mp4; .mp4, .webm, .mov or .gif)
32
+ --from <s> start time in seconds (default 0)
33
+ --to <s> end time in seconds (default the composition duration)
34
+ --fps <n> override data-fps
35
+ --scale <n> device scale factor, e.g. 2 for a 2x render (default 1)
36
+ --audio <file> mux an audio track
37
+ --crf <n> quality for H.264/VP9 (default 18 / 32)
38
+ --frames <dir> where PNG frames go (default <out>_frames)
39
+ --keep-frames keep the PNGs after encoding
40
+ --no-encode write frames only and print the ffmpeg command
41
+ --json machine-readable result
42
+
43
+ Chrome: found automatically, or set CHROME_PATH. ffmpeg: used from PATH when present.
44
+ Exit codes: 0 ok, 1 render/encode failure, 2 usage or environment error.
45
+ `
46
+
47
+ const EPS = 1e-9
48
+
49
+ export class UsageError extends Error {
50
+ constructor(msg) {
51
+ super(msg)
52
+ this.exitCode = 2
53
+ }
54
+ }
55
+
56
+ /** Parse CLI arguments into a normalized options object. Throws UsageError. */
57
+ export function parseRenderArgs(argv) {
58
+ let parsed
59
+ try {
60
+ parsed = parseArgs({
61
+ args: argv,
62
+ allowPositionals: true,
63
+ strict: true,
64
+ options: {
65
+ at: { type: 'string' },
66
+ out: { type: 'string', short: 'o' },
67
+ from: { type: 'string' },
68
+ to: { type: 'string' },
69
+ fps: { type: 'string' },
70
+ scale: { type: 'string' },
71
+ audio: { type: 'string' },
72
+ crf: { type: 'string' },
73
+ frames: { type: 'string' },
74
+ 'keep-frames': { type: 'boolean', default: false },
75
+ 'no-encode': { type: 'boolean', default: false },
76
+ timeout: { type: 'string' },
77
+ json: { type: 'boolean', default: false },
78
+ help: { type: 'boolean', short: 'h', default: false },
79
+ },
80
+ })
81
+ } catch (e) {
82
+ throw new UsageError(e.message)
83
+ }
84
+ const { values: v, positionals } = parsed
85
+ const [cmd, file, ...extra] = positionals
86
+ if (v.help) return { help: true }
87
+ if (!['snapshot', 'render'].includes(cmd)) throw new UsageError(`expected "snapshot" or "render", got ${cmd ? `"${cmd}"` : 'nothing'}`)
88
+ if (!file) throw new UsageError(`${cmd}: name a composition .html file`)
89
+ if (extra.length) throw new UsageError(`unexpected argument "${extra[0]}"`)
90
+ const number = (name, { min = -Infinity, int = false } = {}) => {
91
+ if (v[name] === undefined) return undefined
92
+ const n = Number(v[name])
93
+ if (!Number.isFinite(n) || n < min || (int && !Number.isInteger(n))) throw new UsageError(`--${name} must be a number${min > -Infinity ? ` >= ${min}` : ''}`)
94
+ return n
95
+ }
96
+ const at =
97
+ v.at === undefined
98
+ ? undefined
99
+ : v.at.split(',').map((s) => {
100
+ const n = Number(s.trim())
101
+ if (!s.trim() || !Number.isFinite(n) || n < 0) throw new UsageError(`--at takes comma-separated seconds, got "${s}"`)
102
+ return n
103
+ })
104
+ const opts = {
105
+ cmd,
106
+ file,
107
+ at,
108
+ out: v.out,
109
+ from: number('from', { min: 0 }),
110
+ to: number('to', { min: 0 }),
111
+ fps: number('fps', { min: 1 }),
112
+ scale: number('scale', { min: 0.1 }) ?? 1,
113
+ audio: v.audio,
114
+ crf: number('crf', { min: 0, int: true }),
115
+ frames: v.frames,
116
+ keepFrames: v['keep-frames'],
117
+ encode: !v['no-encode'],
118
+ timeoutMs: (number('timeout', { min: 1 }) ?? 60) * 1000,
119
+ json: v.json,
120
+ }
121
+ if (opts.from !== undefined && opts.to !== undefined && opts.to <= opts.from) throw new UsageError('--to must be after --from')
122
+ return opts
123
+ }
124
+
125
+ /** Frame indices and times for [from, to) at fps. Frame i is at t = i / fps. */
126
+ export function frameTimes({ fps, duration, from = 0, to = duration }) {
127
+ const first = Math.max(0, Math.ceil(from * fps - 1e-6))
128
+ const last = Math.ceil(Math.min(to, duration) * fps - 1e-6) // exclusive
129
+ const out = []
130
+ for (let i = first; i < last; i++) out.push({ index: i, t: i / fps })
131
+ return out
132
+ }
133
+
134
+ /** Default snapshot times: the middle of every scene, plus 0, de-duplicated and sorted. */
135
+ export function defaultSnapshotTimes(scenes, duration) {
136
+ const ts = [0, ...scenes.map((s) => s.start + s.duration / 2)].filter((t) => t >= 0 && t < duration + EPS)
137
+ return [...new Set(ts.map((t) => Number(t.toFixed(3))))].sort((a, b) => a - b)
138
+ }
139
+
140
+ /** ffmpeg arguments to encode frame_%05d.png in framesDir into `out`. */
141
+ export function ffmpegArgs({ fps, framesDir, out, audio, crf, pattern = 'frame_%05d.png' }) {
142
+ const ext = path.extname(out).toLowerCase()
143
+ const input = ['-y', '-hide_banner', '-loglevel', 'error', '-framerate', String(fps), '-start_number', '0', '-i', path.join(framesDir, pattern)]
144
+ const even = ['-vf', 'pad=ceil(iw/2)*2:ceil(ih/2)*2']
145
+ if (ext === '.gif') {
146
+ return [...input, '-vf', 'split[a][b];[a]palettegen=stats_mode=diff[p];[b][p]paletteuse=dither=bayer', '-loop', '0', out]
147
+ }
148
+ const withAudio = audio ? ['-i', audio] : []
149
+ if (ext === '.webm') {
150
+ return [...input, ...withAudio, ...even, '-c:v', 'libvpx-vp9', '-b:v', '0', '-crf', String(crf ?? 32), '-pix_fmt', 'yuv420p', ...(audio ? ['-c:a', 'libopus', '-shortest'] : []), out]
151
+ }
152
+ if (ext === '.mov') {
153
+ return [...input, ...withAudio, '-c:v', 'prores_ks', '-profile:v', '3', '-pix_fmt', 'yuv422p10le', ...(audio ? ['-c:a', 'pcm_s16le', '-shortest'] : []), out]
154
+ }
155
+ return [...input, ...withAudio, ...even, '-c:v', 'libx264', '-preset', 'medium', '-crf', String(crf ?? 18), '-pix_fmt', 'yuv420p', '-movflags', '+faststart', ...(audio ? ['-c:a', 'aac', '-b:a', '192k', '-shortest'] : []), out]
156
+ }
157
+
158
+ /** Quote an argv for a POSIX shell, so the printed command can be pasted. */
159
+ export function shellQuote(args) {
160
+ return args.map((a) => (/^[\w@%+=:,./-]+$/.test(a) ? a : `'${String(a).replace(/'/g, `'\\''`)}'`)).join(' ')
161
+ }
162
+
163
+ /** Absolute path of an executable on PATH, or null. */
164
+ export function which(cmd, env = process.env) {
165
+ const exts = process.platform === 'win32' ? (env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';') : ['']
166
+ for (const dir of (env.PATH ?? '').split(path.delimiter).filter(Boolean)) {
167
+ for (const ext of exts) {
168
+ const p = path.join(dir, cmd + ext)
169
+ try {
170
+ if (fs.statSync(p).isFile()) return p
171
+ } catch {}
172
+ }
173
+ }
174
+ return null
175
+ }
176
+
177
+ // ---------------------------------------------------------------------------
178
+ // Driving the page
179
+ // ---------------------------------------------------------------------------
180
+
181
+ /**
182
+ * Open a composition in headless Chrome at its native size and wait for the
183
+ * runtime to be ready. Returns { page, config, scenes, issues, close }.
184
+ */
185
+ export async function openComposition(file, { scale = 1, timeoutMs = 60000 } = {}) {
186
+ const abs = path.resolve(file)
187
+ const lint = lintFile(abs)
188
+ if (!lint.config || !Number.isInteger(lint.config.width) || !Number.isInteger(lint.config.height)) {
189
+ throw new Error('composition root is missing or has no valid data-width / data-height (run lint)')
190
+ }
191
+ const chrome = findChrome()
192
+ if (!chrome.path) throw Object.assign(new Error(chrome.error), { exitCode: 2 })
193
+ const browser = await launchChrome({ chromePath: chrome.path })
194
+ let cdp
195
+ const close = async () => {
196
+ if (cdp) {
197
+ let t
198
+ await Promise.race([cdp.send('Browser.close').catch(() => {}), new Promise((r) => (t = setTimeout(r, 2000)))])
199
+ clearTimeout(t)
200
+ cdp.close()
201
+ }
202
+ await browser.close()
203
+ }
204
+ try {
205
+ cdp = await CDP.connect(browser.wsUrl)
206
+ const page = await openPage(cdp)
207
+ const issues = []
208
+ const urls = new Map()
209
+ page.on('Runtime.exceptionThrown', (p) => issues.push({ kind: 'exception', message: p.exceptionDetails?.exception?.description ?? p.exceptionDetails?.text }))
210
+ page.on('Runtime.consoleAPICalled', (p) => {
211
+ if (p.type === 'error') issues.push({ kind: 'console', message: p.args.map((a) => a.value ?? a.description ?? '').join(' ') })
212
+ })
213
+ page.on('Network.requestWillBeSent', (p) => urls.set(p.requestId, p.request.url))
214
+ page.on('Network.loadingFailed', (p) => issues.push({ kind: 'network', message: `${p.errorText}: ${urls.get(p.requestId) ?? p.requestId}` }))
215
+ await Promise.all([page.send('Page.enable'), page.send('Runtime.enable'), page.send('Network.enable')])
216
+ await page.send('Page.addScriptToEvaluateOnNewDocument', { source: 'window.__STUDIO_RENDER__ = true' })
217
+ const { width, height } = lint.config
218
+ await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: scale, mobile: false })
219
+ const loaded = page.once('Page.loadEventFired', { timeoutMs })
220
+ await page.send('Page.navigate', { url: pathToFileURL(abs).href })
221
+ await loaded
222
+ const info = await page.evaluate(
223
+ `(async () => {
224
+ if (!window.__studio || typeof window.__studio.seek !== 'function') return null
225
+ const config = await window.__studio.ready
226
+ return { config: window.__studio.config || config, scenes: (window.__studio.scenes || []).map(s => ({ id: s.id, start: s.start, duration: s.duration, track: s.track })) }
227
+ })()`,
228
+ { timeoutMs },
229
+ )
230
+ if (!info) throw new Error('the page has no window.__studio.seek(t): include the studio runtime (see video-compose)')
231
+ return { page, config: info.config, scenes: info.scenes, issues, close }
232
+ } catch (e) {
233
+ await close()
234
+ throw e
235
+ }
236
+ }
237
+
238
+ /** Seek the clock to t and capture the viewport as a PNG buffer. */
239
+ export async function captureAt(page, t, { timeoutMs = 60000 } = {}) {
240
+ await page.evaluate(`window.__studio.seek(${Number(t)}).then(() => true)`, { timeoutMs })
241
+ const { data } = await page.send('Page.captureScreenshot', { format: 'png', fromSurface: true, captureBeyondViewport: false })
242
+ return Buffer.from(data, 'base64')
243
+ }
244
+
245
+ const log = (opts, msg) => {
246
+ if (!opts.json) process.stderr.write(msg)
247
+ }
248
+
249
+ export async function snapshot(opts) {
250
+ const comp = await openComposition(opts.file, opts)
251
+ try {
252
+ const times = (opts.at ?? defaultSnapshotTimes(comp.scenes, comp.config.duration)).map((t) => Math.min(t, comp.config.duration))
253
+ const outDir = path.resolve(opts.out ?? `${path.basename(opts.file, path.extname(opts.file))}_snapshots`)
254
+ fs.mkdirSync(outDir, { recursive: true })
255
+ const files = []
256
+ for (const t of times) {
257
+ const png = await captureAt(comp.page, t, opts)
258
+ const f = path.join(outDir, `t${t.toFixed(3).padStart(8, '0')}s.png`)
259
+ fs.writeFileSync(f, png)
260
+ files.push({ t, file: f })
261
+ log(opts, `snapshot ${t.toFixed(3)}s -> ${f}\n`)
262
+ }
263
+ return { ok: comp.issues.length === 0, config: comp.config, snapshots: files, issues: comp.issues }
264
+ } finally {
265
+ await comp.close()
266
+ }
267
+ }
268
+
269
+ export async function render(opts) {
270
+ const base = path.basename(opts.file, path.extname(opts.file))
271
+ const out = path.resolve(opts.out ?? `${base}.mp4`)
272
+ const framesDir = path.resolve(opts.frames ?? `${out.slice(0, -path.extname(out).length || undefined)}_frames`)
273
+ if (opts.audio && !fs.existsSync(opts.audio)) throw new UsageError(`--audio file not found: ${opts.audio}`)
274
+ const comp = await openComposition(opts.file, opts)
275
+ const fps = opts.fps ?? comp.config.fps
276
+ const frames = frameTimes({ fps, duration: comp.config.duration, from: opts.from ?? 0, to: opts.to ?? comp.config.duration })
277
+ if (!frames.length) {
278
+ await comp.close()
279
+ throw new UsageError('no frames in the requested range')
280
+ }
281
+ fs.mkdirSync(framesDir, { recursive: true })
282
+ for (const f of fs.readdirSync(framesDir)) if (/^frame_\d+\.png$/.test(f)) fs.rmSync(path.join(framesDir, f))
283
+ const started = Date.now()
284
+ try {
285
+ for (let n = 0; n < frames.length; n++) {
286
+ const png = await captureAt(comp.page, frames[n].t, opts)
287
+ fs.writeFileSync(path.join(framesDir, `frame_${String(n).padStart(5, '0')}.png`), png)
288
+ if (process.stderr.isTTY && (n % Math.max(1, Math.round(frames.length / 20)) === 0 || n === frames.length - 1)) log(opts, `\rframe ${n + 1}/${frames.length}`)
289
+ }
290
+ if (process.stderr.isTTY) log(opts, '\n')
291
+ } finally {
292
+ await comp.close()
293
+ }
294
+ const args = ffmpegArgs({ fps, framesDir, out, audio: opts.audio, crf: opts.crf })
295
+ const ffmpeg = which('ffmpeg')
296
+ const result = {
297
+ ok: true,
298
+ config: { ...comp.config, fps },
299
+ frames: frames.length,
300
+ from: frames[0].t,
301
+ to: frames[frames.length - 1].t + 1 / fps,
302
+ framesDir,
303
+ renderSeconds: Number(((Date.now() - started) / 1000).toFixed(2)),
304
+ ffmpegCommand: shellQuote(['ffmpeg', ...args]),
305
+ encoded: false,
306
+ out: null,
307
+ issues: comp.issues,
308
+ }
309
+ if (!opts.encode || !ffmpeg) {
310
+ result.note = ffmpeg ? 'encoding skipped (--no-encode)' : 'ffmpeg is not on PATH: install it, then run this command'
311
+ return result
312
+ }
313
+ fs.mkdirSync(path.dirname(out), { recursive: true })
314
+ const r = spawnSync(ffmpeg, args, { encoding: 'utf8' })
315
+ if (r.status !== 0) {
316
+ result.ok = false
317
+ result.error = `ffmpeg failed (exit ${r.status}): ${(r.stderr || '').trim().slice(-1500)}`
318
+ return result
319
+ }
320
+ result.encoded = true
321
+ result.out = out
322
+ if (!opts.keepFrames) {
323
+ fs.rmSync(framesDir, { recursive: true, force: true })
324
+ result.framesDir = null
325
+ }
326
+ return result
327
+ }
328
+
329
+ function printResult(r, cmd) {
330
+ if (cmd === 'snapshot') {
331
+ console.log(`${r.snapshots.length} snapshot(s) of ${r.config.width}x${r.config.height}`)
332
+ } else {
333
+ console.log(`${r.frames} frames at ${r.config.fps} fps (${r.from}s-${Number(r.to.toFixed(3))}s) in ${r.renderSeconds}s`)
334
+ if (r.encoded) console.log(`wrote ${r.out}`)
335
+ else if (r.error) console.log(r.error)
336
+ else console.log(`frames in ${r.framesDir}\n${r.note}\n\n ${r.ffmpegCommand}\n`)
337
+ }
338
+ for (const i of r.issues) console.log(`page ${i.kind}: ${i.message}`)
339
+ }
340
+
341
+ async function main(argv) {
342
+ let opts
343
+ try {
344
+ opts = parseRenderArgs(argv)
345
+ } catch (e) {
346
+ process.stderr.write(`render: ${e.message}\n\n${HELP}`)
347
+ return 2
348
+ }
349
+ if (opts.help) {
350
+ process.stdout.write(HELP)
351
+ return 0
352
+ }
353
+ if (!fs.existsSync(opts.file)) {
354
+ process.stderr.write(`render: ${opts.file} not found\n`)
355
+ return 2
356
+ }
357
+ try {
358
+ const r = opts.cmd === 'snapshot' ? await snapshot(opts) : await render(opts)
359
+ if (opts.json) console.log(JSON.stringify(r, null, 2))
360
+ else printResult(r, opts.cmd)
361
+ return r.error ? 1 : 0
362
+ } catch (e) {
363
+ const code = e.exitCode ?? (e.code === 'ENOCHROME' || e.code === 'ENODE' ? 2 : 1)
364
+ if (opts.json) console.log(JSON.stringify({ ok: false, error: e.message }, null, 2))
365
+ else process.stderr.write(`render: ${e.message}\n`)
366
+ return code
367
+ }
368
+ }
369
+
370
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) process.exitCode = await main(process.argv.slice(2))