Skip to content

Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.

29.4 KB
Raw Blame
// Phụ đề bản chính: một cảnh HyperFrames nền trong suốt (chỉ có chữ), render ra WebM VP9 có alpha,
// rồi ffmpeg chồng lên video nền. Font tiếng Việt lấy từ engine/fonts (fonts.css của LumReels).
// Mốc chữ đổi từ giây nguồn sang giây bản ra theo keep[] của EDL — cùng luật chia thẻ với phụ đề nháp (lumedit.py).
// Có câu móc (edl.hook) thì bản ra = [móc] + keep: timelineOf(edl) dời mọi mốc; móc lặp lại (repeat) thì chữ của
// câu móc hiện 2 lần (đầu clip và chỗ cũ). Mọi kiểu hiện chữ là hàm của t − c.start (render(t) thuần, gsap seek).
import fs from 'node:fs';
import path from 'node:path';
import { syncLib, runHF } from '../engine/lib.mjs';
import { toOutputNearest, outputDuration, timelineOf, SAFE, OUT, frameCy, captionFloor } from './edl.mjs';
import { graphicsScene, GFX_RUNTIME } from './graphics.mjs';

const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));

/** Chia chữ thành nhóm (cùng luật với caption_cards trong edit/py/lumedit.py). */
function groupWords(words, maxWords) {
  const groups = []; let cur = [];
  words.forEach((w, n) => {
    cur.push(w);
    const nx = words[n + 1];
    const ends = /[.?!,:;…]$/.test(w.w.trim());
    const gap = nx ? nx.start - w.end : 99;
    if (cur.length >= maxWords || ends || gap > 0.45 || !nx) { groups.push(cur); cur = []; }
  });
  return groups;
}

/** Cùng luật với caption_cards trong edit/py/lumedit.py. */
export function captionCards(edl) {
  const cap = edl.captions; const tl = timelineOf(edl); const H = edl.hook;
  // phụ đề chỉnh tay (giây bản ra, edit/manual.mjs): dùng nguyên dòng người dùng đặt, chỉ kiểm không đè nhau
  if (cap.lines) {
    const cards = cap.lines.map((l) => ({ start: l.start, end: l.end, words: l.words.map((w) => ({ w: w.w, i: -1, o: w.o, hl: w.hi })), wordOut: l.words.map((w) => Math.max(l.start, w.o)) }));
    const bad = cardOverlaps(cards);
    if (bad.length) throw new Error('phụ đề chỉnh tay chồng nhau: ' + bad.join('; '));
    return cards;
  }
  // mỗi chữ mang giây bản ra (o) của chính nó: chữ câu móc lặp lại có 2 chỗ trên bản ra
  const mk = (ws, map) => groupWords(ws, cap.maxWords).map((g) => ({ words: g.map((w) => ({ ...w, o: map(w.start) })), start: map(g[0].start), end: map(g[g.length - 1].end) }));
  const cards = mk(cap.words, (t) => toOutputNearest(tl, t)).sort((a, b) => a.start - b.start);
  if (!H) return finishCards(cards, tl);
  // có câu móc: thẻ của câu móc (0 … hookDur) và thẻ phần sau làm riêng, để thẻ móc không kéo dài qua chỗ nối
  const hd = H.end - H.start;
  const inH = H.repeat ? cap.words.filter((w) => (w.start + w.end) / 2 >= H.start && (w.start + w.end) / 2 <= H.end) : [];
  const head = H.repeat ? mk(inH, (t) => Math.min(hd, Math.max(0, t - H.start))) : cards.filter((c) => c.start < hd - 1e-6);
  const rest = cards.filter((c) => c.start >= hd - 1e-6);
  for (const c of head) c.end = Math.min(c.end, hd);
  const a = head.length ? finishCards(head, tl) : [];
  for (const c of a) c.end = Math.min(c.end, hd);
  return a.concat(rest.length ? finishCards(rest, tl) : []);
}

export const MIN_CARD = 0.25;   // một nhóm chữ hiện ít nhất chừng này (nếu chưa tới nhóm sau)
export const MERGE_BELOW = 0.1; // nhóm bị ép ngắn hơn chừng này (chữ nói rất nhanh) thì gộp vào nhóm sau

/**
 * Luật thời gian của nhóm phụ đề (giống caption_cards trong lumedit.py):
 * nối khe < 0,4 s; kéo dài tối thiểu MIN_CARD; KHÔNG BAO GIỜ chồng lên nhóm sau (cắt end về start của nhóm sau);
 * nhóm còn < MERGE_BELOW thì gộp chữ vào nhóm sau. Lỗi cũ: kéo dài tối thiểu 0,25 s chạy SAU bước nối khe nên
 * "TRÀ" (0,22 s) đè lên "SỮA" — 2 nhóm cùng hiện ở cùng chỗ.
 */
export function finishCards(cards, keep) {
  for (let k = 0; k + 1 < cards.length; k++) {
    const gap = cards[k + 1].start - cards[k].end;
    if (gap >= 0 && gap < 0.4) cards[k].end = cards[k + 1].start;
  }
  for (const c of cards) c.end = Math.max(c.end, c.start + MIN_CARD);
  for (let k = 0; k + 1 < cards.length; k++) cards[k].end = Math.min(cards[k].end, cards[k + 1].start);
  const out = [];
  for (let k = 0; k < cards.length; k++) {
    const c = cards[k]; const nx = cards[k + 1];
    if (nx && c.end - c.start < MERGE_BELOW) { nx.words = c.words.concat(nx.words); nx.start = c.start; continue; }
    out.push(c);
  }
  for (const c of out) c.wordOut = c.words.map((w) => Math.max(c.start, w.o ?? toOutputNearest(keep, w.start)));
  const bad = cardOverlaps(out);
  if (bad.length) throw new Error('phụ đề chồng nhau: ' + bad.join('; '));
  return out;
}

/** Luật kiểm: không bao giờ 2 nhóm phụ đề hiện cùng lúc (mọi nhóm cùng 1 vị trí). Trả danh sách lỗi. */
export function cardOverlaps(cards) {
  const errs = [];
  for (let k = 0; k + 1 < cards.length; k++) {
    if (cards[k].end > cards[k + 1].start + 1e-6) errs.push(`"${cards[k].words.map((w) => w.w).join(' ')}" (${cards[k].start.toFixed(2)}–${cards[k].end.toFixed(2)} s) đè "${cards[k + 1].words.map((w) => w.w).join(' ')}" (từ ${cards[k + 1].start.toFixed(2)} s)`);
    if (cards[k].end <= cards[k].start) errs.push(`nhóm ${k} dài 0 s`);
  }
  return errs;
}

// Khoá: font, weight, size (px), upper, color, hi (chữ nhấn/karaoke), karaoke, cy (tâm dòng, phần khung),
// enter (fade | pop | pop-soft | slide-left | typewriter | ticker | slam | fade-slow),
// stroke (px viền, mặc định 10 chữ hoa / 8), shadow (CSS text-shadow), box (thanh tin), quote (trích dẫn).
// Chép từ khối "look" của edit-styles/<id>.md.
export const LOOKS = {
  'sach-gon': { font: "'Be Vietnam Pro'", weight: 800, size: 76, upper: false, color: '#FFFFFF', hi: '#FCE802', karaoke: false, cy: 0.70, enter: 'fade' },
  'thong-tin-do-hoa': { font: "'Be Vietnam Pro'", weight: 800, size: 68, upper: false, color: '#FFFFFF', hi: '#FCE802', karaoke: false, cy: 0.745, enter: 'pop-soft' },
  'phu-de-nay-mau': { font: "'Anton'", weight: 400, size: 150, upper: true, color: '#FFFFFF', hi: '#FCE802', karaoke: true, cy: 0.58, enter: 'pop' },
  'podcast-trich-doan': { font: "'Montserrat'", weight: 800, size: 96, upper: false, color: '#FFFFFF', hi: '#FF8A3D', karaoke: false, cy: 0.56, enter: 'fade' },
  'ke-chuyen': { font: "'Nunito'", weight: 800, size: 80, upper: false, color: '#FFFFFF', hi: '#7CF0C8', karaoke: true, cy: 0.66, enter: 'pop-soft' },
  'top-danh-sach': { font: "'Bungee'", weight: 400, size: 78, upper: true, color: '#FFFFFF', hi: '#FF2E93', karaoke: false, cy: 0.74, enter: 'slide-left' },
  'review-san-pham': { font: "'Oswald'", weight: 700, size: 88, upper: true, color: '#FFFFFF', hi: '#A78BFA', karaoke: false, cy: 0.77, enter: 'pop-soft' },
  'huong-dan-buoc': { font: "'Space Grotesk'", weight: 700, size: 70, upper: false, color: '#FFFFFF', hi: '#5EA2FF', karaoke: false, cy: 0.72, enter: 'typewriter' },
  'ban-tin-nhanh': {
    font: "'Barlow Condensed'", weight: 700, size: 64, upper: true, color: '#FFFFFF', hi: '#00E5FF', karaoke: false, cy: 0.775, enter: 'ticker',
    box: { bg: '#0B1E3F', full: true, align: 'left', stroke: 0, tag: 'TIN NÓNG', tagBg: '#E8202A' },
  },
  'quan-diem-gat': { font: "'Alfa Slab One'", weight: 400, size: 104, upper: true, color: '#FFFFFF', hi: '#FF1F1F', karaoke: true, cy: 0.50, enter: 'slam' },
  'chot-don-livestream': { font: "'Baloo 2'", weight: 800, size: 96, upper: false, color: '#FFFFFF', hi: '#FFB020', karaoke: false, cy: 0.62, enter: 'pop' },
  'vlog-nhe': { font: "'Patrick Hand'", weight: 400, size: 60, upper: false, color: '#FFFDF7', hi: '#F5C6A5', karaoke: false, cy: 0.77, enter: 'fade-slow', stroke: 3, shadow: '0 3px 10px rgba(0,0,0,.45)' },
  'meo-15s': { font: "'Bangers'", weight: 400, size: 128, upper: true, color: '#FFFFFF', hi: '#00FF87', karaoke: false, cy: 0.64, enter: 'pop' },
  'cau-noi-hay': {
    font: "'Lora'", weight: 600, size: 66, upper: false, color: '#F5F1E8', hi: '#D4AF37', karaoke: false, cy: 0.74, enter: 'fade-slow',
    quote: { font: "'Playfair Display'", weight: 700, italic: true, size: 88, cy: 0.48, color: '#F5F1E8', marks: '#D4AF37', dimTo: 0.35, blurPx: 8, dimIn: 0.8, wordStagger: 0.12 },
  },
};
export const lookOf = (captionStyle) => LOOKS[captionStyle] || LOOKS['sach-gon'];

// thanh tin (ticker): ô tag bên trái, chữ căn trái sau tag, cả thanh cao 1,5 em ở cy
const TICKER = { tagX: 60, tagPad: 22, tagEm: 0.62, gap: 24, get right() { return Math.round(SAFE.x1 * OUT.width); } }; // mép phải theo khung đang dùng
const tickerTagW = (look) => Math.round([...look.box.tag].length * 0.56 * look.size * TICKER.tagEm + 2 * TICKER.tagPad);

/** Mép trên (px) của dòng phụ đề kiểu này — đồ hoạ đặt phía trên mép này. */
export function captionTop(captionStyle) {
  const look = lookOf(captionStyle);
  if (look.enter === 'ticker') return Math.round(frameCy(look.cy) * OUT.height - 0.75 * look.size) - 8;
  return Math.round(frameCy(look.cy) * OUT.height - 0.6 * look.size * 1.18) - 8;
}

/** Cỡ chữ cho khối chữ tự xuống dòng: thu nhỏ tới khi ước số dòng ≤ maxLines (ước theo bề rộng trung bình 1 ký tự). */
export function fitBlock(text, widthPx, max, { maxLines = 4, em = 0.5, min = 40 } = {}) {
  const n = [...text].length;
  let size = max;
  while (size > min && Math.ceil((n * em * size * 1.1) / widthPx) > maxLines) size -= 2;
  return size;
}

/** Chữ móc: "*3 GIÂY* LÀ XONG" → [{t, hi}] (chữ trong *…* là chữ nhấn). */
export function hookTextParts(text) {
  const parts = []; const re = /\*([^*]+)\*|([^*]+)/g; let m;
  while ((m = re.exec(String(text)))) { if (m[1]) parts.push({ t: m[1], hi: true }); else if (m[2]) parts.push({ t: m[2], hi: false }); }
  return parts;
}

/** Khoảng câu trích dẫn trên bản ra: {q0, q1, end, words:[{w, i, o}]} hoặc null. */
export function quoteSpan(edl, dur) {
  const q = edl.quote; if (!q) return null;
  const look = lookOf(edl.captions.style).quote || LOOKS['cau-noi-hay'].quote;
  const tl = timelineOf(edl);
  const q0 = toOutputNearest(tl, q.start); const q1 = toOutputNearest(tl, q.end);
  const hold = q1 >= dur - 2.0; // câu chốt ở cuối: giữ tối tới hết clip
  const end = hold ? dur : Math.min(dur, q1 + 0.8);
  let last = -Infinity;
  const words = edl.captions.words.filter((w) => (w.start + w.end) / 2 >= q.start - 1e-6 && (w.start + w.end) / 2 <= q.end + 1e-6).map((w) => {
    const o = Math.max(q0, toOutputNearest(tl, w.start), last + look.wordStagger); last = o;
    return { w: w.w, i: w.i, o };
  });
  return { q0, q1, end, hold, words };
}

/**
 * Ghi cảnh vào sceneDir. Trả {duration, cards, graphics, box}.
 * opts.captions=false: chỉ lớp đồ hoạ (bản nháp: phụ đề đã vẽ PIL trong nền). opts.accent: màu nhấn của đồ hoạ.
 * opts.style: thẻ kiểu (chữ móc hook.text, thanh bước graphics.stepTracker).
 */
export function writeCaptionScene(edl, sceneDir, { captions = true, accent, style = null } = {}) {
  const look = lookOf(edl.captions.style);
  const tlk = timelineOf(edl);
  const dur = Math.max(1 / OUT.fps, Math.round(outputDuration(tlk) * OUT.fps) / OUT.fps);
  let cards = captions && edl.captions.words.length ? captionCards(edl) : [];
  const gfx = (edl.graphics || []).length ? graphicsScene(edl, { accent: accent || look.hi, stepTracker: !!style?.graphics?.stepTracker, dur }) : null;
  const hiSet = new Set(edl.captions.hiOff ? [] : edl.captions.highlights);
  // chữ nhấn: dòng chỉnh tay mang cờ hl riêng; tắt chữ nhấn (hiOff) thì không chữ nào nhấn
  const hi = { has: (i, wd) => !edl.captions.hiOff && (wd?.hl ?? hiSet.has(i)) };
  const x0 = Math.round(SAFE.x0 * OUT.width); const w = Math.round((SAFE.x1 - SAFE.x0) * OUT.width);
  const cy = Math.round(frameCy(look.cy) * OUT.height); const yMax = Math.round(captionFloor() * OUT.height); // cy theo khung (edl.mjs frameCy)

  // câu trích dẫn: phụ đề thường tắt trong lúc đó
  const qs = captions ? quoteSpan(edl, dur) : null;
  if (qs) {
    cards = cards.filter((c) => !(c.start >= qs.q0 - 1e-3 && c.start < qs.end));
    for (const c of cards) if (c.start < qs.q0 && c.end > qs.q0) c.end = qs.q0;
  }
  const ticker = look.enter === 'ticker' && look.box;
  const tagW = ticker ? tickerTagW(look) : 0;
  const tkLeft = TICKER.tagX + tagW + TICKER.gap; const tkW = TICKER.right - tkLeft;
  const stroke = look.box ? (look.box.stroke ?? 0) : (look.stroke ?? (look.upper ? 10 : 8));
  const shadow = look.shadow || (ticker ? 'none' : '0 6px 18px rgba(0,0,0,.55)');

  const cardHtml = cards.map((c, ci) => {
    // dấu , . ; : cuối chữ không hiện trên phụ đề (giữ ? ! …)
    const text = c.words.map((wd) => { const t = wd.w.replace(/[,.;:]+$/u, '') || wd.w; return look.upper ? t.toUpperCase() : t; });
    let size;
    if (ticker) {
      // thanh tin: 1 dòng, thu cỡ theo bề ngang còn lại sau ô tag (Barlow Condensed ~0,46 em mỗi ký tự hoa)
      const n = text.join(' ').length;
      size = Math.max(34, Math.min(look.size, Math.floor(tkW / (n * 0.46 + 0.4))));
    } else {
      // thẻ 1 chữ dài thì thu nhỏ để vừa vùng an toàn (Anton ~0,48 em mỗi ký tự hoa)
      const longest = Math.max(...text.map((t) => t.length));
      size = c.words.length === 1 ? Math.min(look.size, Math.floor(w / (longest * 0.5 + 0.5))) : look.size;
    }
    const inner = (t) => (look.enter === 'typewriter' ? [...t].map((ch) => `<i class="ch">${esc(ch)}</i>`).join('') : esc(t));
    const spans = c.words.map((wd, k) => `<span class="w${hi.has(wd.i, wd) ? ' hi' : ''}" id="c${ci}w${k}">${inner(text[k])}</span>`).join(' ');
    return `<div class="card${ticker ? ' tk' : ''}" id="c${ci}" style="font-size:${size}px">${spans}</div>`;
  });
  const html = cardHtml.join('\n  ');

  // thanh tin: mỗi câu (chuỗi thẻ liền nhau tới dấu kết câu / khoảng lặng > 0,5 s) là 1 lượt thanh trượt vào
  const runs = [];
  if (ticker) {
    cards.forEach((c, ci) => {
      const prev = cards[ci - 1];
      const brk = !prev || /[.?!…]$/.test(prev.words[prev.words.length - 1].w.trim()) || c.start - prev.end > 0.5;
      if (brk) runs.push({ first: ci, start: c.start, end: c.end }); else runs[runs.length - 1].end = c.end;
    });
  }
  const firstOfRun = new Set(runs.map((r) => r.first));

  const timeline = cards.map((c, ci) => {
    const t0 = c.start.toFixed(3);
    const lines = [`tl.set('#c${ci}', {autoAlpha: 1}, ${t0});`];
    switch (look.enter) {
      case 'pop': lines.push(`tl.fromTo('#c${ci}', {scale: 0.55}, {scale: 1, duration: 0.18, ease: 'back.out(3)'}, ${t0});`); break;
      case 'pop-soft': lines.push(`tl.fromTo('#c${ci}', {scale: 0.86, opacity: 0}, {scale: 1, opacity: 1, duration: 0.14, ease: 'back.out(2.2)'}, ${t0});`); break;
      case 'slide-left': lines.push(`tl.fromTo('#c${ci}', {x: 80, opacity: 0}, {x: 0, opacity: 1, duration: 0.16, ease: 'power3.out'}, ${t0});`); break;
      case 'slam': {
        lines.push(`tl.fromTo('#c${ci}', {scale: 1.6, opacity: 0.4}, {scale: 1, opacity: 1, duration: 0.12, ease: 'power4.in'}, ${t0});`);
        [6, -6, 6, 0].forEach((x, k) => lines.push(`tl.to('#c${ci}', {x: ${x}, duration: 0.025, ease: 'none'}, ${(c.start + 0.12 + k * 0.025).toFixed(3)});`));
        break;
      }
      case 'fade-slow': {
        lines.push(`tl.fromTo('#c${ci}', {opacity: 0}, {opacity: 1, duration: 0.3, ease: 'power1.out'}, ${t0});`);
        const nx = cards[ci + 1];
        if ((!nx || nx.start - c.end >= 0.3) && c.end - c.start > 0.55) lines.push(`tl.to('#c${ci}', {opacity: 0, duration: 0.25, ease: 'power1.in'}, ${(c.end - 0.25).toFixed(3)});`);
        break;
      }
      case 'typewriter': {
        // ký tự k hiện ở c.start + k × min(0,035, (end − start) × 0,6 / số ký tự)
        const n = c.words.reduce((s, wd) => s + [...(wd.w.replace(/[,.;:]+$/u, '') || wd.w)].length, 0);
        const stepS = Math.min(0.035, ((c.end - c.start) * 0.6) / Math.max(1, n));
        lines.push(`tl.set('#c${ci} .ch', {opacity: 0}, ${t0});`);
        lines.push(`gsap.utils.toArray('#c${ci} .ch').forEach(function (el, k) { tl.set(el, {opacity: 1}, ${t0} + k * ${stepS.toFixed(4)}); });`);
        break;
      }
      case 'ticker': {
        if (!firstOfRun.has(ci)) lines.push(`tl.fromTo('#c${ci}', {opacity: 0}, {opacity: 1, duration: 0.08, ease: 'none'}, ${t0});`);
        break;
      }
      default: lines.push(`tl.fromTo('#c${ci}', {y: 18, opacity: 0}, {y: 0, opacity: 1, duration: 0.12, ease: 'power2.out'}, ${t0});`);
    }
    if (look.karaoke && c.words.length > 1) {
      c.words.forEach((wd, k) => {
        const a = c.wordOut[k]; const b = k + 1 < c.words.length ? c.wordOut[k + 1] : c.end;
        lines.push(`tl.set('#c${ci}w${k}', {color: '${look.hi}'}, ${a.toFixed(3)}); tl.set('#c${ci}w${k}', {color: '${hi.has(wd.i, wd) ? look.hi : look.color}'}, ${b.toFixed(3)});`);
      });
    }
    lines.push(`tl.set('#c${ci}', {autoAlpha: 0}, ${c.end.toFixed(3)});`);
    return lines.join(' ');
  });
  runs.forEach((r, k) => {
    timeline.push(`tl.set('#tbar', {autoAlpha: 1}, ${r.start.toFixed(3)}); tl.fromTo('#tbar', {x: -${OUT.width}}, {x: 0, duration: 0.2, ease: 'power3.out'}, ${r.start.toFixed(3)});`);
    const nx = runs[k + 1];
    if (!nx || nx.start > r.end + 0.02) timeline.push(`tl.set('#tbar', {autoAlpha: 0}, ${r.end.toFixed(3)});`);
  });

  // câu trích dẫn to giữa khung
  let quoteHtml = ''; let quoteCss = '';
  if (qs && qs.words.length) {
    const q = look.quote || LOOKS['cau-noi-hay'].quote;
    const text = qs.words.map((x) => x.w).join(' ');
    const qsize = fitBlock(`“${text}”`, w, q.size, { maxLines: 4, em: 0.5, min: 44 });
    quoteHtml = `<div id="quote" style="font-size:${qsize}px"><span class="qm" id="qmo">“</span>${qs.words.map((x, k) => `<span class="qw${hi.has(x.i) ? ' hi' : ''}" id="qw${k}">${esc(x.w)}</span>`).join(' ')}<span class="qm" id="qmc">”</span></div>`;
    quoteCss = `
  #quote { position:absolute; left:${x0}px; width:${w}px; top:${Math.round(q.cy * OUT.height)}px; transform:translateY(-50%); text-align:center; line-height:1.25;
           font-family:${q.font}, serif; font-weight:${q.weight}; font-style:${q.italic ? 'italic' : 'normal'}; color:${q.color};
           text-shadow:0 4px 24px rgba(0,0,0,.6); visibility:hidden; opacity:0; }
  #quote .qw { display:inline-block; opacity:0; }
  #quote .qw.hi { color:${q.marks}; }
  #quote .qm { color:${q.marks}; font-size:1.3em; line-height:0; opacity:0; padding:0 .06em; }`;
    timeline.push(`tl.set('#quote', {autoAlpha: 1}, ${qs.q0.toFixed(3)}); tl.to('#qmo', {opacity: 1, duration: 0.3}, ${qs.q0.toFixed(3)});`);
    qs.words.forEach((x, k) => timeline.push(`tl.fromTo('#qw${k}', {opacity: 0, y: 14}, {opacity: 1, y: 0, duration: 0.2, ease: 'power2.out'}, ${x.o.toFixed(3)});`));
    const lastO = qs.words[qs.words.length - 1].o;
    timeline.push(`tl.to('#qmc', {opacity: 1, duration: 0.3}, ${(lastO + 0.15).toFixed(3)});`);
    if (!qs.hold) timeline.push(`tl.to('#quote', {opacity: 0, duration: 0.3}, ${Math.max(lastO + 0.4, qs.end - 0.3).toFixed(3)}); tl.set('#quote', {autoAlpha: 0}, ${qs.end.toFixed(3)});`);
  }

  // chữ móc to 0 → until (kiểu meo-15s)
  let hookHtml = ''; let hookCss = '';
  if (captions && edl.hookText) {
    const ht = { font: "'Bangers'", size: 150, cy: 0.22, color: '#FFFFFF', hi: look.hi, ...(style?.hook?.text || {}) };
    const parts = hookTextParts(edl.hookText.text.toUpperCase());
    const plain = parts.map((p) => p.t).join('');
    const hsize = fitBlock(plain, w, ht.size, { maxLines: 2, em: 0.46, min: 70 });
    hookHtml = `<div id="hooktext" style="font-size:${hsize}px">${parts.map((p) => `<span${p.hi ? ' class="hi"' : ''}>${esc(p.t)}</span>`).join('')}</div>`;
    hookCss = `
  #hooktext { position:absolute; left:${x0}px; width:${w}px; top:${Math.round(ht.cy * OUT.height)}px; margin-top:-0.55em; text-align:center; line-height:1.05;
              font-family:${ht.font}, sans-serif; color:${ht.color}; -webkit-text-stroke:12px #000; paint-order:stroke fill;
              text-shadow:0 8px 24px rgba(0,0,0,.55); transform-origin:50% 50%; visibility:hidden; opacity:0; }
  #hooktext .hi { color:${ht.hi}; }`;
    const until = Math.min(edl.hookText.until, dur);
    timeline.push(`tl.set('#hooktext', {autoAlpha: 1}, 0); tl.fromTo('#hooktext', {scale: 0.4, rotation: -4}, {scale: 1, rotation: -2, duration: 0.3, ease: 'back.out(2.6)'}, 0); tl.to('#hooktext', {opacity: 0, scale: 1.08, duration: 0.18}, ${Math.max(0.35, until - 0.18).toFixed(3)}); tl.set('#hooktext', {autoAlpha: 0}, ${until.toFixed(3)});`);
  }

  const tickerHtml = ticker ? `<div id="tbar"><div class="tag">${esc(look.box.tag)}</div>\n  ${html}\n  </div>` : '';
  const tickerCss = ticker ? `
  #tbar { position:absolute; left:0; width:${OUT.width}px; top:${cy}px; height:${Math.round(1.5 * look.size)}px; margin-top:-${Math.round(0.75 * look.size)}px;
          background:${look.box.bg}; visibility:hidden; opacity:0; box-shadow:0 10px 30px rgba(0,0,0,.35); }
  #tbar .tag { position:absolute; left:${TICKER.tagX}px; top:0; height:100%; width:${tagW}px; box-sizing:border-box; padding:0 ${TICKER.tagPad}px; background:${look.box.tagBg};
               color:#fff; font-family:${look.font}, sans-serif; font-weight:800; font-size:${Math.round(look.size * TICKER.tagEm)}px; line-height:${Math.round(1.5 * look.size)}px; letter-spacing:.04em; white-space:nowrap; text-align:center; }
  #tbar .card.tk { left:${tkLeft}px; width:${tkW}px; top:0; margin-top:0; height:100%; line-height:${Math.round(1.5 * look.size)}px; text-align:left; white-space:nowrap; max-height:none; overflow:hidden; }` : '';

  const doc = `<!doctype html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=${OUT.width}, height=${OUT.height}" />
<link rel="stylesheet" href="./lib/fonts/fonts.css" />
<script src="./lib/vendor/gsap.min.js"></script>
<style>
  html, body { margin:0; width:${OUT.width}px; height:${OUT.height}px; overflow:hidden; background:transparent; }
  #root { position:relative; width:${OUT.width}px; height:${OUT.height}px; overflow:hidden; background:transparent; }
  .card { position:absolute; left:${x0}px; width:${w}px; top:${cy}px; transform-origin:50% 50%;
          margin-top:-0.6em; text-align:center; line-height:1.18; visibility:hidden; opacity:0;
          font-family:${look.font}, sans-serif; font-weight:${look.weight}; color:${look.color};
          -webkit-text-stroke: ${stroke}px #000; paint-order: stroke fill;
          text-shadow: ${shadow}; max-height:${yMax - cy}px; }
  .card .w { display:inline-block; }
  .card .ch { font-style:normal; }
  .card .hi { color:${look.hi}; }${tickerCss}${quoteCss}${hookCss}${gfx ? gfx.css : ''}
</style>
</head>
<body>
<div id="root" data-composition-id="main" data-start="0" data-duration="${dur.toFixed(3)}" data-fps="${OUT.fps}" data-width="${OUT.width}" data-height="${OUT.height}">
  ${gfx ? gfx.html : ''}
  ${ticker ? tickerHtml : html}
  ${quoteHtml}
  ${hookHtml}
</div>
${gfx ? `<script src="./lib/runtime/scene.js"></script>
<script>
  const tl = gsap.timeline({ paused: true });
  tl.set({}, {}, ${dur.toFixed(3)});
  ${timeline.join('\n  ')}
  const G = ${JSON.stringify(gfx.data)};
  const S = ${JSON.stringify(gfx.steps || null)};
  ${GFX_RUNTIME}
  VideoScene.define({ duration: ${dur.toFixed(3)}, fps: ${OUT.fps}, width: ${OUT.width}, height: ${OUT.height},
    render(t) { tl.seek(t, false); gfxRender(t, G); stepsRender(t, S); } });
</script>` : `<script>
  const tl = gsap.timeline({ paused: true });
  tl.set({}, {}, ${dur.toFixed(3)});
  ${timeline.join('\n  ')}
  window.__timelines = window.__timelines || {};
  window.__timelines.main = tl;
</script>`}
</body>
</html>
`;
  fs.mkdirSync(sceneDir, { recursive: true });
  fs.writeFileSync(path.join(sceneDir, 'index.html'), doc);
  syncLib(sceneDir);
  // để render lại từng đoạn (chỉ thẻ đổi): khoá mỗi thẻ = HTML + lệnh timeline của nó (bỏ id theo số thứ tự)
  const noId = (x) => x.replace(/ id="c\d+(w\d+)?"/g, '').replace(/#c\d+(w\d+)?/g, '#c');
  const cardsMeta = cards.map((c, ci) => ({ s: +c.start.toFixed(3), e: +c.end.toFixed(3), k: noId(cardHtml[ci]) + '|' + noId(timeline[ci] || '') }));
  const global = JSON.stringify([edl.captions.style, look, quoteHtml, hookHtml, gfx ? gfx.html : null, gfx ? gfx.data : null, !!ticker, dur]);
  return { duration: dur, cards: cards.length, graphics: (edl.graphics || []).length, box: { x0, x1: x0 + w, cy, yMax }, quote: !!qs, hookText: !!hookHtml, ticker: !!ticker, cardsMeta, global };
}

/**
 * Cảnh HyperFrames của RIÊNG 1 đồ hoạ, chỉ dài đúng khoảng nó hiện [from, from + dur) giây bản ra (lớp đồ hoạ tách khỏi
 * lớp phụ đề: sửa chữ/số/giờ 1 đồ hoạ chỉ render lại vài giây của nó). render(t) = gfxRender(from + t) — cùng HTML/CSS/
 * runtime với cảnh gộp, nên hình giống hệt. Có gsap để scene.js đăng ký window.__timelines.main (thiếu thì HyperFrames chờ
 * 45 s mới chụp).
 */
export function writeGraphicScene(edl, g, sceneDir, { accent, from, dur }) {
  const look = lookOf(edl.captions.style);
  const total = outputDuration(timelineOf(edl));
  const gfx = graphicsScene({ ...edl, graphics: [JSON.parse(JSON.stringify(g))] }, { accent: accent || look.hi, stepTracker: false, dur: total });
  const d = Math.max(1 / OUT.fps, Math.round(dur * OUT.fps) / OUT.fps);
  const doc = `<!doctype html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=${OUT.width}, height=${OUT.height}" />
<link rel="stylesheet" href="./lib/fonts/fonts.css" />
<script src="./lib/vendor/gsap.min.js"></script>
<style>
  html, body { margin:0; width:${OUT.width}px; height:${OUT.height}px; overflow:hidden; background:transparent; }
  #root { position:relative; width:${OUT.width}px; height:${OUT.height}px; overflow:hidden; background:transparent; }${gfx.css}
</style>
</head>
<body>
<div id="root" data-composition-id="main" data-start="0" data-duration="${d.toFixed(3)}" data-fps="${OUT.fps}" data-width="${OUT.width}" data-height="${OUT.height}">
  ${gfx.html}
</div>
<script src="./lib/runtime/scene.js"></script>
<script>
  const G = ${JSON.stringify(gfx.data)};
  const S = null;
  ${GFX_RUNTIME}
  VideoScene.define({ duration: ${d.toFixed(3)}, fps: ${OUT.fps}, width: ${OUT.width}, height: ${OUT.height},
    render(t) { gfxRender(${from.toFixed(3)} + t, G); } });
</script>
</body>
</html>
`;
  fs.mkdirSync(sceneDir, { recursive: true });
  fs.writeFileSync(path.join(sceneDir, 'index.html'), doc);
  syncLib(sceneDir);
  return { duration: d };
}

// Định dạng lớp chữ trong suốt (HyperFrames → ffmpeg chồng lên nền). LUMREELS_CAPTION_LAYER=png|webm|webm-fast|mov.
// Đo lớp chữ 32 s (967 khung) trên máy 20 luồng + RTX 3070 Ti, HF render / cỡ / ghép (overlay + NVENC):
//   webm VP9 alpha 63,7 s / 0,9 MB / 5,7 s · webm --vp9-cpu-used 8 64,5 s (không nhanh hơn: chậm ở chụp khung, không ở VP9)
//   mov ProRes 4444 55,7 s / 87 MB / 6,3 s · png (chuỗi PNG RGBA, không mã hoá video) 45,3 s / 33 MB / 5,9 s → mặc định png.
// Alpha: PNG không mất dữ liệu (VP9 alpha có mất), bản ghép png và webm giống nhau (SSIM 0,995, khác ở khung chữ đang mờ dần).
export const LAYERS = {
  webm: { name: 'webm', file: 'captions.webm', hf: ['--format', 'webm'], input: ['-c:v', 'libvpx-vp9'] },
  'webm-fast': { name: 'webm-fast', file: 'captions.webm', hf: ['--format', 'webm', '--vp9-cpu-used', '8'], input: ['-c:v', 'libvpx-vp9'] },
  png: { name: 'png', file: 'captions-png', hf: ['--format', 'png-sequence'], input: null },
  mov: { name: 'mov', file: 'captions.mov', hf: ['--format', 'mov'], input: [] },
};
export const LAYER = LAYERS[String(process.env.LUMREELS_CAPTION_LAYER || '').trim().toLowerCase()] || LAYERS.png;

/** Tham số ffmpeg đọc lớp chữ (chuỗi PNG: mẫu tên file + số khung đầu). */
export function layerInput(layer, file) {
  if (layer.input) return [...layer.input, '-i', file];
  const files = fs.readdirSync(file).filter((f) => /\.png$/i.test(f)).sort();
  const m = /^(.*?)(\d+)(\.png)$/i.exec(files[0] || '');
  if (!m) throw new Error('lớp chữ PNG rỗng: ' + file);
  return ['-framerate', String(OUT.fps), '-start_number', String(Number(m[2])), '-i', path.join(file, `${m[1]}%0${m[2].length}d${m[3]}`)];
}

/** Render lớp chữ trong suốt (định dạng LAYER: WebM VP9 alpha / chuỗi PNG / ProRes 4444). */
export async function renderCaptionLayer(sceneDir, outWebm, { log = console.log, onPct, format = LAYER.hf } = {}) {
  let last = -1;
  const r = await runHF(['render', sceneDir, '-o', outWebm, ...format, '-f', String(OUT.fps), '-q', 'looks', '--quiet'], {
    onLine: (l) => {
      const m = /^@hf-progress (.*)$/.exec(l);
      if (m) { try { const p = JSON.parse(m[1]); onPct?.(p.pct); const b = Math.floor(p.pct / 20) * 20; if (b !== last) { last = b; log(`phụ đề HyperFrames ${p.pct}% ${p.code}`); } } catch { /* bỏ qua */ } }
    },
  });
  if (r.code !== 0 || !fs.existsSync(outWebm)) throw new Error('HyperFrames render phụ đề lỗi: ' + r.out.trim().split(/\r?\n/).slice(-5).join(' | '));
  return outWebm;
}