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.

18.2 KB
Raw Blame
// EDL của LumReels Edit (bản 1): một file JSON mô tả trọn bản dựng từ 1 video nguồn.
// - Mọi mốc thời gian là GIÂY CỦA NGUỒN (timestamp thật, trừ start_time), không phải giây của bản ra.
//   Video điện thoại (VFR, xoay, HEVC, HDR) được chuẩn hoá trước thành proxy CFR 30 fps cùng trục thời gian
//   (proxy t = nguồn PTS − start_time), nên mốc trong EDL đọc thẳng được trên proxy.
// - Bản ra: hình snap theo khung 30 fps, tiếng snap theo mẫu 48 kHz; âm gốc đi qua mọi vết cắt, nối crossfade 20 ms.
// Nguồn sự thật của schema là zod ở đây; `node edit/edl.mjs --schema` ghi ra edl.schema.json.
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { AsyncLocalStorage } from 'node:async_hooks';
import { z } from 'zod';
import { graphicsErrors } from './graphics.mjs';
import { RATIO_IDS, DEFAULT_RATIO, normRatio, dimsOf, safeArea, isLandscape } from '../engine/ratio.mjs';

export const EDL_VERSION = 1;
export const REMOVE_REASONS = ['pause', 'filler', 'retake', 'false-start', 'aside', 'edge', 'by-hand', 'trim'];

// ---- khung bản ra (tỉ lệ) -----------------------------------------------------------------------------------------
// Mỗi bản edit có 1 tỉ lệ (edl.output.ratio: 9:16 · 16:9 · 4:3 · 3:4). Mọi chỗ đọc OUT.width/height/SAFE (phụ đề,
// đồ hoạ, kiểm) đọc khung của lượt chạy hiện tại: withFrame(edl | tỉ lệ, fn) đặt khung cho fn và mọi await bên trong
// (AsyncLocalStorage — 2 edit khác tỉ lệ chạy xen nhau không lẫn). Ngoài withFrame: 9:16 như trước.
const FRAME = new AsyncLocalStorage();
const frames = Object.fromEntries(RATIO_IDS.map((r) => [r, Object.freeze({ ratio: r, ...dimsOf(r), safe: Object.freeze(safeArea(r)), landscape: isLandscape(r) })]));
/** Khung đang dùng: {ratio, width, height, safe, landscape}. */
export const frameNow = () => FRAME.getStore() || frames[DEFAULT_RATIO];
/** edl | {output} | '16:9' | null → khung. */
export function frameOf(x) {
  const r = typeof x === 'string' ? x : x?.output?.ratio || x?.ratio || (x?.output ? ratioFromDims(x.output) : null);
  return frames[normRatio(r || DEFAULT_RATIO)];
}
const ratioFromDims = (o) => RATIO_IDS.find((r) => frames[r].width === o.width && frames[r].height === o.height) || DEFAULT_RATIO;
/** Chạy fn trong khung của edl/tỉ lệ (fn đồng bộ hay async đều được; trả đúng giá trị của fn). */
export const withFrame = (x, fn) => FRAME.run(frameOf(x), fn);
export const OUT = {
  get ratio() { return frameNow().ratio; },
  get width() { return frameNow().width; },
  get height() { return frameNow().height; },
  fps: 30, audioRate: 48000, lufs: -14,
};
/** Vùng an toàn (phần của khung): 9:16 né nút Reels/Shorts/TikTok (120..960 px, 10..80%); khung khác lề đều (engine/ratio.mjs). */
export const SAFE = {
  get x0() { return frameNow().safe.x0; }, get x1() { return frameNow().safe.x1; },
  get y0() { return frameNow().safe.y0; }, get y1() { return frameNow().safe.y1; },
};
/**
 * Tâm dòng phụ đề (phần chiều cao) của 1 kiểu (LOOKS.cy, viết cho 9:16) trên khung đang dùng: phụ đề dưới (cy ≥ 0,62)
 * xuống sát đáy vùng an toàn (khung ngang/3:4 không có nút đè ở đáy), phụ đề giữa khung giữ gần giữa.
 */
export function frameCy(cy, f = frameNow()) {
  if (f.ratio === '9:16' || !Number.isFinite(cy)) return cy;
  if (cy >= 0.62) return +Math.min(f.safe.y1 - 0.06, (f.landscape ? 0.80 : 0.78) + (cy - 0.70) * 0.5).toFixed(3);
  return +(0.5 + (cy - 0.5) * (f.landscape ? 0.8 : 0.9)).toFixed(3);
}
/** Đáy tối đa của khối phụ đề (phần chiều cao): 9:16 = đáy vùng an toàn (nút của app đè bên dưới); khung khác 97%. */
export const captionFloor = (f = frameNow()) => (f.ratio === '9:16' ? f.safe.y1 : 0.97);

const sec = z.number().finite().min(0);
const span = z.object({ start: sec, end: sec }).strict();

// lớp đồ hoạ thông tin (edit/graphics.mjs). Mốc là giây nguồn; data.at và at của từng dòng/cột/điểm cũng là giây nguồn.
const item = z.object({ at: sec }).passthrough();
export const GraphicSchema = z.object({
  id: z.string(),
  type: z.enum(['counter', 'bar_chart', 'compare', 'spec_table', 'checklist', 'price_tag', 'sticker', 'line_chart', 'title_card']),
  start: sec, end: sec,
  estimate: z.boolean().describe('có số suy ra, không nói thẳng → đồ hoạ ghi "ước tính"'),
  data: z.object({ at: sec, items: z.array(item).optional(), points: z.array(item).optional(), rows: z.array(item).optional() }).passthrough(),
  box: z.object({ x: z.number(), y: z.number(), w: z.number().positive(), h: z.number().positive(), scale: z.number().min(0.3).max(1) }).strict().nullable()
    .describe('vị trí trên khung bản ra (px), đã né mặt'),
  face: z.array(z.number()).length(4).nullable().describe('hợp khung mặt bản ra lúc đồ hoạ hiện (+lề, đã tính push), để kiểm không đè'),
  squeeze: z.object({ scale: z.number().min(0.5).max(1), anchorY: z.number().min(0).max(1920) }).strict().nullable().default(null)
    .describe('thu cả khung hình quanh (giữa, anchorY) trong lúc đồ hoạ hiện — cận mặt, không đủ chỗ phía trên'),
}).strict();

export const EdlSchema = z.object({
  version: z.literal(EDL_VERSION),
  id: z.string().min(1),
  createdAt: z.string(),
  style: z.string().min(1).describe('id thẻ kiểu edit (edit-styles/<id>.md)'),
  source: z.object({
    file: z.string(), sha256: z.string().regex(/^[0-9a-f]{64}$/), size: z.number().int().nonnegative(),
    duration: sec, startTime: z.number().describe('start_time của nguồn, đã trừ khi làm proxy'),
    fps: z.number().positive().describe('avg_frame_rate'), vfr: z.boolean(),
    rotation: z.number().describe('độ xoay trong metadata, đã áp vào proxy'),
    width: z.number().int().positive().describe('chiều ngang khi hiển thị (sau xoay)'), height: z.number().int().positive(),
    codec: z.string(), hdr: z.boolean(), hasAudio: z.boolean(),
  }).strict(),
  proxy: z.object({
    file: z.string(), width: z.number().int().positive(), height: z.number().int().positive(),
    fps: z.literal(30), audioRate: z.literal(48000),
  }).strict(),
  output: z.object({
    ratio: z.enum(RATIO_IDS).default(DEFAULT_RATIO).describe('tỉ lệ khung bản ra: 9:16 = 1080×1920, 16:9 = 1920×1080, 4:3 = 1440×1080, 3:4 = 1080×1440'),
    width: z.number().int().positive(), height: z.number().int().positive(), fps: z.literal(OUT.fps),
    audioRate: z.literal(OUT.audioRate), lufs: z.number().min(-30).max(-8),
  }).strict(),
  keep: z.array(span).min(1).describe('đoạn nguồn được giữ, theo thứ tự, không chồng nhau'),
  removed: z.array(span.extend({ reason: z.enum(REMOVE_REASONS), words: z.string().default('') }).strict())
    .describe('đoạn bị bỏ, để người xem lại và đặt lại'),
  reframe: z.object({ mode: z.enum(['face', 'center', 'fill', 'none']) }).strict(),
  zooms: z.array(z.object({
    at: sec.describe('giây nguồn lúc zoom chạm'), dur: z.number().min(0.2).max(8),
    scale: z.number().min(1).max(1.6), kind: z.enum(['punch', 'push']),
    word: z.number().int().nonnegative().optional(),
  }).strict()),
  captions: z.object({
    style: z.string(), renderer: z.enum(['hyperframes', 'pil']),
    maxWords: z.number().int().min(1).max(8), position: z.enum(['lower', 'middle']),
    words: z.array(z.object({ i: z.number().int().nonnegative(), w: z.string().min(1), start: sec, end: sec }).strict()),
    highlights: z.array(z.number().int().nonnegative()).describe('chỉ số i của chữ nhấn'),
    hiOff: z.boolean().default(false).describe('tắt mọi chữ nhấn (chỉnh tay)'),
    off: z.boolean().default(false).describe('không vẽ phụ đề (reel nhập vào: chữ đã nằm trong cảnh); vẫn giữ chữ để bật lại'),
    lines: z.array(z.object({
      start: sec, end: sec,
      words: z.array(z.object({ w: z.string().min(1).max(80), o: sec, hi: z.boolean() }).strict()).min(1).max(40),
    }).strict()).max(600).optional()
      .describe('dòng phụ đề chỉnh tay, GIÂY BẢN RA (thay cho nhóm chữ tự động; o: giây bản ra của từng chữ cho karaoke)'),
  }).strict(),
  sfx: z.array(z.object({ at: sec, name: z.string(), gainDb: z.number().min(-30).max(6) }).strict()),
  music: z.object({
    file: z.string(), gainDb: z.number().min(-40).max(0), duckDb: z.number().min(0).max(30).describe('0: không hạ nhạc khi nói'), fadeOut: z.number().min(0).max(10),
    start: z.number().min(0).max(600).default(0).describe('giây của bài nhạc phát ở đầu bản ra'),
  }).strict().nullable(),
  graphics: z.array(GraphicSchema).default([]).describe('đồ hoạ bảng biểu (kiểu thong-tin-do-hoa)'),
  hook: z.object({
    start: sec, end: sec,
    repeat: z.boolean().describe('true: câu móc vẫn phát lại ở chỗ cũ; false: đã trừ khỏi keep'),
    flash: z.boolean().describe('chớp trắng 2 khung ở chỗ nối móc → clip'),
    sfx: z.object({ name: z.string(), at: sec.describe('giây nguồn (trong khoảng móc)'), gainDb: z.number().min(-30).max(6) }).strict().nullable(),
  }).strict().nullable().default(null)
    .describe('câu móc kéo lên đầu: bản ra = [hook] + keep[]; mọi mốc bản ra của keep dời thêm (end − start)'),
  hookText: z.object({ text: z.string().min(1).max(40), until: z.number().min(0.5).max(5) }).strict().nullable().default(null)
    .describe('chữ móc to ở 0 → until giây bản ra (chữ nhấn trong *…*)'),
  quote: z.object({
    start: sec, end: sec, dimTo: z.number().min(0.1).max(1), blurPx: z.number().min(0).max(30), dimIn: z.number().min(0.1).max(3),
  }).strict().nullable().default(null).describe('câu trích dẫn to giữa khung (giây nguồn); video tối + mờ trong lúc đó'),
  audio: z.object({
    crossfadeMs: z.number().min(5).max(80), keepSourceAudio: z.literal(true),
    voiceGainDb: z.number().min(-12).max(12).default(0).describe('nâng/hạ giọng gốc so với nhạc (cả bản vẫn chuẩn về −14 LUFS)'),
    sfxOff: z.boolean().default(false).describe('tắt mọi tiếng động (giữ danh sách sfx)'),
  }).strict(),
  notes: z.string().optional(),
}).strict();

// ---- ánh xạ thời gian nguồn → bản ra -------------------------------------------------------------------
// Các hàm dưới nhận `keep` (mảng đoạn giữ). Có câu móc (edl.hook) thì truyền timelineOf(edl): cùng mảng keep, kèm
// thuộc tính .hook — bản ra = [hook] + keep, mọi mốc của keep dời thêm hookDur. Mốc nằm cả trong keep lẫn trong
// hook (repeat) thì lấy chỗ trong keep; mốc chỉ có trong hook (repeat: false) thì về 0 … hookDur.
export const hookDur = (keep) => (keep?.hook ? keep.hook.end - keep.hook.start : 0);
/** Mảng keep của EDL (bản sao) mang theo .hook để các hàm ánh xạ biết câu móc ở đầu bản ra. */
export function timelineOf(edl) {
  const k = edl.keep.map((x) => ({ start: x.start, end: x.end }));
  if (edl.hook) Object.defineProperty(k, 'hook', { value: { ...edl.hook }, enumerable: false });
  return k;
}
const inHook = (keep, t) => !!keep?.hook && t >= keep.hook.start - 1e-9 && t <= keep.hook.end + 1e-9;
export function outputDuration(keep) { return hookDur(keep) + keep.reduce((s, k) => s + (k.end - k.start), 0); }
/** Giây nguồn → giây bản ra; null nếu rơi vào đoạn bỏ. */
export function toOutput(keep, t) {
  let acc = hookDur(keep);
  for (const k of keep) {
    if (t < k.start - 1e-9) break;
    if (t <= k.end + 1e-9) return acc + (t - k.start);
    acc += k.end - k.start;
  }
  return inHook(keep, t) ? t - keep.hook.start : null;
}
/** Như toOutput nhưng mốc rơi vào đoạn bỏ thì dời về mép giữ gần nhất. */
export function toOutputNearest(keep, t) {
  const got = toOutput(keep, t);
  if (got !== null) return got;
  let best = 0; let bd = Infinity; let acc = hookDur(keep);
  for (const k of keep) {
    for (const [src, o] of [[k.start, acc], [k.end, acc + k.end - k.start]]) {
      if (Math.abs(src - t) < bd) { bd = Math.abs(src - t); best = o; }
    }
    acc += k.end - k.start;
  }
  return best;
}
export const inKeep = (keep, t) => keep.some((k) => t >= k.start - 1e-6 && t <= k.end + 1e-6) || inHook(keep, t);

/**
 * Kiểm EDL: schema + luật thời gian. Trả {ok, errors:[{code, path, msg}], edl}.
 * opts.sfxNames: tên sfx hợp lệ; opts.checkFiles: kiểm file nguồn/nhạc có thật.
 */
export function validateEdl(input, opts = {}) {
  let f;
  try { f = frameOf(input); } catch { f = null; } // tỉ lệ lạ: schema báo lỗi
  return f ? FRAME.run(f, () => validateIn(input, opts)) : validateIn(input, opts);
}
function validateIn(input, { sfxNames, checkFiles = true } = {}) {
  const errors = [];
  const add = (code, p, msg) => errors.push({ code, path: p, msg });
  const parsed = EdlSchema.safeParse(input);
  if (!parsed.success) {
    for (const i of parsed.error.issues) add('schema', i.path.join('.'), i.message);
    return { ok: false, errors };
  }
  const e = parsed.data;
  const want = dimsOf(e.output.ratio);
  if (e.output.width !== want.width || e.output.height !== want.height) add('output', 'output', `khung ${e.output.width}×${e.output.height} không khớp tỉ lệ ${e.output.ratio} (${want.width}×${want.height})`);
  const dur = e.source.duration;
  const tl = timelineOf(e);
  const frame = 1 / e.output.fps;
  e.keep.forEach((k, i) => {
    if (k.end - k.start < frame) add('keep-short', `keep.${i}`, `đoạn giữ ${k.start}–${k.end} ngắn hơn 1 khung`);
    if (k.end > dur + 0.05) add('keep-out', `keep.${i}`, `đoạn giữ vượt quá độ dài nguồn (${dur.toFixed(2)} s)`);
    if (i && k.start < e.keep[i - 1].end - 1e-6) add('keep-overlap', `keep.${i}`, `đoạn giữ chồng/ngược thứ tự với đoạn trước`);
  });
  if (e.hook) {
    const h = e.hook; const hd = h.end - h.start;
    if (hd < 0.3 || hd > 6) add('hook-len', 'hook', `câu móc dài ${hd.toFixed(2)} s (cần 0,3–6 s)`);
    if (h.end > dur + 0.05) add('hook-out', 'hook', 'câu móc vượt quá độ dài nguồn');
    if (h.sfx && (h.sfx.at < h.start - 1e-6 || h.sfx.at > h.end + 1e-6)) add('hook-sfx', 'hook.sfx', 'tiếng của câu móc nằm ngoài câu móc');
    if (h.sfx && sfxNames && !sfxNames.includes(h.sfx.name)) add('sfx-name', 'hook.sfx', `không có tiếng "${h.sfx.name}"`);
    if (!h.repeat && e.keep.some((k) => k.start < h.end - 1e-3 && k.end > h.start + 1e-3)) add('hook-overlap', 'hook', 'câu móc không lặp lại (repeat: false) mà vẫn nằm trong keep');
  }
  if (e.quote) {
    if (e.quote.end <= e.quote.start) add('quote', 'quote', 'câu trích dẫn kết thúc trước khi bắt đầu');
    else if (!inKeep(tl, e.quote.start) || !inKeep(tl, e.quote.end)) add('quote-cut', 'quote', 'câu trích dẫn rơi vào đoạn bị bỏ');
  }
  const outDur = outputDuration(tl);
  if (outDur < 1) add('too-short', 'keep', `bản ra chỉ ${outDur.toFixed(2)} s`);
  e.zooms.forEach((zm, i) => {
    if (!inKeep(tl, zm.at)) add('zoom-cut', `zooms.${i}`, `zoom ở ${zm.at} s rơi vào đoạn bị bỏ`);
    if (i && zm.at < e.zooms[i - 1].at) add('zoom-order', `zooms.${i}`, 'zoom phải theo thứ tự thời gian');
  });
  const ids = new Set();
  e.captions.words.forEach((w, i) => {
    if (w.end < w.start) add('word-time', `captions.words.${i}`, `chữ "${w.w}" kết thúc trước khi bắt đầu`);
    if (!inKeep(tl, (w.start + w.end) / 2)) add('word-cut', `captions.words.${i}`, `chữ "${w.w}" ở ${w.start} s nằm trong đoạn bị bỏ`);
    if (i && w.start < e.captions.words[i - 1].start - 1e-6) add('word-order', `captions.words.${i}`, 'chữ phải theo thứ tự thời gian');
    ids.add(w.i);
  });
  (e.captions.lines || []).forEach((l, i) => {
    if (l.end - l.start < 0.05) add('line-time', `captions.lines.${i}`, 'dòng phụ đề kết thúc trước khi bắt đầu');
    if (l.start > outDur + 0.05) add('line-out', `captions.lines.${i}`, `dòng phụ đề ở ${l.start} s, sau cuối bản ra (${outDur.toFixed(2)} s)`);
    if (i && l.start < e.captions.lines[i - 1].end - 1e-6) add('line-overlap', `captions.lines.${i}`, 'dòng phụ đề đè dòng trước');
  });
  e.captions.highlights.forEach((h, i) => { if (!ids.has(h)) add('highlight', `captions.highlights.${i}`, `chữ nhấn ${h} không có trong phụ đề`); });
  e.sfx.forEach((s, i) => {
    if (sfxNames && !sfxNames.includes(s.name)) add('sfx-name', `sfx.${i}`, `không có tiếng "${s.name}"`);
    if (!inKeep(tl, s.at)) add('sfx-cut', `sfx.${i}`, `tiếng "${s.name}" ở ${s.at} s rơi vào đoạn bị bỏ`);
  });
  for (const g of graphicsErrors(e)) errors.push(g);
  if (checkFiles) {
    if (!fs.existsSync(e.proxy.file)) add('file', 'proxy.file', `không thấy proxy ${e.proxy.file}`);
    if (e.music && !fs.existsSync(e.music.file)) add('file', 'music.file', `không thấy file nhạc ${e.music.file}`);
  }
  return { ok: errors.length === 0, errors, edl: e };
}

export function writeJsonSchema(file = path.join(path.dirname(fileURLToPath(import.meta.url)), 'edl.schema.json')) {
  const schema = z.toJSONSchema(EdlSchema, { target: 'draft-2020-12', io: 'input' });
  schema.$id = 'https://reels.lumtek.net/schema/edl-v1.json';
  schema.title = 'LumReels Edit EDL v1';
  schema.description = 'Bản dựng từ 1 video nguồn. Mọi mốc thời gian là giây của nguồn (đã trừ start_time).';
  fs.writeFileSync(file, JSON.stringify(schema, null, 2) + '\n');
  return file;
}

if (path.resolve(process.argv[1] || '') === fileURLToPath(import.meta.url)) {
  const a = process.argv.slice(2);
  if (a[0] === '--schema') console.log(writeJsonSchema());
  else if (a[0]) {
    const r = validateEdl(JSON.parse(fs.readFileSync(a[0], 'utf8')));
    console.log(r.ok ? 'EDL hợp lệ' : r.errors.map((x) => `${x.code} ${x.path}: ${x.msg}`).join('\n'));
    process.exit(r.ok ? 0 : 1);
  } else console.log('node edit/edl.mjs --schema | <edl.json>');
}