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.

24.2 KB
Raw Blame
// Player giữa Studio — xem trước tức thì, không render:
//  · nền SẠCH (preview-clean.mp4: đã cắt + khung, CHƯA zoom/kính/chữ) → MỌI zoom (cũ lẫn mới) chạy bằng CSS transform
//    theo EDL đang sửa, cùng công thức lumedit Zooms (punch/push, tâm đầu lúc zoom bắt đầu, khung đặt 0,42 chiều cao);
//  · phụ đề HTML theo đúng tham số LOOKS (cỡ, stroke, bóng, cy, chữ hoa, bỏ dấu câu cuối) + hiệu ứng vào (GSAP ease
//    tương đương) + karaoke theo giờ từng chữ — tính thuần theo t nên tua tới đâu đúng tới đó;
//  · đồ hoạ: chính HTML/CSS/runtime của lớp HyperFrames trong <iframe sandbox="allow-scripts"> (postMessage), kính mờ
//    dưới thẻ bằng backdrop-filter;
//  · nhạc phát song song (<audio>, âm lượng theo dB, tự hạ khi có lời).
// Không có nền sạch → nền cũ (base.mp4, đã có zoom gốc: chỉ zoom mới chạy CSS). "Bản xuất" → phát MP4 đã xuất, không vẽ đè.
import { el, tx, icon, iconBtn, fmtT, tokens, clamp, t } from './util.js';

const FPS = 30;
// khung bản ra (edl.output.ratio; đổi trong Studio = doc.ratio): cùng bảng với engine/ratio.mjs + edit/edl.mjs frameCy
export const RATIO_DIMS = { '9:16': [1080, 1920], '16:9': [1920, 1080], '4:3': [1440, 1080], '3:4': [1080, 1440] };
const SAFE_OF = { '9:16': { x0: 120 / 1080, x1: 960 / 1080, y1: 0.80 }, '16:9': { x0: 0.06, x1: 0.94, y1: 0.90 }, '4:3': { x0: 0.06, x1: 0.94, y1: 0.90 }, '3:4': { x0: 0.07, x1: 0.93, y1: 0.86 } };
/** Tâm dòng phụ đề (viết cho 9:16) trên khung r — như edit/edl.mjs frameCy. */
export function frameCy(cy, r) {
  if (r === '9:16' || !Number.isFinite(cy)) return cy;
  const land = RATIO_DIMS[r][0] > RATIO_DIMS[r][1];
  if (cy >= 0.62) return Math.min(SAFE_OF[r].y1 - 0.06, (land ? 0.80 : 0.78) + (cy - 0.70) * 0.5);
  return 0.5 + (cy - 0.5) * (land ? 0.8 : 0.9);
}
let W = 1080; let H = 1920; let RATIO = '9:16';
const ease = (x) => { x = clamp(x, 0, 1); return x * x * (3 - 2 * x); };
// GSAP: powerN.out = 1 − (1 − x)^(N+1); back.out(c)
const pOut = (n) => (x) => 1 - (1 - clamp(x, 0, 1)) ** (n + 1);
const pIn = (n) => (x) => clamp(x, 0, 1) ** (n + 1);
const backOut = (c) => (x) => { x = clamp(x, 0, 1); return 1 + (c + 1) * (x - 1) ** 3 + c * (x - 1) ** 2; };

/** Như lumedit Zooms.scale_at: punch (vào 0,08 s, giữ, ra 0,12 s) / push (đẩy chậm, lùi 0,3 s cuối). Trả {s, z}. */
export function zoomAt(zs, tt) {
  for (const z of zs) {
    if (tt < z.at || tt >= z.at + z.dur) continue;
    const u = tt - z.at; let k;
    if (z.kind === 'punch') { k = u < 0.08 ? ease(u / 0.08) : 1; if (u > z.dur - 0.12) k = Math.min(k, ease((z.dur - u) / 0.12)); }
    else { const back = Math.min(0.3, z.dur * 0.2); k = u < z.dur - back ? ease(u / (z.dur - back)) : ease((z.dur - u) / back); }
    return { s: 1 + (z.scale - 1) * k, z };
  }
  return { s: 1, z: null };
}
export const zoomScale = (zs, tt) => zoomAt(zs, tt).s;

export class Player {
  constructor(ctx) {
    this.ctx = ctx; // {store, onTime(t), onPlay(bool), getSel(), gfxScene()}
    this.root = el('section', 'st-stage');
    this.box = el('div', 'st-vid');
    this.video = el('video', null, null, { playsinline: true, preload: 'auto' });
    this.video.playsInline = true;
    this.zoomWrap = el('div', 'st-zw'); this.zoomWrap.append(this.video);
    this.glassLayer = el('div', 'st-glass', null, { 'aria-hidden': 'true' });
    this.frame = el('iframe', 'st-gframe', null, { sandbox: 'allow-scripts', src: '/studio/gfx-frame.html', tabindex: '-1', 'aria-hidden': 'true', title: 'gfx' });
    this.capLayer = el('div', 'st-cap', null, { 'aria-hidden': 'true' });
    this.capText = el('div', 'st-capt'); this.capLayer.append(this.capText);
    this.capSel = el('div', 'st-capsel'); this.capSel.hidden = true;
    this.badge = el('div', 'st-vbadge'); this.badge.hidden = true;
    this.box.append(this.zoomWrap, this.glassLayer, this.frame, this.capLayer, this.capSel, this.badge);
    this.audio = el('audio', null, null, { preload: 'auto' });
    const ctrl = el('div', 'st-ctrl');
    this.tm = el('span', 'st-time mono');
    this.tmNow = el('b', null, '0:00.0'); this.tmDur = el('span', null, '0:00.0');
    this.tm.append(this.tmNow, ' / ', this.tmDur);
    this.bPrev = iconBtn('prev', 'st.prevFrame', 'st-tbtn');
    this.bPlay = el('button', 'st-play', null, { type: 'button' });
    this.bNext = iconBtn('next', 'st.nextFrame', 'st-tbtn');
    // tỉ lệ khung: đổi ở đây = 1 thay đổi (Undo được), xuất bản mới mới reframe theo mặt + đặt lại phụ đề/đồ hoạ
    this.bRatio = el('select', 'st-pill st-ratiosel', null, { 'aria-label': t('st.ratioAria'), title: t('st.ratioAria'), 'data-i18n-aria': 'st.ratioAria', 'data-i18n-title': 'st.ratioAria' });
    for (const r of Object.keys(RATIO_DIMS)) this.bRatio.append(el('option', null, r, { value: r }));
    this.bRatio.addEventListener('change', () => this.ctx.onRatio?.(this.bRatio.value));
    this.bOut = tx('button', 'st-pill st-outsw', 'st.viewOut', { type: 'button', 'aria-pressed': 'false' });
    ctrl.append(this.tm, this.bPrev, this.bPlay, this.bNext, this.bRatio, this.bOut);
    this.root.append(this.box, ctrl, this.audio);
    this.paintPlay();
    this.mode = 'edit'; // 'edit' (nền + vẽ đè) | 'out' (MP4 đã xuất)
    this.src = { clean: null, base: null, out: null };
    this.cap = null; this.raf = 0; this.musicDur = 0; this.frameReady = false; this.gfxIds = []; this.lastGlass = '';
    this.bPlay.addEventListener('click', () => this.toggle());
    this.bPrev.addEventListener('click', () => this.step(-1 / FPS));
    this.bNext.addEventListener('click', () => this.step(1 / FPS));
    this.bOut.addEventListener('click', () => this.setMode(this.mode === 'out' ? 'edit' : 'out'));
    this.box.addEventListener('click', () => this.toggle());
    const v = this.video;
    v.addEventListener('play', () => { this.paintPlay(); this.syncAudio(true); this.loop(); this.ctx.onPlay?.(true); });
    v.addEventListener('pause', () => { this.paintPlay(); this.audio.pause(); this.ctx.onPlay?.(false); this.tick(); });
    v.addEventListener('seeked', () => { this.syncAudio(true); this.tick(); });
    v.addEventListener('loadedmetadata', () => { this.tick(); this.fit(); });
    v.addEventListener('ended', () => this.paintPlay());
    this.audio.addEventListener('loadedmetadata', () => { this.musicDur = this.audio.duration || 0; this.syncAudio(true); });
    window.addEventListener('message', (e) => {
      if (e.source !== this.frame.contentWindow || e.data?.type !== 'gfx-ready') return;
      this.frameReady = true; this.postScene(); this.tick();
    });
    this.ro = new ResizeObserver(() => this.fit());
    this.ro.observe(this.root);
  }
  get time() { return this.video.currentTime || 0; }
  get duration() { return this.ctx.store.view?.duration || this.video.duration || 0; }
  /** Nguồn đang vẽ đè: 'clean' (mọi zoom CSS) | 'base' (zoom gốc đã nằm trong nền) | null (MP4 đã xuất). */
  get layerSrc() { return this.mode !== 'edit' ? null : this.src.clean ? 'clean' : this.src.base ? 'base' : null; }
  paintPlay() {
    const playing = !this.video.paused && !this.video.ended;
    this.bPlay.replaceChildren(icon(playing ? 'pause' : 'play'));
    this.bPlay.setAttribute('aria-label', t(playing ? 'st.pause' : 'st.play'));
    this.bPlay.title = `${t(playing ? 'st.pause' : 'st.play')} (Space)`;
  }
  setSources({ clean = null, base = null, out, music }) {
    this.src = { clean, base, out };
    const edit = clean || base;
    this.bOut.hidden = !edit || !out;
    this.setMode(edit && this.mode !== 'out' ? 'edit' : 'out', true);
    if (music !== undefined) this.setMusic(music);
  }
  setMode(m, force) {
    if (m === 'edit' && !this.src.clean && !this.src.base) m = 'out';
    if (m === this.mode && !force) return;
    const at = this.time; const was = !this.video.paused;
    this.mode = m;
    const url = m === 'edit' ? this.src.clean || this.src.base : this.src.out;
    this.bOut.setAttribute('aria-pressed', String(m === 'out'));
    this.box.classList.toggle('raw', m === 'out');
    if (url && this.video.getAttribute('src') !== url) {
      this.video.src = url;
      this.video.addEventListener('loadedmetadata', () => { this.video.currentTime = Math.min(at, this.video.duration || at); if (was) this.video.play().catch(() => {}); }, { once: true });
    }
    this.paintBadge();
    this.cap = null; this.lastGlass = ''; this.tick();
  }
  setMusic(url) {
    if (!url) { this.audio.pause(); this.audio.removeAttribute('src'); this.audio.load(); this.musicUrl = null; return; }
    if (url === this.musicUrl) return;
    this.musicUrl = url; this.audio.src = url; this.audio.load();
  }
  /** Nhả file (Windows giữ khoá file đang phát): trước khi server ghi đè base.mp4 / bản sạch. */
  release() {
    this.video.pause(); this.video.removeAttribute('src'); this.video.load();
    this.audio.pause(); this.audio.removeAttribute('src'); this.audio.load(); this.musicUrl = null;
    this.src = { clean: null, base: null, out: null };
  }
  toggle() { if (!this.video.getAttribute('src')) return; if (this.video.paused || this.video.ended) this.video.play().catch(() => {}); else this.video.pause(); }
  pause() { this.video.pause(); }
  seek(tt) {
    const d = this.duration;
    const x = clamp(tt, 0, Math.max(0, d - 1 / FPS / 2));
    if (Number.isFinite(x)) this.video.currentTime = x;
    this.tick(x);
  }
  step(dt) { this.pause(); this.seek(Math.round((this.time + dt) * FPS) / FPS); }

  // ---- nhạc song song: âm lượng theo dB (gần đúng), tự hạ khi có lời ----
  musicVolume(tt) {
    const m = this.ctx.store.doc?.music; if (!m || m.source === 'none' || this.mode !== 'edit') return 0;
    let db = m.gainDb + 12; // nền tiếng gốc ~ −12 dBFS
    if (m.duck && this.ctx.store.lineAt(tt) >= 0) db -= this.ctx.store.view?.music?.duckDb || 10;
    const d = this.duration; if (m.fadeOut > 0 && tt > d - m.fadeOut) db += 20 * Math.log10(Math.max(0.001, (d - tt) / m.fadeOut));
    return clamp(10 ** (db / 20), 0, 1);
  }
  syncAudio(hard) {
    const a = this.audio; const m = this.ctx.store.doc?.music;
    if (!this.musicUrl || !m || m.source === 'none' || this.mode !== 'edit') { a.pause(); return; }
    const md = this.musicDur || a.duration || 0; if (!md) return;
    const want = (m.start + this.time) % md;
    if (hard || Math.abs(a.currentTime - want) > 0.25) a.currentTime = want;
    a.volume = this.musicVolume(this.time);
    const vg = this.ctx.store.doc?.voice?.gainDb || 0;
    this.video.volume = clamp(10 ** (Math.min(0, vg) / 20), 0, 1);
    if (!this.video.paused && a.paused) a.play().catch(() => {});
  }
  loop() {
    cancelAnimationFrame(this.raf);
    const f = () => { this.tick(); if (!this.video.paused && !this.video.ended) { this.syncAudio(false); this.raf = requestAnimationFrame(f); } };
    this.raf = requestAnimationFrame(f);
  }
  /**
   * Khung đang xem = tỉ lệ đang sửa (doc.ratio) — khác bản đã xuất thì là xem trước gần đúng: hình cắt giữa (object-fit),
   * phụ đề đúng chỗ khung mới, không zoom CSS / đồ hoạ (vị trí mặt và đồ hoạ chỉ có sau khi xuất).
   */
  applyFrame() {
    const v = this.ctx.store.view; const doc = this.ctx.store.doc;
    const cur = RATIO_DIMS[v?.output?.ratio] ? v.output.ratio : '9:16';
    const want = this.mode === 'out' ? cur : RATIO_DIMS[doc?.ratio] ? doc.ratio : cur;
    this.pendingRatio = want !== cur;
    if (this.bRatio.value !== (doc?.ratio || cur)) this.bRatio.value = doc?.ratio || cur;
    this.bRatio.disabled = !!v?.readOnly || !!this.ctx.busy?.();
    if (want === RATIO && this.box.dataset.ratio === want) return;
    RATIO = want; [W, H] = RATIO_DIMS[want];
    this.box.dataset.ratio = want;
    this.box.style.aspectRatio = `${W} / ${H}`;
    this.frame.style.width = `${W}px`; this.frame.style.height = `${H}px`;
    const sa = SAFE_OF[want];
    this.capText.style.left = `${(sa.x0 * 100).toFixed(3)}%`; this.capText.style.width = `${((sa.x1 - sa.x0) * 100).toFixed(3)}%`;
    this.cap = null; this.lastGlass = '';
    this.fit();
  }
  /** Vẽ 1 khung theo t: giờ, zoom CSS, phụ đề, đồ hoạ (iframe), kính. */
  tick(at) {
    this.applyFrame();
    let tt = at ?? this.time;
    // đang phát qua chỗ đã cắt (chưa xuất bản): nhảy qua như bản sau khi cắt
    const cut = this.layerSrc && !this.video.paused ? this.ctx.store.cutAt(tt) : null;
    if (cut) { this.video.currentTime = Math.min(cut[1] + 0.001, this.duration); tt = cut[1]; }
    this.tmNow.textContent = fmtT(tt); this.tmDur.textContent = fmtT(this.duration);
    this.ctx.onTime?.(tt);
    const src = this.layerSrc; const doc = this.ctx.store.doc;
    this.paintZoom(src, doc, tt);
    this.paintCap(src && doc && doc.show !== false && !this.ctx.store.cutAt(tt) ? doc.lines.findIndex((l) => tt >= l.start && tt < l.end) : -1, tt);
    this.paintGfx(src && doc ? tt : null);
    this.paintSel();
  }
  /** Tâm zoom (px khung bản ra, vd 1080×1920): tâm khung đầu lúc zoom bắt đầu (faces-out), không có mặt thì (giữa, 40%). */
  zoomCenter(z) {
    const f = this.ctx.store.view?.faces; let c = [W / 2, H * 0.4];
    if (f?.boxes?.length) {
      let best = null;
      for (const [ft, b] of f.boxes) if (b && (!best || Math.abs(ft - z.at) < Math.abs(best[0] - z.at))) best = [ft, b];
      if (best && Math.abs(best[0] - z.at) < 1) c = [(best[1][0] + best[1][2]) / 2, (best[1][1] + best[1][3]) / 2];
    }
    return c;
  }
  paintBadge() {
    const out = this.mode !== 'edit' && !!(this.src.clean || this.src.base);
    const key = out ? 'st.viewingOut' : this.pendingRatio ? 'st.ratioPending' : null;
    this.badge.hidden = !key;
    if (key) { this.badge.textContent = t(key, { r: RATIO }); if (key === 'st.viewingOut') this.badge.dataset.i18n = key; else delete this.badge.dataset.i18n; } // chuỗi có {r}: vẽ lại ở tick khi đổi ngôn ngữ
  }
  paintZoom(src, doc, tt) {
    let tr = '';
    if (src && doc && !this.pendingRatio) {
      let zs = doc.zooms;
      if (src === 'base') { const orig = this.ctx.store.orig?.zooms || []; zs = zs.filter((z) => !orig.some((o) => o.n === z.n && Math.abs(o.at - z.at) < 0.005 && o.dur === z.dur && o.scale === z.scale && o.kind === z.kind)); }
      const { s, z } = zoomAt(zs, tt);
      if (s > 1.0005) {
        const k = this.k || 0.25;
        if (src === 'clean') {
          // như lumedit: cửa sổ W/s × H/s, x0 = cx − W/2s, y0 = cy − 0,42·H/s, kẹp trong khung
          const [cx, cy] = this.zoomCenter(z);
          const x0 = clamp(cx - W / (2 * s), 0, W - W / s); const y0 = clamp(cy - (H * 0.42) / s, 0, H - H / s);
          tr = `translate(${(-x0 * s * k).toFixed(2)}px, ${(-y0 * s * k).toFixed(2)}px) scale(${s.toFixed(4)})`;
        } else tr = `translate(${((1 - s) * W * 0.5 * k).toFixed(2)}px, ${((1 - s) * H * 0.4 * k).toFixed(2)}px) scale(${s.toFixed(4)})`;
      }
    }
    if (this.zoomWrap.style.transform !== tr) this.zoomWrap.style.transform = tr;
  }
  fit() {
    const w = this.box.clientWidth || 1;
    this.k = w / W;
    this.box.style.setProperty('--k', String(this.k));
    this.frame.style.transform = `scale(${this.k})`;
    this.cap = null; this.lastGlass = '';
    this.tick();
  }
  lookCss() {
    const s = this.ctx.store; const id = s.doc?.look;
    return s.view?.captions.looks.find((l) => l.id === id)?.css || null;
  }

  // ---- phụ đề: dựng DOM khi đổi dòng, mỗi khung chỉ đổi transform/opacity/màu ----
  /** Giờ từng chữ: giờ karaoke gốc (co giãn theo giờ dòng mới) nếu chữ không đổi, không thì chia theo số ký tự như server. */
  wordTimes(line, ws) {
    const o = line.wo; const n = ws.length;
    if (Array.isArray(o) && o.length === n && line.wt === line.text && Number.isFinite(line.w0) && line.w1 > line.w0) {
      const f = (line.end - line.start) / (line.w1 - line.w0);
      return o.map((x) => line.start + (x - line.w0) * f);
    }
    const len = ws.map((w) => [...w.w].length); const tot = len.reduce((a, b) => a + b, 0) || 1;
    let acc = 0; return len.map((l) => { const x = line.start + ((line.end - line.start) * acc) / tot; acc += l; return x; });
  }
  buildCap(line, look) {
    const s = this.ctx.store; const k = this.k || 0.25;
    const box = this.capText; const ticker = look.enter === 'ticker' && look.box;
    const ws = tokens(line.text);
    const text = ws.map((w) => { const x = w.w.replace(/[,.;:]+$/u, '') || w.w; return look.upper ? x.toUpperCase() : x; });
    let size = look.size;
    const sa = SAFE_OF[RATIO];
    if (ticker) { const nch = text.join(' ').length; size = Math.max(34, Math.min(look.size, Math.floor((sa.x1 * W - 300) / (nch * 0.46 + 0.4)))); }
    else if (ws.length === 1) size = Math.min(look.size, Math.floor(((sa.x1 - sa.x0) * W) / (Math.max(...text.map((x) => x.length)) * 0.5 + 0.5)));
    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)');
    box.className = 'st-capt' + (ticker ? ' ticker' : '');
    box.style.fontFamily = `${look.font}, 'Be Vietnam Pro', sans-serif`;
    box.style.fontWeight = String(look.weight);
    box.style.fontSize = `${(size * k).toFixed(2)}px`;
    box.style.color = look.color;
    box.style.top = `${(frameCy(look.cy0 ?? look.cy, RATIO) * H * k).toFixed(1)}px`;
    box.style.webkitTextStroke = stroke ? `${(stroke * k).toFixed(2)}px #000` : '0';
    box.style.textShadow = shadow === 'none' ? 'none' : shadow.replace(/(-?\d+(?:\.\d+)?)px/g, (m0, v) => `${(Number(v) * k).toFixed(2)}px`);
    box.style.background = ticker ? look.box.bg : '';
    const hiOn = !!s.doc.hi;
    const kids = []; const words = [];
    if (ticker && look.box.tag) { const tg = el('span', 'tag', look.box.tag); tg.style.background = look.box.tagBg || '#E8202A'; kids.push(tg); }
    ws.forEach((w, i) => {
      if (i) kids.push(' ');
      const sp = el('span', 'w');
      const base = w.hi && hiOn ? look.hi : look.color;
      if (look.enter === 'typewriter') for (const ch of [...text[i]]) sp.append(el('i', 'ch', ch)); else sp.textContent = text[i];
      sp.style.color = base;
      kids.push(sp); words.push({ el: sp, base });
    });
    box.replaceChildren(...kids);
    const wo = this.wordTimes(line, ws);
    const L = s.doc.lines; const idx = L.indexOf(line); const next = L[idx + 1]; const prev = L[idx - 1];
    const chars = [...box.querySelectorAll('.ch')];
    return { line, look, words, wo, chars, ticker, fadeOut: (!next || next.start - line.end >= 0.3) && line.end - line.start > 0.55,
      runStart: ticker && (!prev || line.start - prev.end > 0.5 || /[.?!…]$/.test(prev.text.trim())) };
  }
  paintCap(idx, tt) {
    const s = this.ctx.store; const L = s.doc?.lines || []; const line = L[idx]; const look = this.lookCss();
    const box = this.capText;
    if (!line || !look) { if (this.cap) { box.replaceChildren(); box.hidden = true; this.cap = null; } return; }
    const key = `${line.u}|${line.text}|${line.start}|${line.end}|${s.doc.look}|${s.doc.hi}|${this.k}|${s.doc.show}|${RATIO}`;
    if (!this.cap || this.cap.key !== key) { this.cap = this.buildCap(line, look); this.cap.key = key; }
    box.hidden = false;
    const c = this.cap; const u = tt - line.start; const k = this.k || 0.25;
    let x = 0; let y = 0; let sc = 1; let op = 1;
    switch (look.enter) {
      case 'pop': sc = 0.55 + 0.45 * backOut(3)(u / 0.18); break;
      case 'pop-soft': { const e = backOut(2.2)(u / 0.14); sc = 0.86 + 0.14 * e; op = clamp(e, 0, 1); break; }
      case 'slide-left': { const e = pOut(3)(u / 0.16); x = 80 * (1 - e); op = e; break; }
      case 'slam': {
        const e = pIn(4)(u / 0.12); sc = 1.6 - 0.6 * e; op = 0.4 + 0.6 * e;
        const sh = [6, -6, 6, 0]; let px = 0;
        for (let q = 0; q < 4; q++) { const a0 = 0.12 + q * 0.025; if (u >= a0) px = u >= a0 + 0.025 ? sh[q] : px + (sh[q] - px) * ((u - a0) / 0.025); }
        x = px; break;
      }
      case 'fade-slow': op = pOut(1)(u / 0.3); if (c.fadeOut && tt > line.end - 0.25) op *= 1 - pIn(1)((tt - (line.end - 0.25)) / 0.25); break;
      case 'typewriter': {
        const n = c.chars.length; const st = Math.min(0.035, ((line.end - line.start) * 0.6) / Math.max(1, n));
        c.chars.forEach((ch, q) => { const v = u >= q * st ? '1' : '0'; if (ch.style.opacity !== v) ch.style.opacity = v; });
        break;
      }
      case 'ticker': if (c.runStart) x = -W * (1 - pOut(3)(u / 0.2)); else op = clamp(u / 0.08, 0, 1); break;
      default: { const e = pOut(2)(u / 0.12); y = 18 * (1 - e); op = e; }
    }
    box.style.transform = `translate(${(x * k).toFixed(2)}px, ${(y * k).toFixed(2)}px) scale(${sc.toFixed(4)})`;
    box.style.opacity = op.toFixed(3);
    // karaoke: chữ đang nói tô màu nhấn
    if (look.karaoke && c.words.length > 1) {
      c.words.forEach((w, q) => {
        const a = c.wo[q]; const b = q + 1 < c.wo.length ? c.wo[q + 1] : line.end;
        const col = tt >= a && tt < b ? look.hi : w.base;
        if (w.el.style.color !== col) w.el.style.color = col;
      });
    }
  }
  /** Khung chọn quanh dòng chữ đang chọn (như mẫu) — chỉ khi dòng đó đang hiện. */
  paintSel() {
    const sel = this.ctx.getSel?.();
    const show = !!this.layerSrc && sel?.kind === 'cap' && !this.capText.hidden && this.cap?.line?.u === sel.u;
    this.capSel.hidden = !show;
    if (!show) return;
    const b = this.box.getBoundingClientRect(); const r = this.capText.getBoundingClientRect();
    this.capSel.style.transform = `translate(${(r.left - b.left - 6).toFixed(1)}px, ${(r.top - b.top - 4).toFixed(1)}px)`;
    this.capSel.style.width = `${(r.width + 12).toFixed(1)}px`; this.capSel.style.height = `${(r.height + 8).toFixed(1)}px`;
  }

  // ---- đồ hoạ: cảnh thật trong iframe sandbox + kính mờ ----
  /** Cảnh mới (server dựng từ đồ hoạ đang sửa): gửi vào khung. scene = {css, html, data} | null. */
  setGfxScene(scene) { this.gfxScene = scene; this.postScene(); this.tick(); }
  postScene() {
    if (!this.frameReady || !this.frame.contentWindow) return;
    const sc = this.gfxScene || { css: '', html: '', data: [] };
    // khung sandbox có origin rỗng → targetOrigin '*'; chỉ gửi cảnh đồ hoạ (không có gì bí mật)
    this.frame.contentWindow.postMessage({ type: 'scene', css: sc.css, html: sc.html, G: sc.data }, '*');
  }
  paintGfx(tt) {
    this.paintBadge();
    const on = tt != null && !!this.gfxScene?.data?.length && !this.pendingRatio;
    this.frame.hidden = !on;
    if (on && this.frameReady && tt !== this.lastGfxT) { this.lastGfxT = tt; this.frame.contentWindow.postMessage({ type: 't', t: tt }, '*'); }
    // kính mờ dưới thẻ (như bước ghép: tem giá / sticker / thẻ ghim không có kính)
    const doc = this.ctx.store.doc; const k = this.k || 0.25;
    const list = on && this.layerSrc === 'clean' ? doc.gfx.filter((g) => g.box && !['price_tag', 'sticker'].includes(g.type) && !g.data?.pin && tt >= g.at && tt < g.until) : [];
    const key = list.map((g) => `${g.u}|${JSON.stringify(g.box)}`).join('#') + k;
    if (key !== this.lastGlass) {
      this.lastGlass = key;
      this.glassLayer.replaceChildren(...list.map((g) => {
        const d = el('div', 'gl', null, { 'data-u': g.u }); const b = g.box;
        d.style.transform = `translate(${(b.x * k).toFixed(1)}px, ${(b.y * k).toFixed(1)}px)`;
        d.style.width = `${(b.w * k).toFixed(1)}px`; d.style.height = `${(b.h * k).toFixed(1)}px`;
        d.style.borderRadius = `${(38 * (b.scale ?? 1) * k).toFixed(1)}px`;
        d.style.backdropFilter = d.style.webkitBackdropFilter = `blur(${(24 * k).toFixed(1)}px)`;
        return d;
      }));
    }
    for (const d of this.glassLayer.children) {
      const g = doc.gfx.find((x) => x.u === d.dataset.u); if (!g) continue;
      const a = Math.min(ease((tt - g.at) / 0.15), ease((g.until - tt) / 0.22));
      d.style.opacity = a.toFixed(3);
    }
  }
  destroy() { cancelAnimationFrame(this.raf); this.ro.disconnect(); this.release(); }
}