1
0

render-video.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. #!/usr/bin/env node
  2. /**
  3. * HTML animation → MP4 via Playwright recordVideo + ffmpeg.
  4. *
  5. * Requires: global playwright (`npm install -g playwright`), ffmpeg on PATH.
  6. *
  7. * Usage:
  8. * NODE_PATH=$(npm root -g) node render-video.js <html-file> \
  9. * [--duration=30] [--width=1920] [--height=1080] \
  10. * [--trim=<seconds>] [--fontwait=1.5] [--readytimeout=8] \
  11. * [--keep-chrome]
  12. *
  13. * Design:
  14. * 1. Warmup context (no record) — caches fonts/assets, closes cleanly
  15. * 2. Record context (fresh, recordVideo ON) — WebM starts writing at
  16. * context creation. Babel-standalone compile + React mount +
  17. * fonts.ready can take 1.5-3s, during which WebM writes black frames.
  18. * We measure this by waiting for window.__ready (set by animations.jsx
  19. * Stage component after first paint), then trim exactly that offset.
  20. * 3. addInitScript injects CSS hiding "chrome" elements (progress bar,
  21. * replay button, masthead, footer, etc.) that are fine for human
  22. * debugging but shouldn't appear in exported video.
  23. *
  24. * Animation-ready signal:
  25. * Set `window.__ready = true` in your HTML after first paint. This tells
  26. * the recorder "animation has started rendering — treat now as t=0".
  27. * If you use animations.jsx, Stage does this automatically. Otherwise
  28. * add: `document.fonts.ready.then(() => requestAnimationFrame(() => { window.__ready = true }));`
  29. * after your first render call.
  30. *
  31. * Without __ready, falls back to --fontwait=1.5s (may leave 1-2s of black
  32. * at the start). Pass --trim=<seconds> to override manually.
  33. *
  34. * Chrome elements hidden by default (all common class names + `.no-record`
  35. * convention). Pass --keep-chrome to disable this and see raw HTML.
  36. *
  37. * Output: next to the HTML file, same basename with .mp4 suffix.
  38. */
  39. const { chromium } = require('playwright');
  40. const path = require('path');
  41. const fs = require('fs');
  42. const { spawnSync } = require('child_process');
  43. function arg(name, def) {
  44. const p = process.argv.find(a => a.startsWith('--' + name + '='));
  45. return p ? p.slice(name.length + 3) : def;
  46. }
  47. function hasFlag(name) {
  48. return process.argv.includes('--' + name);
  49. }
  50. const HTML_FILE = process.argv[2];
  51. if (!HTML_FILE || HTML_FILE.startsWith('--')) {
  52. console.error('Usage: node render-video.js <html-file>');
  53. console.error('Example: NODE_PATH=$(npm root -g) node render-video.js my-animation.html');
  54. process.exit(1);
  55. }
  56. const DURATION = parseFloat(arg('duration', '30'));
  57. const WIDTH = parseInt(arg('width', '1920'));
  58. const HEIGHT = parseInt(arg('height', '1080'));
  59. const TRIM_OVERRIDE = arg('trim', null); // manual override (seconds). If unset, auto-detected.
  60. const FONT_WAIT = parseFloat(arg('fontwait', '1.5')); // fallback when no __ready signal
  61. const READY_TIMEOUT = parseFloat(arg('readytimeout', '8'));
  62. const KEEP_CHROME = hasFlag('keep-chrome');
  63. const HTML_ABS = path.resolve(HTML_FILE);
  64. const BASENAME = path.basename(HTML_FILE, path.extname(HTML_FILE));
  65. const DIR = path.dirname(HTML_ABS);
  66. const TMP_DIR = path.join(DIR, '.video-tmp-' + Date.now() + '-' + process.pid);
  67. const MP4_OUT = path.join(DIR, BASENAME + '.mp4');
  68. // CSS to hide "chrome" elements during recording.
  69. // Covers class-name conventions seen across skill-built animations,
  70. // plus a `.no-record` explicit opt-out class.
  71. const HIDE_CHROME_CSS = `
  72. .no-record,
  73. .progress, .progress-bar,
  74. .counter, .tCur,
  75. .phases, .phase-label, .phase,
  76. .replay, button.replay,
  77. .masthead, .kicker, .title,
  78. .footer,
  79. [data-role="chrome"], [data-record="hidden"] {
  80. display: none !important;
  81. }
  82. `;
  83. console.log(`▸ Rendering: ${HTML_FILE}`);
  84. console.log(` size: ${WIDTH}x${HEIGHT} · duration: ${DURATION}s · hide-chrome: ${!KEEP_CHROME}`);
  85. console.log(` output: ${MP4_OUT}`);
  86. (async () => {
  87. fs.mkdirSync(TMP_DIR, { recursive: true });
  88. const browser = await chromium.launch();
  89. const url = 'file://' + HTML_ABS;
  90. // ── Phase 1: WARMUP (no recording, caches fonts/assets) ─────────────
  91. console.log('▸ Warmup (caching fonts)…');
  92. const warmupCtx = await browser.newContext({
  93. viewport: { width: WIDTH, height: HEIGHT },
  94. });
  95. const warmupPage = await warmupCtx.newPage();
  96. // 'load' not 'networkidle' — unpkg/Google Fonts can keep connections alive
  97. // past our 30s budget even after all critical resources are in. __ready
  98. // flag + FONT_WAIT handle animation-readiness properly.
  99. await warmupPage.goto(url, { waitUntil: 'load', timeout: 60000 });
  100. await warmupPage.waitForTimeout(FONT_WAIT * 1000);
  101. await warmupCtx.close();
  102. // ── Phase 2: RECORD (fresh context, animation from t=0) ─────────────
  103. console.log('▸ Recording (clean start)…');
  104. const recordCtx = await browser.newContext({
  105. viewport: { width: WIDTH, height: HEIGHT },
  106. deviceScaleFactor: 1,
  107. recordVideo: {
  108. dir: TMP_DIR,
  109. size: { width: WIDTH, height: HEIGHT },
  110. },
  111. });
  112. // Tell the page it's being recorded — animations.jsx Stage reads this
  113. // and forces loop=false so the export ends on the final frame instead of
  114. // capturing the start of the next cycle. Hand-written Stage components
  115. // should also honor this signal (see animation-pitfalls.md §13).
  116. await recordCtx.addInitScript(() => { window.__recording = true; });
  117. // Inject CSS + JS heuristic to hide "chrome" elements.
  118. // Two layers:
  119. // A. CSS selectors for common class-name conventions (cheap)
  120. // B. JS heuristic for fixed-position bars containing buttons or time
  121. // readouts (catches inline-styled chrome like <Stage> controls)
  122. // Persists across reloads via addInitScript.
  123. if (!KEEP_CHROME) {
  124. await recordCtx.addInitScript(css => {
  125. const HIDE_MARK = 'data-video-hidden';
  126. function injectStyle() {
  127. const style = document.createElement('style');
  128. style.setAttribute('data-inject', 'render-video-chrome-hide');
  129. style.textContent = css;
  130. (document.head || document.documentElement).appendChild(style);
  131. }
  132. function hideChromeBars() {
  133. const vh = window.innerHeight;
  134. document.querySelectorAll('div, nav, header, footer, section, aside')
  135. .forEach(el => {
  136. if (el.hasAttribute(HIDE_MARK)) return;
  137. if (el.dataset.recordKeep === 'true') return;
  138. const s = getComputedStyle(el);
  139. if (s.position !== 'fixed' && s.position !== 'sticky') return;
  140. const r = el.getBoundingClientRect();
  141. // Only skinny bars (not full-screen overlays)
  142. if (r.height > vh * 0.25) return;
  143. const atBottom = r.bottom >= vh - 30;
  144. const atTop = r.top <= 30 && r.height < 80;
  145. if (!atBottom && !atTop) return;
  146. // Chrome-like: contains button or scrubber/time glyphs
  147. const txt = el.textContent || '';
  148. const hasBtn = !!el.querySelector('button, [role="button"]');
  149. const hasCtrls = /[⏸▶⏮⏭↻↺↩↪]|\d+\.\d+\s*s/.test(txt);
  150. if (hasBtn || hasCtrls) {
  151. el.style.setProperty('display', 'none', 'important');
  152. el.setAttribute(HIDE_MARK, '1');
  153. }
  154. });
  155. }
  156. const start = () => {
  157. injectStyle();
  158. hideChromeBars();
  159. // Re-run as React/Vue commits DOM changes
  160. const obs = new MutationObserver(hideChromeBars);
  161. obs.observe(document.body, { childList: true, subtree: true });
  162. setTimeout(() => obs.disconnect(), 6000);
  163. };
  164. if (document.readyState === 'loading') {
  165. document.addEventListener('DOMContentLoaded', start, { once: true });
  166. } else {
  167. start();
  168. }
  169. }, HIDE_CHROME_CSS);
  170. }
  171. // Record context opens page. The WebM starts writing the moment the
  172. // context is created — so we track T0 here and measure how many seconds
  173. // elapse before the animation is actually ready (Babel compile + React
  174. // mount + fonts.ready). That elapsed time = exact trim offset.
  175. const T0 = Date.now();
  176. const page = await recordCtx.newPage();
  177. await page.goto(url, { waitUntil: 'load', timeout: 60000 });
  178. // Wait for animation ready signal. Stage component (animations.jsx) sets
  179. // window.__ready = true on its first rAF after mount + fonts.ready.
  180. // Fallback: if HTML doesn't set __ready within READY_TIMEOUT, use fontwait.
  181. let animationStartSec;
  182. const hasReady = await page.waitForFunction(
  183. () => window.__ready === true,
  184. { timeout: READY_TIMEOUT * 1000 },
  185. ).then(() => true).catch(() => false);
  186. if (hasReady) {
  187. // 第二道防线:主动把动画 time 归零——对付 HTML 不严格遵守 starter tick 模板
  188. // 的情况(例如 lastTick 用 performance.now() 导致字体加载时间被算进首帧 dt)
  189. // 详见 references/animation-pitfalls.md §12
  190. const seekCorrected = await page.evaluate(() => {
  191. if (typeof window.__seek === 'function') {
  192. window.__seek(0);
  193. return true;
  194. }
  195. return false;
  196. });
  197. if (seekCorrected) {
  198. // 等两个 rAF 让 seek 生效并渲染出 t=0 的画面
  199. await page.evaluate(() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r))));
  200. }
  201. animationStartSec = (Date.now() - T0) / 1000;
  202. console.log(`▸ Ready at ${animationStartSec.toFixed(2)}s (from window.__ready${seekCorrected ? ' + __seek(0) correction' : ''})`);
  203. } else {
  204. await page.waitForTimeout(FONT_WAIT * 1000);
  205. animationStartSec = (Date.now() - T0) / 1000;
  206. // Fallback offset is unreliable: animation may have started in raf loop
  207. // already, so trim could land mid-cycle. Add 0.5s safety margin (see
  208. // animation-pitfalls.md §13). Loud warning so user knows to fix the HTML.
  209. console.log('');
  210. console.log(` ⚠️ WARNING: window.__ready signal not detected within ${READY_TIMEOUT}s`);
  211. console.log(` Recording will use fallback trim of ${animationStartSec.toFixed(2)}s + 0.5s safety margin.`);
  212. console.log(` This is UNRELIABLE — your video may start mid-animation or skip frames.`);
  213. console.log('');
  214. console.log(` FIX: in your HTML's animation tick (or rAF first frame), add:`);
  215. console.log(` window.__ready = true;`);
  216. console.log(` animations.jsx-based HTML does this automatically. If you wrote your`);
  217. console.log(` own Stage, see references/animation-pitfalls.md §12 for the pattern.`);
  218. console.log('');
  219. }
  220. // Now let the animation play out its full duration
  221. await page.waitForTimeout(DURATION * 1000 + 300);
  222. await page.close();
  223. await recordCtx.close();
  224. await browser.close();
  225. const webmFiles = fs.readdirSync(TMP_DIR).filter(f => f.endsWith('.webm'));
  226. if (webmFiles.length === 0) {
  227. console.error('✗ No webm produced');
  228. process.exit(1);
  229. }
  230. const webmPath = path.join(TMP_DIR, webmFiles[0]);
  231. console.log(`▸ WebM: ${(fs.statSync(webmPath).size / 1024 / 1024).toFixed(1)} MB`);
  232. // Resolve final trim offset:
  233. // - manual --trim=X → use X (explicit user override)
  234. // - hasReady → animationStartSec + 0.05s (Babel-commit nudge)
  235. // - fallback (no __ready) → animationStartSec + 0.5s safety margin (raf
  236. // loop may have started running already; without
  237. // this we'd capture mid-cycle frames)
  238. const resolvedTrim = TRIM_OVERRIDE !== null
  239. ? parseFloat(TRIM_OVERRIDE)
  240. : animationStartSec + (hasReady ? 0.05 : 0.5);
  241. console.log(`▸ ffmpeg: trim=${resolvedTrim.toFixed(2)}s${TRIM_OVERRIDE !== null ? ' (manual)' : ' (auto)'}, encode H.264…`);
  242. const ffmpeg = spawnSync('ffmpeg', [
  243. '-y',
  244. '-ss', String(resolvedTrim),
  245. '-i', webmPath,
  246. '-t', String(DURATION),
  247. '-c:v', 'libx264',
  248. '-pix_fmt', 'yuv420p',
  249. '-crf', '18',
  250. '-preset', 'medium',
  251. '-movflags', '+faststart',
  252. MP4_OUT,
  253. ], { stdio: ['ignore', 'ignore', 'pipe'] });
  254. if (ffmpeg.status !== 0) {
  255. console.error('✗ ffmpeg failed:\n' + ffmpeg.stderr.toString().slice(-2000));
  256. process.exit(1);
  257. }
  258. fs.rmSync(TMP_DIR, { recursive: true, force: true });
  259. const mp4Size = (fs.statSync(MP4_OUT).size / 1024 / 1024).toFixed(1);
  260. console.log(`✓ Done: ${MP4_OUT} (${mp4Size} MB)`);
  261. })();