render-video.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. await warmupPage.goto(url, { waitUntil: 'networkidle' });
  97. await warmupPage.waitForTimeout(FONT_WAIT * 1000);
  98. await warmupCtx.close();
  99. // ── Phase 2: RECORD (fresh context, animation from t=0) ─────────────
  100. console.log('▸ Recording (clean start)…');
  101. const recordCtx = await browser.newContext({
  102. viewport: { width: WIDTH, height: HEIGHT },
  103. deviceScaleFactor: 1,
  104. recordVideo: {
  105. dir: TMP_DIR,
  106. size: { width: WIDTH, height: HEIGHT },
  107. },
  108. });
  109. // Inject CSS + JS heuristic to hide "chrome" elements.
  110. // Two layers:
  111. // A. CSS selectors for common class-name conventions (cheap)
  112. // B. JS heuristic for fixed-position bars containing buttons or time
  113. // readouts (catches inline-styled chrome like <Stage> controls)
  114. // Persists across reloads via addInitScript.
  115. if (!KEEP_CHROME) {
  116. await recordCtx.addInitScript(css => {
  117. const HIDE_MARK = 'data-video-hidden';
  118. function injectStyle() {
  119. const style = document.createElement('style');
  120. style.setAttribute('data-inject', 'render-video-chrome-hide');
  121. style.textContent = css;
  122. (document.head || document.documentElement).appendChild(style);
  123. }
  124. function hideChromeBars() {
  125. const vh = window.innerHeight;
  126. document.querySelectorAll('div, nav, header, footer, section, aside')
  127. .forEach(el => {
  128. if (el.hasAttribute(HIDE_MARK)) return;
  129. if (el.dataset.recordKeep === 'true') return;
  130. const s = getComputedStyle(el);
  131. if (s.position !== 'fixed' && s.position !== 'sticky') return;
  132. const r = el.getBoundingClientRect();
  133. // Only skinny bars (not full-screen overlays)
  134. if (r.height > vh * 0.25) return;
  135. const atBottom = r.bottom >= vh - 30;
  136. const atTop = r.top <= 30 && r.height < 80;
  137. if (!atBottom && !atTop) return;
  138. // Chrome-like: contains button or scrubber/time glyphs
  139. const txt = el.textContent || '';
  140. const hasBtn = !!el.querySelector('button, [role="button"]');
  141. const hasCtrls = /[⏸▶⏮⏭↻↺↩↪]|\d+\.\d+\s*s/.test(txt);
  142. if (hasBtn || hasCtrls) {
  143. el.style.setProperty('display', 'none', 'important');
  144. el.setAttribute(HIDE_MARK, '1');
  145. }
  146. });
  147. }
  148. const start = () => {
  149. injectStyle();
  150. hideChromeBars();
  151. // Re-run as React/Vue commits DOM changes
  152. const obs = new MutationObserver(hideChromeBars);
  153. obs.observe(document.body, { childList: true, subtree: true });
  154. setTimeout(() => obs.disconnect(), 6000);
  155. };
  156. if (document.readyState === 'loading') {
  157. document.addEventListener('DOMContentLoaded', start, { once: true });
  158. } else {
  159. start();
  160. }
  161. }, HIDE_CHROME_CSS);
  162. }
  163. // Record context opens page. The WebM starts writing the moment the
  164. // context is created — so we track T0 here and measure how many seconds
  165. // elapse before the animation is actually ready (Babel compile + React
  166. // mount + fonts.ready). That elapsed time = exact trim offset.
  167. const T0 = Date.now();
  168. const page = await recordCtx.newPage();
  169. await page.goto(url, { waitUntil: 'networkidle' });
  170. // Wait for animation ready signal. Stage component (animations.jsx) sets
  171. // window.__ready = true on its first rAF after mount + fonts.ready.
  172. // Fallback: if HTML doesn't set __ready within READY_TIMEOUT, use fontwait.
  173. let animationStartSec;
  174. const hasReady = await page.waitForFunction(
  175. () => window.__ready === true,
  176. { timeout: READY_TIMEOUT * 1000 },
  177. ).then(() => true).catch(() => false);
  178. if (hasReady) {
  179. animationStartSec = (Date.now() - T0) / 1000;
  180. console.log(`▸ Ready at ${animationStartSec.toFixed(2)}s (from window.__ready)`);
  181. } else {
  182. await page.waitForTimeout(FONT_WAIT * 1000);
  183. animationStartSec = (Date.now() - T0) / 1000;
  184. console.log(`▸ No window.__ready signal; using fallback wait (${animationStartSec.toFixed(2)}s)`);
  185. console.log(` tip: in animations.jsx-based HTML this is automatic;`);
  186. console.log(` otherwise set window.__ready=true after your first paint.`);
  187. }
  188. // Now let the animation play out its full duration
  189. await page.waitForTimeout(DURATION * 1000 + 300);
  190. await page.close();
  191. await recordCtx.close();
  192. await browser.close();
  193. const webmFiles = fs.readdirSync(TMP_DIR).filter(f => f.endsWith('.webm'));
  194. if (webmFiles.length === 0) {
  195. console.error('✗ No webm produced');
  196. process.exit(1);
  197. }
  198. const webmPath = path.join(TMP_DIR, webmFiles[0]);
  199. console.log(`▸ WebM: ${(fs.statSync(webmPath).size / 1024 / 1024).toFixed(1)} MB`);
  200. // Resolve final trim offset:
  201. // - manual --trim=X → use X (explicit user override)
  202. // - otherwise → use animationStartSec (measured), with a tiny
  203. // +0.05s nudge to clear the first Babel-commit frame
  204. const resolvedTrim = TRIM_OVERRIDE !== null
  205. ? parseFloat(TRIM_OVERRIDE)
  206. : animationStartSec + 0.05;
  207. console.log(`▸ ffmpeg: trim=${resolvedTrim.toFixed(2)}s${TRIM_OVERRIDE !== null ? ' (manual)' : ' (auto)'}, encode H.264…`);
  208. const ffmpeg = spawnSync('ffmpeg', [
  209. '-y',
  210. '-ss', String(resolvedTrim),
  211. '-i', webmPath,
  212. '-t', String(DURATION),
  213. '-c:v', 'libx264',
  214. '-pix_fmt', 'yuv420p',
  215. '-crf', '18',
  216. '-preset', 'medium',
  217. '-movflags', '+faststart',
  218. MP4_OUT,
  219. ], { stdio: ['ignore', 'ignore', 'pipe'] });
  220. if (ffmpeg.status !== 0) {
  221. console.error('✗ ffmpeg failed:\n' + ffmpeg.stderr.toString().slice(-2000));
  222. process.exit(1);
  223. }
  224. fs.rmSync(TMP_DIR, { recursive: true, force: true });
  225. const mp4Size = (fs.statSync(MP4_OUT).size / 1024 / 1024).toFixed(1);
  226. console.log(`✓ Done: ${MP4_OUT} (${mp4Size} MB)`);
  227. })();