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.

39.7 KB
Raw Blame
// Chỉnh tay sau khi AI edit xong (không gọi LLM): phụ đề (chữ, mốc, gộp/tách/xoá dòng, chữ nhấn, đổi look),
// nhạc (đổi/tải/bỏ, dB, ducking, fade out, giây bắt đầu), âm lượng giọng, bật/tắt sfx, xoá zoom, xoá đồ hoạ.
// Mỗi lần chỉnh → EDL mới + bản out-r<n>.mp4 mới (pipeline.manualEdit). Ở đây: schema chặt, đọc trạng thái cho UI,
// áp bản vá lên EDL và cho biết lớp nào phải dựng lại (nền / lớp chữ / tiếng).
// Mốc phụ đề là GIÂY BẢN RA (người dùng nhìn video ra mà sửa); EDL lưu ở captions.lines (cũng giây bản ra).
import fs from 'node:fs';
import path from 'node:path';
import { z } from 'zod';
import { MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';
import { captionCards, cardOverlaps, LOOKS, captionTop } from './captions-hf.mjs';
import { outputDuration, timelineOf, toOutputNearest, inKeep, hookDur, validateEdl, OUT, frameCy, frameOf } from './edl.mjs';
import { RATIO_IDS, dimsOf } from '../engine/ratio.mjs';
import { outputToSource, layoutGraphics, MIN_GRAPHIC } from './graphics.mjs';
import { applyExtraCuts, outputCutToSource } from './planner.mjs';

export const LOOK_IDS = Object.keys(LOOKS);
export const MAX_LINES = 600;
export const UPLOAD_RE = /^music-up-\d{1,4}\.(mp3|wav|m4a|aac|ogg|flac|opus)$/;
const httpErr = (code, msg) => Object.assign(new Error(msg), { code });
const r2 = (x) => Math.round(x * 100) / 100;
const sec = z.number().finite().min(0).max(3600);
const ZOOM = { at: sec, dur: z.number().finite().min(0.2).max(8), scale: z.number().finite().min(1).max(1.6), kind: z.enum(['punch', 'push']) };
const partialOf = (o) => Object.fromEntries(Object.entries(o).map(([k, v]) => [k, v.optional()]));
const txt = (n) => z.string().trim().max(n);
const cell = z.union([z.string().trim().max(30), z.number().finite()]);
const k10 = z.number().int().min(0).max(9);
// ô chữ/số sửa được của đồ hoạ (graphics.mjs checkGraphics): chỉ đổi giá trị, không thêm/bớt dòng
const GfxData = z.object({
  title: txt(30).optional(), unit: txt(10).optional(), label: txt(26).optional(), prefix: txt(6).optional(), suffix: txt(10).optional(),
  text: txt(16).optional(), kicker: txt(20).optional(), a: txt(12).optional(), b: txt(12).optional(),
  value: cell.optional(), old: cell.optional(),
  items: z.array(z.object({ k: k10, label: cell.optional(), text: txt(30).optional(), value: cell.optional(), ok: z.boolean().optional() }).strict()).max(10).optional(),
  rows: z.array(z.object({ k: k10, label: txt(14).optional(), value: cell.optional(), a: txt(12).optional(), b: txt(12).optional() }).strict()).max(10).optional(),
  points: z.array(z.object({ k: k10, label: txt(8).optional(), value: cell.optional() }).strict()).max(10).optional(),
}).strict();
/** Các ô của đồ hoạ cho UI (cùng tên trường với GfxData). */
export const GFX_FIELDS = ['title', 'unit', 'label', 'prefix', 'suffix', 'text', 'kicker', 'a', 'b', 'value', 'old'];
const ROW_FIELDS = { items: ['label', 'text', 'value', 'ok'], rows: ['label', 'value', 'a', 'b'], points: ['label', 'value'] };

export const ManualSchema = z.object({
  // đổi tỉ lệ khung (Studio): reframe lại theo mặt, phụ đề/đồ hoạ đặt lại theo khung mới, xuất bản mới
  ratio: z.enum(RATIO_IDS).optional(),
  captions: z.object({
    lines: z.array(z.object({ start: sec, end: sec, text: z.string().trim().min(1).max(200) }).strict()).max(MAX_LINES).optional(),
    highlights: z.boolean().optional(),
    look: z.enum(LOOK_IDS).optional(),
    show: z.boolean().optional(),
  }).strict().optional(),
  music: z.object({
    source: z.union([
      z.enum(['keep', 'none']),
      z.string().regex(/^synth:[a-z0-9-]{1,30}$/),
      z.string().regex(/^upload:music-up-\d{1,4}\.(mp3|wav|m4a|aac|ogg|flac|opus)$/),
    ]).optional(),
    gainDb: z.number().finite().min(-40).max(0).optional(),
    duck: z.boolean().optional(),
    fadeOut: z.number().finite().min(0).max(10).optional(),
    start: z.number().finite().min(0).max(600).optional(),
  }).strict().optional(),
  voice: z.object({ gainDb: z.number().finite().min(-12).max(12) }).strict().optional(),
  // cắt bỏ đoạn trên track video: khoảng GIÂY BẢN RA của bản hiện tại (Studio: chọn vùng → Xoá, hoặc S tách clip rồi xoá)
  cuts: z.object({ remove: z.array(z.object({ start: sec, end: sec }).strict()).min(1).max(50) }).strict().optional(),
  sfx: z.object({ on: z.boolean() }).strict().optional(),
  zooms: z.object({
    remove: z.array(z.number().int().min(0).max(999)).max(200).optional(),
    // mốc at của add/set là GIÂY BẢN RA (người dùng kéo trên timeline); server đổi về giây nguồn
    add: z.array(z.object(ZOOM).strict()).max(50).optional(),
    set: z.array(z.object({ n: z.number().int().min(0).max(999), ...partialOf(ZOOM) }).strict()).max(200).optional(),
  }).strict().optional(),
  graphics: z.object({
    remove: z.array(z.string().min(1).max(80)).max(100).optional(),
    // start/end: giây bản ra; data: chỉ các ô chữ/số đã có của đồ hoạ đó (kiểu phải khớp)
    set: z.array(z.object({ id: z.string().min(1).max(80), start: sec.optional(), end: sec.optional(), data: GfxData.optional() }).strict()).max(100).optional(),
  }).strict().optional(),
}).strict();

/** Kiểm bản vá: lỗi schema → throw 400 kèm đường dẫn trường. Rỗng → 400. */
export function parseManual(body) {
  const r = ManualSchema.safeParse(body);
  if (!r.success) throw httpErr(400, 'chỉnh tay không hợp lệ: ' + r.error.issues.slice(0, 5).map((i) => `${i.path.join('.') || '(gốc)'}: ${i.message}`).join('; '));
  const p = r.data;
  if (!Object.keys(p).length || Object.values(p).every((v) => v && typeof v === 'object' && !Object.keys(v).length)) throw httpErr(400, 'chỉnh tay rỗng: không có gì để đổi');
  return p;
}

// ---- dòng phụ đề ⇄ chữ ------------------------------------------------------------------------------------------
const key = (w) => String(w).toLowerCase().normalize('NFC').replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, '');

/** "*Giá* tăng *gấp đôi*" → [{w, hi}] (chữ trong *…* là chữ nhấn). */
export function lineTokens(text) {
  const out = []; const re = /\*([^*]+)\*|([^*]+)/g; let m;
  while ((m = re.exec(String(text)))) {
    const hi = !!m[1];
    for (const w of (m[1] || m[2]).split(/\s+/)) if (w.trim()) out.push({ w: w.trim(), hi });
  }
  return out.slice(0, 40);
}
/** [{w, hi}] → "*Giá* tăng *gấp* *đôi*" (mỗi chữ nhấn một cặp sao: dễ đọc lại, đổi qua lại không mất gì). */
export const lineText = (words) => words.map((w) => (w.hi ? `*${w.w}*` : w.w)).join(' ');

/** Dòng phụ đề hiện tại (giây bản ra) của EDL: captions.lines nếu đã chỉnh tay, không thì nhóm chữ tự động. */
export function currentLines(edl) {
  if (edl.captions.lines) return edl.captions.lines.map((l) => ({ start: l.start, end: l.end, words: l.words.map((w) => ({ ...w })) }));
  if (!edl.captions.words.length) return [];
  const hi = new Set(edl.captions.highlights);
  return captionCards(edl).map((c) => ({
    start: r2(c.start), end: r2(c.end),
    words: c.words.map((w, k) => ({ w: w.w, o: r2(c.wordOut[k]), hi: hi.has(w.i) })),
  }));
}

/**
 * Dòng người dùng gửi ({start, end, text}) → dòng EDL ({start, end, words:[{w, o, hi}]}). Mốc từng chữ (karaoke):
 * chữ giống chữ cũ nằm trong dòng thì giữ mốc cũ, chữ mới chia đều theo số ký tự. Kiểm thứ tự, chồng, độ dài.
 */
export function buildLines(input, prevLines, dur) {
  const lines = input.map((l, n) => ({ ...l, n })).sort((a, b) => a.start - b.start || a.n - b.n);
  const old = prevLines.flatMap((l) => l.words.map((w) => ({ k: key(w.w), o: w.o })));
  const out = [];
  for (const [n, l] of lines.entries()) {
    const start = r2(l.start); const end = r2(Math.min(l.end, dur));
    if (start >= dur) throw httpErr(400, `dòng ${n + 1} bắt đầu ở ${start} s, sau cuối video (${dur.toFixed(2)} s)`);
    if (end - start < 0.1) throw httpErr(400, `dòng ${n + 1} ("${l.text.slice(0, 30)}") ngắn hơn 0,1 s hoặc kết thúc trước khi bắt đầu`);
    const toks = lineTokens(l.text);
    if (!toks.length) throw httpErr(400, `dòng ${n + 1} không có chữ`);
    // mốc neo: chữ trùng chữ cũ trong khoảng dòng (theo thứ tự, không lùi); chữ còn lại chia đều theo số ký tự
    // giữa hai neo kề nó (hoặc mép dòng)
    let last = start - 1e-6;
    const anchor = toks.map((t) => {
      const hit = old.find((o) => o.k && o.k === key(t.w) && o.o >= Math.max(start - 0.05, last) && o.o < end);
      if (!hit) return null;
      last = hit.o + 1e-6;
      return Math.max(start, hit.o);
    });
    const len = toks.map((t) => [...t.w].length);
    const os = anchor.slice();
    for (let k = 0; k < toks.length;) {
      if (os[k] != null) { k++; continue; }
      let j = k; while (j < toks.length && os[j] == null) j++;
      const a = k ? os[k - 1] : start; // khoảng trống nằm giữa neo trước (hoặc mép dòng) và neo sau (hoặc cuối dòng)
      const b = j < toks.length ? os[j] : end;
      // chữ neo phía trước cũng cần thời gian của nó: chia [a, b] theo số ký tự, phần của nó trước
      const from = k ? Math.min(b, a + ((b - a) * len[k - 1]) / (len.slice(k - 1, j).reduce((s, x) => s + x, 0) || 1)) : a;
      const span = Math.max(0, b - from); const tot = len.slice(k, j).reduce((s, x) => s + x, 0) || 1;
      let acc = 0;
      for (let q = k; q < j; q++) { os[q] = from + (span * acc) / tot; acc += len[q]; }
      k = j;
    }
    let prevO = start;
    const words = toks.map((t, k) => { const o = r2(Math.max(prevO, Math.min(end - 0.02, os[k]))); prevO = o; return { w: t.w, o, hi: t.hi }; });
    out.push({ start, end, words });
  }
  const bad = cardOverlaps(out.map((c) => ({ ...c, words: c.words })));
  if (bad.length) throw httpErr(400, 'dòng phụ đề đè nhau: ' + bad.slice(0, 3).join('; '));
  return out;
}

/**
 * Khoá so dòng: giờ + chữ đã chuẩn hoá qua lineTokens. Chữ AI sửa thành 2 từ ("RTX 5060" là 1 chữ trong EDL, nhấn) in ra
 * "*RTX 5060*" nhưng tách lại thành "*RTX* *5060*" — không chuẩn hoá thì dòng không sửa cũng bị đếm là "đổi".
 */
export const lineKey = (l) => `${r2(l.start)}|${r2(l.end)}|${lineText(lineTokens(lineText(l.words)))}`;
/** Số dòng đổi: dòng mới không có trong bản cũ (đếm theo bội) + số dòng bị bớt. */
export function changedLines(before, after) {
  const left = new Map(); for (const x of before) left.set(x, (left.get(x) || 0) + 1);
  let n = 0;
  for (const x of after) { const c = left.get(x) || 0; if (c) left.set(x, c - 1); else n++; }
  return n + Math.max(0, before.length - after.length);
}

/** Chữ ký phần cắt (keep + móc): dòng phụ đề chỉnh tay (giây bản ra) chỉ còn đúng khi phần cắt không đổi. */
export const cutSig = (edl) => JSON.stringify([edl.keep.map((k) => [r2(k.start), r2(k.end)]), edl.hook ? [r2(edl.hook.start), r2(edl.hook.end), !!edl.hook.repeat] : null]);

// ---- trạng thái cho UI -------------------------------------------------------------------------------------------
/** Ô chữ/số sửa được của 1 đồ hoạ (cho bảng thuộc tính Studio): chỉ trường GfxData, không mốc giờ nội bộ. */
export function gfxFields(d = {}) {
  const out = {};
  for (const k of GFX_FIELDS) if (typeof d[k] === 'string' || typeof d[k] === 'number') out[k] = d[k];
  for (const [arr, fs2] of Object.entries(ROW_FIELDS)) {
    if (!Array.isArray(d[arr])) continue;
    out[arr] = d[arr].map((it) => Object.fromEntries(fs2.filter((f) => ['string', 'number', 'boolean'].includes(typeof it[f])).map((f) => [f, it[f]])));
  }
  return out;
}
/** Mốc các vết cắt trên bản ra (giây): chỗ nối câu móc → clip và giữa các đoạn giữ. */
export function cutsOf(edl) {
  const tl = timelineOf(edl); const out = [];
  let acc = hookDur(tl);
  if (acc > 0) out.push(r2(acc));
  tl.forEach((k, i) => { acc += k.end - k.start; if (i < tl.length - 1) out.push(r2(acc)); });
  return out;
}
/** Thông số kiểu chữ cho lớp xem trước HTML của Studio (gần đúng với lớp chữ HyperFrames). */
const lookCss = (l) => ({ font: l.font, weight: l.weight, size: l.size, upper: !!l.upper, color: l.color, hi: l.hi, cy: frameCy(l.cy), cy0: l.cy, karaoke: !!l.karaoke, enter: l.enter, stroke: l.stroke ?? null, shadow: l.shadow || null, box: l.box ? { bg: l.box.bg, tag: l.box.tag || null, tagBg: l.box.tagBg || null, stroke: l.box.stroke ?? null } : null });

/** Mọi thứ chỉnh tay được của bản hiện tại (UI vẽ bảng từ đây). */
export function manualView(edl, state, { lookNames = {}, uploads = {} } = {}) {
  const tl = timelineOf(edl);
  const dur = r2(outputDuration(tl));
  const man = state.manual || {};
  const m = edl.music;
  const syn = m && /music-([a-z0-9-]+)\.wav$/.exec(m.file);
  const musicName = !m ? null : man.musicName || (/music-reel\.wav$/.test(m.file) ? 'reel' : syn && MUSIC_STYLES.includes(syn[1]) ? `synth:${syn[1]}` : path.basename(m.file));
  const f = frameOf(edl);
  return {
    duration: dur, draft: !!state.draft, cuts: cutsOf(edl),
    output: { ratio: f.ratio, width: f.width, height: f.height, safe: f.safe },
    captions: {
      // wo: giây bản ra của từng chữ (karaoke xem trước)
      lines: currentLines(edl).map((l) => ({ start: l.start, end: l.end, text: lineText(l.words), wo: l.words.map((w) => w.o) })),
      edited: !!edl.captions.lines, highlights: !edl.captions.hiOff, look: edl.captions.style, show: !edl.captions.off,
      looks: LOOK_IDS.map((id) => ({ id, name: lookNames[id]?.name || id, nameEn: lookNames[id]?.nameEn || lookNames[id]?.name || id, hi: LOOKS[id].hi, css: lookCss(LOOKS[id]) })),
    },
    music: {
      on: !!m, name: musicName, gainDb: m ? m.gainDb : (man.music?.gainDb ?? -22), duck: m ? m.duckDb > 0 : man.music?.duck !== false,
      duckDb: m?.duckDb || man.music?.duckDb || 10,
      fadeOut: m ? m.fadeOut : (man.music?.fadeOut ?? 1.5), start: m ? (m.start || 0) : 0,
      synth: MUSIC_STYLES, uploads: Object.entries(uploads).map(([file, name]) => ({ file, name })),
    },
    voice: { gainDb: edl.audio.voiceGainDb || 0 },
    sfx: { on: !edl.audio.sfxOff, count: edl.sfx.length + (edl.hook?.sfx ? 1 : 0) },
    zooms: edl.zooms.map((zm, n) => ({ n, at: r2(toOutputNearest(tl, zm.at)), kind: zm.kind, scale: zm.scale, dur: zm.dur })),
    graphics: (edl.graphics || []).map((g) => ({
      id: g.id, type: g.type, at: r2(toOutputNearest(tl, g.start)), until: r2(toOutputNearest(tl, g.end)),
      title: g.data?.title || g.data?.label || g.data?.text || '', data: gfxFields(g.data), box: g.box || null, estimate: !!g.estimate,
    })),
  };
}

// ---- zoom & đồ hoạ (Studio: kéo/giãn trên timeline, mốc giây bản ra) ------------------------------------------------
const sameZ = (a, b) => Math.abs(a - b) < 0.02;
/** Khoảng bản ra [o, o + dur) của các zoom chạm nhau → lỗi (lumedit chỉ chạy zoom đầu tiên trong khoảng chồng). */
function zoomClash(edl, touched) {
  const tl = timelineOf(edl);
  const span = edl.zooms.map((zm) => [toOutputNearest(tl, zm.at), toOutputNearest(tl, zm.at) + zm.dur]);
  for (const i of touched) {
    for (let j = 0; j < span.length; j++) {
      if (j !== i && span[i][0] < span[j][1] - 1e-3 && span[j][0] < span[i][1] - 1e-3) return `zoom ở ${span[i][0].toFixed(2)} s chồng zoom ở ${span[j][0].toFixed(2)} s`;
    }
  }
  return null;
}
function applyZooms(edl, p, { dur, man, redo, summary }) {
  const tl = timelineOf(edl);
  const n0 = edl.zooms.length;
  const all = [...new Set([...(p.remove || []), ...(p.set || []).map((x) => x.n)])];
  const bad = all.filter((n) => n >= n0);
  if (bad.length) throw httpErr(400, `không có zoom số ${bad.join(', ')} (có ${n0} zoom, đếm từ 0)`);
  const toSrc = (o, d) => {
    if (o >= dur - 0.2) throw httpErr(400, `zoom ở ${o} s nằm sát/sau cuối video (${dur.toFixed(2)} s)`);
    if (o + d > dur + 0.05) throw httpErr(400, `zoom ở ${o} s dài ${d} s chạy quá cuối video (${dur.toFixed(2)} s)`);
    return +outputToSource(tl, o).toFixed(3);
  };
  const items = edl.zooms.map((zm, n) => ({ ...zm, n }));
  const bits = [];
  man.zoomsSet = man.zoomsSet || [];
  for (const s of p.set || []) {
    const it = items[s.n]; const from = it.at;
    const next = { at: it.at, dur: it.dur, scale: it.scale, kind: it.kind };
    for (const k of ['dur', 'scale', 'kind']) if (s[k] !== undefined) next[k] = s[k];
    if (s.at !== undefined) next.at = toSrc(s.at, next.dur);
    if (next.at === it.at && next.dur === it.dur && next.scale === it.scale && next.kind === it.kind) continue;
    Object.assign(it, next); it.touched = true; delete it.word;
    man.zoomsSet.push({ from, z: next });
    man.zoomsRemovedAt = (man.zoomsRemovedAt || []).filter((x) => !sameZ(x, next.at));
    bits.push(`sửa zoom ${toOutputNearest(tl, from).toFixed(1)} s`);
  }
  const rm = new Set(p.remove || []);
  if (rm.size) {
    const gone = items.filter((it) => rm.has(it.n));
    man.zoomsRemovedAt = [...new Set([...(man.zoomsRemovedAt || []), ...gone.map((zm) => zm.at)])];
    man.zoomsAdded = (man.zoomsAdded || []).filter((a) => !gone.some((g) => sameZ(g.at, a.at)));
    bits.push(`xoá ${gone.length} zoom (${gone.map((zm) => `${toOutputNearest(tl, zm.at).toFixed(1)} s`).join(', ')})`);
  }
  const kept = items.filter((it) => !rm.has(it.n));
  man.zoomsAdded = man.zoomsAdded || [];
  for (const a of p.add || []) {
    const zm = { at: toSrc(a.at, a.dur), dur: a.dur, scale: a.scale, kind: a.kind, touched: true };
    if (kept.some((k) => sameZ(k.at, zm.at))) throw httpErr(400, `đã có zoom ở ${a.at} s`);
    kept.push(zm); man.zoomsAdded.push({ at: zm.at, dur: zm.dur, scale: zm.scale, kind: zm.kind });
    man.zoomsRemovedAt = (man.zoomsRemovedAt || []).filter((x) => !sameZ(x, zm.at));
    bits.push(`thêm zoom ${a.kind} ${a.at.toFixed(1)} s`);
  }
  if (!bits.length) return;
  kept.sort((x, y) => x.at - y.at);
  const touched = kept.map((x, i) => (x.touched ? i : -1)).filter((i) => i >= 0);
  edl.zooms = kept.map(({ n: _n, touched: _t, ...zm }) => zm);
  const clash = zoomClash(edl, touched);
  if (clash) throw httpErr(400, clash);
  redo.base = true; summary.push(bits.join(', '));
}

const REQUIRED_TEXT = { sticker: ['text'], title_card: ['title'] };
export function patchGfxData(g, d) {
  const cur = g.data; const changed = [];
  const put = (obj, k, v, where, required) => {
    if (!(k in obj)) throw httpErr(400, `đồ hoạ ${g.id} (${g.type}) không có ô ${where}`);
    const t0 = typeof obj[k];
    let val = v;
    if (t0 === 'number' && typeof v === 'string') { val = Number(v.replace(',', '.')); if (!v.trim() || !Number.isFinite(val)) throw httpErr(400, `ô ${where} của ${g.id} phải là số`); }
    if (t0 === 'string' && typeof v === 'number') val = String(v);
    if (typeof val !== t0) throw httpErr(400, `ô ${where} của ${g.id} sai kiểu (${t0})`);
    if (t0 === 'string' && required && !val.trim()) throw httpErr(400, `ô ${where} của ${g.id} không được trống`);
    if (obj[k] !== val) { obj[k] = val; changed.push(where); }
  };
  for (const k of GFX_FIELDS) if (d[k] !== undefined) put(cur, k, d[k], k, (REQUIRED_TEXT[g.type] || []).includes(k));
  for (const arr of Object.keys(ROW_FIELDS)) {
    for (const row of d[arr] || []) {
      if (!Array.isArray(cur[arr]) || !cur[arr][row.k]) throw httpErr(400, `đồ hoạ ${g.id} không có ${arr}[${row.k}]`);
      for (const f of ROW_FIELDS[arr]) if (row[f] !== undefined) put(cur[arr][row.k], f, row[f], `${arr}[${row.k}].${f}`, f === 'text' || f === 'label');
    }
  }
  return changed;
}
/** Dời/giãn đồ hoạ (giây bản ra) + sửa ô chữ/số. Mốc nội bộ (data.at, dòng/cột) dời theo đầu đồ hoạ, kẹp trong khoảng mới. */
function applyGraphicsSet(edl, list, { dur, dir, style, man, redo, summary, warnings, noLayout = false }) {
  const tl = timelineOf(edl);
  let retimed = false;
  man.graphicsSet = man.graphicsSet || {};
  for (const s of list) {
    const g = (edl.graphics || []).find((x) => x.id === s.id);
    if (!g) throw httpErr(400, `không có đồ hoạ ${s.id}`);
    const rec = man.graphicsSet[g.id] || {};
    if (s.data) {
      const ch = patchGfxData(g, s.data);
      if (ch.length) { redo.layer = true; summary.push(`sửa chữ đồ hoạ ${g.type} (${ch.join(', ')})`); rec.data = JSON.parse(JSON.stringify(g.data)); }
    }
    if (s.start !== undefined || s.end !== undefined) {
      const o0 = toOutputNearest(tl, g.start); const o1 = toOutputNearest(tl, g.end);
      const a = r2(s.start ?? o0); const b = r2(Math.min(dur, s.end ?? o1));
      if (b - a < MIN_GRAPHIC - 1e-6) throw httpErr(400, `đồ hoạ ${g.id} phải hiện ít nhất ${MIN_GRAPHIC} s (đang ${(b - a).toFixed(2)} s)`);
      if (Math.abs(a - o0) < 0.01 && Math.abs(b - o1) < 0.01) { if (Object.keys(rec).length) man.graphicsSet[g.id] = rec; continue; }
      const shift = a - o0;
      const move = (src) => { const o = toOutputNearest(tl, src) + shift; return +outputToSource(tl, Math.min(b - 0.2, Math.max(a, o))).toFixed(3); };
      g.data.at = move(g.data.at ?? g.start);
      for (const arr of [g.data.items, g.data.points, g.data.rows]) if (Array.isArray(arr)) for (const it of arr) if (Number.isFinite(it.at)) it.at = move(it.at);
      g.start = +outputToSource(tl, a).toFixed(3); g.end = +outputToSource(tl, b).toFixed(3);
      if (!inKeep(tl, g.data.at)) g.data.at = g.start;
      rec.start = g.start; rec.end = g.end; rec.data = JSON.parse(JSON.stringify(g.data));
      retimed = true; redo.layer = true; redo.base = true;
      summary.push(`đồ hoạ ${g.type} ${o0.toFixed(1)}–${o1.toFixed(1)} s → ${a.toFixed(1)}–${b.toFixed(1)} s`);
    }
    if (Object.keys(rec).length) man.graphicsSet[g.id] = rec;
  }
  if (!retimed || noLayout) return; // đổi tỉ lệ cùng lúc: đặt lại vị trí ở manualEdit (đo mặt trên khung mới)
  // đặt lại vị trí né mặt theo khoảng mới (khung mặt bản ra đã đo ở lần dựng trước: faces-out.json)
  edl.graphics.sort((x, y) => x.start - y.start);
  let faces = null;
  try { faces = JSON.parse(fs.readFileSync(path.join(dir, 'faces-out.json'), 'utf8')); } catch { /* không có: giữ vị trí cũ */ }
  if (faces) {
    const before = edl.graphics.map((g) => g.id);
    const w = layoutGraphics(edl.graphics, tl, faces, captionTop(edl.captions.style), { stepTracker: !!style?.graphics?.stepTracker });
    const lost = before.filter((id) => !edl.graphics.some((g) => g.id === id));
    if (lost.length) throw httpErr(400, `không đủ chỗ né mặt cho đồ hoạ ${lost.join(', ')} ở khoảng mới: ${w.join('; ')}`);
  } else warnings.push('không có khung mặt đã đo (faces-out.json): đồ hoạ giữ vị trí cũ');
}

/**
 * Cảnh xem trước đồ hoạ cho Studio (POST /api/edits/:id/gfx-preview): đồ hoạ của bản hiện tại với giờ (giây bản ra) và ô
 * chữ/số đang sửa ở máy. Kiểm như bản vá (GfxData, kiểu khớp). Không ghi gì. Trả {css, html, data} của graphicsScene.
 */
export const GfxPreviewSchema = z.object({
  graphics: z.array(z.object({ id: z.string().min(1).max(80), at: sec, until: sec, data: GfxData.optional() }).strict()).max(60),
}).strict();
export function previewGraphics(edl, body, { accent, graphicsScene }) {
  const r = GfxPreviewSchema.safeParse(body);
  if (!r.success) throw httpErr(400, 'xem trước đồ hoạ không hợp lệ: ' + r.error.issues.slice(0, 3).map((i) => `${i.path.join('.')}: ${i.message}`).join('; '));
  const tl = timelineOf(edl); const dur = outputDuration(tl);
  const list = r.data.graphics.map((x) => {
    const g0 = (edl.graphics || []).find((g) => g.id === x.id);
    if (!g0) throw httpErr(400, `không có đồ hoạ ${x.id}`);
    const g = JSON.parse(JSON.stringify(g0));
    if (x.data) patchGfxData(g, x.data);
    // giờ mới: dời mốc nội bộ theo đầu đồ hoạ (như applyGraphicsSet)
    const o0 = toOutputNearest(tl, g.start); const a = Math.min(x.at, dur); const b = Math.min(Math.max(x.until, a + 0.1), dur);
    const move = (src) => +outputToSource(tl, Math.min(b - 0.2, Math.max(a, toOutputNearest(tl, src) + a - o0))).toFixed(3);
    g.data.at = move(g.data.at ?? g.start);
    for (const arr of [g.data.items, g.data.points, g.data.rows]) if (Array.isArray(arr)) for (const it of arr) if (Number.isFinite(it.at)) it.at = move(it.at);
    g.start = +outputToSource(tl, a).toFixed(3); g.end = +outputToSource(tl, b).toFixed(3);
    return g;
  });
  const sc = graphicsScene({ ...edl, graphics: list }, { accent, stepTracker: false, dur });
  return { css: sc.css, html: sc.html, data: sc.data, ids: list.map((g) => g.id) };
}

// ---- cắt bỏ đoạn trên track video (giây bản ra) -----------------------------------------------------------------------
/**
 * Trừ các khoảng bản ra khỏi EDL: keep (giây nguồn, không bám chữ — người dùng chọn đúng chỗ), dòng phụ đề chỉnh tay dời
 * theo (dòng nằm trọn trong chỗ cắt thì bỏ), zoom / sfx / đồ hoạ / trích dẫn rơi vào chỗ cắt thì bỏ. Trả các khoảng nguồn
 * (để lưu state.extraCuts: sửa bằng lời / dựng lại vẫn giữ chỗ cắt).
 */
function applyCuts(edl, list, { man, redo, summary, warnings }) {
  const tl = timelineOf(edl); const dur = outputDuration(tl); const hd = hookDur(tl);
  const rs = [];
  for (const [a, b] of list.map((c) => [Math.max(0, Math.min(c.start, c.end)), Math.min(dur, Math.max(c.start, c.end))]).filter(([a, b]) => b - a >= 1 / 30).sort((x, y) => x[0] - y[0])) {
    const m = rs[rs.length - 1]; if (m && a <= m[1] + 1e-3) m[1] = Math.max(m[1], b); else rs.push([a, b]);
  }
  if (!rs.length) throw httpErr(400, 'khoảng cắt rỗng (ngắn hơn 1 khung)');
  const total = rs.reduce((s, [a, b]) => s + b - a, 0);
  if (dur - total < 1) throw httpErr(400, `cắt xong chỉ còn ${(dur - total).toFixed(2)} s (cần ≥ 1 s)`);
  if (hd > 0 && rs.some(([a]) => a < hd - 1e-3)) throw httpErr(400, `chưa cắt được trong câu móc đầu video (0–${hd.toFixed(2)} s)`);
  const src = rs.flatMap(([a, b]) => outputCutToSource(tl, a, b, []));
  // dời giây bản ra: điểm nằm trong chỗ cắt dồn về mép trái chỗ cắt
  const shift = (o) => { let s = 0; for (const [a, b] of rs) { if (o >= b) s += b - a; else if (o > a) return a - s; else break; } return o - s; };
  const prevLines = edl.captions.lines ? currentLines(edl) : null;
  const before = { zooms: edl.zooms.length, gfx: (edl.graphics || []).length };
  const cut = applyExtraCuts(edl, src);
  Object.assign(edl, cut);
  const tl2 = timelineOf(edl); const dur2 = outputDuration(tl2);
  const inK = (t) => inKeep(tl2, t);
  if (prevLines) {
    const lines = [];
    for (const l of prevLines) {
      const a = r2(shift(l.start)); const b = r2(Math.min(dur2, shift(l.end)));
      if (b - a < 0.1) continue;
      let p = a;
      const words = l.words.map((w) => { const o = r2(Math.max(p, Math.min(b - 0.02, shift(w.o)))); p = o; return { ...w, o }; });
      lines.push({ start: a, end: b, words });
    }
    edl.captions.lines = lines;
    man.lines = { sig: cutSig(edl), lines };
  }
  const gone = (edl.graphics || []).filter((g) => !inK(g.data?.at ?? g.start) || toOutputNearest(tl2, g.end) - toOutputNearest(tl2, g.start) < MIN_GRAPHIC - 1e-3);
  if (gone.length) {
    edl.graphics = edl.graphics.filter((g) => !gone.includes(g));
    man.graphicsRemoved = [...new Set([...(man.graphicsRemoved || []), ...gone.map((g) => g.id)])];
  }
  if (edl.quote && (!inK(edl.quote.start) || !inK(edl.quote.end))) edl.quote = null;
  const lostZ = before.zooms - edl.zooms.length;
  if (lostZ) warnings.push(`${lostZ} zoom nằm trong chỗ cắt, bỏ`);
  if (gone.length) warnings.push(`${gone.length} đồ hoạ nằm trong chỗ cắt, bỏ (${gone.map((g) => g.type).join(', ')})`);
  redo.base = true; redo.layer = true; redo.mix = true;
  summary.push(`cắt bỏ ${rs.length} đoạn (${rs.map(([a, b]) => `${a.toFixed(1)}–${b.toFixed(1)} s`).join(', ')}; −${total.toFixed(1)} s)`);
  return src.map((c) => ({ start: +c.start.toFixed(3), end: +c.end.toFixed(3) }));
}

// ---- áp bản vá -------------------------------------------------------------------------------------------------
/**
 * Áp bản vá lên bản sao EDL. Trả {edl, manual (để lưu vào state), music (đường dẫn nhạc cho state), redo: {base, layer, mix},
 * summary: [chuỗi ngắn], warnings}. dir: thư mục edit (nhạc tổng hợp/tải lên nằm ở đây). style: thẻ kiểu (mặc định nhạc).
 */
export function applyPatch(edlIn, state, patch, { dir, style = null, uploads = {} } = {}) {
  const edl = JSON.parse(JSON.stringify(edlIn));
  const man = JSON.parse(JSON.stringify(state.manual || {}));
  const redo = { base: false, layer: false, mix: false };
  const summary = []; const warnings = [];
  const dur = outputDuration(timelineOf(edl));
  let music = state.music || null;
  const draft = !!state.draft;
  // tỉ lệ khung: đổi → mọi thứ vẽ theo khung dựng lại; vị trí đồ hoạ đặt lại sau (manualEdit đo mặt trên khung mới)
  const ratio0 = frameOf(edl).ratio;
  const relayout = !!patch.ratio && patch.ratio !== ratio0;
  if (relayout) {
    const d = dimsOf(patch.ratio);
    edl.output = { ...edl.output, ratio: patch.ratio, width: d.width, height: d.height };
    man.ratio = patch.ratio;
    redo.base = true; redo.layer = true;
    summary.push(`khung ${ratio0} → ${patch.ratio} (${d.width}×${d.height})`);
  }

  if (patch.captions) {
    const c = patch.captions;
    if (draft && (c.lines || c.look || c.highlights !== undefined)) throw httpErr(409, 'bản nháp vẽ phụ đề thẳng vào nền: dựng lại bản chính (bỏ "nháp") rồi mới sửa phụ đề tay được');
    if (c.lines) {
      const prev = currentLines(edl);
      const lines = buildLines(c.lines, prev, dur);
      const before = prev.map(lineKey); const after = lines.map(lineKey);
      const changed = changedLines(before, after);
      if (changed || before.length !== after.length) {
        edl.captions.lines = lines; man.lines = { sig: cutSig(edl), lines };
        redo.layer = true; summary.push(`phụ đề: ${changed} dòng đổi (${before.length} → ${after.length} dòng)`);
      }
    }
    if (c.highlights !== undefined && !!edl.captions.hiOff === c.highlights) {
      edl.captions.hiOff = !c.highlights; man.hiOff = !c.highlights; redo.layer = true;
      summary.push(c.highlights ? 'bật chữ nhấn' : 'tắt chữ nhấn');
    }
    if (c.look && c.look !== edl.captions.style) {
      const from = edl.captions.style;
      edl.captions.style = c.look; man.look = c.look; redo.layer = true;
      summary.push(`kiểu phụ đề ${from} → ${c.look}`);
      const top = captionTop(c.look);
      const hit = (edl.graphics || []).filter((g) => g.box && g.box.y + g.box.h > top);
      if (hit.length) warnings.push(`kiểu phụ đề ${c.look} cao hơn: ${hit.length} đồ hoạ có thể chạm dòng chữ (${hit.map((g) => g.type).join(', ')})`);
    }
  }

  if (patch.captions?.show !== undefined && !!edl.captions.off === patch.captions.show) {
    if (draft) throw httpErr(409, 'bản nháp vẽ phụ đề thẳng vào nền: dựng lại bản chính rồi mới bật/tắt phụ đề');
    edl.captions.off = !patch.captions.show; man.capsOff = edl.captions.off; redo.layer = true;
    summary.push(patch.captions.show ? 'bật phụ đề' : 'tắt phụ đề');
  }
  if (patch.graphics?.set?.length) applyGraphicsSet(edl, patch.graphics.set, { dur, dir, style, man, redo, summary, warnings, noLayout: relayout });
  if (patch.graphics?.remove?.length) {
    const ids = new Set(patch.graphics.remove);
    const known = new Set((edl.graphics || []).map((g) => g.id));
    const miss = [...ids].filter((x) => !known.has(x));
    if (miss.length) throw httpErr(400, `không có đồ hoạ ${miss.join(', ')}`);
    const gone = edl.graphics.filter((g) => ids.has(g.id));
    edl.graphics = edl.graphics.filter((g) => !ids.has(g.id));
    man.graphicsRemoved = [...new Set([...(man.graphicsRemoved || []), ...ids])];
    if (man.graphicsSet) for (const id of ids) delete man.graphicsSet[id];
    redo.layer = true; redo.base = true; // kính mờ dưới thẻ đồ hoạ vẽ trong nền
    summary.push(`xoá ${gone.length} đồ hoạ (${gone.map((g) => g.type).join(', ')})`);
  }

  if (patch.zooms && (patch.zooms.remove?.length || patch.zooms.add?.length || patch.zooms.set?.length)) applyZooms(edl, patch.zooms, { dur, man, redo, summary });
  if (patch.graphics?.set?.length || patch.zooms?.add?.length || patch.zooms?.set?.length) {
    // kiểm ngay (4xx đồng bộ) những luật thời gian/vị trí mà render sẽ kiểm lại: zoom trong đoạn giữ, đồ hoạ ≥ 1,5 s, không đè mặt/đè nhau
    const v = validateEdl(edl, { checkFiles: false });
    // đổi tỉ lệ: vị trí đồ hoạ cũ (khung cũ) sẽ đặt lại → chỉ kiểm luật thời gian, bỏ lỗi vị trí
    const posErr = (e) => relayout && e.code === 'graphic' && /tràn vùng an toàn|đè mặt|đè |chưa có vị trí/.test(e.msg);
    const errs = v.ok ? [] : v.errors.filter((e) => (/^(zoom|graphic)/.test(e.code) || /^(zooms|graphics)/.test(e.path)) && !posErr(e));
    if (errs.length) throw httpErr(400, 'zoom/đồ hoạ sau chỉnh không hợp lệ: ' + errs.slice(0, 3).map((e) => e.msg).join('; '));
  }

  if (patch.music) {
    const p = patch.music;
    const defaults = { gainDb: style?.music?.gainDb ?? -22, duckDb: style?.music?.duckDb || 10, fadeOut: style?.music?.fadeOut ?? 1.5 };
    const prev = edl.music;
    let file = prev?.file || null;
    if (p.source === 'none') { file = null; man.musicName = null; }
    else if (p.source?.startsWith('synth:')) {
      const name = p.source.slice(6);
      if (!MUSIC_STYLES.includes(name)) throw httpErr(400, `không có nhạc tổng hợp "${name}" (có: ${MUSIC_STYLES.join(', ')})`);
      file = path.join(dir, `music-${name}.wav`);
      if (!fs.existsSync(file)) writeMusic(name, file, 60, 1);
      man.musicName = p.source;
    } else if (p.source?.startsWith('upload:')) {
      const f = p.source.slice(7);
      if (!UPLOAD_RE.test(f) || !fs.existsSync(path.join(dir, f))) throw httpErr(400, `chưa tải lên file nhạc ${f}`);
      file = path.join(dir, f); man.musicName = uploads[f] || f;
    }
    if (p.source === 'keep' && !file) throw httpErr(400, 'bản này chưa có nhạc để giữ: chọn nhạc tổng hợp hoặc tải file');
    const duckOn = p.duck ?? (prev ? prev.duckDb > 0 : man.music?.duck !== false);
    const duckDb = man.music?.duckDb || (prev?.duckDb > 0 ? prev.duckDb : defaults.duckDb);
    const next = file ? {
      file, gainDb: p.gainDb ?? prev?.gainDb ?? defaults.gainDb, duckDb: duckOn ? duckDb : 0,
      fadeOut: p.fadeOut ?? prev?.fadeOut ?? defaults.fadeOut, start: p.start ?? (p.source && p.source !== 'keep' ? 0 : prev?.start || 0),
    } : null;
    man.music = { gainDb: next?.gainDb ?? p.gainDb ?? prev?.gainDb, duck: duckOn, duckDb, fadeOut: next?.fadeOut, start: next?.start };
    const same = JSON.stringify(prev ? { ...prev, start: prev.start || 0 } : null) === JSON.stringify(next);
    if (!same) {
      const bits = [];
      if ((prev?.file || null) !== (next?.file || null)) bits.push(next ? `đổi nhạc → ${String(man.musicName || path.basename(next.file)).replace(/^synth:/, 'nhạc tổng hợp ')}` : 'bỏ nhạc');
      if (prev && next) {
        if (prev.gainDb !== next.gainDb) bits.push(`nhạc ${prev.gainDb} → ${next.gainDb} dB`);
        if ((prev.duckDb > 0) !== (next.duckDb > 0)) bits.push(next.duckDb > 0 ? 'bật ducking' : 'tắt ducking');
        if (prev.fadeOut !== next.fadeOut) bits.push(`fade out ${next.fadeOut} s`);
        if ((prev.start || 0) !== next.start) bits.push(`nhạc từ giây ${next.start}`);
      }
      edl.music = next; music = next?.file || null; redo.mix = true;
      summary.push(bits.join(', ') || 'chỉnh nhạc');
    }
  }

  if (patch.voice && (edl.audio.voiceGainDb || 0) !== patch.voice.gainDb) {
    summary.push(`giọng ${(edl.audio.voiceGainDb || 0)} → ${patch.voice.gainDb} dB`);
    edl.audio.voiceGainDb = patch.voice.gainDb; man.voiceGainDb = patch.voice.gainDb; redo.mix = true;
  }
  if (patch.sfx && !!edl.audio.sfxOff === patch.sfx.on) {
    edl.audio.sfxOff = !patch.sfx.on; man.sfxOff = !patch.sfx.on; redo.mix = true;
    summary.push(patch.sfx.on ? 'bật tiếng động' : 'tắt tiếng động');
  }
  let extraCuts = null;
  if (patch.cuts?.remove?.length) extraCuts = applyCuts(edl, patch.cuts.remove, { man, redo, summary, warnings });
  if (!summary.length) throw httpErr(400, 'không có gì khác bản hiện tại');
  return { edl, manual: man, music, redo, summary, warnings, extraCuts, relayout };
}

/**
 * Dựng lại EDL từ state (sửa bằng lời, sửa lẹm chữ): giữ các chỉnh tay đã làm. Dòng phụ đề chỉnh tay chỉ giữ khi
 * phần cắt không đổi (mốc là giây bản ra); đổi thì bỏ, trả cảnh báo.
 */
export function applyManual(edl, man) {
  const warnings = [];
  if (!man) return warnings;
  if (man.look && LOOKS[man.look]) edl.captions.style = man.look;
  if (man.capsOff !== undefined) edl.captions.off = !!man.capsOff;
  if (man.hiOff) edl.captions.hiOff = true;
  if (man.lines) {
    if (man.lines.sig === cutSig(edl)) edl.captions.lines = man.lines.lines;
    else warnings.push('phần cắt đã đổi nên phụ đề chỉnh tay được thay bằng phụ đề tự động (mốc cũ không còn đúng)');
  }
  if (man.graphicsRemoved?.length) edl.graphics = (edl.graphics || []).filter((g) => !man.graphicsRemoved.includes(g.id));
  // đồ hoạ dời giờ / sửa chữ trong Studio (giây nguồn; vị trí né mặt đặt lại sau đó ở buildEdl)
  for (const [id, r] of Object.entries(man.graphicsSet || {})) {
    const g = (edl.graphics || []).find((x) => x.id === id);
    if (!g) continue;
    if (r.data && r.data.at !== undefined) g.data = JSON.parse(JSON.stringify(r.data));
    if (Number.isFinite(r.start) && Number.isFinite(r.end) && r.end > r.start) { g.start = r.start; g.end = r.end; }
  }
  // zoom: thêm → sửa (theo thứ tự đã làm) → xoá
  const tlz = timelineOf(edl);
  for (const a of man.zoomsAdded || []) if (inKeep(tlz, a.at) && !edl.zooms.some((zm) => Math.abs(zm.at - a.at) < 0.02)) edl.zooms.push({ ...a });
  for (const s of man.zoomsSet || []) { const zm = edl.zooms.find((x) => Math.abs(x.at - s.from) < 0.02); if (zm && inKeep(tlz, s.z.at)) { Object.assign(zm, s.z); delete zm.word; } }
  if (man.zoomsRemovedAt?.length) edl.zooms = edl.zooms.filter((zm) => !man.zoomsRemovedAt.some((a) => Math.abs(a - zm.at) < 0.02));
  edl.zooms.sort((x, y) => x.at - y.at);
  if (edl.music && man.music) {
    if (man.music.gainDb != null) edl.music.gainDb = man.music.gainDb;
    if (man.music.duck === false) edl.music.duckDb = 0;
    if (man.music.fadeOut != null) edl.music.fadeOut = man.music.fadeOut;
    if (man.music.start != null) edl.music.start = man.music.start;
  }
  if (man.voiceGainDb) edl.audio.voiceGainDb = man.voiceGainDb;
  if (man.sfxOff) edl.audio.sfxOff = true;
  return warnings;
}

export { OUT };