/ scripts / render-video.js
render-video.js
  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  
 40  const { chromium } = require('playwright');
 41  const path = require('path');
 42  const fs = require('fs');
 43  const { spawnSync } = require('child_process');
 44  
 45  function arg(name, def) {
 46    const p = process.argv.find(a => a.startsWith('--' + name + '='));
 47    return p ? p.slice(name.length + 3) : def;
 48  }
 49  function hasFlag(name) {
 50    return process.argv.includes('--' + name);
 51  }
 52  
 53  const HTML_FILE = process.argv[2];
 54  if (!HTML_FILE || HTML_FILE.startsWith('--')) {
 55    console.error('Usage: node render-video.js <html-file>');
 56    console.error('Example: NODE_PATH=$(npm root -g) node render-video.js my-animation.html');
 57    process.exit(1);
 58  }
 59  
 60  const DURATION  = parseFloat(arg('duration', '30'));
 61  const WIDTH     = parseInt(arg('width', '1920'));
 62  const HEIGHT    = parseInt(arg('height', '1080'));
 63  const TRIM_OVERRIDE = arg('trim', null);              // manual override (seconds). If unset, auto-detected.
 64  const FONT_WAIT = parseFloat(arg('fontwait', '1.5')); // fallback when no __ready signal
 65  const READY_TIMEOUT = parseFloat(arg('readytimeout', '8'));
 66  const KEEP_CHROME = hasFlag('keep-chrome');
 67  
 68  const HTML_ABS = path.resolve(HTML_FILE);
 69  const BASENAME = path.basename(HTML_FILE, path.extname(HTML_FILE));
 70  const DIR      = path.dirname(HTML_ABS);
 71  const TMP_DIR  = path.join(DIR, '.video-tmp-' + Date.now() + '-' + process.pid);
 72  const MP4_OUT  = path.join(DIR, BASENAME + '.mp4');
 73  
 74  // CSS to hide "chrome" elements during recording.
 75  // Covers class-name conventions seen across skill-built animations,
 76  // plus a `.no-record` explicit opt-out class.
 77  const HIDE_CHROME_CSS = `
 78    .no-record,
 79    .progress, .progress-bar,
 80    .counter, .tCur,
 81    .phases, .phase-label, .phase,
 82    .replay, button.replay,
 83    .masthead, .kicker, .title,
 84    .footer,
 85    [data-role="chrome"], [data-record="hidden"] {
 86      display: none !important;
 87    }
 88  `;
 89  
 90  console.log(`▸ Rendering: ${HTML_FILE}`);
 91  console.log(`  size: ${WIDTH}x${HEIGHT} · duration: ${DURATION}s · hide-chrome: ${!KEEP_CHROME}`);
 92  console.log(`  output: ${MP4_OUT}`);
 93  
 94  (async () => {
 95    fs.mkdirSync(TMP_DIR, { recursive: true });
 96  
 97    const browser = await chromium.launch();
 98    const url = 'file://' + HTML_ABS;
 99  
100    // ── Phase 1: WARMUP (no recording, caches fonts/assets) ─────────────
101    console.log('▸ Warmup (caching fonts)…');
102    const warmupCtx = await browser.newContext({
103      viewport: { width: WIDTH, height: HEIGHT },
104    });
105    const warmupPage = await warmupCtx.newPage();
106    // 'load' not 'networkidle' — unpkg/Google Fonts can keep connections alive
107    // past our 30s budget even after all critical resources are in. __ready
108    // flag + FONT_WAIT handle animation-readiness properly.
109    await warmupPage.goto(url, { waitUntil: 'load', timeout: 60000 });
110    await warmupPage.waitForTimeout(FONT_WAIT * 1000);
111    await warmupCtx.close();
112  
113    // ── Phase 2: RECORD (fresh context, animation from t=0) ─────────────
114    console.log('▸ Recording (clean start)…');
115    const recordCtx = await browser.newContext({
116      viewport: { width: WIDTH, height: HEIGHT },
117      deviceScaleFactor: 1,
118      recordVideo: {
119        dir: TMP_DIR,
120        size: { width: WIDTH, height: HEIGHT },
121      },
122    });
123  
124    // Tell the page it's being recorded — animations.jsx Stage reads this
125    // and forces loop=false so the export ends on the final frame instead of
126    // capturing the start of the next cycle. Hand-written Stage components
127    // should also honor this signal (see animation-pitfalls.md §13).
128    await recordCtx.addInitScript(() => { window.__recording = true; });
129  
130    // Inject CSS + JS heuristic to hide "chrome" elements.
131    // Two layers:
132    //   A. CSS selectors for common class-name conventions (cheap)
133    //   B. JS heuristic for fixed-position bars containing buttons or time
134    //      readouts (catches inline-styled chrome like <Stage> controls)
135    // Persists across reloads via addInitScript.
136    if (!KEEP_CHROME) {
137      await recordCtx.addInitScript(css => {
138        const HIDE_MARK = 'data-video-hidden';
139  
140        function injectStyle() {
141          const style = document.createElement('style');
142          style.setAttribute('data-inject', 'render-video-chrome-hide');
143          style.textContent = css;
144          (document.head || document.documentElement).appendChild(style);
145        }
146  
147        function hideChromeBars() {
148          const vh = window.innerHeight;
149          document.querySelectorAll('div, nav, header, footer, section, aside')
150            .forEach(el => {
151              if (el.hasAttribute(HIDE_MARK)) return;
152              if (el.dataset.recordKeep === 'true') return;
153              const s = getComputedStyle(el);
154              if (s.position !== 'fixed' && s.position !== 'sticky') return;
155              const r = el.getBoundingClientRect();
156              // Only skinny bars (not full-screen overlays)
157              if (r.height > vh * 0.25) return;
158              const atBottom = r.bottom >= vh - 30;
159              const atTop = r.top <= 30 && r.height < 80;
160              if (!atBottom && !atTop) return;
161              // Chrome-like: contains button or scrubber/time glyphs
162              const txt = el.textContent || '';
163              const hasBtn = !!el.querySelector('button, [role="button"]');
164              const hasCtrls = /[⏸▶⏮⏭↻↺↩↪]|\d+\.\d+\s*s/.test(txt);
165              if (hasBtn || hasCtrls) {
166                el.style.setProperty('display', 'none', 'important');
167                el.setAttribute(HIDE_MARK, '1');
168              }
169            });
170        }
171  
172        const start = () => {
173          injectStyle();
174          hideChromeBars();
175          // Re-run as React/Vue commits DOM changes
176          const obs = new MutationObserver(hideChromeBars);
177          obs.observe(document.body, { childList: true, subtree: true });
178          setTimeout(() => obs.disconnect(), 6000);
179        };
180  
181        if (document.readyState === 'loading') {
182          document.addEventListener('DOMContentLoaded', start, { once: true });
183        } else {
184          start();
185        }
186      }, HIDE_CHROME_CSS);
187    }
188  
189    // Record context opens page. The WebM starts writing the moment the
190    // context is created — so we track T0 here and measure how many seconds
191    // elapse before the animation is actually ready (Babel compile + React
192    // mount + fonts.ready). That elapsed time = exact trim offset.
193    const T0 = Date.now();
194    const page = await recordCtx.newPage();
195    await page.goto(url, { waitUntil: 'load', timeout: 60000 });
196  
197    // Wait for animation ready signal. Stage component (animations.jsx) sets
198    // window.__ready = true on its first rAF after mount + fonts.ready.
199    // Fallback: if HTML doesn't set __ready within READY_TIMEOUT, use fontwait.
200    let animationStartSec;
201    const hasReady = await page.waitForFunction(
202      () => window.__ready === true,
203      { timeout: READY_TIMEOUT * 1000 },
204    ).then(() => true).catch(() => false);
205  
206    if (hasReady) {
207      // Second defense: actively reset animation time to zero — handles HTML that doesn't
208      // strictly follow the starter tick template (e.g., lastTick uses performance.now()
209      // causing font loading time to be included in first frame dt)
210      // See references/animation-pitfalls.md §12
211      const seekCorrected = await page.evaluate(() => {
212        if (typeof window.__seek === 'function') {
213          window.__seek(0);
214          return true;
215        }
216        return false;
217      });
218      if (seekCorrected) {
219        // Wait two rAFs for seek to take effect and render t=0 frame
220        await page.evaluate(() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r))));
221      }
222      animationStartSec = (Date.now() - T0) / 1000;
223      console.log(`▸ Ready at ${animationStartSec.toFixed(2)}s (from window.__ready${seekCorrected ? ' + __seek(0) correction' : ''})`);
224    } else {
225      await page.waitForTimeout(FONT_WAIT * 1000);
226      animationStartSec = (Date.now() - T0) / 1000;
227      // Fallback offset is unreliable: animation may have started in raf loop
228      // already, so trim could land mid-cycle. Add 0.5s safety margin (see
229      // animation-pitfalls.md §13). Loud warning so user knows to fix the HTML.
230      console.log('');
231      console.log(`  ⚠️  WARNING: window.__ready signal not detected within ${READY_TIMEOUT}s`);
232      console.log(`     Recording will use fallback trim of ${animationStartSec.toFixed(2)}s + 0.5s safety margin.`);
233      console.log(`     This is UNRELIABLE — your video may start mid-animation or skip frames.`);
234      console.log('');
235      console.log(`     FIX: in your HTML's animation tick (or rAF first frame), add:`);
236      console.log(`        window.__ready = true;`);
237      console.log(`     animations.jsx-based HTML does this automatically. If you wrote your`);
238      console.log(`     own Stage, see references/animation-pitfalls.md §12 for the pattern.`);
239      console.log('');
240    }
241  
242    // Now let the animation play out its full duration
243    await page.waitForTimeout(DURATION * 1000 + 300);
244  
245    await page.close();
246    await recordCtx.close();
247    await browser.close();
248  
249    const webmFiles = fs.readdirSync(TMP_DIR).filter(f => f.endsWith('.webm'));
250    if (webmFiles.length === 0) {
251      console.error('✗ No webm produced');
252      process.exit(1);
253    }
254    const webmPath = path.join(TMP_DIR, webmFiles[0]);
255    console.log(`▸ WebM: ${(fs.statSync(webmPath).size / 1024 / 1024).toFixed(1)} MB`);
256  
257    // Resolve final trim offset:
258    //   - manual --trim=X       → use X (explicit user override)
259    //   - hasReady              → animationStartSec + 0.05s (Babel-commit nudge)
260    //   - fallback (no __ready) → animationStartSec + 0.5s safety margin (raf
261    //                             loop may have started running already; without
262    //                             this we'd capture mid-cycle frames)
263    const resolvedTrim = TRIM_OVERRIDE !== null
264      ? parseFloat(TRIM_OVERRIDE)
265      : animationStartSec + (hasReady ? 0.05 : 0.5);
266  
267    console.log(`▸ ffmpeg: trim=${resolvedTrim.toFixed(2)}s${TRIM_OVERRIDE !== null ? ' (manual)' : ' (auto)'}, encode H.264…`);
268    const ffmpeg = spawnSync('ffmpeg', [
269      '-y',
270      '-ss', String(resolvedTrim),
271      '-i', webmPath,
272      '-t', String(DURATION),
273      '-c:v', 'libx264',
274      '-pix_fmt', 'yuv420p',
275      '-crf', '18',
276      '-preset', 'medium',
277      '-movflags', '+faststart',
278      MP4_OUT,
279    ], { stdio: ['ignore', 'ignore', 'pipe'] });
280  
281    if (ffmpeg.status !== 0) {
282      console.error('✗ ffmpeg failed:\n' + ffmpeg.stderr.toString().slice(-2000));
283      process.exit(1);
284    }
285  
286    fs.rmSync(TMP_DIR, { recursive: true, force: true });
287  
288    const mp4Size = (fs.statSync(MP4_OUT).size / 1024 / 1024).toFixed(1);
289    console.log(`✓ Done: ${MP4_OUT} (${mp4Size} MB)`);
290  })();