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.
// Trạng thái chỉnh của 1 bản edit trong Studio: bản gốc (từ GET /manual) + bản đang sửa + Undo/Redo.
// Mọi thay đổi giữ ở máy (localStorage theo id + tên bản ra mới nhất) tới khi "Xuất bản mới" gửi 1 bản vá
// (POST /api/edits/:id/manual, schema edit/manual.mjs).
import { store, r2, tokens, untokens, plain } from './util.js';
const KEY = (id) => `lumreels.studio.v1.${id}`;
const MAX_HIST = 200;
let uid = 0;
const nid = (p) => `${p}${++uid}`;
/** View server → doc (đơn vị: giây bản ra). */
function toDoc(v) {
return {
lines: v.captions.lines.map((l) => ({ u: nid('l'), start: l.start, end: l.end, text: l.text, ...(Array.isArray(l.wo) ? { wo: l.wo, wt: l.text, w0: l.start, w1: l.end } : {}) })),
look: v.captions.look, hi: !!v.captions.highlights, show: v.captions.show !== false,
ratio: v.output?.ratio || '9:16',
cuts: [], vsplits: [],
music: { source: v.music.on ? 'keep' : 'none', gainDb: v.music.gainDb, duck: !!v.music.duck, fadeOut: v.music.fadeOut, start: v.music.start || 0 },
voice: { gainDb: v.voice.gainDb }, sfx: { on: !!v.sfx.on },
zooms: v.zooms.map((z) => ({ u: nid('z'), n: z.n, at: z.at, dur: z.dur, scale: z.scale, kind: z.kind })),
gfx: v.graphics.map((g) => ({ u: 'g:' + g.id, id: g.id, type: g.type, at: g.at, until: g.until, data: JSON.parse(JSON.stringify(g.data || {})), box: g.box, estimate: !!g.estimate })),
};
}
const snap = (d) => JSON.stringify(d);
const eqT = (a, b) => Math.abs(a - b) < 0.005;
export class Store {
constructor() { this.view = null; this.orig = null; this.doc = null; this.undo = []; this.redo = []; this.subs = new Set(); this.id = null; this.outKey = null; this.pending = null; }
on(f) { this.subs.add(f); return () => this.subs.delete(f); }
emit(what) { for (const f of this.subs) f(what); }
/** Nạp view; khôi phục bản nháp cục bộ nếu cùng bản ra mới nhất. */
load(id, view) {
this.id = id; this.view = view;
this.outKey = `${view.latest}|${view.versions?.[view.latest]?.out || ''}`;
this.orig = toDoc(view);
this.doc = JSON.parse(snap(this.orig));
this.undo = []; this.redo = [];
if (!view.readOnly) {
const saved = store.get(KEY(id));
if (saved && saved.outKey === this.outKey && saved.doc) {
try {
// giữ uid gốc của dòng/zoom bản gốc (để so) — doc lưu đủ trường
this.orig = saved.orig || this.orig; this.doc = saved.doc; this.undo = saved.undo || []; this.redo = saved.redo || [];
for (const l of this.doc.lines) l.u = l.u || nid('l');
} catch { /* hỏng: dùng bản server */ }
} else if (saved) store.del(KEY(id));
}
this.emit('load');
}
persist() {
if (!this.id || this.view?.readOnly) return;
if (!this.undo.length && !this.redo.length) { store.del(KEY(this.id)); return; }
store.set(KEY(this.id), { outKey: this.outKey, orig: this.orig, doc: this.doc, undo: this.undo.slice(-60), redo: this.redo.slice(-60) });
}
clearDraft() { if (this.id) store.del(KEY(this.id)); }
/** Thay đổi 1 bước (undo được). fn(doc) sửa tại chỗ. */
commit(fn, what = 'doc') {
if (this.view?.readOnly) return false;
this.typing = null;
const before = snap(this.doc);
fn(this.doc);
if (snap(this.doc) === before) return false;
this.undo.push(before); if (this.undo.length > MAX_HIST) this.undo.shift();
this.redo = [];
this.persist(); this.emit(what);
return true;
}
/** Gõ / kéo thanh trượt liên tục cùng 1 ô: gộp thành 1 bước Undo nếu cách nhau < 1,5 s. */
commitTyping(key, fn) {
const now = Date.now();
if (this.typing?.key === key && now - this.typing.at < 1500 && this.undo.length) {
const before = snap(this.doc); fn(this.doc);
this.typing.at = now;
if (snap(this.doc) !== before) { this.redo = []; this.persist(); this.emit('doc'); }
return true;
}
const ok = this.commit(fn);
this.typing = ok ? { key, at: now } : null;
return ok;
}
/** Kéo trên timeline: chụp trước khi kéo, tới lúc thả mới thành 1 bước. */
begin() { this.pending = snap(this.doc); }
end() {
if (this.pending == null) return false;
const before = this.pending; this.pending = null;
if (snap(this.doc) === before) return false;
this.undo.push(before); this.redo = []; this.persist(); this.emit('doc');
return true;
}
cancel() { if (this.pending != null) { this.doc = JSON.parse(this.pending); this.pending = null; this.emit('doc'); } }
doUndo() { this.typing = null; if (!this.undo.length) return false; this.redo.push(snap(this.doc)); this.doc = JSON.parse(this.undo.pop()); this.persist(); this.emit('doc'); return true; }
doRedo() { this.typing = null; if (!this.redo.length) return false; this.undo.push(snap(this.doc)); this.doc = JSON.parse(this.redo.pop()); this.persist(); this.emit('doc'); return true; }
reset() { if (this.view?.readOnly) return; this.undo.push(snap(this.doc)); this.doc = JSON.parse(snap(this.orig)); this.redo = []; this.persist(); this.emit('doc'); }
get changes() { return Object.keys(this.patch()).length ? this.undo.length || 1 : 0; }
// ---- phụ đề ----
/** Chỗ cắt (giây bản ra hiện tại) chứa tt, hoặc null. */
cutAt(tt) { return (this.doc?.cuts || []).find(([a, b]) => tt >= a - 1e-3 && tt < b) || null; }
/** Cắt bỏ [a, b] trên track video (gộp với chỗ cắt chồng/kề). */
addCut(a, b) {
const dur = this.view?.duration || 0; a = Math.max(0, Math.min(a, b)); b = Math.min(dur, Math.max(a, b));
if (b - a < 1 / 30) return false;
return this.commit((d) => {
const all = [...(d.cuts || []), [r2(a), r2(b)]].sort((x, y) => x[0] - y[0]); const out = [];
for (const c of all) { const m = out[out.length - 1]; if (m && c[0] <= m[1] + 1e-3) m[1] = Math.max(m[1], c[1]); else out.push([...c]); }
d.cuts = out;
});
}
lineAt(tt) { return this.doc.lines.findIndex((l) => tt >= l.start - 1e-3 && tt < l.end); }
/** Tách dòng k tại giây tt (chữ chia theo tỉ lệ thời gian). Trả false nếu không tách được. */
splitLine(k, tt) {
const l = this.doc.lines[k]; if (!l) return false;
const ws = tokens(l.text); if (ws.length < 2) return false;
if (tt == null || tt <= l.start + 0.1 || tt >= l.end - 0.1) tt = l.start + (l.end - l.start) / 2;
const cut = Math.min(ws.length - 1, Math.max(1, Math.round((ws.length * (tt - l.start)) / (l.end - l.start))));
const m = r2(tt);
return this.commit((d) => {
d.lines.splice(k, 1, { u: l.u, start: l.start, end: m, text: untokens(ws.slice(0, cut)) }, { u: nid('l'), start: m, end: l.end, text: untokens(ws.slice(cut)) });
});
}
mergeLine(k) {
const a = this.doc.lines[k]; const b = this.doc.lines[k + 1]; if (!a || !b) return false;
return this.commit((d) => { d.lines.splice(k, 2, { u: a.u, start: a.start, end: b.end, text: `${a.text} ${b.text}`.trim() }); });
}
// ---- bản vá (chỉ phần khác bản gốc) ----
patch() {
const o = this.orig; const c = this.doc; if (!o || !c) return {};
const p = {};
const cap = {};
const ls = (x) => JSON.stringify(x.map((l) => [Math.round(l.start * 100), Math.round(l.end * 100), l.text.trim()]));
if (ls(o.lines) !== ls(c.lines)) cap.lines = c.lines.map((l) => ({ start: r2(l.start), end: r2(l.end), text: l.text.trim() }));
if (o.hi !== c.hi) cap.highlights = c.hi;
if (o.look !== c.look) cap.look = c.look;
if ((o.show !== false) !== (c.show !== false)) cap.show = c.show !== false;
if (Object.keys(cap).length) p.captions = cap;
const mu = {}; const src0 = o.music.source; const src = c.music.source;
if (src !== src0) mu.source = src;
if (src !== 'none') for (const k of ['gainDb', 'duck', 'fadeOut', 'start']) if (c.music[k] !== o.music[k] || mu.source) mu[k] = c.music[k];
if (Object.keys(mu).length) p.music = mu;
if (c.voice.gainDb !== o.voice.gainDb) p.voice = { gainDb: c.voice.gainDb };
if (c.sfx.on !== o.sfx.on) p.sfx = { on: c.sfx.on };
// zoom: n = số thứ tự trong bản gốc; zoom mới không có n
const zr = o.zooms.filter((z) => !c.zooms.some((x) => x.n === z.n)).map((z) => z.n);
const zs = []; const za = [];
for (const z of c.zooms) {
if (z.n == null) { za.push({ at: r2(z.at), dur: r2(z.dur), scale: r2(z.scale), kind: z.kind }); continue; }
const oz = o.zooms.find((x) => x.n === z.n); if (!oz) continue;
const s = { n: z.n };
if (!eqT(oz.at, z.at)) s.at = r2(z.at);
if (!eqT(oz.dur, z.dur)) s.dur = r2(z.dur);
if (!eqT(oz.scale, z.scale)) s.scale = r2(z.scale);
if (oz.kind !== z.kind) s.kind = z.kind;
if (Object.keys(s).length > 1) zs.push(s);
}
if (zr.length || zs.length || za.length) p.zooms = { ...(zr.length ? { remove: zr } : {}), ...(zs.length ? { set: zs } : {}), ...(za.length ? { add: za } : {}) };
const gr = o.gfx.filter((g) => !c.gfx.some((x) => x.id === g.id)).map((g) => g.id);
const gs = [];
for (const g of c.gfx) {
const og = o.gfx.find((x) => x.id === g.id); if (!og) continue;
const s = { id: g.id };
if (!eqT(og.at, g.at)) s.start = r2(g.at);
if (!eqT(og.until, g.until)) s.end = r2(g.until);
const dd = dataDiff(og.data, g.data); if (dd) s.data = dd;
if (Object.keys(s).length > 1) gs.push(s);
}
if (gr.length || gs.length) p.graphics = { ...(gr.length ? { remove: gr } : {}), ...(gs.length ? { set: gs } : {}) };
if (c.cuts?.length) p.cuts = { remove: c.cuts.map(([a, b]) => ({ start: r2(a), end: r2(b) })) };
if ((c.ratio || '9:16') !== (o.ratio || '9:16')) p.ratio = c.ratio;
return p;
}
/** Lỗi chặn xuất bản (dòng rỗng/ngắn/đè). Map uid → lý do. */
lineErrors() {
const bad = new Map(); const L = this.doc?.lines || []; const dur = this.view?.duration || 0;
L.forEach((l, k) => {
if (!(l.end - l.start >= 0.1)) bad.set(l.u, 'short');
else if (l.start >= dur) bad.set(l.u, 'after');
else if (k && l.start < L[k - 1].end - 1e-6) bad.set(l.u, 'overlap');
else if (!plain(l.text).trim()) bad.set(l.u, 'empty');
});
return bad;
}
}
function dataDiff(a = {}, b = {}) {
const out = {};
for (const k of Object.keys(b)) {
if (Array.isArray(b[k])) {
const rows = [];
b[k].forEach((row, i) => { const r = { k: i }; for (const f of Object.keys(row)) if (a[k]?.[i]?.[f] !== row[f]) r[f] = row[f]; if (Object.keys(r).length > 1) rows.push(r); });
if (rows.length) out[k] = rows;
} else if (a[k] !== b[k]) out[k] = b[k];
}
return Object.keys(out).length ? out : null;
}