#!/usr/bin/env node // Renders docs/promo/web/index.html to docs/promo/hold-on-promo.mp4 by driving // a headless Edge/Chrome over the DevTools protocol. No npm dependencies. import { spawn } from 'node:child_process'; import { mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; const here = dirname(fileURLToPath(import.meta.url)); const promo = resolve(here, '..'); const framesDir = join(promo, 'frames'); const page = join(here, 'index.html'); const video = join(promo, 'hold-on-promo.mp4'); const poster = join(promo, 'hold-on-poster.png'); const score = join(promo, 'score.wav'); const scoreScript = join(here, 'score.mjs'); const args = process.argv.slice(2); const posterOnly = args.includes('--poster-only') || args.includes('--poster'); const skipFrames = args.includes('--skip-frames'); const FPS = 30; const DURATION = 28.6; const TOTAL = Math.round(FPS * DURATION); const PORT = 9333 + Math.floor(Math.random() * 200); const BROWSERS = [ 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', 'C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome', '/usr/bin/chromium', ]; function browserPath() { const found = BROWSERS.find(p => existsSync(p)); if (!found) throw new Error('no Edge/Chrome found'); return found; } const sleep = ms => new Promise(r => setTimeout(r, ms)); async function waitJson(url, tries = 100) { for (let i = 0; i < tries; i++) { try { const res = await fetch(url); if (res.ok) return await res.json(); } catch {} await sleep(100); } throw new Error(`devtools endpoint never answered: ${url}`); } class Cdp { constructor(url) { this.ws = new WebSocket(url); this.id = 0; this.pending = new Map(); this.ready = new Promise((res, rej) => { this.ws.onopen = res; this.ws.onerror = rej; }); this.ws.onmessage = ev => { const msg = JSON.parse(ev.data); if (msg.id && this.pending.has(msg.id)) { const { res, rej } = this.pending.get(msg.id); this.pending.delete(msg.id); msg.error ? rej(new Error(msg.error.message)) : res(msg.result); } }; } async send(method, params = {}) { await this.ready; const id = ++this.id; const p = new Promise((res, rej) => this.pending.set(id, { res, rej })); this.ws.send(JSON.stringify({ id, method, params })); return p; } close() { try { this.ws.close(); } catch {} } } async function launch() { const profile = join(process.env.TEMP || '.', `hold-on-cdp-${Date.now()}`); mkdirSync(profile, { recursive: true }); const child = spawn(browserPath(), [ '--headless=new', `--remote-debugging-port=${PORT}`, `--user-data-dir=${profile}`, '--no-first-run', '--no-default-browser-check', '--disable-extensions', '--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--hide-scrollbars', '--force-device-scale-factor=1', '--window-size=1920,1080', `file:///${page.replace(/\\/g, '/')}?render`, ], { stdio: 'ignore' }); const targets = await waitJson(`http://127.0.0.1:${PORT}/json/list`); const target = targets.find(t => t.type === 'page'); if (!target) throw new Error('no page target'); const cdp = new Cdp(target.webSocketDebuggerUrl); await cdp.send('Page.enable'); await cdp.send('Runtime.enable'); await cdp.send('Emulation.setDeviceMetricsOverride', { width: 1920, height: 1080, deviceScaleFactor: 1, mobile: false, }); await sleep(500); return { cdp, child, profile }; } async function seekAndShot(cdp, t, format = 'jpeg') { await cdp.send('Runtime.evaluate', { expression: `new Promise(r => { window.seek(${t.toFixed(4)}); requestAnimationFrame(() => r()); })`, awaitPromise: true, }); const shot = await cdp.send('Page.captureScreenshot', { format, ...(format === 'jpeg' ? { quality: 88 } : {}), captureBeyondViewport: false, fromSurface: true, }); return Buffer.from(shot.data, 'base64'); } async function main() { if (!existsSync(score)) { await new Promise((res, rej) => { const p = spawn(process.execPath, [scoreScript], { stdio: 'inherit' }); p.on('exit', c => (c === 0 ? res() : rej(new Error('score failed')))); p.on('error', rej); }); } if (!skipFrames) rmSync(framesDir, { recursive: true, force: true }); mkdirSync(framesDir, { recursive: true }); const started = Date.now(); const { cdp, child, profile } = await launch(); try { if (posterOnly) { writeFileSync(poster, await seekAndShot(cdp, 1.75, 'png')); console.log(`poster: ${poster}`); return; } if (!skipFrames) { for (let i = 0; i < TOTAL; i++) { const buf = await seekAndShot(cdp, i / FPS); writeFileSync(join(framesDir, `${String(i).padStart(5, '0')}.jpg`), buf); if (i % 60 === 0) { const secs = ((Date.now() - started) / 1000).toFixed(1); console.log(`frame ${i}/${TOTAL} ${secs}s`); } } } writeFileSync(poster, await seekAndShot(cdp, 1.75, 'png')); console.log('encoding…'); const encoder = await pickEncoder(); await encode(encoder); const secs = ((Date.now() - started) / 1000).toFixed(1); console.log(`video: ${video} ${secs}s`); } finally { cdp.close(); child.kill(); await sleep(300); try { rmSync(profile, { recursive: true, force: true }); } catch {} } } async function pickEncoder() { const run = codec => new Promise(res => { const p = spawn('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-f', 'lavfi', '-i', 'color=c=black:s=320x180:d=0.1', '-c:v', codec, '-f', 'null', '-'], { stdio: 'ignore' }); p.on('exit', c => res(c === 0)); p.on('error', () => res(false)); }); return (await run('h264_qsv')) ? 'h264_qsv' : 'libx264'; } function encode(codec) { return new Promise((res, rej) => { const videoArgs = codec === 'h264_qsv' ? ['-c:v', 'h264_qsv', '-global_quality', '20', '-preset', 'veryfast'] : ['-c:v', 'libx264', '-preset', 'veryfast', '-crf', '19']; const p = spawn('ffmpeg', [ '-y', '-loglevel', 'error', '-framerate', String(FPS), '-i', join(framesDir, '%05d.jpg'), '-i', score, ...videoArgs, '-pix_fmt', 'yuv420p', '-movflags', '+faststart', '-c:a', 'aac', '-b:a', '160k', '-shortest', video, ], { stdio: 'inherit' }); p.on('exit', c => (c === 0 ? res() : rej(new Error(`ffmpeg exited ${c}`)))); p.on('error', rej); }); } main().catch(err => { console.error(err); process.exit(1); });