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.

API cho Studio: thêm/sửa zoom, dời giờ + sửa ô đồ hoạ, manual?rev, dải ảnh khung, đỉnh sóng nhạc

Lumtekdb8091a2edbd
diff --git a/edit/http.mjs b/edit/http.mjs
index 208fe52..1dcc4c5 100644
--- a/edit/http.mjs
+++ b/edit/http.mjs
@@ -1,323 +1,350 @@
-// REST cho Edit video (server/server.mjs gọi handleEditRoute). Chống DNS rebinding đã làm ở server (Host),
-// ở đây chặn thêm Origin lạ cho mọi lệnh ghi (trang web khác không gửi form upload/đường dẫn/xoá vào được).
-// GET /api/edit-options → {ready, missing, setup, styles[], music[], maxUploadBytes}
-// GET /api/edit-setup → tiến độ cài (nút "Cài ngay"): {running, step, ok, word, hint, elapsedS, log[]}
-// POST /api/edit-setup → chạy node edit/setup.mjs nền (409 nếu đang cài)
-// GET /api/edits → danh sách
-// POST /api/edits → multipart (video ≤ 2 GB, music?, style, musicStyle?, content?, names?, draft?, target?)
-// hoặc JSON {path, style, music?(đường dẫn|tên nhạc tổng hợp), content?, names?, draft?, target?}
-// GET /api/edits/:id → trạng thái, tiến độ, log, chữ LLM đã sửa, các lần sửa
-// POST /api/edits/:id/revise → {instruction}: LLM sửa EDL theo lời, render lại, không phân tích lại
-// GET /api/edits/:id/manual → những gì chỉnh tay được: dòng phụ đề (giây bản ra), nhạc, giọng, sfx, zoom, đồ hoạ
-// POST /api/edits/:id/manual → JSON bản vá (edit/manual.mjs ManualSchema, kiểm chặt): dựng lại phần cần thiết → out-r<n>.mp4
-// POST /api/edits/:id/music → multipart music (≤ 200 MB): nhạc cho chỉnh tay → {file: "music-up-<n>.<ext>", name}
-// DELETE /api/edits/:id → xoá hẳn thư mục edits/<id>
-// GET /edits/:id/(out.mp4|out-r<n>.mp4|preview.jpg|preview-final.jpg|edl.json)
-// GET /edit-styles/thumbs/<id>.webp → ảnh minh hoạ dọc của thẻ kiểu (lưới chọn kiểu)
-import fs from 'node:fs';
-import path from 'node:path';
-import { MUSIC_LIST, MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';
-import {
- ID_RE, EDITS, editDir, newEditId, createEdit, runEditJob, reviseEditJob, editView, listEdits, editStyles, editReady, readEditJob,
- markStaleEdits, deleteEdit, STYLE_THUMBS, manualState, manualEditJob, addMusicUpload, checkMusic, currentOut,
-} from './jobs.mjs';
-import { installStatus, startInstall } from './setup-run.mjs';
-
-export const MAX_UPLOAD = 2 * 1024 ** 3; // 2 GB
-const MAX_BODY = MAX_UPLOAD + 200 * 1024 ** 2; // + nhạc + trường chữ
-const MAX_MUSIC = 200 * 1024 ** 2; // nhạc tải lên cho chỉnh tay
-const DISK_FACTOR = 5; // cần trống ≥ 5× cỡ upload (nguồn + proxy + nền + bản ra + dự phòng)
-const SMALL = 64 * 1024; // bộ đệm tối đa trước dấu phân cách đầu / sau dấu kết thúc / trường chữ
-const VIDEO_EXT = new Set(['.mp4', '.mov', '.m4v', '.mkv', '.webm', '.avi', '.3gp']);
-const AUDIO_EXT = new Set(['.mp3', '.wav', '.m4a', '.aac', '.ogg', '.flac', '.opus']);
-const httpErr = (code, msg) => Object.assign(new Error(msg), { code });
-
-export function initEdits() { markStaleEdits(); }
-
-/** Nhạc tổng hợp có sẵn → file wav 60 s trong thư mục edit (lặp khi video dài hơn). */
-function synthMusicFile(id, styleName) {
- if (!MUSIC_STYLES.includes(styleName)) throw httpErr(400, 'không có nhạc tổng hợp "' + styleName + '"');
- const f = path.join(editDir(id), `music-${styleName}.wav`);
- if (!fs.existsSync(f)) writeMusic(styleName, f, 60, 1);
- return f;
-}
-
-/**
- * Đọc multipart/form-data theo luồng (file ghi thẳng ra đĩa, không giữ trong RAM).
- * Bộ đệm luôn nhỏ: trước dấu phân cách đầu ≤ 64 KB, đầu mỗi phần ≤ 16 KB, trường chữ ≤ 64 KB, sau dấu kết thúc ≤ 64 KB;
- * trong thân file chỉ giữ lại đuôi đủ dài để bắt dấu phân cách bị cắt ngang 2 chunk (không nối dồn → chi phí tuyến tính).
- * fileTarget(field, filename) → đường dẫn | null (bỏ qua) | throw (từ chối). Tổng ≤ maxBytes (vượt → 413 tooBig).
- */
-export function parseMultipart(req, { maxBytes, fileTarget, tooBig = `file quá lớn (tối đa ${Math.round(MAX_UPLOAD / 1024 ** 3)} GB)` }) {
- return new Promise((resolve, reject) => {
- const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(req.headers['content-type'] || '');
- if (!m) return reject(httpErr(400, 'thiếu boundary multipart'));
- const delim = Buffer.from('\r\n--' + (m[1] || m[2]).trim());
- const fields = {}; const files = {}; const opened = [];
- let buf = Buffer.from('\r\n'); // để dấu phân cách đầu tiên giống mọi dấu sau
- let state = 'pre'; let total = 0; let epilogue = 0; let cur = null; let failed = false;
- const fail = (e) => {
- if (failed) return; failed = true;
- for (const s of opened) s.destroy();
- req.pause();
- reject(e.code ? e : httpErr(400, e.message));
- };
- const write = (data) => {
- if (!cur || !data.length) return;
- if (cur.stream) { cur.size += data.length; if (!cur.stream.write(data)) { req.pause(); cur.stream.once('drain', () => { if (!failed) req.resume(); }); } }
- else if (cur.text !== null) { cur.text += data.toString('utf8'); if (cur.text.length > SMALL) throw httpErr(413, `trường ${cur.name} quá dài`); }
- };
- const closePart = () => {
- if (!cur) return;
- if (cur.stream) { const s = cur.stream; s.end(); files[cur.name] = { path: cur.path, filename: cur.filename, size: cur.size, done: new Promise((r) => s.on('close', r)) }; }
- else if (cur.text !== null) fields[cur.name] = cur.text;
- cur = null;
- };
- const pump = () => {
- for (;;) {
- if (state === 'pre' || state === 'body') {
- const i = buf.indexOf(delim);
- if (i < 0) {
- const keep = delim.length + 4;
- if (state === 'pre') { if (buf.length > SMALL) throw httpErr(400, 'không thấy dấu phân cách multipart trong 64 KB đầu'); return; }
- if (buf.length > keep) { write(buf.subarray(0, buf.length - keep)); buf = Buffer.from(buf.subarray(buf.length - keep)); }
- return;
- }
- if (state === 'body') write(buf.subarray(0, i));
- closePart();
- if (buf.length < i + delim.length + 2) { buf = Buffer.from(buf.subarray(i)); state = 'pre'; return; }
- const tail = buf.subarray(i + delim.length, i + delim.length + 2).toString();
- if (tail === '--') { state = 'end'; epilogue = buf.length - (i + delim.length + 2); buf = Buffer.alloc(0); if (epilogue > SMALL) throw httpErr(400, 'dữ liệu thừa sau multipart'); return; }
- buf = buf.subarray(i + delim.length + 2); state = 'head';
- } else if (state === 'head') {
- const j = buf.indexOf('\r\n\r\n');
- if (j < 0) { if (buf.length > 16 * 1024) throw httpErr(400, 'đầu phần multipart quá dài'); return; }
- const head = buf.subarray(0, j).toString('utf8'); buf = buf.subarray(j + 4);
- const name = /name="([^"]*)"/i.exec(head)?.[1] || '';
- const filename = /filename="([^"]*)"/i.exec(head)?.[1];
- cur = { name, filename, text: null, stream: null, size: 0 };
- if (filename !== undefined) {
- if (files[name]) throw httpErr(400, `trường ${name} gửi 2 lần`);
- const target = filename ? fileTarget(name, filename, fields) : null; // fields: các trường chữ đã gửi trước file
- if (target) { cur.path = target; cur.stream = fs.createWriteStream(target); opened.push(cur.stream); cur.stream.on('error', fail); }
- } else cur.text = '';
- state = 'body';
- } else return;
- }
- };
- req.on('data', (chunk) => {
- if (failed) return;
- total += chunk.length;
- try {
- if (total > maxBytes) throw httpErr(413, tooBig);
- if (state === 'end') { epilogue += chunk.length; if (epilogue > SMALL) throw httpErr(400, 'dữ liệu thừa sau multipart'); return; }
- buf = buf.length ? Buffer.concat([buf, chunk]) : chunk; // buf ≤ 64 KB + chunk ở mọi trạng thái
- pump();
- } catch (e) { fail(e); }
- });
- req.on('end', async () => {
- if (failed) return;
- if (state !== 'end') return fail(httpErr(400, 'multipart bị cắt ngang'));
- await Promise.all(Object.values(files).map((f) => f.done));
- resolve({ fields, files });
- });
- req.on('aborted', () => fail(httpErr(400, 'tải lên bị ngắt')));
- req.on('error', fail);
- });
-}
-
-export const originOk = (req, allowedHosts) => {
- const o = req.headers.origin;
- if (!o) return true; // curl/agent cục bộ không gửi Origin
- try { return allowedHosts.has(new URL(o).host.toLowerCase()); } catch { return false; }
-};
-
-/** Trả lỗi rồi đóng kết nối (không đọc nốt phần thân còn lại của upload hỏng). */
-export function sendAndClose(res, req, send, code, body) {
- res.setHeader('Connection', 'close');
- res.on('finish', () => req.destroy());
- send(res, code, body);
-}
-
-function freeBytes(dir) {
- try { const s = fs.statfsSync(dir); return Number(s.bavail) * Number(s.bsize); } catch { return Infinity; }
-}
-
-let uploading = false; // một lúc chỉ nhận 1 upload
-const musicUploading = new Set(); // id đang nhận nhạc cho chỉnh tay
-
-/** Trả true nếu đã xử lý route. */
-export async function handleEditRoute(req, res, p, { send, readBody, serveFile, allowedHosts }) {
- // ảnh minh hoạ của thẻ kiểu edit (lưới chọn kiểu)
- const th = /^\/edit-styles\/thumbs\/([a-z0-9-]{1,40}\.webp)$/.exec(p);
- if (th && (req.method === 'GET' || req.method === 'HEAD')) { serveFile(req, res, STYLE_THUMBS, th[1]); return true; }
- if (!p.startsWith('/api/edit') && !p.startsWith('/edits/')) return false;
- if (['POST', 'DELETE', 'PUT', 'PATCH'].includes(req.method) && !originOk(req, allowedHosts)) { sendAndClose(res, req, send, 403, { error: 'origin không hợp lệ' }); return true; }
-
- if (p === '/api/edit-options' && req.method === 'GET') {
- send(res, 200, { ...editReady(), styles: editStyles(), music: MUSIC_LIST.map((m) => ({ id: m.name, desc: m.desc })), maxUploadBytes: MAX_UPLOAD });
- return true;
- }
- if (p === '/api/edit-setup' && req.method === 'GET') { send(res, 200, { ...installStatus(), ready: editReady().ready }); return true; }
- if (p === '/api/edit-setup' && req.method === 'POST') {
- const r = startInstall();
- send(res, r.started ? 202 : 409, r.started ? installStatus() : { error: r.reason });
- return true;
- }
- if (p === '/api/edits' && req.method === 'GET') { send(res, 200, listEdits()); return true; }
- if (p === '/api/edits' && req.method === 'POST') {
- const ready = editReady();
- if (!ready.ready) { sendAndClose(res, req, send, 503, { error: ready.note }); return true; }
- const ct = String(req.headers['content-type'] || '');
- if (/^multipart\/form-data/i.test(ct)) {
- const len = Number(req.headers['content-length']);
- if (!Number.isFinite(len) || len <= 0) { sendAndClose(res, req, send, 411, { error: 'cần Content-Length (trình duyệt tự gửi)' }); return true; }
- if (len > MAX_BODY) { sendAndClose(res, req, send, 413, { error: 'file quá lớn (tối đa 2 GB)' }); return true; }
- fs.mkdirSync(EDITS, { recursive: true });
- const free = freeBytes(EDITS);
- if (free < DISK_FACTOR * len) {
- sendAndClose(res, req, send, 507, { error: `ổ đĩa còn ${(free / 1e9).toFixed(1)} GB, cần ≥ ${((DISK_FACTOR * len) / 1e9).toFixed(1)} GB (5× cỡ video) để dựng` });
- return true;
- }
- if (uploading) { sendAndClose(res, req, send, 429, { error: 'đang nhận 1 video khác, chờ tải xong rồi gửi tiếp' }); return true; }
- uploading = true;
- const id = newEditId();
- const dir = editDir(id);
- try {
- fs.mkdirSync(dir, { recursive: true });
- const { fields, files } = await parseMultipart(req, {
- maxBytes: MAX_BODY,
- fileTarget: (field, filename) => {
- const ext = path.extname(filename).toLowerCase();
- if (field === 'video') { if (!VIDEO_EXT.has(ext)) throw httpErr(415, `định dạng video ${ext || '?'} chưa hỗ trợ`); return path.join(dir, 'source' + ext); }
- if (field === 'music') { if (!AUDIO_EXT.has(ext)) throw httpErr(415, `định dạng nhạc ${ext || '?'} chưa hỗ trợ`); return path.join(dir, 'music' + ext); }
- return null;
- },
- });
- uploading = false;
- if (!files.video?.size) throw httpErr(400, 'thiếu file video');
- let music = files.music?.size ? files.music.path : null;
- if (!music && fields.musicStyle && fields.musicStyle !== 'none') music = synthMusicFile(id, fields.musicStyle);
- const job = await createEdit({
- id, video: files.video.path, sourceName: files.video.filename, style: fields.style, music,
- musicName: files.music?.filename || (fields.musicStyle && fields.musicStyle !== 'none' ? `nhạc tổng hợp ${fields.musicStyle}` : null),
- content: fields.content, names: fields.names, draft: fields.draft === '1' || fields.draft === 'true', target: fields.target,
- });
- runEditJob(job.id).catch((e) => console.error('[edit]', job.id, e.message));
- send(res, 202, editView(job.id));
- } catch (e) {
- uploading = false;
- try { fs.rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }); } catch (err) { console.error("[edit] không xoá được", dir, err.message); } // không để source.* mồ côi
- const code = Number.isInteger(e.code) ? e.code : 422;
- if (res.headersSent) return true;
- if (req.complete) send(res, code, { error: e.message }); else sendAndClose(res, req, send, code, { error: e.message });
- }
- return true;
- }
- // JSON {path}: gọi từ máy (agent, script)
- const body = await readBody(req, 32 * 1024);
- if (!body.path) { send(res, 400, { error: 'cần multipart (video) hoặc JSON {path}' }); return true; }
- const id = newEditId();
- try {
- let music = null; let musicName = null;
- if (body.music && MUSIC_STYLES.includes(body.music)) { fs.mkdirSync(editDir(id), { recursive: true }); music = synthMusicFile(id, body.music); musicName = `nhạc tổng hợp ${body.music}`; }
- else if (body.music && body.music !== 'none') music = body.music;
- const job = await createEdit({ id, video: body.path, style: body.style, music, musicName, content: body.content ?? body.notes, names: body.names, draft: !!body.draft, llm: body.llm, target: body.target });
- runEditJob(job.id).catch((e) => console.error('[edit]', job.id, e.message));
- send(res, 202, editView(job.id));
- } catch (e) {
- try { fs.rmSync(editDir(id), { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }); } catch { /* bỏ qua */ }
- send(res, Number.isInteger(e.code) ? e.code : 422, { error: e.message });
- }
- return true;
- }
- let m = /^\/api\/edits\/([\w-]+)$/.exec(p);
- if (m && req.method === 'GET') {
- const v = ID_RE.test(m[1]) && editView(m[1]);
- send(res, v ? 200 : 404, v || { error: 'không thấy edit' });
- return true;
- }
- if (m && req.method === 'DELETE') {
- try { deleteEdit(m[1]); send(res, 200, { ok: true, id: m[1] }); }
- catch (e) { send(res, Number.isInteger(e.code) ? e.code : /không thấy/.test(e.message) ? 404 : 400, { error: e.message }); }
- return true;
- }
- m = /^\/api\/edits\/([\w-]+)\/revise$/.exec(p);
- if (m && req.method === 'POST') {
- const body = await readBody(req, 16 * 1024);
- try {
- if (!ID_RE.test(m[1]) || !readEditJob(m[1])) throw httpErr(404, 'không thấy edit');
- // kiểm đầu vào đồng bộ (throw → 4xx); phần chạy nền có .catch riêng
- reviseEditJob(m[1], body.instruction).catch((e) => console.error('[edit revise]', m[1], e.message));
- send(res, 202, editView(m[1]));
- } catch (e) { send(res, Number.isInteger(e.code) ? e.code : 422, { error: e.message }); }
- return true;
- }
- m = /^\/api\/edits\/([\w-]+)\/manual$/.exec(p);
- if (m && req.method === 'GET') {
- const v = ID_RE.test(m[1]) && readEditJob(m[1]) && manualState(m[1]);
- send(res, v ? 200 : 404, v || { error: 'không thấy edit (hoặc chưa dựng xong lần đầu)' });
- return true;
- }
- if (m && req.method === 'POST') {
- if (!/^application\/json\b/i.test(String(req.headers['content-type'] || ''))) { sendAndClose(res, req, send, 415, { error: 'cần Content-Type: application/json' }); return true; }
- let body;
- try { body = await readBody(req, 256 * 1024); } catch (e) {
- const big = /quá lớn/.test(e.message);
- sendAndClose(res, req, send, big ? 413 : 400, { error: big ? 'bản vá quá lớn (tối đa 256 KB)' : 'JSON không hợp lệ' });
- return true;
- }
- if (!body || typeof body !== 'object' || Array.isArray(body)) { send(res, 400, { error: 'bản vá phải là object JSON' }); return true; }
- try {
- if (!ID_RE.test(m[1]) || !readEditJob(m[1])) throw httpErr(404, 'không thấy edit');
- manualEditJob(m[1], body).catch((e) => console.error('[edit manual]', m[1], e.message));
- send(res, 202, editView(m[1]));
- } catch (e) { send(res, Number.isInteger(e.code) ? e.code : 422, { error: e.message }); }
- return true;
- }
- m = /^\/api\/edits\/([\w-]+)\/music$/.exec(p);
- if (m && req.method === 'POST') {
- const id = m[1];
- const job = ID_RE.test(id) && readEditJob(id);
- if (!job) { sendAndClose(res, req, send, 404, { error: 'không thấy edit' }); return true; }
- if (!currentOut(id)) { sendAndClose(res, req, send, 409, { error: 'edit này chưa dựng xong lần đầu' }); return true; }
- if (!/^multipart\/form-data/i.test(String(req.headers['content-type'] || ''))) { sendAndClose(res, req, send, 415, { error: 'cần multipart/form-data (trường music)' }); return true; }
- const len = Number(req.headers['content-length']);
- if (!Number.isFinite(len) || len <= 0) { sendAndClose(res, req, send, 411, { error: 'cần Content-Length' }); return true; }
- if (len > MAX_MUSIC) { sendAndClose(res, req, send, 413, { error: 'file nhạc quá lớn (tối đa 200 MB)' }); return true; }
- if (musicUploading.has(id)) { sendAndClose(res, req, send, 429, { error: 'đang nhận 1 file nhạc khác cho bản này' }); return true; }
- musicUploading.add(id);
- const dir = editDir(id);
- let n = 1; while (n < 9999 && fs.readdirSync(dir).some((f) => f.startsWith(`music-up-${n}.`))) n++;
- let saved = null;
- try {
- const { files } = await parseMultipart(req, {
- maxBytes: MAX_MUSIC, tooBig: 'file nhạc quá lớn (tối đa 200 MB)',
- fileTarget: (field, filename) => {
- if (field !== 'music') return null;
- const ext = path.extname(filename).toLowerCase();
- if (!AUDIO_EXT.has(ext)) throw httpErr(415, `định dạng nhạc ${ext || '?'} chưa hỗ trợ`);
- saved = path.join(dir, `music-up-${n}${ext}`);
- return saved;
- },
- });
- if (!files.music?.size) throw httpErr(400, 'thiếu file nhạc (trường music)');
- try { await checkMusic(files.music.path); } catch (e) { throw httpErr(422, e.message); }
- const name = path.basename(files.music.path);
- addMusicUpload(id, name, files.music.filename);
- send(res, 201, { file: name, name: files.music.filename });
- } catch (e) {
- if (saved) setTimeout(() => { try { fs.rmSync(saved, { force: true, maxRetries: 5, retryDelay: 200 }); } catch { /* bỏ qua */ } }, 50); // luồng ghi vừa huỷ còn giữ file (Windows)
- const code = Number.isInteger(e.code) ? e.code : 422;
- if (res.headersSent) return true;
- if (req.complete) send(res, code, { error: e.message }); else sendAndClose(res, req, send, code, { error: e.message });
- } finally { musicUploading.delete(id); }
- return true;
- }
- if (p.startsWith('/api/')) return false;
- // ---- file ----
- m = /^\/edits\/([\w-]+)\/(out(?:-r\d{1,4})?\.mp4|preview\.jpg|preview-final\.jpg|edl\.json)$/.exec(p);
- if (m && (req.method === 'GET' || req.method === 'HEAD') && ID_RE.test(m[1])) { serveFile(req, res, editDir(m[1]), m[2]); return true; }
- send(res, 404, { error: 'không thấy file' });
- return true;
-}
+// REST cho Edit video (server/server.mjs gọi handleEditRoute). Chống DNS rebinding đã làm ở server (Host),
+// ở đây chặn thêm Origin lạ cho mọi lệnh ghi (trang web khác không gửi form upload/đường dẫn/xoá vào được).
+// GET /api/edit-options → {ready, missing, setup, styles[], music[], maxUploadBytes}
+// GET /api/edit-setup → tiến độ cài (nút "Cài ngay"): {running, step, ok, word, hint, elapsedS, log[]}
+// POST /api/edit-setup → chạy node edit/setup.mjs nền (409 nếu đang cài)
+// GET /api/edits → danh sách
+// POST /api/edits → multipart (video ≤ 2 GB, music?, style, musicStyle?, content?, names?, draft?, target?)
+// hoặc JSON {path, style, music?(đường dẫn|tên nhạc tổng hợp), content?, names?, draft?, target?}
+// GET /api/edits/:id → trạng thái, tiến độ, log, chữ LLM đã sửa, các lần sửa
+// POST /api/edits/:id/revise → {instruction}: LLM sửa EDL theo lời, render lại, không phân tích lại
+// GET /api/edits/:id/manual → những gì chỉnh tay được: dòng phụ đề (giây bản ra), nhạc, giọng, sfx, zoom, đồ hoạ
+// POST /api/edits/:id/manual → JSON bản vá (edit/manual.mjs ManualSchema, kiểm chặt): dựng lại phần cần thiết → out-r<n>.mp4
+// GET /api/edits/:id/manual?rev=N → như trên nhưng của bản rN (chỉ đọc; 0 = bản gốc)
+// POST /api/edits/:id/music → multipart music (≤ 200 MB): nhạc cho chỉnh tay → {file: "music-up-<n>.<ext>", name}
+// GET /api/edits/:id/strip?out=out-r<n>.mp4 → dải ảnh khung cho timeline Studio {url, n, every, tileW, tileH, seconds}
+// GET /api/edits/:id/wave?src=keep|synth:<tên>|upload:<file> → đỉnh sóng nhạc {url, rate, seconds, peaks[]}
+// DELETE /api/edits/:id → xoá hẳn thư mục edits/<id>
+// GET /edits/:id/(out.mp4|out-r<n>.mp4|preview.jpg|preview-final.jpg|edl.json|base.mp4|strip-out*.jpg|music*.wav…)
+// GET /edit-styles/thumbs/<id>.webp → ảnh minh hoạ dọc của thẻ kiểu (lưới chọn kiểu)
+import fs from 'node:fs';
+import path from 'node:path';
+import { MUSIC_LIST, MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';
+import {
+ ID_RE, EDITS, editDir, newEditId, createEdit, runEditJob, reviseEditJob, editView, listEdits, editStyles, editReady, readEditJob,
+ markStaleEdits, deleteEdit, STYLE_THUMBS, manualState, manualEditJob, addMusicUpload, checkMusic, currentOut,
+} from './jobs.mjs';
+import { installStatus, startInstall } from './setup-run.mjs';
+import { stripOf, waveOf, musicFileFor, isMusicName } from './studio-media.mjs';
+
+export const MAX_UPLOAD = 2 * 1024 ** 3; // 2 GB
+const MAX_BODY = MAX_UPLOAD + 200 * 1024 ** 2; // + nhạc + trường chữ
+const MAX_MUSIC = 200 * 1024 ** 2; // nhạc tải lên cho chỉnh tay
+const DISK_FACTOR = 5; // cần trống ≥ 5× cỡ upload (nguồn + proxy + nền + bản ra + dự phòng)
+const SMALL = 64 * 1024; // bộ đệm tối đa trước dấu phân cách đầu / sau dấu kết thúc / trường chữ
+const VIDEO_EXT = new Set(['.mp4', '.mov', '.m4v', '.mkv', '.webm', '.avi', '.3gp']);
+const AUDIO_EXT = new Set(['.mp3', '.wav', '.m4a', '.aac', '.ogg', '.flac', '.opus']);
+const httpErr = (code, msg) => Object.assign(new Error(msg), { code });
+
+export function initEdits() { markStaleEdits(); }
+
+/** Nhạc tổng hợp có sẵn → file wav 60 s trong thư mục edit (lặp khi video dài hơn). */
+function synthMusicFile(id, styleName) {
+ if (!MUSIC_STYLES.includes(styleName)) throw httpErr(400, 'không có nhạc tổng hợp "' + styleName + '"');
+ const f = path.join(editDir(id), `music-${styleName}.wav`);
+ if (!fs.existsSync(f)) writeMusic(styleName, f, 60, 1);
+ return f;
+}
+
+/**
+ * Đọc multipart/form-data theo luồng (file ghi thẳng ra đĩa, không giữ trong RAM).
+ * Bộ đệm luôn nhỏ: trước dấu phân cách đầu ≤ 64 KB, đầu mỗi phần ≤ 16 KB, trường chữ ≤ 64 KB, sau dấu kết thúc ≤ 64 KB;
+ * trong thân file chỉ giữ lại đuôi đủ dài để bắt dấu phân cách bị cắt ngang 2 chunk (không nối dồn → chi phí tuyến tính).
+ * fileTarget(field, filename) → đường dẫn | null (bỏ qua) | throw (từ chối). Tổng ≤ maxBytes (vượt → 413 tooBig).
+ */
+export function parseMultipart(req, { maxBytes, fileTarget, tooBig = `file quá lớn (tối đa ${Math.round(MAX_UPLOAD / 1024 ** 3)} GB)` }) {
+ return new Promise((resolve, reject) => {
+ const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(req.headers['content-type'] || '');
+ if (!m) return reject(httpErr(400, 'thiếu boundary multipart'));
+ const delim = Buffer.from('\r\n--' + (m[1] || m[2]).trim());
+ const fields = {}; const files = {}; const opened = [];
+ let buf = Buffer.from('\r\n'); // để dấu phân cách đầu tiên giống mọi dấu sau
+ let state = 'pre'; let total = 0; let epilogue = 0; let cur = null; let failed = false;
+ const fail = (e) => {
+ if (failed) return; failed = true;
+ for (const s of opened) s.destroy();
+ req.pause();
+ reject(e.code ? e : httpErr(400, e.message));
+ };
+ const write = (data) => {
+ if (!cur || !data.length) return;
+ if (cur.stream) { cur.size += data.length; if (!cur.stream.write(data)) { req.pause(); cur.stream.once('drain', () => { if (!failed) req.resume(); }); } }
+ else if (cur.text !== null) { cur.text += data.toString('utf8'); if (cur.text.length > SMALL) throw httpErr(413, `trường ${cur.name} quá dài`); }
+ };
+ const closePart = () => {
+ if (!cur) return;
+ if (cur.stream) { const s = cur.stream; s.end(); files[cur.name] = { path: cur.path, filename: cur.filename, size: cur.size, done: new Promise((r) => s.on('close', r)) }; }
+ else if (cur.text !== null) fields[cur.name] = cur.text;
+ cur = null;
+ };
+ const pump = () => {
+ for (;;) {
+ if (state === 'pre' || state === 'body') {
+ const i = buf.indexOf(delim);
+ if (i < 0) {
+ const keep = delim.length + 4;
+ if (state === 'pre') { if (buf.length > SMALL) throw httpErr(400, 'không thấy dấu phân cách multipart trong 64 KB đầu'); return; }
+ if (buf.length > keep) { write(buf.subarray(0, buf.length - keep)); buf = Buffer.from(buf.subarray(buf.length - keep)); }
+ return;
+ }
+ if (state === 'body') write(buf.subarray(0, i));
+ closePart();
+ if (buf.length < i + delim.length + 2) { buf = Buffer.from(buf.subarray(i)); state = 'pre'; return; }
+ const tail = buf.subarray(i + delim.length, i + delim.length + 2).toString();
+ if (tail === '--') { state = 'end'; epilogue = buf.length - (i + delim.length + 2); buf = Buffer.alloc(0); if (epilogue > SMALL) throw httpErr(400, 'dữ liệu thừa sau multipart'); return; }
+ buf = buf.subarray(i + delim.length + 2); state = 'head';
+ } else if (state === 'head') {
+ const j = buf.indexOf('\r\n\r\n');
+ if (j < 0) { if (buf.length > 16 * 1024) throw httpErr(400, 'đầu phần multipart quá dài'); return; }
+ const head = buf.subarray(0, j).toString('utf8'); buf = buf.subarray(j + 4);
+ const name = /name="([^"]*)"/i.exec(head)?.[1] || '';
+ const filename = /filename="([^"]*)"/i.exec(head)?.[1];
+ cur = { name, filename, text: null, stream: null, size: 0 };
+ if (filename !== undefined) {
+ if (files[name]) throw httpErr(400, `trường ${name} gửi 2 lần`);
+ const target = filename ? fileTarget(name, filename, fields) : null; // fields: các trường chữ đã gửi trước file
+ if (target) { cur.path = target; cur.stream = fs.createWriteStream(target); opened.push(cur.stream); cur.stream.on('error', fail); }
+ } else cur.text = '';
+ state = 'body';
+ } else return;
+ }
+ };
+ req.on('data', (chunk) => {
+ if (failed) return;
+ total += chunk.length;
+ try {
+ if (total > maxBytes) throw httpErr(413, tooBig);
+ if (state === 'end') { epilogue += chunk.length; if (epilogue > SMALL) throw httpErr(400, 'dữ liệu thừa sau multipart'); return; }
+ buf = buf.length ? Buffer.concat([buf, chunk]) : chunk; // buf ≤ 64 KB + chunk ở mọi trạng thái
+ pump();
+ } catch (e) { fail(e); }
+ });
+ req.on('end', async () => {
+ if (failed) return;
+ if (state !== 'end') return fail(httpErr(400, 'multipart bị cắt ngang'));
+ await Promise.all(Object.values(files).map((f) => f.done));
+ resolve({ fields, files });
+ });
+ req.on('aborted', () => fail(httpErr(400, 'tải lên bị ngắt')));
+ req.on('error', fail);
+ });
+}
+
+export const originOk = (req, allowedHosts) => {
+ const o = req.headers.origin;
+ if (!o) return true; // curl/agent cục bộ không gửi Origin
+ try { return allowedHosts.has(new URL(o).host.toLowerCase()); } catch { return false; }
+};
+
+/** Trả lỗi rồi đóng kết nối (không đọc nốt phần thân còn lại của upload hỏng). */
+export function sendAndClose(res, req, send, code, body) {
+ res.setHeader('Connection', 'close');
+ res.on('finish', () => req.destroy());
+ send(res, code, body);
+}
+
+function freeBytes(dir) {
+ try { const s = fs.statfsSync(dir); return Number(s.bavail) * Number(s.bsize); } catch { return Infinity; }
+}
+
+let uploading = false; // một lúc chỉ nhận 1 upload
+const musicUploading = new Set(); // id đang nhận nhạc cho chỉnh tay
+
+/** Trả true nếu đã xử lý route. */
+export async function handleEditRoute(req, res, p, { send, readBody, serveFile, allowedHosts }) {
+ // ảnh minh hoạ của thẻ kiểu edit (lưới chọn kiểu)
+ const th = /^\/edit-styles\/thumbs\/([a-z0-9-]{1,40}\.webp)$/.exec(p);
+ if (th && (req.method === 'GET' || req.method === 'HEAD')) { serveFile(req, res, STYLE_THUMBS, th[1]); return true; }
+ if (!p.startsWith('/api/edit') && !p.startsWith('/edits/')) return false;
+ if (['POST', 'DELETE', 'PUT', 'PATCH'].includes(req.method) && !originOk(req, allowedHosts)) { sendAndClose(res, req, send, 403, { error: 'origin không hợp lệ' }); return true; }
+
+ if (p === '/api/edit-options' && req.method === 'GET') {
+ send(res, 200, { ...editReady(), styles: editStyles(), music: MUSIC_LIST.map((m) => ({ id: m.name, desc: m.desc })), maxUploadBytes: MAX_UPLOAD });
+ return true;
+ }
+ if (p === '/api/edit-setup' && req.method === 'GET') { send(res, 200, { ...installStatus(), ready: editReady().ready }); return true; }
+ if (p === '/api/edit-setup' && req.method === 'POST') {
+ const r = startInstall();
+ send(res, r.started ? 202 : 409, r.started ? installStatus() : { error: r.reason });
+ return true;
+ }
+ if (p === '/api/edits' && req.method === 'GET') { send(res, 200, listEdits()); return true; }
+ if (p === '/api/edits' && req.method === 'POST') {
+ const ready = editReady();
+ if (!ready.ready) { sendAndClose(res, req, send, 503, { error: ready.note }); return true; }
+ const ct = String(req.headers['content-type'] || '');
+ if (/^multipart\/form-data/i.test(ct)) {
+ const len = Number(req.headers['content-length']);
+ if (!Number.isFinite(len) || len <= 0) { sendAndClose(res, req, send, 411, { error: 'cần Content-Length (trình duyệt tự gửi)' }); return true; }
+ if (len > MAX_BODY) { sendAndClose(res, req, send, 413, { error: 'file quá lớn (tối đa 2 GB)' }); return true; }
+ fs.mkdirSync(EDITS, { recursive: true });
+ const free = freeBytes(EDITS);
+ if (free < DISK_FACTOR * len) {
+ sendAndClose(res, req, send, 507, { error: `ổ đĩa còn ${(free / 1e9).toFixed(1)} GB, cần ≥ ${((DISK_FACTOR * len) / 1e9).toFixed(1)} GB (5× cỡ video) để dựng` });
+ return true;
+ }
+ if (uploading) { sendAndClose(res, req, send, 429, { error: 'đang nhận 1 video khác, chờ tải xong rồi gửi tiếp' }); return true; }
+ uploading = true;
+ const id = newEditId();
+ const dir = editDir(id);
+ try {
+ fs.mkdirSync(dir, { recursive: true });
+ const { fields, files } = await parseMultipart(req, {
+ maxBytes: MAX_BODY,
+ fileTarget: (field, filename) => {
+ const ext = path.extname(filename).toLowerCase();
+ if (field === 'video') { if (!VIDEO_EXT.has(ext)) throw httpErr(415, `định dạng video ${ext || '?'} chưa hỗ trợ`); return path.join(dir, 'source' + ext); }
+ if (field === 'music') { if (!AUDIO_EXT.has(ext)) throw httpErr(415, `định dạng nhạc ${ext || '?'} chưa hỗ trợ`); return path.join(dir, 'music' + ext); }
+ return null;
+ },
+ });
+ uploading = false;
+ if (!files.video?.size) throw httpErr(400, 'thiếu file video');
+ let music = files.music?.size ? files.music.path : null;
+ if (!music && fields.musicStyle && fields.musicStyle !== 'none') music = synthMusicFile(id, fields.musicStyle);
+ const job = await createEdit({
+ id, video: files.video.path, sourceName: files.video.filename, style: fields.style, music,
+ musicName: files.music?.filename || (fields.musicStyle && fields.musicStyle !== 'none' ? `nhạc tổng hợp ${fields.musicStyle}` : null),
+ content: fields.content, names: fields.names, draft: fields.draft === '1' || fields.draft === 'true', target: fields.target,
+ noMusic: fields.musicStyle === 'none' && !files.music?.size,
+ });
+ runEditJob(job.id).catch((e) => console.error('[edit]', job.id, e.message));
+ send(res, 202, editView(job.id));
+ } catch (e) {
+ uploading = false;
+ try { fs.rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }); } catch (err) { console.error("[edit] không xoá được", dir, err.message); } // không để source.* mồ côi
+ const code = Number.isInteger(e.code) ? e.code : 422;
+ if (res.headersSent) return true;
+ if (req.complete) send(res, code, { error: e.message }); else sendAndClose(res, req, send, code, { error: e.message });
+ }
+ return true;
+ }
+ // JSON {path}: gọi từ máy (agent, script)
+ const body = await readBody(req, 32 * 1024);
+ if (!body.path) { send(res, 400, { error: 'cần multipart (video) hoặc JSON {path}' }); return true; }
+ const id = newEditId();
+ try {
+ let music = null; let musicName = null;
+ if (body.music && MUSIC_STYLES.includes(body.music)) { fs.mkdirSync(editDir(id), { recursive: true }); music = synthMusicFile(id, body.music); musicName = `nhạc tổng hợp ${body.music}`; }
+ else if (body.music && body.music !== 'none') music = body.music;
+ const job = await createEdit({ id, video: body.path, style: body.style, music, musicName, content: body.content ?? body.notes, names: body.names, draft: !!body.draft, llm: body.llm, target: body.target });
+ runEditJob(job.id).catch((e) => console.error('[edit]', job.id, e.message));
+ send(res, 202, editView(job.id));
+ } catch (e) {
+ try { fs.rmSync(editDir(id), { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }); } catch { /* bỏ qua */ }
+ send(res, Number.isInteger(e.code) ? e.code : 422, { error: e.message });
+ }
+ return true;
+ }
+ let m = /^\/api\/edits\/([\w-]+)$/.exec(p);
+ if (m && req.method === 'GET') {
+ const v = ID_RE.test(m[1]) && editView(m[1]);
+ send(res, v ? 200 : 404, v || { error: 'không thấy edit' });
+ return true;
+ }
+ if (m && req.method === 'DELETE') {
+ try { deleteEdit(m[1]); send(res, 200, { ok: true, id: m[1] }); }
+ catch (e) { send(res, Number.isInteger(e.code) ? e.code : /không thấy/.test(e.message) ? 404 : 400, { error: e.message }); }
+ return true;
+ }
+ m = /^\/api\/edits\/([\w-]+)\/revise$/.exec(p);
+ if (m && req.method === 'POST') {
+ const body = await readBody(req, 16 * 1024);
+ try {
+ if (!ID_RE.test(m[1]) || !readEditJob(m[1])) throw httpErr(404, 'không thấy edit');
+ // kiểm đầu vào đồng bộ (throw → 4xx); phần chạy nền có .catch riêng
+ reviseEditJob(m[1], body.instruction).catch((e) => console.error('[edit revise]', m[1], e.message));
+ send(res, 202, editView(m[1]));
+ } catch (e) { send(res, Number.isInteger(e.code) ? e.code : 422, { error: e.message }); }
+ return true;
+ }
+ m = /^\/api\/edits\/([\w-]+)\/manual$/.exec(p);
+ if (m && req.method === 'GET') {
+ try {
+ const rev = new URL(req.url, 'http://x').searchParams.get('rev');
+ const v = ID_RE.test(m[1]) && readEditJob(m[1]) && manualState(m[1], rev);
+ send(res, v ? 200 : 404, v || { error: 'không thấy edit (hoặc chưa dựng xong lần đầu)' });
+ } catch (e) { send(res, Number.isInteger(e.code) ? e.code : 422, { error: e.message }); }
+ return true;
+ }
+ if (m && req.method === 'POST') {
+ if (!/^application\/json\b/i.test(String(req.headers['content-type'] || ''))) { sendAndClose(res, req, send, 415, { error: 'cần Content-Type: application/json' }); return true; }
+ let body;
+ try { body = await readBody(req, 256 * 1024); } catch (e) {
+ const big = /quá lớn/.test(e.message);
+ sendAndClose(res, req, send, big ? 413 : 400, { error: big ? 'bản vá quá lớn (tối đa 256 KB)' : 'JSON không hợp lệ' });
+ return true;
+ }
+ if (!body || typeof body !== 'object' || Array.isArray(body)) { send(res, 400, { error: 'bản vá phải là object JSON' }); return true; }
+ try {
+ if (!ID_RE.test(m[1]) || !readEditJob(m[1])) throw httpErr(404, 'không thấy edit');
+ manualEditJob(m[1], body).catch((e) => console.error('[edit manual]', m[1], e.message));
+ send(res, 202, editView(m[1]));
+ } catch (e) { send(res, Number.isInteger(e.code) ? e.code : 422, { error: e.message }); }
+ return true;
+ }
+ m = /^\/api\/edits\/([\w-]+)\/music$/.exec(p);
+ if (m && req.method === 'POST') {
+ const id = m[1];
+ const job = ID_RE.test(id) && readEditJob(id);
+ if (!job) { sendAndClose(res, req, send, 404, { error: 'không thấy edit' }); return true; }
+ if (!currentOut(id)) { sendAndClose(res, req, send, 409, { error: 'edit này chưa dựng xong lần đầu' }); return true; }
+ if (!/^multipart\/form-data/i.test(String(req.headers['content-type'] || ''))) { sendAndClose(res, req, send, 415, { error: 'cần multipart/form-data (trường music)' }); return true; }
+ const len = Number(req.headers['content-length']);
+ if (!Number.isFinite(len) || len <= 0) { sendAndClose(res, req, send, 411, { error: 'cần Content-Length' }); return true; }
+ if (len > MAX_MUSIC) { sendAndClose(res, req, send, 413, { error: 'file nhạc quá lớn (tối đa 200 MB)' }); return true; }
+ if (musicUploading.has(id)) { sendAndClose(res, req, send, 429, { error: 'đang nhận 1 file nhạc khác cho bản này' }); return true; }
+ musicUploading.add(id);
+ const dir = editDir(id);
+ let n = 1; while (n < 9999 && fs.readdirSync(dir).some((f) => f.startsWith(`music-up-${n}.`))) n++;
+ let saved = null;
+ try {
+ const { files } = await parseMultipart(req, {
+ maxBytes: MAX_MUSIC, tooBig: 'file nhạc quá lớn (tối đa 200 MB)',
+ fileTarget: (field, filename) => {
+ if (field !== 'music') return null;
+ const ext = path.extname(filename).toLowerCase();
+ if (!AUDIO_EXT.has(ext)) throw httpErr(415, `định dạng nhạc ${ext || '?'} chưa hỗ trợ`);
+ saved = path.join(dir, `music-up-${n}${ext}`);
+ return saved;
+ },
+ });
+ if (!files.music?.size) throw httpErr(400, 'thiếu file nhạc (trường music)');
+ try { await checkMusic(files.music.path); } catch (e) { throw httpErr(422, e.message); }
+ const name = path.basename(files.music.path);
+ addMusicUpload(id, name, files.music.filename);
+ send(res, 201, { file: name, name: files.music.filename });
+ } catch (e) {
+ if (saved) setTimeout(() => { try { fs.rmSync(saved, { force: true, maxRetries: 5, retryDelay: 200 }); } catch { /* bỏ qua */ } }, 50); // luồng ghi vừa huỷ còn giữ file (Windows)
+ const code = Number.isInteger(e.code) ? e.code : 422;
+ if (res.headersSent) return true;
+ if (req.complete) send(res, code, { error: e.message }); else sendAndClose(res, req, send, code, { error: e.message });
+ } finally { musicUploading.delete(id); }
+ return true;
+ }
+ // ---- Studio: dải ảnh khung + đỉnh sóng nhạc ----
+ m = /^\/api\/edits\/([\w-]+)\/(strip|wave)$/.exec(p);
+ if (m && req.method === 'GET') {
+ try {
+ if (!ID_RE.test(m[1]) || !readEditJob(m[1])) throw httpErr(404, 'không thấy edit');
+ const q = new URL(req.url, 'http://x').searchParams;
+ const dir = editDir(m[1]);
+ if (m[2] === 'strip') send(res, 200, await stripOf(dir, m[1], q.get('out') || currentOut(m[1]) || ''));
+ else {
+ let cur = null; try { cur = JSON.parse(fs.readFileSync(path.join(dir, 'edl.json'), 'utf8')).music?.file || null; } catch { /* chưa có */ }
+ const f = q.get('file');
+ const name = f && isMusicName(f) && fs.existsSync(path.join(dir, f)) ? f : musicFileFor(dir, q.get('src') || 'keep', cur);
+ const w = await waveOf(dir, name);
+ send(res, 200, { ...w, file: name, url: `/edits/${m[1]}/${name}?v=${Math.round(fs.statSync(path.join(dir, name)).mtimeMs)}` });
+ }
+ } catch (e) { send(res, Number.isInteger(e.code) ? e.code : 422, { error: e.message }); }
+ return true;
+ }
+ if (p.startsWith('/api/')) return false;
+ // ---- file ----
+ m = /^\/edits\/([\w-]+)\/(out(?:-r\d{1,4})?\.mp4|preview\.jpg|preview-final\.jpg|edl\.json|base\.mp4|strip-out(?:-r\d{1,4})?\.jpg|[\w.-]{1,60})$/.exec(p);
+ const fileOk = (f) => /^(out(-r\d{1,4})?\.mp4|preview\.jpg|preview-final\.jpg|edl\.json|base\.mp4|strip-out(-r\d{1,4})?\.jpg)$/.test(f) || isMusicName(f);
+ if (m && (req.method === 'GET' || req.method === 'HEAD') && ID_RE.test(m[1]) && fileOk(m[2])) { serveFile(req, res, editDir(m[1]), m[2]); return true; }
+ send(res, 404, { error: 'không thấy file' });
+ return true;
+}
diff --git a/edit/jobs.mjs b/edit/jobs.mjs
index c9c1244..6db8489 100644
--- a/edit/jobs.mjs
+++ b/edit/jobs.mjs
@@ -1,347 +1,378 @@
-// Việc Edit video dùng chung cho REST (server), MCP và CLI: hồ sơ edits/<id>/job.json, tiến độ, hàng chờ, dọn đĩa.
-// Mỗi lúc chỉ 1 edit chạy trên cả máy (khoá file edits/.edit.lock tạo độc quyền "wx", có pid; khoá của tiến trình
-// đã chết được gỡ dưới một khoá phụ cũng "wx" nên hai tiến trình không thể cùng gỡ/cùng giữ).
-import fs from 'node:fs';
-import path from 'node:path';
-import { EDITS, editDir, newEditId, editVideo, reviseEdit, manualEdit, STEPS } from './pipeline.mjs';
-import { parseManual, manualView, applyPatch } from './manual.mjs';
-import { LAYER } from './captions-hf.mjs';
-import { listStyles, loadStyle, parseNames, STYLES_DIR } from './planner.mjs';
-import { setupStatus } from './env.mjs';
-import { resolveEditStyle } from '../packs/registry.mjs';
-import { probeSource } from './ingest.mjs';
-
-export { STEPS, EDITS, newEditId, editDir };
-export const ID_RE = /^[\w-]{1,80}$/;
-const LOCK = path.join(EDITS, '.edit.lock');
-const BREAKER = path.join(EDITS, '.edit.lock.break');
-const readJson = (f, d = null) => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return d; } };
-export const pidAlive = (pid) => { if (!Number.isInteger(pid) || pid <= 0) return false; try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
-const jobFile = (id) => path.join(editDir(id), 'job.json');
-
-/** Tên file MP4 mới nhất (out.mp4 hoặc out-r<n>.mp4 sau mỗi lần sửa), null nếu chưa có. */
-export function currentOut(id) {
- const st = readJson(path.join(editDir(id), 'state.json'), {});
- for (const f of [st.out, 'out.mp4']) if (f && /^out(-r\d{1,4})?\.mp4$/.test(f) && fs.existsSync(path.join(editDir(id), f))) return f;
- return null;
-}
-
-function writeJob(id, patch) {
- const cur = readJson(jobFile(id), {});
- const next = { ...cur, ...patch, id, updatedAt: new Date().toISOString() };
- fs.mkdirSync(editDir(id), { recursive: true });
- const tmp = jobFile(id) + `.${process.pid}.tmp`;
- fs.writeFileSync(tmp, JSON.stringify(next, null, 1));
- fs.renameSync(tmp, jobFile(id));
- return next;
-}
-
-/**
- * Job "queued"/"running" mà tiến trình giữ nó đã chết (CLI/MCP bị tắt, máy khởi động lại) → tự chuyển sang
- * error (dựng lần đầu) hoặc done + reviseError (sửa, bản cũ vẫn còn), kèm lý do. Gọi ở mọi lần đọc.
- */
-function reapIfDead(job) {
- if (!job || !['queued', 'running'].includes(job.status) || pidAlive(job.pid)) return job;
- const why = `bị ngắt giữa chừng (tiến trình ${job.pid || '?'} đã tắt lúc "${job.step || 'chờ lượt'}")`;
- if (['revise', 'manual'].includes(job.action) && currentOut(job.id)) return writeJob(job.id, { status: 'done', reviseError: why + ' — bấm Render lại' });
- return writeJob(job.id, { status: 'error', error: why + ' — bấm Dựng lại' });
-}
-
-export function readEditJob(id) {
- if (!ID_RE.test(String(id))) return null;
- return reapIfDead(readJson(jobFile(id)));
-}
-
-/** Ảnh minh hoạ dọc của từng kiểu (khung từ bản demo), server phục vụ ở /edit-styles/thumbs/<id>.webp. */
-export const STYLE_THUMBS = path.join(STYLES_DIR, 'thumbs');
-
-/** Kiểu edit có sẵn (cho UI/MCP): tên + tóm tắt VI/EN, ảnh minh hoạ (nếu có), màu nhấn, độ dài mặc định. */
-export function editStyles() {
- return listStyles().map((id) => {
- const s = loadStyle(id);
- const builtin = (s.source || 'builtin') === 'builtin';
- // ảnh của cách dựng trong gói: packs/http.mjs phục vụ ở /pack-thumbs/<packId>/edit-style-<slug>.webp
- const r = builtin ? null : resolveEditStyle(id);
- const thumb = builtin ? (fs.existsSync(path.join(STYLE_THUMBS, `${id}.webp`)) ? `/edit-styles/thumbs/${id}.webp` : null)
- : r?.thumbFile ? `/pack-thumbs/${r.packId}/edit-style-${r.slug}.webp` : null;
- return {
- id, source: s.source || 'builtin', ...(r ? { packId: r.packId, restricted: true } : {}), order: builtin ? (s.order ?? 99) : 200 + (Number(s.order) || 0), name: s.name, nameEn: s.nameEn || s.name,
- summary: s.summary || s.guide.split('\n').find((l) => l.trim() && !l.startsWith('#')) || '', summaryEn: s.summaryEn || '',
- thumb, accent: s.graphics?.accent || s.look?.hi || null, target: s.target ?? null,
- };
- }).sort((a, b) => a.order - b.order);
-}
-
-/** Đã cài đủ chưa (python, gói, model whisper, model mặt/người, font). UI hiện hướng dẫn cài nếu chưa. */
-export function editReady() {
- const st = setupStatus();
- return {
- ready: st.ready, missing: st.missing, setup: 'node edit/setup.mjs',
- note: st.ready ? '' : `Chưa cài đủ phần Edit video (thiếu: ${st.missing.join(', ')}). Cần Python 3.10–3.12, ~6 GB gồm whisper large-v3. Chạy trong thư mục LumReels: node edit/setup.mjs`,
- };
-}
-
-/** ffprobe ngay khi tạo: video phải có hình + độ dài > 0; nhạc phải có tiếng. Lỗi → throw (chưa chạy whisper/LLM). */
-export async function checkMedia(video, music) {
- let info;
- try { info = await probeSource(video); } catch (e) { throw new Error(`không đọc được video (${path.basename(video)}): ${e.message}`); }
- if (!Number.isFinite(info.duration) || info.duration < 1) throw new Error('video quá ngắn hoặc hỏng (dưới 1 giây)');
- if (!info.hasAudio) throw new Error('video không có tiếng: cần tiếng nói để cắt và làm phụ đề');
- if (info.duration > 30 * 60) throw new Error(`video dài ${Math.round(info.duration / 60)} phút; tối đa 30 phút`);
- if (music) await checkMusic(music);
- return info;
-}
-
-/** File nhạc phải có luồng tiếng đọc được (ffprobe). Lỗi → throw. */
-export async function checkMusic(music) {
- const { run } = await import('../engine/lib.mjs');
- const r = await run('ffprobe', ['-v', 'error', '-select_streams', 'a:0', '-show_entries', 'stream=codec_type:format=duration', '-of', 'json', music]);
- let j = null; try { j = JSON.parse(r.out); } catch { /* bỏ qua */ }
- if (!j?.streams?.length) throw new Error(`file nhạc ${path.basename(music)} không có tiếng hoặc hỏng`);
-}
-
-/**
- * Tạo hồ sơ edit (chưa chạy). input: {id?, video, style, music?, musicName?, content?, names?, draft?, llm?, sourceName?}
- * Kiểm kiểu edit, file và ffprobe trước khi ghi job.json.
- */
-export async function createEdit(input) {
- const id = input.id || newEditId();
- if (!ID_RE.test(id)) throw new Error('id không hợp lệ');
- const video = path.resolve(String(input.video || ''));
- if (!input.video || !fs.existsSync(video) || !fs.statSync(video).isFile()) throw new Error(`không thấy video ${input.video || ''}`);
- const style = String(input.style || 'sach-gon');
- if (!listStyles().includes(style)) throw new Error(`không có kiểu edit "${style}" (có: ${listStyles().join(', ')})`);
- const music = input.music ? path.resolve(String(input.music)) : null;
- if (music && (!fs.existsSync(music) || !fs.statSync(music).isFile())) throw new Error(`không thấy file nhạc ${input.music}`);
- const info = await checkMedia(video, music);
- const content = String(input.content || '').slice(0, 2000);
- const target = parseTarget(input.target);
- if (target && target >= info.duration) throw Object.assign(new Error(`--target ${target} s không ngắn hơn video (${Math.round(info.duration)} s)`), { code: 400 });
- return writeJob(id, {
- status: 'queued', action: 'edit', step: null, stepIndex: -1, stepTotal: STEPS.length, pct: 0, note: '',
- source: video, sourceName: input.sourceName || path.basename(video), sourceSeconds: +info.duration.toFixed(2),
- style, music, musicName: input.musicName || (music ? path.basename(music) : null),
- content, names: parseNames(input.names), draft: !!input.draft, llm: input.llm === 'off' ? 'off' : 'on', target,
- createdAt: new Date().toISOString(), error: null, out: null, pid: process.pid,
- });
-}
-
-/** --target (giây của short muốn ra): rỗng → null; số nguyên 15–180, sai → throw 400. */
-export function parseTarget(v) {
- if (v === undefined || v === null || v === '' || v === false) return null;
- const n = Number(v);
- if (!Number.isFinite(n) || n < 15 || n > 180) throw Object.assign(new Error('target phải là số giây 15–180 (vd 45)'), { code: 400 });
- return Math.round(n);
-}
-
-// ---- khoá toàn máy ------------------------------------------------------------------------------------------------
-function tryCreate(file, data) {
- try { fs.writeFileSync(file, data, { flag: 'wx' }); return true; } catch (e) { if (e.code === 'EEXIST') return false; throw e; }
-}
-/** Gỡ khoá của tiến trình đã chết, dưới khoá phụ "wx" (chỉ 1 tiến trình được gỡ, và chỉ gỡ đúng khoá đã thấy là chết). */
-function breakStaleLock(seen) {
- if (!tryCreate(BREAKER, JSON.stringify({ pid: process.pid, at: Date.now() }))) {
- const b = readJson(BREAKER);
- if (!b || (!pidAlive(b.pid) && Date.now() - (b.at || 0) > 5000)) { try { fs.unlinkSync(BREAKER); } catch { /* người khác vừa gỡ */ } }
- return;
- }
- try {
- const again = readJson(LOCK);
- if (again && again.pid === seen.pid && again.at === seen.at && !pidAlive(again.pid)) fs.unlinkSync(LOCK);
- } catch { /* đã bị gỡ */ } finally { try { fs.unlinkSync(BREAKER); } catch { /* bỏ qua */ } }
-}
-export async function withLock(id, fn) {
- fs.mkdirSync(EDITS, { recursive: true });
- const me = { pid: process.pid, id, at: Date.now() };
- while (!tryCreate(LOCK, JSON.stringify(me))) {
- const cur = readJson(LOCK);
- if (cur && !pidAlive(cur.pid)) breakStaleLock(cur);
- else await new Promise((r) => setTimeout(r, 2000));
- }
- try { return await fn(); } finally {
- try { const cur = readJson(LOCK); if (cur?.pid === me.pid && cur?.at === me.at) fs.unlinkSync(LOCK); } catch { /* bỏ qua */ }
- }
-}
-/** Edit đang chiếm khoá (nếu có). */
-export function editLockHolder() { const cur = readJson(LOCK); return cur && pidAlive(cur.pid) ? cur : null; }
-
-const onProgress = (id) => (p) => writeJob(id, { step: p.step, stepIndex: p.index, stepTotal: p.total, pct: p.pct, note: p.note || '' });
-
-// ---- dọn đĩa ---------------------------------------------------------------------------------------------------------
-/**
- * Xong 1 lượt (dù được hay lỗi): xoá file trung gian lớn, chỉ giữ nguồn, edl, out*, phụ đề (index.html), log và
- * các JSON nhỏ (phân tích, chép lời, mặt) để sửa bằng lời không phải phân tích lại. Proxy dựng lại từ nguồn khi cần.
- * Giữ cho chỉnh tay: video nền (base.mp4), lớp chữ trong suốt, bản trộn tiếng (audio/mix.wav) — chỉnh nhạc thì
- * chỉ trộn lại tiếng, chỉnh chữ thì chỉ render lại lớp chữ, không phải cắt lại nền.
- */
-export function cleanupEdit(id) {
- const dir = editDir(id);
- let freed = 0;
- const rm = (rel) => {
- const f = path.join(dir, rel);
- try {
- const st = fs.statSync(f);
- freed += st.isDirectory() ? dirBytes(f) : st.size;
- fs.rmSync(f, { recursive: true, force: true });
- } catch { /* không có */ }
- };
- for (const f of ['proxy.mov', 'base.words.json', 'base.face.json', path.join('captions', 'lib'), 'qc.jpg', 'proxy.mov.part']) rm(f);
- for (const f of ['captions.webm', 'captions.mov', 'captions-png']) if (f !== LAYER.file) rm(f); // lớp chữ định dạng khác
- try { for (const f of fs.readdirSync(path.join(dir, 'audio'))) if (f !== 'mix.wav') rm(path.join('audio', f)); } catch { /* chưa có */ }
- try { for (const f of fs.readdirSync(dir)) if (/\.part\.mp4$|\.tmp$/.test(f)) rm(f); } catch { /* bỏ qua */ }
- return freed;
-}
-function dirBytes(d) {
- let n = 0;
- for (const e of fs.readdirSync(d, { withFileTypes: true })) {
- const f = path.join(d, e.name);
- n += e.isDirectory() ? dirBytes(f) : fs.statSync(f).size;
- }
- return n;
-}
-
-/** Xoá hẳn 1 edit (thư mục edits/<id>). Đang chạy → throw. */
-export function deleteEdit(id) {
- if (!ID_RE.test(String(id))) throw new Error('id không hợp lệ');
- const job = readEditJob(id);
- if (!job) throw new Error('không thấy edit ' + id);
- if (['queued', 'running'].includes(job.status)) throw Object.assign(new Error('edit này đang chạy, chờ xong rồi xoá'), { code: 409 });
- const dir = editDir(id);
- if (path.dirname(dir) !== EDITS) throw new Error('đường dẫn lạ');
- fs.rmSync(dir, { recursive: true, force: true });
- return true;
-}
-
-// ---- chạy ------------------------------------------------------------------------------------------------------------
-/** Chạy dựng lần đầu (chờ khoá). log: hàm in dòng (mặc định im lặng). */
-export async function runEditJob(id, { log = () => {} } = {}) {
- const job = readEditJob(id);
- if (!job) throw new Error('không thấy edit ' + id);
- writeJob(id, { status: 'queued', action: 'edit', error: null, pid: process.pid });
- return withLock(id, async () => {
- writeJob(id, { status: 'running', startedAt: new Date().toISOString(), pid: process.pid });
- let r;
- try {
- r = await editVideo(job.source, {
- id, style: job.style, music: job.music, content: job.content, names: job.names, draft: job.draft, llm: job.llm, target: job.target, log, progress: onProgress(id),
- });
- } catch (e) { r = { ok: false, id, error: e.message }; }
- const freed = cleanupEdit(id);
- writeJob(id, r.ok ? { status: 'done', out: r.out, pct: 100, error: null, freedBytes: freed } : { status: 'error', error: r.error, freedBytes: freed });
- return r;
- });
-}
-
-/**
- * Sửa bằng lời rồi render lại. Kiểm đầu vào NGAY (throw đồng bộ: REST trả 4xx), rồi trả Promise chạy nền.
- * Lỗi lúc chạy thì bản cũ vẫn giữ (status về done, ghi reviseError).
- */
-export function reviseEditJob(id, instruction, { log = () => {} } = {}) {
- const job = readEditJob(id);
- if (!job) throw Object.assign(new Error('không thấy edit ' + id), { code: 404 });
- if (['queued', 'running'].includes(job.status)) throw Object.assign(new Error('edit này đang chạy, chờ xong rồi sửa'), { code: 409 });
- if (!fs.existsSync(path.join(editDir(id), 'state.json'))) throw Object.assign(new Error('edit này chưa dựng xong lần đầu'), { code: 409 });
- const text = String(instruction || '').trim();
- if (!text) throw Object.assign(new Error('thiếu lời sửa'), { code: 400 });
- if (text.length > 1000) throw Object.assign(new Error('lời sửa quá dài (tối đa 1000 ký tự)'), { code: 413 });
- writeJob(id, { status: 'queued', action: 'revise', instruction: text, reviseError: null, pid: process.pid });
- return withLock(id, async () => {
- writeJob(id, { status: 'running', startedAt: new Date().toISOString(), stepIndex: 2, pid: process.pid });
- let r;
- try { r = await reviseEdit(id, text, { log, progress: onProgress(id) }); } catch (e) { r = { ok: false, id, error: e.message }; }
- const freed = cleanupEdit(id);
- const hasOut = !!currentOut(id);
- writeJob(id, r.ok ? { status: 'done', out: r.out, pct: 100, reviseError: null, freedBytes: freed }
- : { status: hasOut ? 'done' : 'error', reviseError: r.error, error: hasOut ? null : r.error, freedBytes: freed });
- return r;
- });
-}
-
-/** Tên gốc của file nhạc tải lên cho chỉnh tay: edits/<id>/uploads.json {music-up-<n>.<ext>: tên gốc}. */
-export function musicUploads(id) { return readJson(path.join(editDir(id), 'uploads.json'), {}); }
-export function addMusicUpload(id, file, name) {
- const all = musicUploads(id); all[file] = String(name || file).slice(0, 120);
- fs.writeFileSync(path.join(editDir(id), 'uploads.json'), JSON.stringify(all, null, 1));
- return all;
-}
-
-/** Những gì chỉnh tay được (bảng phụ đề, nhạc, giọng, sfx, zoom, đồ hoạ) của bản hiện tại. null nếu chưa dựng xong. */
-export function manualState(id) {
- if (!ID_RE.test(String(id))) return null;
- const dir = editDir(id);
- const edl = readJson(path.join(dir, 'edl.json')); const state = readJson(path.join(dir, 'state.json'));
- if (!edl || !state) return null;
- const lookNames = Object.fromEntries(editStyles().map((s) => [s.id, { name: s.name, nameEn: s.nameEn }]));
- return manualView(edl, state, { lookNames, uploads: musicUploads(id) });
-}
-
-/**
- * Chỉnh tay rồi dựng lại phần cần thiết. Kiểm đầu vào NGAY (schema chặt; throw đồng bộ → REST 4xx), rồi chạy nền.
- * Lỗi lúc chạy thì bản cũ vẫn giữ (status về done, ghi reviseError).
- */
-export function manualEditJob(id, body, { log = () => {} } = {}) {
- const job = readEditJob(id);
- if (!job) throw Object.assign(new Error('không thấy edit ' + id), { code: 404 });
- if (['queued', 'running'].includes(job.status)) throw Object.assign(new Error('edit này đang chạy, chờ xong rồi chỉnh'), { code: 409 });
- if (!fs.existsSync(path.join(editDir(id), 'state.json')) || !currentOut(id)) throw Object.assign(new Error('edit này chưa dựng xong lần đầu'), { code: 409 });
- const patch = parseManual(body);
- // thử áp lên EDL hiện tại ngay (zoom/đồ hoạ không có, dòng đè nhau, bản nháp, không đổi gì…) → 4xx đồng bộ, không xếp hàng
- const dir = editDir(id);
- const st = readJson(path.join(dir, 'state.json'), {});
- let style = null; try { style = loadStyle(st.style); } catch { /* kiểu đã xoá */ }
- applyPatch(readJson(path.join(dir, 'edl.json')), st, patch, { dir, style, uploads: musicUploads(id) });
- writeJob(id, { status: 'queued', action: 'manual', instruction: null, reviseError: null, pid: process.pid, stepFrom: patch.zooms?.remove?.length || patch.graphics?.remove?.length ? 4 : 5 });
- return withLock(id, async () => {
- writeJob(id, { status: 'running', startedAt: new Date().toISOString(), stepIndex: 4, pct: 0, pid: process.pid });
- let r;
- try { r = await manualEdit(id, patch, { log, progress: onProgress(id), uploads: musicUploads(id) }); } catch (e) { r = { ok: false, id, error: e.message }; }
- const freed = cleanupEdit(id);
- const hasOut = !!currentOut(id);
- writeJob(id, r.ok ? { status: 'done', out: r.out, pct: 100, reviseError: null, freedBytes: freed }
- : { status: hasOut ? 'done' : 'error', reviseError: r.error, error: hasOut ? null : r.error, freedBytes: freed });
- return r;
- });
-}
-
-/** Hồ sơ đầy đủ cho UI/MCP: trạng thái, tiến độ, link file, chữ LLM đã sửa, các lần sửa, log cuối. */
-export function editView(id, { withLog = true, urlBase = `/edits/${id}` } = {}) {
- const job = readEditJob(id);
- if (!job) return null;
- const dir = editDir(id);
- const has = (f) => fs.existsSync(path.join(dir, f));
- const result = readJson(path.join(dir, 'result.json'), {});
- const state = readJson(path.join(dir, 'state.json'), {});
- const stamp = (f) => { try { return Math.round(fs.statSync(path.join(dir, f)).mtimeMs); } catch { return 0; } };
- const outName = currentOut(id);
- const v = {
- ...job,
- styleName: (() => { try { return loadStyle(job.style).name; } catch { return job.style; } })(),
- steps: STEPS,
- fixes: result.checks?.fixes || [],
- revisions: (state.revisions || []).map((r) => ({ ...r, url: r.out && /^out-r\d{1,4}\.mp4$/.test(r.out) && has(r.out) ? `${urlBase}/${r.out}?v=${stamp(r.out)}` : null })),
- originalUrl: has('out.mp4') ? `${urlBase}/out.mp4?v=${stamp('out.mp4')}` : null,
- checks: result.checks || null,
- timings: result.timings || null,
- warnings: result.warnings || [],
- links: {
- out: outName ? `${urlBase}/${outName}?v=${stamp(outName)}` : null,
- preview: has('preview.jpg') ? `${urlBase}/preview.jpg?v=${stamp('preview.jpg')}` : null,
- previewFinal: has('preview-final.jpg') ? `${urlBase}/preview-final.jpg?v=${stamp('preview-final.jpg')}` : null,
- edl: has('edl.json') ? `${urlBase}/edl.json` : null,
- },
- files: { dir, out: outName ? path.join(dir, outName) : null, edl: has('edl.json') ? path.join(dir, 'edl.json') : null },
- };
- if (withLog) {
- try { v.log = fs.readFileSync(path.join(dir, 'log.txt'), 'utf8').trim().split(/\r?\n/).slice(-40); } catch { v.log = []; }
- }
- return v;
-}
-
-export function listEdits(limit = 50) {
- if (!fs.existsSync(EDITS)) return [];
- return fs.readdirSync(EDITS).filter((d) => ID_RE.test(d) && fs.existsSync(jobFile(d)))
- .sort().reverse().slice(0, limit).map((id) => editView(id, { withLog: false })).filter(Boolean);
-}
-
-/** Server khởi động: quét mọi edit để job của tiến trình đã chết được chuyển trạng thái (readEditJob tự làm). */
-export function markStaleEdits() { listEdits(500); }
+// Việc Edit video dùng chung cho REST (server), MCP và CLI: hồ sơ edits/<id>/job.json, tiến độ, hàng chờ, dọn đĩa.
+// Mỗi lúc chỉ 1 edit chạy trên cả máy (khoá file edits/.edit.lock tạo độc quyền "wx", có pid; khoá của tiến trình
+// đã chết được gỡ dưới một khoá phụ cũng "wx" nên hai tiến trình không thể cùng gỡ/cùng giữ).
+import fs from 'node:fs';
+import path from 'node:path';
+import { EDITS, editDir, newEditId, editVideo, reviseEdit, manualEdit, STEPS, baseSig } from './pipeline.mjs';
+import { parseManual, manualView, applyPatch } from './manual.mjs';
+import { isMusicName } from './studio-media.mjs';
+import { LAYER } from './captions-hf.mjs';
+import { listStyles, loadStyle, parseNames, STYLES_DIR } from './planner.mjs';
+import { setupStatus } from './env.mjs';
+import { resolveEditStyle } from '../packs/registry.mjs';
+import { probeSource } from './ingest.mjs';
+
+export { STEPS, EDITS, newEditId, editDir };
+export const ID_RE = /^[\w-]{1,80}$/;
+const LOCK = path.join(EDITS, '.edit.lock');
+const BREAKER = path.join(EDITS, '.edit.lock.break');
+const readJson = (f, d = null) => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return d; } };
+export const pidAlive = (pid) => { if (!Number.isInteger(pid) || pid <= 0) return false; try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
+const jobFile = (id) => path.join(editDir(id), 'job.json');
+
+/** Tên file MP4 mới nhất (out.mp4 hoặc out-r<n>.mp4 sau mỗi lần sửa), null nếu chưa có. */
+export function currentOut(id) {
+ const st = readJson(path.join(editDir(id), 'state.json'), {});
+ for (const f of [st.out, 'out.mp4']) if (f && /^out(-r\d{1,4})?\.mp4$/.test(f) && fs.existsSync(path.join(editDir(id), f))) return f;
+ return null;
+}
+
+function writeJob(id, patch) {
+ const cur = readJson(jobFile(id), {});
+ const next = { ...cur, ...patch, id, updatedAt: new Date().toISOString() };
+ fs.mkdirSync(editDir(id), { recursive: true });
+ const tmp = jobFile(id) + `.${process.pid}.tmp`;
+ fs.writeFileSync(tmp, JSON.stringify(next, null, 1));
+ fs.renameSync(tmp, jobFile(id));
+ return next;
+}
+
+/**
+ * Job "queued"/"running" mà tiến trình giữ nó đã chết (CLI/MCP bị tắt, máy khởi động lại) → tự chuyển sang
+ * error (dựng lần đầu) hoặc done + reviseError (sửa, bản cũ vẫn còn), kèm lý do. Gọi ở mọi lần đọc.
+ */
+function reapIfDead(job) {
+ if (!job || !['queued', 'running'].includes(job.status) || pidAlive(job.pid)) return job;
+ const why = `bị ngắt giữa chừng (tiến trình ${job.pid || '?'} đã tắt lúc "${job.step || 'chờ lượt'}")`;
+ if (['revise', 'manual'].includes(job.action) && currentOut(job.id)) return writeJob(job.id, { status: 'done', reviseError: why + ' — bấm Render lại' });
+ return writeJob(job.id, { status: 'error', error: why + ' — bấm Dựng lại' });
+}
+
+export function readEditJob(id) {
+ if (!ID_RE.test(String(id))) return null;
+ return reapIfDead(readJson(jobFile(id)));
+}
+
+/** Ảnh minh hoạ dọc của từng kiểu (khung từ bản demo), server phục vụ ở /edit-styles/thumbs/<id>.webp. */
+export const STYLE_THUMBS = path.join(STYLES_DIR, 'thumbs');
+
+/** Kiểu edit có sẵn (cho UI/MCP): tên + tóm tắt VI/EN, ảnh minh hoạ (nếu có), màu nhấn, độ dài mặc định. */
+export function editStyles() {
+ return listStyles().map((id) => {
+ const s = loadStyle(id);
+ const builtin = (s.source || 'builtin') === 'builtin';
+ // ảnh của cách dựng trong gói: packs/http.mjs phục vụ ở /pack-thumbs/<packId>/edit-style-<slug>.webp
+ const r = builtin ? null : resolveEditStyle(id);
+ const thumb = builtin ? (fs.existsSync(path.join(STYLE_THUMBS, `${id}.webp`)) ? `/edit-styles/thumbs/${id}.webp` : null)
+ : r?.thumbFile ? `/pack-thumbs/${r.packId}/edit-style-${r.slug}.webp` : null;
+ return {
+ id, source: s.source || 'builtin', ...(r ? { packId: r.packId, restricted: true } : {}), order: builtin ? (s.order ?? 99) : 200 + (Number(s.order) || 0), name: s.name, nameEn: s.nameEn || s.name,
+ summary: s.summary || s.guide.split('\n').find((l) => l.trim() && !l.startsWith('#')) || '', summaryEn: s.summaryEn || '',
+ thumb, accent: s.graphics?.accent || s.look?.hi || null, target: s.target ?? null,
+ };
+ }).sort((a, b) => a.order - b.order);
+}
+
+/** Đã cài đủ chưa (python, gói, model whisper, model mặt/người, font). UI hiện hướng dẫn cài nếu chưa. */
+export function editReady() {
+ const st = setupStatus();
+ return {
+ ready: st.ready, missing: st.missing, setup: 'node edit/setup.mjs',
+ note: st.ready ? '' : `Chưa cài đủ phần Edit video (thiếu: ${st.missing.join(', ')}). Cần Python 3.10–3.12, ~6 GB gồm whisper large-v3. Chạy trong thư mục LumReels: node edit/setup.mjs`,
+ };
+}
+
+/** ffprobe ngay khi tạo: video phải có hình + độ dài > 0; nhạc phải có tiếng. Lỗi → throw (chưa chạy whisper/LLM). */
+export async function checkMedia(video, music) {
+ let info;
+ try { info = await probeSource(video); } catch (e) { throw new Error(`không đọc được video (${path.basename(video)}): ${e.message}`); }
+ if (!Number.isFinite(info.duration) || info.duration < 1) throw new Error('video quá ngắn hoặc hỏng (dưới 1 giây)');
+ if (!info.hasAudio) throw new Error('video không có tiếng: cần tiếng nói để cắt và làm phụ đề');
+ if (info.duration > 30 * 60) throw new Error(`video dài ${Math.round(info.duration / 60)} phút; tối đa 30 phút`);
+ if (music) await checkMusic(music);
+ return info;
+}
+
+/** File nhạc phải có luồng tiếng đọc được (ffprobe). Lỗi → throw. */
+export async function checkMusic(music) {
+ const { run } = await import('../engine/lib.mjs');
+ const r = await run('ffprobe', ['-v', 'error', '-select_streams', 'a:0', '-show_entries', 'stream=codec_type:format=duration', '-of', 'json', music]);
+ let j = null; try { j = JSON.parse(r.out); } catch { /* bỏ qua */ }
+ if (!j?.streams?.length) throw new Error(`file nhạc ${path.basename(music)} không có tiếng hoặc hỏng`);
+}
+
+/**
+ * Tạo hồ sơ edit (chưa chạy). input: {id?, video, style, music?, musicName?, content?, names?, draft?, llm?, sourceName?}
+ * Kiểm kiểu edit, file và ffprobe trước khi ghi job.json.
+ */
+export async function createEdit(input) {
+ const id = input.id || newEditId();
+ if (!ID_RE.test(id)) throw new Error('id không hợp lệ');
+ const video = path.resolve(String(input.video || ''));
+ if (!input.video || !fs.existsSync(video) || !fs.statSync(video).isFile()) throw new Error(`không thấy video ${input.video || ''}`);
+ const style = String(input.style || 'sach-gon');
+ if (!listStyles().includes(style)) throw new Error(`không có kiểu edit "${style}" (có: ${listStyles().join(', ')})`);
+ const music = input.music ? path.resolve(String(input.music)) : null;
+ if (music && (!fs.existsSync(music) || !fs.statSync(music).isFile())) throw new Error(`không thấy file nhạc ${input.music}`);
+ const info = await checkMedia(video, music);
+ const content = String(input.content || '').slice(0, 2000);
+ const target = parseTarget(input.target);
+ if (target && target >= info.duration) throw Object.assign(new Error(`--target ${target} s không ngắn hơn video (${Math.round(info.duration)} s)`), { code: 400 });
+ return writeJob(id, {
+ status: 'queued', action: 'edit', step: null, stepIndex: -1, stepTotal: STEPS.length, pct: 0, note: '',
+ source: video, sourceName: input.sourceName || path.basename(video), sourceSeconds: +info.duration.toFixed(2),
+ style, music, musicName: input.musicName || (music ? path.basename(music) : null),
+ content, names: parseNames(input.names), draft: !!input.draft, llm: input.llm === 'off' ? 'off' : 'on', target, noMusic: !music && !!input.noMusic,
+ createdAt: new Date().toISOString(), error: null, out: null, pid: process.pid,
+ });
+}
+
+/** --target (giây của short muốn ra): rỗng → null; số nguyên 15–180, sai → throw 400. */
+export function parseTarget(v) {
+ if (v === undefined || v === null || v === '' || v === false) return null;
+ const n = Number(v);
+ if (!Number.isFinite(n) || n < 15 || n > 180) throw Object.assign(new Error('target phải là số giây 15–180 (vd 45)'), { code: 400 });
+ return Math.round(n);
+}
+
+// ---- khoá toàn máy ------------------------------------------------------------------------------------------------
+function tryCreate(file, data) {
+ try { fs.writeFileSync(file, data, { flag: 'wx' }); return true; } catch (e) { if (e.code === 'EEXIST') return false; throw e; }
+}
+/** Gỡ khoá của tiến trình đã chết, dưới khoá phụ "wx" (chỉ 1 tiến trình được gỡ, và chỉ gỡ đúng khoá đã thấy là chết). */
+function breakStaleLock(seen) {
+ if (!tryCreate(BREAKER, JSON.stringify({ pid: process.pid, at: Date.now() }))) {
+ const b = readJson(BREAKER);
+ if (!b || (!pidAlive(b.pid) && Date.now() - (b.at || 0) > 5000)) { try { fs.unlinkSync(BREAKER); } catch { /* người khác vừa gỡ */ } }
+ return;
+ }
+ try {
+ const again = readJson(LOCK);
+ if (again && again.pid === seen.pid && again.at === seen.at && !pidAlive(again.pid)) fs.unlinkSync(LOCK);
+ } catch { /* đã bị gỡ */ } finally { try { fs.unlinkSync(BREAKER); } catch { /* bỏ qua */ } }
+}
+export async function withLock(id, fn) {
+ fs.mkdirSync(EDITS, { recursive: true });
+ const me = { pid: process.pid, id, at: Date.now() };
+ while (!tryCreate(LOCK, JSON.stringify(me))) {
+ const cur = readJson(LOCK);
+ if (cur && !pidAlive(cur.pid)) breakStaleLock(cur);
+ else await new Promise((r) => setTimeout(r, 2000));
+ }
+ try { return await fn(); } finally {
+ try { const cur = readJson(LOCK); if (cur?.pid === me.pid && cur?.at === me.at) fs.unlinkSync(LOCK); } catch { /* bỏ qua */ }
+ }
+}
+/** Edit đang chiếm khoá (nếu có). */
+export function editLockHolder() { const cur = readJson(LOCK); return cur && pidAlive(cur.pid) ? cur : null; }
+
+const onProgress = (id) => (p) => writeJob(id, { step: p.step, stepIndex: p.index, stepTotal: p.total, pct: p.pct, note: p.note || '' });
+
+// ---- dọn đĩa ---------------------------------------------------------------------------------------------------------
+/**
+ * Xong 1 lượt (dù được hay lỗi): xoá file trung gian lớn, chỉ giữ nguồn, edl, out*, phụ đề (index.html), log và
+ * các JSON nhỏ (phân tích, chép lời, mặt) để sửa bằng lời không phải phân tích lại. Proxy dựng lại từ nguồn khi cần.
+ * Giữ cho chỉnh tay: video nền (base.mp4), lớp chữ trong suốt, bản trộn tiếng (audio/mix.wav) — chỉnh nhạc thì
+ * chỉ trộn lại tiếng, chỉnh chữ thì chỉ render lại lớp chữ, không phải cắt lại nền.
+ */
+export function cleanupEdit(id) {
+ const dir = editDir(id);
+ let freed = 0;
+ const rm = (rel) => {
+ const f = path.join(dir, rel);
+ try {
+ const st = fs.statSync(f);
+ freed += st.isDirectory() ? dirBytes(f) : st.size;
+ fs.rmSync(f, { recursive: true, force: true });
+ } catch { /* không có */ }
+ };
+ for (const f of ['proxy.mov', 'base.words.json', 'base.face.json', path.join('captions', 'lib'), 'qc.jpg', 'proxy.mov.part']) rm(f);
+ for (const f of ['captions.webm', 'captions.mov', 'captions-png']) if (f !== LAYER.file) rm(f); // lớp chữ định dạng khác
+ try { for (const f of fs.readdirSync(path.join(dir, 'audio'))) if (f !== 'mix.wav') rm(path.join('audio', f)); } catch { /* chưa có */ }
+ try { for (const f of fs.readdirSync(dir)) if (/\.part\.mp4$|\.tmp$/.test(f)) rm(f); } catch { /* bỏ qua */ }
+ return freed;
+}
+function dirBytes(d) {
+ let n = 0;
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
+ const f = path.join(d, e.name);
+ n += e.isDirectory() ? dirBytes(f) : fs.statSync(f).size;
+ }
+ return n;
+}
+
+/** Xoá hẳn 1 edit (thư mục edits/<id>). Đang chạy → throw. */
+export function deleteEdit(id) {
+ if (!ID_RE.test(String(id))) throw new Error('id không hợp lệ');
+ const job = readEditJob(id);
+ if (!job) throw new Error('không thấy edit ' + id);
+ if (['queued', 'running'].includes(job.status)) throw Object.assign(new Error('edit này đang chạy, chờ xong rồi xoá'), { code: 409 });
+ const dir = editDir(id);
+ if (path.dirname(dir) !== EDITS) throw new Error('đường dẫn lạ');
+ fs.rmSync(dir, { recursive: true, force: true });
+ return true;
+}
+
+// ---- chạy ------------------------------------------------------------------------------------------------------------
+/** Chạy dựng lần đầu (chờ khoá). log: hàm in dòng (mặc định im lặng). */
+export async function runEditJob(id, { log = () => {} } = {}) {
+ const job = readEditJob(id);
+ if (!job) throw new Error('không thấy edit ' + id);
+ writeJob(id, { status: 'queued', action: 'edit', error: null, pid: process.pid });
+ return withLock(id, async () => {
+ writeJob(id, { status: 'running', startedAt: new Date().toISOString(), pid: process.pid });
+ let r;
+ try {
+ r = await editVideo(job.source, {
+ id, style: job.style, music: job.music, noMusic: !!job.noMusic, content: job.content, names: job.names, draft: job.draft, llm: job.llm, target: job.target, log, progress: onProgress(id),
+ });
+ } catch (e) { r = { ok: false, id, error: e.message }; }
+ const freed = cleanupEdit(id);
+ writeJob(id, r.ok ? { status: 'done', out: r.out, pct: 100, error: null, freedBytes: freed } : { status: 'error', error: r.error, freedBytes: freed });
+ return r;
+ });
+}
+
+/**
+ * Sửa bằng lời rồi render lại. Kiểm đầu vào NGAY (throw đồng bộ: REST trả 4xx), rồi trả Promise chạy nền.
+ * Lỗi lúc chạy thì bản cũ vẫn giữ (status về done, ghi reviseError).
+ */
+export function reviseEditJob(id, instruction, { log = () => {} } = {}) {
+ const job = readEditJob(id);
+ if (!job) throw Object.assign(new Error('không thấy edit ' + id), { code: 404 });
+ if (['queued', 'running'].includes(job.status)) throw Object.assign(new Error('edit này đang chạy, chờ xong rồi sửa'), { code: 409 });
+ if (!fs.existsSync(path.join(editDir(id), 'state.json'))) throw Object.assign(new Error('edit này chưa dựng xong lần đầu'), { code: 409 });
+ const text = String(instruction || '').trim();
+ if (!text) throw Object.assign(new Error('thiếu lời sửa'), { code: 400 });
+ if (text.length > 1000) throw Object.assign(new Error('lời sửa quá dài (tối đa 1000 ký tự)'), { code: 413 });
+ writeJob(id, { status: 'queued', action: 'revise', instruction: text, reviseError: null, pid: process.pid });
+ return withLock(id, async () => {
+ writeJob(id, { status: 'running', startedAt: new Date().toISOString(), stepIndex: 2, pid: process.pid });
+ let r;
+ try { r = await reviseEdit(id, text, { log, progress: onProgress(id) }); } catch (e) { r = { ok: false, id, error: e.message }; }
+ const freed = cleanupEdit(id);
+ const hasOut = !!currentOut(id);
+ writeJob(id, r.ok ? { status: 'done', out: r.out, pct: 100, reviseError: null, freedBytes: freed }
+ : { status: hasOut ? 'done' : 'error', reviseError: r.error, error: hasOut ? null : r.error, freedBytes: freed });
+ return r;
+ });
+}
+
+/** Tên gốc của file nhạc tải lên cho chỉnh tay: edits/<id>/uploads.json {music-up-<n>.<ext>: tên gốc}. */
+export function musicUploads(id) { return readJson(path.join(editDir(id), 'uploads.json'), {}); }
+export function addMusicUpload(id, file, name) {
+ const all = musicUploads(id); all[file] = String(name || file).slice(0, 120);
+ fs.writeFileSync(path.join(editDir(id), 'uploads.json'), JSON.stringify(all, null, 1));
+ return all;
+}
+
+/**
+ * Những gì chỉnh tay được (bảng phụ đề, nhạc, giọng, sfx, zoom, đồ hoạ) của bản hiện tại. null nếu chưa dựng xong.
+ * rev (số bản, 0 = bản gốc out.mp4): xem lại bản cũ, chỉ đọc (EDL lấy từ versions/edl-<rev+1>.json).
+ * Kèm media cho Studio: video nền không chữ (base.mp4, khi chữ ký nền khớp EDL) để vẽ phụ đề xem trước, file nhạc, các bản.
+ */
+export function manualState(id, rev = null) {
+ if (!ID_RE.test(String(id))) return null;
+ const dir = editDir(id);
+ const state = readJson(path.join(dir, 'state.json'));
+ let edl = readJson(path.join(dir, 'edl.json'));
+ if (!edl || !state) return null;
+ const revs = state.revisions || [];
+ const latest = revs.length;
+ let n = latest;
+ if (rev !== null && rev !== undefined && rev !== '') {
+ n = Number(rev);
+ if (!Number.isInteger(n) || n < 0 || n > latest) throw Object.assign(new Error(`không có bản r${rev} (có r0–r${latest})`), { code: 404 });
+ if (n < latest) {
+ edl = readJson(path.join(dir, 'versions', `edl-${n + 1}.json`));
+ if (!edl) throw Object.assign(new Error(`bản r${n} không còn EDL`), { code: 404 });
+ }
+ }
+ const lookNames = Object.fromEntries(editStyles().map((s) => [s.id, { name: s.name, nameEn: s.nameEn }]));
+ const v = manualView(edl, state, { lookNames, uploads: musicUploads(id) });
+ const has = (f) => fs.existsSync(path.join(dir, f));
+ const stamp = (f) => { try { return Math.round(fs.statSync(path.join(dir, f)).mtimeMs); } catch { return 0; } };
+ const url = (f) => `/edits/${id}/${f}?v=${stamp(f)}`;
+ const outOf = (k) => (k === 0 ? 'out.mp4' : revs[k - 1]?.out);
+ const sig = readJson(path.join(dir, 'render.sig.json'), {});
+ const baseOk = n === latest && has('base.mp4') && sig.base === baseSig(edl, state.draft);
+ const mf = edl.music?.file && path.dirname(path.resolve(edl.music.file)) === path.resolve(dir) && isMusicName(path.basename(edl.music.file)) ? path.basename(edl.music.file) : null;
+ v.rev = n; v.latest = latest; v.readOnly = n !== latest;
+ v.media = {
+ out: outOf(n) && has(outOf(n)) ? url(outOf(n)) : null, outName: outOf(n) || null,
+ base: baseOk ? url('base.mp4') : null, music: mf && has(mf) ? url(mf) : null, musicFile: mf && has(mf) ? mf : null,
+ };
+ v.versions = [{ n: 0, out: has('out.mp4') ? 'out.mp4' : null }, ...revs.map((r) => ({ n: r.n, out: r.out && has(r.out) ? r.out : null, manual: !!r.manual, instruction: r.instruction || '', at: r.at || null }))];
+ return v;
+}
+
+/**
+ * Chỉnh tay rồi dựng lại phần cần thiết. Kiểm đầu vào NGAY (schema chặt; throw đồng bộ → REST 4xx), rồi chạy nền.
+ * Lỗi lúc chạy thì bản cũ vẫn giữ (status về done, ghi reviseError).
+ */
+export function manualEditJob(id, body, { log = () => {} } = {}) {
+ const job = readEditJob(id);
+ if (!job) throw Object.assign(new Error('không thấy edit ' + id), { code: 404 });
+ if (['queued', 'running'].includes(job.status)) throw Object.assign(new Error('edit này đang chạy, chờ xong rồi chỉnh'), { code: 409 });
+ if (!fs.existsSync(path.join(editDir(id), 'state.json')) || !currentOut(id)) throw Object.assign(new Error('edit này chưa dựng xong lần đầu'), { code: 409 });
+ const patch = parseManual(body);
+ // thử áp lên EDL hiện tại ngay (zoom/đồ hoạ không có, dòng đè nhau, bản nháp, không đổi gì…) → 4xx đồng bộ, không xếp hàng
+ const dir = editDir(id);
+ const st = readJson(path.join(dir, 'state.json'), {});
+ let style = null; try { style = loadStyle(st.style); } catch { /* kiểu đã xoá */ }
+ applyPatch(readJson(path.join(dir, 'edl.json')), st, patch, { dir, style, uploads: musicUploads(id) });
+ writeJob(id, { status: 'queued', action: 'manual', instruction: null, reviseError: null, pid: process.pid, stepFrom: patch.zooms || patch.graphics ? 4 : 5 });
+ return withLock(id, async () => {
+ writeJob(id, { status: 'running', startedAt: new Date().toISOString(), stepIndex: 4, pct: 0, pid: process.pid });
+ let r;
+ try { r = await manualEdit(id, patch, { log, progress: onProgress(id), uploads: musicUploads(id) }); } catch (e) { r = { ok: false, id, error: e.message }; }
+ const freed = cleanupEdit(id);
+ const hasOut = !!currentOut(id);
+ writeJob(id, r.ok ? { status: 'done', out: r.out, pct: 100, reviseError: null, freedBytes: freed }
+ : { status: hasOut ? 'done' : 'error', reviseError: r.error, error: hasOut ? null : r.error, freedBytes: freed });
+ return r;
+ });
+}
+
+/** Hồ sơ đầy đủ cho UI/MCP: trạng thái, tiến độ, link file, chữ LLM đã sửa, các lần sửa, log cuối. */
+export function editView(id, { withLog = true, urlBase = `/edits/${id}` } = {}) {
+ const job = readEditJob(id);
+ if (!job) return null;
+ const dir = editDir(id);
+ const has = (f) => fs.existsSync(path.join(dir, f));
+ const result = readJson(path.join(dir, 'result.json'), {});
+ const state = readJson(path.join(dir, 'state.json'), {});
+ const stamp = (f) => { try { return Math.round(fs.statSync(path.join(dir, f)).mtimeMs); } catch { return 0; } };
+ const outName = currentOut(id);
+ const v = {
+ ...job,
+ styleName: (() => { try { return loadStyle(job.style).name; } catch { return job.style; } })(),
+ steps: STEPS,
+ fixes: result.checks?.fixes || [],
+ revisions: (state.revisions || []).map((r) => ({ ...r, url: r.out && /^out-r\d{1,4}\.mp4$/.test(r.out) && has(r.out) ? `${urlBase}/${r.out}?v=${stamp(r.out)}` : null })),
+ originalUrl: has('out.mp4') ? `${urlBase}/out.mp4?v=${stamp('out.mp4')}` : null,
+ checks: result.checks || null,
+ timings: result.timings || null,
+ warnings: result.warnings || [],
+ links: {
+ out: outName ? `${urlBase}/${outName}?v=${stamp(outName)}` : null,
+ preview: has('preview.jpg') ? `${urlBase}/preview.jpg?v=${stamp('preview.jpg')}` : null,
+ previewFinal: has('preview-final.jpg') ? `${urlBase}/preview-final.jpg?v=${stamp('preview-final.jpg')}` : null,
+ edl: has('edl.json') ? `${urlBase}/edl.json` : null,
+ },
+ files: { dir, out: outName ? path.join(dir, outName) : null, edl: has('edl.json') ? path.join(dir, 'edl.json') : null },
+ };
+ if (withLog) {
+ try { v.log = fs.readFileSync(path.join(dir, 'log.txt'), 'utf8').trim().split(/\r?\n/).slice(-40); } catch { v.log = []; }
+ }
+ return v;
+}
+
+export function listEdits(limit = 50) {
+ if (!fs.existsSync(EDITS)) return [];
+ return fs.readdirSync(EDITS).filter((d) => ID_RE.test(d) && fs.existsSync(jobFile(d)))
+ .sort().reverse().slice(0, limit).map((id) => editView(id, { withLog: false })).filter(Boolean);
+}
+
+/** Server khởi động: quét mọi edit để job của tiến trình đã chết được chuyển trạng thái (readEditJob tự làm). */
+export function markStaleEdits() { listEdits(500); }
diff --git a/edit/manual.mjs b/edit/manual.mjs
index 00b1848..ac77971 100644
--- a/edit/manual.mjs
+++ b/edit/manual.mjs
@@ -1,296 +1,488 @@
-// 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, OUT } from './edl.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);
-
-export const ManualSchema = z.object({
- 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(),
- }).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(),
- sfx: z.object({ on: z.boolean() }).strict().optional(),
- zooms: z.object({ remove: z.array(z.number().int().min(0).max(999)).max(200) }).strict().optional(),
- graphics: z.object({ remove: z.array(z.string().min(1).max(80)).max(100) }).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;
-}
-
-/** 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 -------------------------------------------------------------------------------------------
-/** 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 musicName = !m ? null : man.musicName || (/music-([a-z0-9-]+)\.wav$/.test(m.file) ? `synth:${/music-([a-z0-9-]+)\.wav$/.exec(m.file)[1]}` : path.basename(m.file));
- return {
- duration: dur, draft: !!state.draft,
- captions: {
- lines: currentLines(edl).map((l) => ({ start: l.start, end: l.end, text: lineText(l.words) })),
- edited: !!edl.captions.lines, highlights: !edl.captions.hiOff, look: edl.captions.style,
- looks: LOOK_IDS.map((id) => ({ id, name: lookNames[id]?.name || id, nameEn: lookNames[id]?.nameEn || lookNames[id]?.name || id, hi: LOOKS[id].hi })),
- },
- music: {
- on: !!m, name: musicName, gainDb: m ? m.gainDb : (man.music?.gainDb ?? -22), duck: m ? m.duckDb > 0 : man.music?.duck !== false,
- 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 || '' })),
- };
-}
-
-// ---- á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;
-
- 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((l) => `${l.start}|${l.end}|${lineText(l.words)}`);
- const after = lines.map((l) => `${l.start}|${l.end}|${lineText(l.words)}`);
- const changed = after.filter((x) => !before.includes(x)).length + Math.max(0, before.length - after.length);
- 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.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])];
- 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?.remove?.length) {
- const idx = [...new Set(patch.zooms.remove)];
- const bad = idx.filter((n) => n >= edl.zooms.length);
- if (bad.length) throw httpErr(400, `không có zoom số ${bad.join(', ')} (có ${edl.zooms.length} zoom, đếm từ 0)`);
- const gone = idx.map((n) => edl.zooms[n]);
- edl.zooms = edl.zooms.filter((_, n) => !idx.includes(n));
- man.zoomsRemovedAt = [...new Set([...(man.zoomsRemovedAt || []), ...gone.map((zm) => zm.at)])];
- redo.base = true; summary.push(`xoá ${gone.length} zoom (${gone.map((zm) => `${toOutputNearest(timelineOf(edl), zm.at).toFixed(1)} s`).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');
- }
- 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 };
-}
-
-/**
- * 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.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));
- if (man.zoomsRemovedAt?.length) edl.zooms = edl.zooms.filter((zm) => !man.zoomsRemovedAt.some((a) => Math.abs(a - zm.at) < 0.02));
- 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 };
+// 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 } from './edl.mjs';
+import { outputToSource, layoutGraphics, MIN_GRAPHIC } from './graphics.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({
+ 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(),
+ }).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(),
+ 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;
+}
+
+/** 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: l.cy, karaoke: !!l.karaoke, 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 } : 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 musicName = !m ? null : man.musicName || (/music-([a-z0-9-]+)\.wav$/.test(m.file) ? `synth:${/music-([a-z0-9-]+)\.wav$/.exec(m.file)[1]}` : path.basename(m.file));
+ return {
+ duration: dur, draft: !!state.draft, cuts: cutsOf(edl),
+ captions: {
+ lines: currentLines(edl).map((l) => ({ start: l.start, end: l.end, text: lineText(l.words) })),
+ edited: !!edl.captions.lines, highlights: !edl.captions.hiOff, look: edl.captions.style,
+ 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'] };
+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 }) {
+ 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) return;
+ // đặ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ũ');
+}
+
+// ---- á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;
+
+ 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((l) => `${l.start}|${l.end}|${lineText(l.words)}`);
+ const after = lines.map((l) => `${l.start}|${l.end}|${lineText(l.words)}`);
+ const changed = after.filter((x) => !before.includes(x)).length + Math.max(0, before.length - after.length);
+ 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.graphics?.set?.length) applyGraphicsSet(edl, patch.graphics.set, { dur, dir, style, man, redo, summary, warnings });
+ 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 });
+ const errs = v.ok ? [] : v.errors.filter((e) => /^(zoom|graphic)/.test(e.code) || /^(zooms|graphics)/.test(e.path));
+ 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');
+ }
+ 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 };
+}
+
+/**
+ * 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.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 };
diff --git a/edit/pipeline.mjs b/edit/pipeline.mjs
index a7ea382..1e7deb3 100644
--- a/edit/pipeline.mjs
+++ b/edit/pipeline.mjs
@@ -1,599 +1,599 @@
-// LumReels Edit — luồng dựng video người dùng tự quay theo một thẻ kiểu edit.
-// 1 nạp (probe, băm, proxy CFR 30) 2 phân tích (whisper large-v3 tiếng Việt, khoảng lặng, mặt)
-// 3 LLM lập đề xuất → code dựng EDL → kiểm 4 xem trước lưới 16 khung
-// 5 render nền 1 lượt (cắt + reframe 9:16 + zoom; tiếng gốc nối 20 ms) + kiểm lẹm chữ (nghe lại)
-// 6 phụ đề: HyperFrames lớp trong suốt (bản chính) hoặc PIL vẽ thẳng (--draft)
-// 7 tiếng: giọng gốc + nhạc tự hạ + sfx → −14 LUFS 8 ghép → out.mp4 9 kiểm (qc-check + kích thước + lưới khung)
-// Sửa bằng lời (reviseEdit): LLM sửa đề xuất/cắt theo giây bản ra/núm kiểu → dựng lại EDL → bước 4–9. KHÔNG phân tích lại.
-// Đầu ra: edits/<id>/ (edl.json, preview.jpg, out.mp4, preview-final.jpg, qc.json, result.json, state.json, log.txt,
-// mỗi lần sửa n ra out-r<n>.mp4 MỚI (Windows khoá file đang phát nên không ghi đè), bản trước giữ nguyên,
-// versions/edl-<n>.json = EDL trước lần sửa n; state.json.out = tên file bản mới nhất)
-import fs from 'node:fs';
-import path from 'node:path';
-import crypto from 'node:crypto';
-import { run } from '../engine/lib.mjs';
-import { SFX_NAMES } from '../engine/audio/sfx.mjs';
-import { measureLoudness } from '../engine/audio/mix.mjs';
-import { ROOT, runLumedit } from './env.mjs';
-import { ingest, makeProxy } from './ingest.mjs';
-import {
- loadStyle, wordList, propose, compileEdl, parseNames, proposeRevision, applyOverrides, applyExtraCuts, outputCutToSource,
- callClaude, parseProposal, repairCuts, maxSecRequest,
-} from './planner.mjs';
-import { selectSegments, planGraphics, layoutGraphics, fillUnits, figureList, checkFigures, dropLowFigures } from './graphics.mjs';
-import { fmtVi } from './numbers.mjs';
-import { validateEdl, toOutputNearest, outputDuration, timelineOf, inKeep, OUT } from './edl.mjs';
-import { writeCaptionScene, renderCaptionLayer, captionTop, LAYER, layerInput } from './captions-hf.mjs';
-import { buildEditMix } from './audio.mjs';
-import { pickEncoder, videoArgs } from './encoder.mjs';
-import { applyPatch, applyManual } from './manual.mjs';
-
-export const EDITS = path.join(ROOT, 'edits');
-const wordKey = (w) => w.toLowerCase().normalize('NFC').replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, '');
-/** Các bước (để UI vẽ thanh tiến độ). Sửa bằng lời bắt đầu từ "LLM lập EDL". */
-export const STEPS = ['nạp', 'phân tích', 'LLM lập EDL', 'xem trước', 'render nền', 'phụ đề', 'tiếng', 'ghép', 'kiểm'];
-
-export function newEditId() {
- const d = new Date(); const p = (n) => String(n).padStart(2, '0');
- return `${String(d.getFullYear()).slice(2)}${p(d.getMonth() + 1)}${p(d.getDate())}${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}-${crypto.randomBytes(2).toString('hex')}`;
-}
-export const editDir = (id) => path.join(EDITS, id);
-const readJson = (f, d = null) => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return d; } };
-
-/** Bộ khung chung cho 1 lượt chạy: log, đo giờ từng bước, báo tiến độ. */
-function runner(dir, opts) {
- fs.mkdirSync(dir, { recursive: true });
- const logFile = path.join(dir, 'log.txt');
- const log = (s) => { const line = `[${new Date().toISOString().slice(11, 19)}] ${s}`; fs.appendFileSync(logFile, line + '\n'); (opts.log || console.log)(line); };
- const timings = {}; const checks = {}; const warnings = [];
- const progress = (step, pct = 0, note = '') => { try { opts.progress?.({ step, index: STEPS.indexOf(step), total: STEPS.length, pct, note }); } catch { /* bỏ qua */ } };
- const step = async (name, fn) => {
- const t = Date.now(); log(`— ${name}`); progress(name, 0);
- const r = await fn((pct, note) => progress(name, pct, note));
- const took = +((Date.now() - t) / 1000).toFixed(1);
- timings[name] = +((timings[name] || 0) + took).toFixed(1); log(` xong ${name}: ${took} s`); progress(name, 100); // bước chạy lại (sửa lẹm chữ) cộng dồn
- return r;
- };
- return { log, timings, checks, warnings, step };
-}
-
-/**
- * Dựng mới. opts: {style, music?, content?, names?, draft?, llm?: 'on'|'off', target?: giây, id?, log?, progress?}
- * target: clip nguồn dài → LLM chọn các đoạn hay nhất (hook … kết) ghép thành short ≈ target giây, rồi mới cắt ngập ngừng.
- * Trả {ok, id, dir, out, edl, timings, checks, warnings, error?}
- */
-export async function editVideo(video, opts = {}) {
- const id = opts.id || newEditId();
- const dir = editDir(id);
- const R = runner(dir, opts);
- const { log, timings, checks, warnings, step } = R;
- const result = { ok: false, id, dir, video: path.resolve(video), style: opts.style, draft: !!opts.draft, timings, checks, warnings };
- try {
- if (!fs.existsSync(video)) throw new Error(`không thấy video ${video}`);
- if (opts.music && !fs.existsSync(opts.music)) throw new Error(`không thấy file nhạc ${opts.music}`);
- const style = { ...loadStyle(opts.style || 'sach-gon'), sfxNames: SFX_NAMES };
- const names = parseNames(opts.names);
- log(`edit ${id}: ${path.basename(video)} · kiểu ${style.id}${opts.draft ? ' · bản nháp (phụ đề PIL)' : ''}${opts.music ? ' · nhạc ' + path.basename(opts.music) : ''}${names.length ? ' · tên riêng: ' + names.join(', ') : ''}`);
-
- const ing = await step('nạp', () => ingest(path.resolve(video), path.join(dir, 'proxy.mov'), { log }));
- fs.writeFileSync(path.join(dir, 'ingest.json'), JSON.stringify(ing, null, 1));
- (checks.encoders ||= {}).proxy = ing.encoder === 'gpu' ? 'h264_nvenc' : 'libx264';
-
- const analysisFile = path.join(dir, 'analysis.json');
- const an = await step('phân tích', async (pg) => {
- const r = await runLumedit(['analyze', ing.proxy.file, '--out', analysisFile], {
- onProgress: (p) => { log(` ${p.step}${p.note ? ': ' + p.note : ''}`); pg({ words: 10, quiet: 70, face: 80 }[p.step] ?? 50, p.step); },
- });
- if (!r.ok) throw new Error('phân tích lỗi: ' + r.error);
- checks.whisperDevice = r.result.device || null;
- return { ...r.result, data: JSON.parse(fs.readFileSync(analysisFile, 'utf8')) };
- });
- log(` ${an.words} chữ chắc + ${an.unsure} chữ không chắc · whisper ${an.seconds.words} s (${an.device || '?'}) · mặt ${an.seconds.face} s (thấy mặt ${Math.round(an.data.face.found_share * 100)}% khung)`);
- if (!an.words) throw new Error('không nghe được lời nào trong video');
-
- const words = wordList(an.data);
- style.hesitations = new Set(an.data.hesitations || []);
- // độ dài: --target của người dùng, không có thì theo thẻ kiểu (style.target; nguồn đã ngắn thì bỏ qua như cũ)
- const target = Number(opts.target) > 0 ? Math.round(Number(opts.target)) : Number(style.target) > 0 ? Math.round(style.target) : null;
- if (!(Number(opts.target) > 0) && target) log(` độ dài theo kiểu: ${target} s${style.maxSec ? ` (trần ${style.maxSec} s)` : ''}`);
- const llmOn = (opts.llm || 'on') !== 'off';
- let selection = null;
- const plan = await step('LLM lập EDL', async (pg) => {
- if (target && !llmOn) warnings.push('--target cần LLM: bỏ qua (LLM tắt)');
- else if (target && ing.source.duration < target * 1.15) log(` nguồn ${ing.source.duration.toFixed(0)} s đã gần ${target} s: không chọn đoạn`);
- else if (target) {
- pg(5, 'chọn đoạn hay');
- selection = await selectSegments({ words, target, style, content: opts.content, names, duration: ing.source.duration, callClaude, parse: parseProposal, log });
- warnings.push(...selection.warnings);
- log(` chọn ${selection.segments.length} đoạn ≈ ${selection.seconds.toFixed(1)} s nói: ${selection.segments.map((x) => `${x.role} ${words[x.from].s.toFixed(1)}–${words[x.to].e.toFixed(1)} s`).join(', ')}`);
- }
- pg(35, 'cắt ngập ngừng');
- const p = await propose({ words, style, content: opts.content, names, duration: ing.source.duration, llm: opts.llm || 'on', log, exclude: selection?.exclude });
- if (style.graphics && llmOn) {
- pg(70, 'kế hoạch đồ hoạ');
- const dropped = new Set(selection?.exclude || []);
- for (const d of p.proposal.drop) for (let i = d.from; i <= d.to; i++) dropped.add(i);
- if (style.cutFillers) for (const w of words) if (style.hesitations.has(wordKey(w.w))) dropped.add(w.i);
- const gp = await planGraphics({ words, dropped, style, content: opts.content, names, callClaude, parse: parseProposal, log });
- p.warnings.push(...gp.warnings);
- log(` đồ hoạ (vòng ${gp.rounds}): ${gp.graphics.map((g) => `${g.type}@${words[g.at].s.toFixed(1)}s`).join(', ') || 'không có'}`);
- pg(85, 'đơn vị + nghe lại số');
- const fc = await checkGraphicNumbers({ graphics: gp.graphics, words, proxy: ing.proxy.file, dir, log, warnings: p.warnings });
- p.graphics = fc.graphics; p.figures = fc.figures; p.units = fc.units;
- }
- return p;
- });
- fs.writeFileSync(path.join(dir, 'proposal.json'), JSON.stringify({ ...plan, words: words.map((w) => `${w.i}:${w.w}${w.unsure ? '?' : ''}`) }, null, 1));
- warnings.push(...plan.warnings);
- log(` đề xuất (vòng ${plan.rounds}): bỏ ${plan.proposal.drop.length} khoảng, ${plan.proposal.zooms.length} zoom, ${plan.proposal.highlights.length} chữ nhấn, ${plan.proposal.fixes.length} chữ sửa${plan.proposal.notes ? ' · ' + plan.proposal.notes : ''}`);
-
- // kiểu có nhạc mặc định (vd thong-tin-do-hoa: lofi nhẹ) mà người dùng không chọn nhạc → nhạc tổng hợp, lặp theo độ dài
- let music = opts.music ? path.resolve(opts.music) : null;
- if (!music && style.music?.default) {
- const { writeMusic, MUSIC_STYLES } = await import('../engine/audio/music.mjs');
- if (MUSIC_STYLES.includes(style.music.default)) { music = writeMusic(style.music.default, path.join(dir, `music-${style.music.default}.wav`), 60, 1); log(` nhạc nền mặc định của kiểu: ${style.music.default}`); }
- }
- const state = {
- version: 1, style: style.id, music, content: opts.content || '', names,
- draft: !!opts.draft, llm: opts.llm || 'on', proposal: plan.proposal, overrides: {}, extraCuts: [], revisions: [],
- target, segments: selection?.segments || null, exclude: selection ? [...selection.exclude] : [], graphics: plan.graphics || [],
- figures: plan.figures || [], units: plan.units || [], cutRepairs: [],
- };
- fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify(state, null, 1));
- let edl = await buildEdl({ id, dir, ing, analysis: an.data, words, style, state, checks, warnings, log });
- // kiểu có trần độ dài (maxSec, vd meo-15s 20 s): quá thì LLM sửa 1 vòng "bỏ thêm X giây"; vẫn quá thì chỉ cảnh báo
- const over = maxSecRequest(style, outputDuration(timelineOf(edl)));
- if (over && llmOn) {
- log(' ' + over);
- const p2 = await step('LLM lập EDL', () => propose({ words, style, content: opts.content, names, duration: ing.source.duration, llm: 'on', log, exclude: selection?.exclude,
- extra: `${over}\nĐề xuất trước: ${JSON.stringify(state.proposal)}` }));
- warnings.push(...p2.warnings);
- state.proposal = p2.proposal; state.maxSecRetry = { before: +outputDuration(timelineOf(edl)).toFixed(2) };
- edl = await buildEdl({ id, dir, ing, analysis: an.data, words, style, state, checks, warnings, log });
- state.maxSecRetry.after = +outputDuration(timelineOf(edl)).toFixed(2);
- fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify(state, null, 1));
- checks.maxSec = { max: style.maxSec, ...state.maxSecRetry };
- }
- const still = maxSecRequest(style, outputDuration(timelineOf(edl)));
- if (still) warnings.push(`bản ra ${outputDuration(timelineOf(edl)).toFixed(1)} s vẫn quá trần ${style.maxSec} s của kiểu ${style.id} (không tự cắt, cần người xem lại)`);
- const repair = cutRepairer({ id, dir, ing, analysis: an.data, words, style, state, checks, warnings, log });
- const r = await renderEdl({ dir, edl, draft: state.draft, R, outName: 'out.mp4', repair });
- fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify({ ...state, out: 'out.mp4' }, null, 1));
- Object.assign(result, r, { ok: true });
- } catch (e) {
- result.error = e.message;
- log('LỖI: ' + e.message);
- }
- fs.writeFileSync(path.join(dir, 'result.json'), JSON.stringify(result, null, 2));
- return result;
-}
-
-/**
- * Số trên đồ hoạ (kế hoạch theo chỉ số chữ): điền đơn vị người nói dùng (ngay sau số hoặc câu xung quanh), nghe lại
- * riêng từng chỗ có số (lumedit hear), số không chắc thì không in lên đồ hoạ. Trả {graphics, figures, units}.
- */
-async function checkGraphicNumbers({ graphics, words, proxy, dir, log, warnings }) {
- const units = fillUnits(graphics, words);
- for (const u of units) log(` đơn vị ${u.inferred ? 'suy từ câu xung quanh' : 'theo lời'}: ${u.type} "${u.text}" → ${u.unit} (lời: "${u.from}" ở ${u.at.toFixed(1)} s)`);
- const figs = figureList(graphics, words);
- const spans = [...new Set(figs.filter((f) => f.span).map((f) => `${f.span[0].toFixed(2)}-${f.span[1].toFixed(2)}`))];
- let heard = {};
- if (spans.length) {
- const hf = path.join(dir, 'figures.heard.json');
- const r = await runLumedit(['hear', proxy, '--spans', spans.join(','), '--out', hf]);
- if (r.ok) heard = readJson(hf, {});
- else warnings.push('nghe lại số lỗi, chỉ xét xác suất whisper: ' + r.error);
- }
- const low = checkFigures(figs, words, heard);
- const dl = dropLowFigures(graphics, low);
- const figures = low.map((f) => ({
- value: f.value, unit: f.unit, type: f.type, where: f.where, at: f.from != null ? +words[f.from].s.toFixed(2) : null,
- said: f.said, heard: f.heard, why: f.why, text: `${fmtVi(f.value)}${f.unit ? (/^[%°]/.test(f.unit) ? '' : ' ') + f.unit : ''}`,
- }));
- for (const f of figures) log(` số không chắc, không in lên đồ hoạ: ${f.text} (${f.type}${f.at != null ? ` ở ${f.at.toFixed(1)} s` : ''}, lời "${f.said}"): ${f.why}`);
- for (const d of dl.dropped) log(` → ${d}`);
- log(` kiểm số: ${figs.length} số trên đồ hoạ, ${spans.length} chỗ nghe lại, ${figures.length} số không chắc`);
- return { graphics: dl.plan, figures, units };
-}
-
-/** notes của EDL: ghi chú LLM + những gì người dùng cần biết (số không chắc, đơn vị suy ra, sửa lẹm chữ). */
-function edlNotes(base, state) {
- const parts = [base || ''];
- if (state.figures?.length) parts.push(`Số máy nghe không chắc, không in lên đồ hoạ (cần người xem lại): ${state.figures.map((f) => `${f.text}${f.at != null ? ` ở ${f.at.toFixed(1)} s nguồn` : ''} — ${f.why}`).join('; ')}.`);
- if (state.units?.length) parts.push(`Đơn vị điền thêm: ${state.units.map((u) => `"${u.text}" → ${u.unit}${u.inferred ? ` (suy từ "${u.from}")` : ''}`).join('; ')}.`);
- if (state.cutRepairs?.length) parts.push(`Sửa lẹm chữ sau khi nghe lại bản cắt: ${state.cutRepairs.map((r) => r.why).join('; ')}.`);
- return parts.filter(Boolean).join(' ');
-}
-
-/** Sau render nền: chữ mất/lẹm ở vết nối → giữ lại/nới vết cắt (repairCuts), dựng lại EDL. Một lần; trả EDL mới hoặc null. */
-function cutRepairer(ctx, rounds = 2) {
- let used = 0;
- return async (overcut) => {
- if (used >= rounds) return null;
- used++;
- const cur = readJson(path.join(ctx.dir, 'edl.json'));
- const fixes = repairCuts(cur, overcut, ctx.analysis);
- if (!fixes.length) return null;
- ctx.state.cutRepairs = [...(ctx.state.cutRepairs || []), ...fixes];
- for (const f of fixes) ctx.log(` sửa lẹm chữ: ${f.why}`);
- return buildEdl(ctx);
- };
-}
-
-/** state (đề xuất + núm kiểu + cắt thêm + đồ hoạ) → EDL đã kiểm (đồ hoạ đã đặt né mặt). */
-async function buildEdl({ id, dir, ing, analysis, words, style, state, checks, warnings, log }) {
- const st = applyOverrides(style, state.overrides);
- const byI = new Map(words.map((w) => [w.i, w.w]));
- checks.fixes = state.proposal.fixes.map((f) => ({ word: f.word, heard: byI.get(f.word), text: f.text }));
- if (checks.fixes.length) log(` chữ LLM sửa (cần người xem lại): ${checks.fixes.map((f) => `${f.heard} → ${f.text || '(ẩn)'}`).join(', ')}`);
- checks.figures = state.figures || [];
- checks.units = state.units || [];
- if (state.cutRepairs?.length) checks.cutRepairs = state.cutRepairs;
- let edl = compileEdl({ id, ingestRes: ing, analysis, words, proposal: state.proposal, style: st, music: state.music, draft: state.draft,
- exclude: state.exclude || [], graphics: state.graphics || [], restore: state.cutRepairs || [] });
- const gw = edl._warnings || []; delete edl._warnings;
- const kept = gw.filter((w) => w.startsWith('không bỏ '));
- edl.notes = edlNotes(edl.notes, state) + (kept.length ? ` Code giữ lại (nói liền, cắt sẽ vào giữa từ): ${kept.map((w) => w.slice('không bỏ '.length)).join('; ')}.` : '');
- edl = applyExtraCuts(edl, state.extraCuts);
- gw.push(...applyManual(edl, state.manual)); // chỉnh tay đã làm (nhạc, giọng, look, zoom/đồ hoạ đã xoá…) giữ qua lần dựng lại
- if (edl.graphics.length) {
- // đồ hoạ: đo khung mặt bản ra (sau reframe + zoom) rồi đặt né mặt, phía trên phụ đề
- const tlk = timelineOf(edl);
- const lost = edl.graphics.filter((g) => !inKeep(tlk, g.data.at));
- for (const g of lost) gw.push(`đồ hoạ ${g.type} ở ${g.data.at} s rơi vào đoạn bị bỏ, không hiện`);
- edl.graphics = edl.graphics.filter((g) => inKeep(tlk, g.data.at));
- const tmp = path.join(dir, 'edl.faces.json');
- fs.writeFileSync(tmp, JSON.stringify(edl));
- const facesFile = path.join(dir, 'faces-out.json');
- const fr = await runLumedit(['faces', tmp, '--out', facesFile, '--step', '0.25']);
- fs.rmSync(tmp, { force: true });
- if (!fr.ok) throw new Error('đo khung mặt cho đồ hoạ lỗi: ' + fr.error);
- const faces = JSON.parse(fs.readFileSync(facesFile, 'utf8'));
- gw.push(...layoutGraphics(edl.graphics, tlk, faces, captionTop(edl.captions.style), { stepTracker: !!st.graphics?.stepTracker }));
- checks.graphics = {
- count: edl.graphics.length, faceFound: faces.found_share,
- items: edl.graphics.map((g) => ({ type: g.type, at: +toOutputNearest(tlk, g.start).toFixed(2), until: +toOutputNearest(tlk, g.end).toFixed(2), estimate: g.estimate, box: g.box, faceAvoided: !!g.face, pinned: !!g.data.pin })),
- dropped: gw,
- };
- log(` đồ hoạ: ${edl.graphics.map((g) => `${g.type} ${toOutputNearest(tlk, g.start).toFixed(1)}–${toOutputNearest(tlk, g.end).toFixed(1)} s @y${g.box.y}×${g.box.scale}`).join(', ')}`);
- }
- for (const w of gw) { log(' ' + w); warnings?.push(w); }
- const v = validateEdl(edl, { sfxNames: SFX_NAMES });
- if (!v.ok) throw new Error('EDL không hợp lệ: ' + v.errors.map((e) => `${e.code} ${e.path}: ${e.msg}`).join('; '));
- const outDur = outputDuration(timelineOf(edl));
- if (state.segments) checks.selection = { target: state.target, segments: state.segments.map((x) => ({ role: x.role, from: x.from, to: x.to, why: x.why })) };
- checks.edl = { keep: edl.keep.length, removed: edl.removed.length, removedSeconds: +(ing.source.duration - outDur).toFixed(2), outSeconds: +outDur.toFixed(2), zooms: edl.zooms.length, sfx: edl.sfx.length, captionWords: edl.captions.words.length };
- if (edl.hook) checks.hook = { start: edl.hook.start, end: edl.hook.end, seconds: +(edl.hook.end - edl.hook.start).toFixed(2), repeat: edl.hook.repeat, text: edl.captions.words.filter((w) => w.start >= edl.hook.start - 0.05 && w.end <= edl.hook.end + 0.05).map((w) => w.w).join(' ') };
- if (edl.quote) checks.quote = { start: edl.quote.start, end: edl.quote.end, text: edl.captions.words.filter((w) => (w.start + w.end) / 2 >= edl.quote.start && (w.start + w.end) / 2 <= edl.quote.end).map((w) => w.w).join(' ') };
- if (edl.hookText) checks.hookText = edl.hookText.text;
- log(` EDL: ${ing.source.duration.toFixed(2)} s → ${outDur.toFixed(2)} s, ${edl.keep.length} đoạn giữ, ${edl.zooms.length} zoom, ${edl.sfx.length} sfx${edl.hook ? `, móc ${edl.hook.start.toFixed(2)}–${edl.hook.end.toFixed(2)} s nguồn lên đầu ("${checks.hook.text}")` : ''}${edl.quote ? `, trích dẫn "${checks.quote.text}"` : ''}${edl.hookText ? `, chữ móc "${edl.hookText.text}"` : ''}`);
- for (const r of edl.removed) log(` bỏ ${r.start.toFixed(2)}–${r.end.toFixed(2)} s (${r.reason})${r.words ? ': ' + r.words : ''}`);
- return edl;
-}
-
-/**
- * Bước 4–9 từ 1 EDL. Ghi edl.json, <outName>… Trả {out, edl, ...}.
- * repair(overcut): sau render nền, nghe lại thấy mất/lẹm chữ ở vết nối → trả EDL đã sửa (render nền lại 1 lần) hoặc null.
- */
-async function renderEdl({ dir, edl, draft, R, outName = 'out.mp4', repair = null }) {
- const { log, checks, warnings, step } = R;
- const edlFile = path.join(dir, 'edl.json');
- fs.writeFileSync(edlFile, JSON.stringify(edl, null, 1));
- const preview = () => step('xem trước', async () => {
- const r = await runLumedit(['stills', edlFile, '--out', path.join(dir, 'preview.jpg'), '--count', '16', '--draft-captions']);
- if (!r.ok) throw new Error('xem trước lỗi: ' + r.error);
- });
- await preview();
-
- const base = path.join(dir, 'base.mp4');
- let rb = await renderBase({ edlFile, base, draft, R });
- const bad = (oc) => (oc?.lost?.length || 0) + (oc?.chopped?.length || 0);
- // nghe lại thấy lẹm → sửa vết cắt, dựng lại nền (tối đa 2 lần; mỗi lần ~1,5 phút cho clip 45 s)
- while (repair && bad(rb.overcut)) {
- const next = await repair(rb.overcut);
- if (!next) break;
- edl = next;
- fs.writeFileSync(edlFile, JSON.stringify(edl, null, 1));
- (checks.overcutBefore ||= []).push(rb.overcut);
- log(' dựng lại nền sau khi sửa lẹm chữ');
- await preview();
- rb = await renderBase({ edlFile, base, draft, R });
- }
- if (bad(rb.overcut)) {
- const left = [...(rb.overcut.lost || []), ...(rb.overcut.chopped || [])].map((x) => `"${x.word}" ở ${x.at} s`).join(', ');
- warnings.push(`còn lẹm chữ (cần người xem lại): ${left}`);
- edl.notes = `${edl.notes ? edl.notes + ' ' : ''}Nghe lại bản cắt còn thấy lẹm chữ (cần người xem lại): ${left}.`;
- fs.writeFileSync(edlFile, JSON.stringify(edl, null, 1));
- }
- return finishRender({ dir, edl, edlFile, base, rb, draft, R, outName });
-}
-
-/**
- * Render nền 1 lượt + nghe lại bản cắt (lumedit render). check=false: không nghe lại (chỉnh tay không đổi phần cắt).
- * Mã hoá: NVENC nếu có (edit/encoder.mjs, FX_VCODEC_ARGS), lỗi thì làm lại bằng libx264.
- */
-async function renderBase({ edlFile, base, draft, R, check = true }) {
- const { log, timings, checks, step } = R;
- const enc = await pickEncoder();
- const rb = await step('render nền', async (pg) => {
- const go = (kind) => runLumedit(['render', edlFile, '--out', base, ...(draft ? ['--draft-captions'] : []), ...(check ? [] : ['--no-check'])], {
- env: kind === 'gpu' ? { FX_VCODEC_ARGS: JSON.stringify(videoArgs('gpu', { quality: 18 })) } : {},
- onProgress: (p) => {
- if (p.step === 'render') { pg(Math.round(p.pct * 0.6), `${p.done}/${p.total} khung`); if (p.pct % 25 === 0) log(` render ${p.pct}% (${p.done}/${p.total})`); }
- else { pg(65, 'nghe lại bản cắt'); log(` ${p.step}${p.note ? ': ' + p.note : ''}`); }
- },
- });
- let r = await go(enc.kind);
- if (!r.ok && enc.kind === 'gpu') { log(` render nền bằng NVENC lỗi (${String(r.error).split(/\r?\n/).pop()}), làm lại bằng libx264`); r = await go('cpu'); r.kind = 'cpu'; }
- if (!r.ok) throw new Error('render nền lỗi: ' + r.error);
- return { ...r.result, encoder: r.kind || enc.kind };
- });
- timings['render nền (vẽ khung)'] = rb.seconds.render;
- if (rb.seconds.overcut_check !== undefined) timings['kiểm lẹm chữ (nghe lại)'] = rb.seconds.overcut_check;
- (checks.encoders ||= {}).base = rb.encoder === 'gpu' ? 'h264_nvenc' : 'libx264';
- if (check) { checks.overcut = rb.overcut; log(` lẹm chữ: ${rb.overcut?.verdict}`); }
- saveSig(path.dirname(base), 'base', baseSig(readJson(edlFile), draft));
- saveSig(path.dirname(base), 'baseSeconds', rb.seconds_out);
- return rb;
-}
-
-/**
- * Tiếng động theo giây bản ra. Câu móc lặp lại (repeat): tiếng nằm trong khoảng móc phát cả ở đầu clip lẫn chỗ cũ;
- * tiếng riêng của câu móc (hook.sfx, vd "boom") chỉ phát ở đầu clip.
- */
-export function outputSfx(edl) {
- const tl = timelineOf(edl); const H = edl.hook;
- const out = edl.sfx.map((s) => ({ t: toOutputNearest(tl, s.at), name: s.name, gainDb: s.gainDb }));
- if (H?.repeat) for (const s of edl.sfx) if (s.at >= H.start && s.at <= H.end) out.push({ t: s.at - H.start, name: s.name, gainDb: s.gainDb });
- if (H?.sfx) out.push({ t: Math.max(0, H.sfx.at - H.start), name: H.sfx.name, gainDb: H.sfx.gainDb });
- return out.sort((a, b) => a.t - b.t);
-}
-
-/**
- * Bước 6–9: phụ đề, tiếng, ghép, kiểm. reuse.layer / reuse.mix: dùng lại lớp chữ / bản trộn tiếng của lượt trước
- * (chỉnh tay chỉ đổi nhạc thì không render lại chữ, chỉ đổi chữ thì không trộn lại tiếng). qc=false: bỏ qc-check.
- */
-async function finishRender({ dir, edl, edlFile, base, rb, draft, R, outName, reuse = {}, qc = true }) {
- const { log, timings, checks, warnings, step } = R;
- const layerFile = path.join(dir, LAYER.file);
- const mixFile = path.join(dir, 'audio', 'mix.wav');
- // dùng lại chỉ khi chữ ký khớp đúng EDL hiện tại (lượt trước hỏng giữa chừng thì file cũ không khớp → dựng lại)
- const lSig = layerSig(edl, draft); const mSig = mixSig(edl);
-
- let overlay = null;
- const hasLayer = () => (edl.graphics || []).length > 0 || (!draft && edl.captions.words.length > 0);
- if (reuse.layer !== false && sigOk(dir, 'layer', lSig) && (!hasLayer() || fs.existsSync(layerFile))) {
- overlay = hasLayer() ? layerFile : null; log(' phụ đề: dùng lại lớp chữ lượt trước (không đổi)');
- } else await step('phụ đề', async (pg) => {
- fs.rmSync(layerFile, { force: true, recursive: true });
- if (!hasLayer()) { pg(100, draft ? 'phụ đề nháp đã vẽ trong nền' : 'không có chữ'); saveSig(dir, 'layer', lSig); return; }
- let accent; let style = null;
- try { style = loadStyle(edl.style); accent = style.graphics?.accent; } catch { /* kiểu đã bị xoá: màu mặc định */ }
- const sc = writeCaptionScene(edl, path.join(dir, 'captions'), { captions: !draft, accent, style });
- checks.captions = { cards: sc.cards, graphics: sc.graphics, overlaps: 0, box: sc.box, safeZone: 'trong 120–960 px, đáy ≤ 80% khung', quote: sc.quote, hookText: sc.hookText, ticker: sc.ticker, layer: LAYER.name };
- overlay = await renderCaptionLayer(path.join(dir, 'captions'), layerFile, { log, onPct: (p) => pg(p, 'HyperFrames'), format: LAYER.hf });
- saveSig(dir, 'layer', lSig);
- });
-
- const duration = rb.seconds_out;
- let mix;
- if (reuse.mix !== false && sigOk(dir, 'mix', mSig) && fs.existsSync(mixFile)) { mix = { wav: mixFile }; log(' tiếng: dùng lại bản trộn lượt trước (không đổi)'); }
- else {
- mix = await step('tiếng', () => buildEditMix({
- base, duration, workDir: path.join(dir, 'audio'), lufs: edl.output.lufs, log,
- sfx: edl.audio?.sfxOff ? [] : outputSfx(edl), music: edl.music, voiceGainDb: edl.audio?.voiceGainDb || 0,
- }));
- saveSig(dir, 'mix', mSig);
- }
-
- const out = path.join(dir, outName);
- const enc = await pickEncoder();
- // hình bản ra = nền + lớp chữ: cả hai không đổi so với bản trước (chỉ chỉnh tiếng) → chép luồng hình của bản trước, không mã hoá lại
- const sigs = readJson(sigFile(dir), {});
- const vSig = sha([sigs.base || null, lSig, !!overlay]);
- const prevVideo = sigs.video === vSig && sigs.videoFile && sigs.videoFile !== outName && fs.existsSync(path.join(dir, sigs.videoFile)) ? path.join(dir, sigs.videoFile) : null;
- await step('ghép', async () => {
- const tmp = out.replace(/\.mp4$/, '.part.mp4');
- const mux = (kind) => {
- if (kind === 'reuse') {
- return run('ffmpeg', ['-hide_banner', '-y', '-i', prevVideo, '-i', mix.wav, '-map', '0:v:0', '-c:v', 'copy', '-map', '1:a:0', '-c:a', 'aac', '-b:a', '192k', '-ar', '48000', '-ac', '2',
- '-shortest', '-movflags', '+faststart', tmp], { timeoutMs: 60 * 60e3 });
- }
- const args = ['-hide_banner', '-y', '-i', base];
- if (overlay) args.push(...layerInput(LAYER, overlay));
- args.push('-i', mix.wav);
- const ai = overlay ? 2 : 1;
- if (overlay) args.push('-filter_complex', '[0:v][1:v]overlay=0:0:format=auto:eof_action=pass,format=yuv420p[v]', '-map', '[v]', ...videoArgs(kind, { quality: 18 }), '-pix_fmt', 'yuv420p', '-r', String(OUT.fps));
- else args.push('-map', '0:v:0', '-c:v', 'copy');
- args.push('-map', `${ai}:a:0`, '-c:a', 'aac', '-b:a', '192k', '-ar', '48000', '-ac', '2', '-shortest', '-movflags', '+faststart', tmp);
- return run('ffmpeg', args, { timeoutMs: 60 * 60e3 });
- };
- let kind = prevVideo ? 'reuse' : overlay ? enc.kind : 'copy';
- if (prevVideo) log(` ghép: hình không đổi, chép luồng hình của ${path.basename(prevVideo)} (không mã hoá lại)`);
- let r = await mux(kind);
- if (r.code !== 0 && kind === 'reuse') { kind = overlay ? enc.kind : 'copy'; r = await mux(kind); }
- if (r.code !== 0 && kind === 'gpu') { log(` ghép bằng NVENC lỗi (${r.out.trim().split(/\r?\n/).pop()}), làm lại bằng libx264`); kind = 'cpu'; r = await mux('cpu'); }
- if (r.code !== 0) throw new Error('ghép lỗi: ' + r.out.trim().split(/\r?\n/).slice(-3).join(' | '));
- (checks.encoders ||= {}).mux = kind === 'gpu' ? 'h264_nvenc' : kind === 'cpu' ? 'libx264' : kind === 'reuse' ? 'chép hình bản trước' : 'copy';
- fs.renameSync(tmp, out);
- saveSig(dir, 'video', vSig); saveSig(dir, 'videoFile', outName);
- });
-
- await step('kiểm', async () => {
- const pr = await run('ffprobe', ['-v', 'error', '-show_entries', 'stream=codec_type,codec_name,width,height,r_frame_rate:format=duration,size', '-of', 'json', out]);
- const j = JSON.parse(pr.out);
- const vs = j.streams.find((s) => s.codec_type === 'video'); const as = j.streams.find((s) => s.codec_type === 'audio');
- checks.file = { width: vs.width, height: vs.height, fps: vs.r_frame_rate, video: vs.codec_name, audio: as?.codec_name || null, duration: +Number(j.format.duration).toFixed(2), bytes: Number(j.format.size) || null };
- checks.file.ok = vs.width === OUT.width && vs.height === OUT.height && vs.r_frame_rate === '30/1' && !!as;
- const loud = await measureLoudness(out);
- checks.loudness = { lufs: +loud.lufs.toFixed(1), truePeak: +loud.truePeak.toFixed(1), ok: Math.abs(loud.lufs - OUT.lufs) <= 1 && loud.truePeak <= -1 };
- const n = 16; const d = checks.file.duration;
- const sel = Array.from({ length: n }, (_, k) => `eq(n\\,${Math.floor(((k + 0.5) / n) * d * OUT.fps)})`).join('+');
- await run('ffmpeg', ['-hide_banner', '-y', '-i', out, '-vf', `select='${sel}',scale=270:480,tile=4x4:padding=6:color=0x181818`, '-frames:v', '1', '-q:v', '3', path.join(dir, 'preview-final.jpg')]);
- if (qc) {
- const q = await runLumedit(['qc', out, '--out', path.join(dir, 'qc.json')]);
- if (q.ok) {
- checks.qc = { verdict: q.result.verdict, fails: q.result.findings.filter((f) => f.level === 'fail').map((f) => `${f.check}: ${f.what}`), warns: q.result.findings.filter((f) => f.level === 'warn').map((f) => `${f.check}: ${f.what}`) };
- } else warnings.push('qc-check lỗi: ' + q.error);
- }
- log(` file ${checks.file.width}×${checks.file.height} ${checks.file.fps} ${checks.file.duration} s · ${checks.loudness.lufs} LUFS / ${checks.loudness.truePeak} dBTP · qc ${qc ? checks.qc?.verdict || '?' : 'bỏ qua (chỉnh tay)'}`);
- for (const f of checks.qc?.fails || []) log(` qc FAIL ${f}`);
- });
- timings.total = +Object.entries(timings).filter(([k]) => !k.includes('(') && k !== 'total').reduce((s, [, v]) => s + v, 0).toFixed(1);
- log(`XONG ${out} (${timings.total} s)`);
- return { out, edl: edlFile };
-}
-
-/**
- * Sửa bằng lời: không phân tích lại. Ra out-r<n>.mp4 mới; EDL cũ → versions/edl-<n>.json.
- * opts: {log?, progress?}. Trả như editVideo (+ revision).
- */
-export async function reviseEdit(id, instruction, opts = {}) {
- const dir = editDir(id);
- const R = runner(dir, opts);
- const { log, timings, checks, warnings, step } = R;
- const result = { ok: false, id, dir, revision: null, timings, checks, warnings };
- let backup = null;
- try {
- instruction = String(instruction || '').trim();
- if (!instruction) throw new Error('thiếu lời sửa');
- if (instruction.length > 1000) throw new Error('lời sửa quá dài (tối đa 1000 ký tự)');
- const state = readJson(path.join(dir, 'state.json'));
- const ing = readJson(path.join(dir, 'ingest.json'));
- const analysis = readJson(path.join(dir, 'analysis.json'));
- const curEdl = readJson(path.join(dir, 'edl.json'));
- if (!state || !ing || !analysis || !curEdl) throw new Error('bản dựng này chưa xong lần đầu (thiếu state/ingest/analysis/edl)');
- const style = { ...loadStyle(state.style), sfxNames: SFX_NAMES, hesitations: new Set(analysis.hesitations || []) };
- const words = wordList(analysis);
- const n = (state.revisions?.length || 0) + 1;
- log(`sửa lần ${n}: "${instruction}"`);
- const rev = await step('LLM lập EDL', () => proposeRevision({
- words, edl: curEdl, proposal: state.proposal, style: applyOverrides(style, state.overrides), overrides: state.overrides, instruction, names: state.names, log,
- exclude: new Set(state.exclude || []),
- }));
- const newCuts = rev.cutsOut.flatMap((c) => outputCutToSource(timelineOf(curEdl), c.start, c.end, words));
- log(` LLM: ${rev.notes || '(không ghi chú)'}${newCuts.length ? ` · cắt thêm ${newCuts.map((c) => `${c.start.toFixed(2)}–${c.end.toFixed(2)} s nguồn`).join(', ')}` : ''}`);
- // giữ bản cũ
- const vdir = path.join(dir, 'versions');
- fs.mkdirSync(vdir, { recursive: true });
- backup = path.join(vdir, `edl-${n}.json`);
- fs.copyFileSync(path.join(dir, 'edl.json'), backup);
- const next = { ...state, proposal: rev.proposal, overrides: rev.overrides, extraCuts: [...(state.extraCuts || []), ...newCuts] };
- if (!fs.existsSync(ing.proxy.file)) {
- // proxy bị dọn sau lượt trước (jobs.cleanupEdit): dựng lại từ nguồn, cùng thông số → cùng file (x264 tất định),
- // nên cache chữ/mặt (proxy.words.json, proxy.face.json) dùng lại, không chép lời lại
- if (!fs.existsSync(ing.source.file)) throw new Error('không còn file nguồn ' + ing.source.file);
- const t = Date.now();
- await makeProxy(ing.source.file, ing.info, ing.proxy.file, { log, encoder: ing.encoder || 'cpu' });
- log(` dựng lại proxy từ nguồn: ${((Date.now() - t) / 1000).toFixed(1)} s`);
- }
- const edl = await buildEdl({ id, dir, ing, analysis, words, style, state: next, checks, warnings, log });
- const outName = `out-r${n}.mp4`;
- next.revisions = [...(state.revisions || []), { n, instruction, notes: rev.notes, at: new Date().toISOString(), previous: state.out || 'out.mp4', out: outName }];
- const repair = cutRepairer({ id, dir, ing, analysis, words, style, state: next, checks, warnings, log });
- const r = await renderEdl({ dir, edl, draft: state.draft, R, outName, repair });
- next.out = outName;
- fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify(next, null, 1));
- Object.assign(result, r, { ok: true, revision: next.revisions[next.revisions.length - 1] });
- } catch (e) {
- result.error = e.message;
- log('LỖI: ' + e.message);
- // lỗi giữa chừng: trả edl.json về bản trước lần sửa (state.json chỉ ghi khi render xong nên vẫn là bản cũ)
- if (backup && fs.existsSync(backup)) fs.copyFileSync(backup, path.join(dir, 'edl.json'));
- }
- const prevResult = readJson(path.join(dir, 'result.json'), {});
- fs.writeFileSync(path.join(dir, 'result.json'), JSON.stringify({ ...prevResult, ...(result.ok ? result : {}), lastRevise: { ok: result.ok, error: result.error || null, at: new Date().toISOString() } }, null, 2));
- return result;
-}
-
-// cho script kiểm thử: dựng lại EDL + render từ state.json đã có (không gọi LLM, không phân tích lại)
-// ---- chữ ký từng lớp (render.sig.json): lớp nào chưa đổi so với EDL hiện tại thì chỉnh tay dùng lại được -------------
-const sha = (x) => crypto.createHash('sha1').update(JSON.stringify(x)).digest('hex');
-/** Nền: phần cắt, móc, zoom, khung, đồ hoạ (kính mờ + thu khung vẽ trong nền), trích dẫn, phụ đề nháp (vẽ PIL trong nền). */
-export const baseSig = (edl, draft) => sha([edl.proxy.file, edl.keep, edl.hook, edl.zooms, edl.reframe, edl.graphics || [], edl.quote, draft ? edl.captions : null, !!draft]);
-/** Lớp chữ: phụ đề + đồ hoạ + chữ móc + trích dẫn trên trục bản ra. */
-export const layerSig = (edl, draft) => sha([LAYER.name, edl.style, edl.keep, edl.hook, edl.captions, edl.graphics || [], edl.hookText, edl.quote, !!draft]);
-/** Tiếng: giọng gốc (theo phần cắt) + nhạc + sfx + giọng/sfx chỉnh tay + LUFS. */
-export const mixSig = (edl) => sha([edl.keep, edl.hook, edl.audio, edl.music, edl.audio?.sfxOff ? [] : outputSfx(edl), edl.output.lufs]);
-const sigFile = (dir) => path.join(dir, 'render.sig.json');
-const sigOk = (dir, k, v) => readJson(sigFile(dir), {})[k] === v;
-function saveSig(dir, k, v) { const all = readJson(sigFile(dir), {}); all[k] = v; fs.writeFileSync(sigFile(dir), JSON.stringify(all, null, 1)); }
-
-/** Số giây của video nền (số khung / 30): độ dài bản trộn tiếng khi không render lại nền. */
-async function baseSeconds(base) {
- const r = await run('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-count_packets', '-show_entries', 'stream=nb_read_packets', '-of', 'csv=p=0', base]);
- const n = parseInt(r.out, 10);
- if (!Number.isFinite(n) || n <= 0) throw new Error('không đọc được video nền ' + path.basename(base));
- return +(n / OUT.fps).toFixed(3);
-}
-
-/**
- * Chỉnh tay (edit/manual.mjs): không LLM, không phân tích lại, chỉ dựng lại lớp cần thiết —
- * xoá zoom → render nền (không nghe lại); phụ đề/look/chữ nhấn/đồ hoạ → lớp chữ; nhạc/giọng/sfx → trộn tiếng; luôn ghép.
- * Ra out-r<n>.mp4 mới, EDL cũ → versions/edl-<n>.json. patch đã qua parseManual. opts: {log?, progress?, uploads?}.
- */
-export async function manualEdit(id, patch, opts = {}) {
- const dir = editDir(id);
- const R = runner(dir, opts);
- const { log, checks, warnings } = R;
- const result = { ok: false, id, dir, revision: null, timings: R.timings, checks, warnings };
- let backup = null;
- try {
- const state = readJson(path.join(dir, 'state.json'));
- const ing = readJson(path.join(dir, 'ingest.json'));
- const curEdl = readJson(path.join(dir, 'edl.json'));
- if (!state || !ing || !curEdl) throw new Error('bản dựng này chưa xong lần đầu (thiếu state/ingest/edl)');
- let style = null;
- try { style = loadStyle(state.style); } catch { /* kiểu đã bị xoá: mặc định nhạc −22 dB */ }
- const ap = applyPatch(curEdl, state, patch, { dir, style, uploads: opts.uploads || {} });
- const n = (state.revisions?.length || 0) + 1;
- log(`chỉnh tay lần ${n}: ${ap.summary.join('; ')}`);
- for (const w of ap.warnings) { log(' ' + w); warnings.push(w); }
- const edl = ap.edl;
- const base = path.join(dir, 'base.mp4');
- // nền chỉ dựng lại khi phần vẽ trong nền đổi (zoom, đồ hoạ có kính mờ) hoặc thiếu/không khớp chữ ký
- const redoBase = !fs.existsSync(base) || !sigOk(dir, 'base', baseSig(edl, state.draft));
- if (ap.redo.base && !redoBase) log(' nền: không đổi, dùng lại');
- const v = validateEdl(edl, { sfxNames: SFX_NAMES, checkFiles: false });
- if (!v.ok) throw Object.assign(new Error('EDL sau chỉnh tay không hợp lệ: ' + v.errors.slice(0, 4).map((e) => `${e.code} ${e.path}: ${e.msg}`).join('; ')), { code: 400 });
- if (edl.music && !fs.existsSync(edl.music.file)) throw new Error('không thấy file nhạc ' + path.basename(edl.music.file));
- const vdir = path.join(dir, 'versions');
- fs.mkdirSync(vdir, { recursive: true });
- backup = path.join(vdir, `edl-${n}.json`);
- fs.copyFileSync(path.join(dir, 'edl.json'), backup);
- const edlFile = path.join(dir, 'edl.json');
- fs.writeFileSync(edlFile, JSON.stringify(edl, null, 1));
- let rb;
- if (redoBase) {
- if (!fs.existsSync(ing.proxy.file)) {
- if (!fs.existsSync(ing.source.file)) throw new Error('không còn file nguồn ' + ing.source.file);
- const t = Date.now();
- await makeProxy(ing.source.file, ing.info, ing.proxy.file, { log, encoder: ing.encoder || 'cpu' });
- R.timings['dựng lại proxy'] = +((Date.now() - t) / 1000).toFixed(1); // proxy bị dọn sau lượt trước (jobs.cleanupEdit)
- log(` dựng lại proxy từ nguồn: ${R.timings['dựng lại proxy']} s`);
- }
- rb = await renderBase({ edlFile, base, draft: state.draft, R, check: false });
- } else rb = { seconds_out: readJson(sigFile(dir), {}).baseSeconds || await baseSeconds(base) };
- // lớp chữ / bản trộn dùng lại khi chữ ký khớp EDL mới (nền đổi vì zoom thì tiếng gốc vẫn y hệt → trộn cũ dùng được)
- const reuse = {};
- const outName = `out-r${n}.mp4`;
- const r = await finishRender({ dir, edl, edlFile, base, rb, draft: state.draft, R, outName, reuse, qc: false });
- const next = {
- ...state, manual: ap.manual, music: ap.music, out: outName,
- revisions: [...(state.revisions || []), { n, manual: true, instruction: ap.summary.join('; '), notes: ap.warnings.join('; '), at: new Date().toISOString(), previous: state.out || 'out.mp4', out: outName, seconds: R.timings.total }],
- };
- fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify(next, null, 1));
- Object.assign(result, r, { ok: true, revision: next.revisions[next.revisions.length - 1] });
- } catch (e) {
- result.error = e.message;
- log('LỖI: ' + e.message);
- if (backup && fs.existsSync(backup)) fs.copyFileSync(backup, path.join(dir, 'edl.json'));
- }
- const prevResult = readJson(path.join(dir, 'result.json'), {});
- // giữ checks/timings của lần dựng đầy đủ (qc, lẹm chữ…), cập nhật phần file/tiếng/thời gian của bản mới
- const merged = result.ok ? { ...prevResult, out: result.out, edl: result.edl, checks: { ...prevResult.checks, ...checks }, lastManual: { timings: R.timings, warnings } } : prevResult;
- fs.writeFileSync(path.join(dir, 'result.json'), JSON.stringify({ ...merged, lastRevise: { ok: result.ok, manual: true, error: result.error || null, at: new Date().toISOString() } }, null, 2));
- return result;
-}
-
-export const _internal = { buildEdl, renderEdl, runner };
+// LumReels Edit — luồng dựng video người dùng tự quay theo một thẻ kiểu edit.
+// 1 nạp (probe, băm, proxy CFR 30) 2 phân tích (whisper large-v3 tiếng Việt, khoảng lặng, mặt)
+// 3 LLM lập đề xuất → code dựng EDL → kiểm 4 xem trước lưới 16 khung
+// 5 render nền 1 lượt (cắt + reframe 9:16 + zoom; tiếng gốc nối 20 ms) + kiểm lẹm chữ (nghe lại)
+// 6 phụ đề: HyperFrames lớp trong suốt (bản chính) hoặc PIL vẽ thẳng (--draft)
+// 7 tiếng: giọng gốc + nhạc tự hạ + sfx → −14 LUFS 8 ghép → out.mp4 9 kiểm (qc-check + kích thước + lưới khung)
+// Sửa bằng lời (reviseEdit): LLM sửa đề xuất/cắt theo giây bản ra/núm kiểu → dựng lại EDL → bước 4–9. KHÔNG phân tích lại.
+// Đầu ra: edits/<id>/ (edl.json, preview.jpg, out.mp4, preview-final.jpg, qc.json, result.json, state.json, log.txt,
+// mỗi lần sửa n ra out-r<n>.mp4 MỚI (Windows khoá file đang phát nên không ghi đè), bản trước giữ nguyên,
+// versions/edl-<n>.json = EDL trước lần sửa n; state.json.out = tên file bản mới nhất)
+import fs from 'node:fs';
+import path from 'node:path';
+import crypto from 'node:crypto';
+import { run } from '../engine/lib.mjs';
+import { SFX_NAMES } from '../engine/audio/sfx.mjs';
+import { measureLoudness } from '../engine/audio/mix.mjs';
+import { ROOT, runLumedit } from './env.mjs';
+import { ingest, makeProxy } from './ingest.mjs';
+import {
+ loadStyle, wordList, propose, compileEdl, parseNames, proposeRevision, applyOverrides, applyExtraCuts, outputCutToSource,
+ callClaude, parseProposal, repairCuts, maxSecRequest,
+} from './planner.mjs';
+import { selectSegments, planGraphics, layoutGraphics, fillUnits, figureList, checkFigures, dropLowFigures } from './graphics.mjs';
+import { fmtVi } from './numbers.mjs';
+import { validateEdl, toOutputNearest, outputDuration, timelineOf, inKeep, OUT } from './edl.mjs';
+import { writeCaptionScene, renderCaptionLayer, captionTop, LAYER, layerInput } from './captions-hf.mjs';
+import { buildEditMix } from './audio.mjs';
+import { pickEncoder, videoArgs } from './encoder.mjs';
+import { applyPatch, applyManual } from './manual.mjs';
+
+export const EDITS = path.join(ROOT, 'edits');
+const wordKey = (w) => w.toLowerCase().normalize('NFC').replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, '');
+/** Các bước (để UI vẽ thanh tiến độ). Sửa bằng lời bắt đầu từ "LLM lập EDL". */
+export const STEPS = ['nạp', 'phân tích', 'LLM lập EDL', 'xem trước', 'render nền', 'phụ đề', 'tiếng', 'ghép', 'kiểm'];
+
+export function newEditId() {
+ const d = new Date(); const p = (n) => String(n).padStart(2, '0');
+ return `${String(d.getFullYear()).slice(2)}${p(d.getMonth() + 1)}${p(d.getDate())}${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}-${crypto.randomBytes(2).toString('hex')}`;
+}
+export const editDir = (id) => path.join(EDITS, id);
+const readJson = (f, d = null) => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return d; } };
+
+/** Bộ khung chung cho 1 lượt chạy: log, đo giờ từng bước, báo tiến độ. */
+function runner(dir, opts) {
+ fs.mkdirSync(dir, { recursive: true });
+ const logFile = path.join(dir, 'log.txt');
+ const log = (s) => { const line = `[${new Date().toISOString().slice(11, 19)}] ${s}`; fs.appendFileSync(logFile, line + '\n'); (opts.log || console.log)(line); };
+ const timings = {}; const checks = {}; const warnings = [];
+ const progress = (step, pct = 0, note = '') => { try { opts.progress?.({ step, index: STEPS.indexOf(step), total: STEPS.length, pct, note }); } catch { /* bỏ qua */ } };
+ const step = async (name, fn) => {
+ const t = Date.now(); log(`— ${name}`); progress(name, 0);
+ const r = await fn((pct, note) => progress(name, pct, note));
+ const took = +((Date.now() - t) / 1000).toFixed(1);
+ timings[name] = +((timings[name] || 0) + took).toFixed(1); log(` xong ${name}: ${took} s`); progress(name, 100); // bước chạy lại (sửa lẹm chữ) cộng dồn
+ return r;
+ };
+ return { log, timings, checks, warnings, step };
+}
+
+/**
+ * Dựng mới. opts: {style, music?, noMusic? (không dùng nhạc mặc định của kiểu), content?, names?, draft?, llm?: 'on'|'off', target?: giây, id?, log?, progress?}
+ * target: clip nguồn dài → LLM chọn các đoạn hay nhất (hook … kết) ghép thành short ≈ target giây, rồi mới cắt ngập ngừng.
+ * Trả {ok, id, dir, out, edl, timings, checks, warnings, error?}
+ */
+export async function editVideo(video, opts = {}) {
+ const id = opts.id || newEditId();
+ const dir = editDir(id);
+ const R = runner(dir, opts);
+ const { log, timings, checks, warnings, step } = R;
+ const result = { ok: false, id, dir, video: path.resolve(video), style: opts.style, draft: !!opts.draft, timings, checks, warnings };
+ try {
+ if (!fs.existsSync(video)) throw new Error(`không thấy video ${video}`);
+ if (opts.music && !fs.existsSync(opts.music)) throw new Error(`không thấy file nhạc ${opts.music}`);
+ const style = { ...loadStyle(opts.style || 'sach-gon'), sfxNames: SFX_NAMES };
+ const names = parseNames(opts.names);
+ log(`edit ${id}: ${path.basename(video)} · kiểu ${style.id}${opts.draft ? ' · bản nháp (phụ đề PIL)' : ''}${opts.music ? ' · nhạc ' + path.basename(opts.music) : ''}${names.length ? ' · tên riêng: ' + names.join(', ') : ''}`);
+
+ const ing = await step('nạp', () => ingest(path.resolve(video), path.join(dir, 'proxy.mov'), { log }));
+ fs.writeFileSync(path.join(dir, 'ingest.json'), JSON.stringify(ing, null, 1));
+ (checks.encoders ||= {}).proxy = ing.encoder === 'gpu' ? 'h264_nvenc' : 'libx264';
+
+ const analysisFile = path.join(dir, 'analysis.json');
+ const an = await step('phân tích', async (pg) => {
+ const r = await runLumedit(['analyze', ing.proxy.file, '--out', analysisFile], {
+ onProgress: (p) => { log(` ${p.step}${p.note ? ': ' + p.note : ''}`); pg({ words: 10, quiet: 70, face: 80 }[p.step] ?? 50, p.step); },
+ });
+ if (!r.ok) throw new Error('phân tích lỗi: ' + r.error);
+ checks.whisperDevice = r.result.device || null;
+ return { ...r.result, data: JSON.parse(fs.readFileSync(analysisFile, 'utf8')) };
+ });
+ log(` ${an.words} chữ chắc + ${an.unsure} chữ không chắc · whisper ${an.seconds.words} s (${an.device || '?'}) · mặt ${an.seconds.face} s (thấy mặt ${Math.round(an.data.face.found_share * 100)}% khung)`);
+ if (!an.words) throw new Error('không nghe được lời nào trong video');
+
+ const words = wordList(an.data);
+ style.hesitations = new Set(an.data.hesitations || []);
+ // độ dài: --target của người dùng, không có thì theo thẻ kiểu (style.target; nguồn đã ngắn thì bỏ qua như cũ)
+ const target = Number(opts.target) > 0 ? Math.round(Number(opts.target)) : Number(style.target) > 0 ? Math.round(style.target) : null;
+ if (!(Number(opts.target) > 0) && target) log(` độ dài theo kiểu: ${target} s${style.maxSec ? ` (trần ${style.maxSec} s)` : ''}`);
+ const llmOn = (opts.llm || 'on') !== 'off';
+ let selection = null;
+ const plan = await step('LLM lập EDL', async (pg) => {
+ if (target && !llmOn) warnings.push('--target cần LLM: bỏ qua (LLM tắt)');
+ else if (target && ing.source.duration < target * 1.15) log(` nguồn ${ing.source.duration.toFixed(0)} s đã gần ${target} s: không chọn đoạn`);
+ else if (target) {
+ pg(5, 'chọn đoạn hay');
+ selection = await selectSegments({ words, target, style, content: opts.content, names, duration: ing.source.duration, callClaude, parse: parseProposal, log });
+ warnings.push(...selection.warnings);
+ log(` chọn ${selection.segments.length} đoạn ≈ ${selection.seconds.toFixed(1)} s nói: ${selection.segments.map((x) => `${x.role} ${words[x.from].s.toFixed(1)}–${words[x.to].e.toFixed(1)} s`).join(', ')}`);
+ }
+ pg(35, 'cắt ngập ngừng');
+ const p = await propose({ words, style, content: opts.content, names, duration: ing.source.duration, llm: opts.llm || 'on', log, exclude: selection?.exclude });
+ if (style.graphics && llmOn) {
+ pg(70, 'kế hoạch đồ hoạ');
+ const dropped = new Set(selection?.exclude || []);
+ for (const d of p.proposal.drop) for (let i = d.from; i <= d.to; i++) dropped.add(i);
+ if (style.cutFillers) for (const w of words) if (style.hesitations.has(wordKey(w.w))) dropped.add(w.i);
+ const gp = await planGraphics({ words, dropped, style, content: opts.content, names, callClaude, parse: parseProposal, log });
+ p.warnings.push(...gp.warnings);
+ log(` đồ hoạ (vòng ${gp.rounds}): ${gp.graphics.map((g) => `${g.type}@${words[g.at].s.toFixed(1)}s`).join(', ') || 'không có'}`);
+ pg(85, 'đơn vị + nghe lại số');
+ const fc = await checkGraphicNumbers({ graphics: gp.graphics, words, proxy: ing.proxy.file, dir, log, warnings: p.warnings });
+ p.graphics = fc.graphics; p.figures = fc.figures; p.units = fc.units;
+ }
+ return p;
+ });
+ fs.writeFileSync(path.join(dir, 'proposal.json'), JSON.stringify({ ...plan, words: words.map((w) => `${w.i}:${w.w}${w.unsure ? '?' : ''}`) }, null, 1));
+ warnings.push(...plan.warnings);
+ log(` đề xuất (vòng ${plan.rounds}): bỏ ${plan.proposal.drop.length} khoảng, ${plan.proposal.zooms.length} zoom, ${plan.proposal.highlights.length} chữ nhấn, ${plan.proposal.fixes.length} chữ sửa${plan.proposal.notes ? ' · ' + plan.proposal.notes : ''}`);
+
+ // kiểu có nhạc mặc định (vd thong-tin-do-hoa: lofi nhẹ) mà người dùng không chọn nhạc → nhạc tổng hợp, lặp theo độ dài
+ let music = opts.music ? path.resolve(opts.music) : null;
+ if (!music && !opts.noMusic && style.music?.default) {
+ const { writeMusic, MUSIC_STYLES } = await import('../engine/audio/music.mjs');
+ if (MUSIC_STYLES.includes(style.music.default)) { music = writeMusic(style.music.default, path.join(dir, `music-${style.music.default}.wav`), 60, 1); log(` nhạc nền mặc định của kiểu: ${style.music.default}`); }
+ }
+ const state = {
+ version: 1, style: style.id, music, content: opts.content || '', names,
+ draft: !!opts.draft, llm: opts.llm || 'on', proposal: plan.proposal, overrides: {}, extraCuts: [], revisions: [],
+ target, segments: selection?.segments || null, exclude: selection ? [...selection.exclude] : [], graphics: plan.graphics || [],
+ figures: plan.figures || [], units: plan.units || [], cutRepairs: [],
+ };
+ fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify(state, null, 1));
+ let edl = await buildEdl({ id, dir, ing, analysis: an.data, words, style, state, checks, warnings, log });
+ // kiểu có trần độ dài (maxSec, vd meo-15s 20 s): quá thì LLM sửa 1 vòng "bỏ thêm X giây"; vẫn quá thì chỉ cảnh báo
+ const over = maxSecRequest(style, outputDuration(timelineOf(edl)));
+ if (over && llmOn) {
+ log(' ' + over);
+ const p2 = await step('LLM lập EDL', () => propose({ words, style, content: opts.content, names, duration: ing.source.duration, llm: 'on', log, exclude: selection?.exclude,
+ extra: `${over}\nĐề xuất trước: ${JSON.stringify(state.proposal)}` }));
+ warnings.push(...p2.warnings);
+ state.proposal = p2.proposal; state.maxSecRetry = { before: +outputDuration(timelineOf(edl)).toFixed(2) };
+ edl = await buildEdl({ id, dir, ing, analysis: an.data, words, style, state, checks, warnings, log });
+ state.maxSecRetry.after = +outputDuration(timelineOf(edl)).toFixed(2);
+ fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify(state, null, 1));
+ checks.maxSec = { max: style.maxSec, ...state.maxSecRetry };
+ }
+ const still = maxSecRequest(style, outputDuration(timelineOf(edl)));
+ if (still) warnings.push(`bản ra ${outputDuration(timelineOf(edl)).toFixed(1)} s vẫn quá trần ${style.maxSec} s của kiểu ${style.id} (không tự cắt, cần người xem lại)`);
+ const repair = cutRepairer({ id, dir, ing, analysis: an.data, words, style, state, checks, warnings, log });
+ const r = await renderEdl({ dir, edl, draft: state.draft, R, outName: 'out.mp4', repair });
+ fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify({ ...state, out: 'out.mp4' }, null, 1));
+ Object.assign(result, r, { ok: true });
+ } catch (e) {
+ result.error = e.message;
+ log('LỖI: ' + e.message);
+ }
+ fs.writeFileSync(path.join(dir, 'result.json'), JSON.stringify(result, null, 2));
+ return result;
+}
+
+/**
+ * Số trên đồ hoạ (kế hoạch theo chỉ số chữ): điền đơn vị người nói dùng (ngay sau số hoặc câu xung quanh), nghe lại
+ * riêng từng chỗ có số (lumedit hear), số không chắc thì không in lên đồ hoạ. Trả {graphics, figures, units}.
+ */
+async function checkGraphicNumbers({ graphics, words, proxy, dir, log, warnings }) {
+ const units = fillUnits(graphics, words);
+ for (const u of units) log(` đơn vị ${u.inferred ? 'suy từ câu xung quanh' : 'theo lời'}: ${u.type} "${u.text}" → ${u.unit} (lời: "${u.from}" ở ${u.at.toFixed(1)} s)`);
+ const figs = figureList(graphics, words);
+ const spans = [...new Set(figs.filter((f) => f.span).map((f) => `${f.span[0].toFixed(2)}-${f.span[1].toFixed(2)}`))];
+ let heard = {};
+ if (spans.length) {
+ const hf = path.join(dir, 'figures.heard.json');
+ const r = await runLumedit(['hear', proxy, '--spans', spans.join(','), '--out', hf]);
+ if (r.ok) heard = readJson(hf, {});
+ else warnings.push('nghe lại số lỗi, chỉ xét xác suất whisper: ' + r.error);
+ }
+ const low = checkFigures(figs, words, heard);
+ const dl = dropLowFigures(graphics, low);
+ const figures = low.map((f) => ({
+ value: f.value, unit: f.unit, type: f.type, where: f.where, at: f.from != null ? +words[f.from].s.toFixed(2) : null,
+ said: f.said, heard: f.heard, why: f.why, text: `${fmtVi(f.value)}${f.unit ? (/^[%°]/.test(f.unit) ? '' : ' ') + f.unit : ''}`,
+ }));
+ for (const f of figures) log(` số không chắc, không in lên đồ hoạ: ${f.text} (${f.type}${f.at != null ? ` ở ${f.at.toFixed(1)} s` : ''}, lời "${f.said}"): ${f.why}`);
+ for (const d of dl.dropped) log(` → ${d}`);
+ log(` kiểm số: ${figs.length} số trên đồ hoạ, ${spans.length} chỗ nghe lại, ${figures.length} số không chắc`);
+ return { graphics: dl.plan, figures, units };
+}
+
+/** notes của EDL: ghi chú LLM + những gì người dùng cần biết (số không chắc, đơn vị suy ra, sửa lẹm chữ). */
+function edlNotes(base, state) {
+ const parts = [base || ''];
+ if (state.figures?.length) parts.push(`Số máy nghe không chắc, không in lên đồ hoạ (cần người xem lại): ${state.figures.map((f) => `${f.text}${f.at != null ? ` ở ${f.at.toFixed(1)} s nguồn` : ''} — ${f.why}`).join('; ')}.`);
+ if (state.units?.length) parts.push(`Đơn vị điền thêm: ${state.units.map((u) => `"${u.text}" → ${u.unit}${u.inferred ? ` (suy từ "${u.from}")` : ''}`).join('; ')}.`);
+ if (state.cutRepairs?.length) parts.push(`Sửa lẹm chữ sau khi nghe lại bản cắt: ${state.cutRepairs.map((r) => r.why).join('; ')}.`);
+ return parts.filter(Boolean).join(' ');
+}
+
+/** Sau render nền: chữ mất/lẹm ở vết nối → giữ lại/nới vết cắt (repairCuts), dựng lại EDL. Một lần; trả EDL mới hoặc null. */
+function cutRepairer(ctx, rounds = 2) {
+ let used = 0;
+ return async (overcut) => {
+ if (used >= rounds) return null;
+ used++;
+ const cur = readJson(path.join(ctx.dir, 'edl.json'));
+ const fixes = repairCuts(cur, overcut, ctx.analysis);
+ if (!fixes.length) return null;
+ ctx.state.cutRepairs = [...(ctx.state.cutRepairs || []), ...fixes];
+ for (const f of fixes) ctx.log(` sửa lẹm chữ: ${f.why}`);
+ return buildEdl(ctx);
+ };
+}
+
+/** state (đề xuất + núm kiểu + cắt thêm + đồ hoạ) → EDL đã kiểm (đồ hoạ đã đặt né mặt). */
+async function buildEdl({ id, dir, ing, analysis, words, style, state, checks, warnings, log }) {
+ const st = applyOverrides(style, state.overrides);
+ const byI = new Map(words.map((w) => [w.i, w.w]));
+ checks.fixes = state.proposal.fixes.map((f) => ({ word: f.word, heard: byI.get(f.word), text: f.text }));
+ if (checks.fixes.length) log(` chữ LLM sửa (cần người xem lại): ${checks.fixes.map((f) => `${f.heard} → ${f.text || '(ẩn)'}`).join(', ')}`);
+ checks.figures = state.figures || [];
+ checks.units = state.units || [];
+ if (state.cutRepairs?.length) checks.cutRepairs = state.cutRepairs;
+ let edl = compileEdl({ id, ingestRes: ing, analysis, words, proposal: state.proposal, style: st, music: state.music, draft: state.draft,
+ exclude: state.exclude || [], graphics: state.graphics || [], restore: state.cutRepairs || [] });
+ const gw = edl._warnings || []; delete edl._warnings;
+ const kept = gw.filter((w) => w.startsWith('không bỏ '));
+ edl.notes = edlNotes(edl.notes, state) + (kept.length ? ` Code giữ lại (nói liền, cắt sẽ vào giữa từ): ${kept.map((w) => w.slice('không bỏ '.length)).join('; ')}.` : '');
+ edl = applyExtraCuts(edl, state.extraCuts);
+ gw.push(...applyManual(edl, state.manual)); // chỉnh tay đã làm (nhạc, giọng, look, zoom/đồ hoạ đã xoá…) giữ qua lần dựng lại
+ if (edl.graphics.length) {
+ // đồ hoạ: đo khung mặt bản ra (sau reframe + zoom) rồi đặt né mặt, phía trên phụ đề
+ const tlk = timelineOf(edl);
+ const lost = edl.graphics.filter((g) => !inKeep(tlk, g.data.at));
+ for (const g of lost) gw.push(`đồ hoạ ${g.type} ở ${g.data.at} s rơi vào đoạn bị bỏ, không hiện`);
+ edl.graphics = edl.graphics.filter((g) => inKeep(tlk, g.data.at));
+ const tmp = path.join(dir, 'edl.faces.json');
+ fs.writeFileSync(tmp, JSON.stringify(edl));
+ const facesFile = path.join(dir, 'faces-out.json');
+ const fr = await runLumedit(['faces', tmp, '--out', facesFile, '--step', '0.25']);
+ fs.rmSync(tmp, { force: true });
+ if (!fr.ok) throw new Error('đo khung mặt cho đồ hoạ lỗi: ' + fr.error);
+ const faces = JSON.parse(fs.readFileSync(facesFile, 'utf8'));
+ gw.push(...layoutGraphics(edl.graphics, tlk, faces, captionTop(edl.captions.style), { stepTracker: !!st.graphics?.stepTracker }));
+ checks.graphics = {
+ count: edl.graphics.length, faceFound: faces.found_share,
+ items: edl.graphics.map((g) => ({ type: g.type, at: +toOutputNearest(tlk, g.start).toFixed(2), until: +toOutputNearest(tlk, g.end).toFixed(2), estimate: g.estimate, box: g.box, faceAvoided: !!g.face, pinned: !!g.data.pin })),
+ dropped: gw,
+ };
+ log(` đồ hoạ: ${edl.graphics.map((g) => `${g.type} ${toOutputNearest(tlk, g.start).toFixed(1)}–${toOutputNearest(tlk, g.end).toFixed(1)} s @y${g.box.y}×${g.box.scale}`).join(', ')}`);
+ }
+ for (const w of gw) { log(' ' + w); warnings?.push(w); }
+ const v = validateEdl(edl, { sfxNames: SFX_NAMES });
+ if (!v.ok) throw new Error('EDL không hợp lệ: ' + v.errors.map((e) => `${e.code} ${e.path}: ${e.msg}`).join('; '));
+ const outDur = outputDuration(timelineOf(edl));
+ if (state.segments) checks.selection = { target: state.target, segments: state.segments.map((x) => ({ role: x.role, from: x.from, to: x.to, why: x.why })) };
+ checks.edl = { keep: edl.keep.length, removed: edl.removed.length, removedSeconds: +(ing.source.duration - outDur).toFixed(2), outSeconds: +outDur.toFixed(2), zooms: edl.zooms.length, sfx: edl.sfx.length, captionWords: edl.captions.words.length };
+ if (edl.hook) checks.hook = { start: edl.hook.start, end: edl.hook.end, seconds: +(edl.hook.end - edl.hook.start).toFixed(2), repeat: edl.hook.repeat, text: edl.captions.words.filter((w) => w.start >= edl.hook.start - 0.05 && w.end <= edl.hook.end + 0.05).map((w) => w.w).join(' ') };
+ if (edl.quote) checks.quote = { start: edl.quote.start, end: edl.quote.end, text: edl.captions.words.filter((w) => (w.start + w.end) / 2 >= edl.quote.start && (w.start + w.end) / 2 <= edl.quote.end).map((w) => w.w).join(' ') };
+ if (edl.hookText) checks.hookText = edl.hookText.text;
+ log(` EDL: ${ing.source.duration.toFixed(2)} s → ${outDur.toFixed(2)} s, ${edl.keep.length} đoạn giữ, ${edl.zooms.length} zoom, ${edl.sfx.length} sfx${edl.hook ? `, móc ${edl.hook.start.toFixed(2)}–${edl.hook.end.toFixed(2)} s nguồn lên đầu ("${checks.hook.text}")` : ''}${edl.quote ? `, trích dẫn "${checks.quote.text}"` : ''}${edl.hookText ? `, chữ móc "${edl.hookText.text}"` : ''}`);
+ for (const r of edl.removed) log(` bỏ ${r.start.toFixed(2)}–${r.end.toFixed(2)} s (${r.reason})${r.words ? ': ' + r.words : ''}`);
+ return edl;
+}
+
+/**
+ * Bước 4–9 từ 1 EDL. Ghi edl.json, <outName>… Trả {out, edl, ...}.
+ * repair(overcut): sau render nền, nghe lại thấy mất/lẹm chữ ở vết nối → trả EDL đã sửa (render nền lại 1 lần) hoặc null.
+ */
+async function renderEdl({ dir, edl, draft, R, outName = 'out.mp4', repair = null }) {
+ const { log, checks, warnings, step } = R;
+ const edlFile = path.join(dir, 'edl.json');
+ fs.writeFileSync(edlFile, JSON.stringify(edl, null, 1));
+ const preview = () => step('xem trước', async () => {
+ const r = await runLumedit(['stills', edlFile, '--out', path.join(dir, 'preview.jpg'), '--count', '16', '--draft-captions']);
+ if (!r.ok) throw new Error('xem trước lỗi: ' + r.error);
+ });
+ await preview();
+
+ const base = path.join(dir, 'base.mp4');
+ let rb = await renderBase({ edlFile, base, draft, R });
+ const bad = (oc) => (oc?.lost?.length || 0) + (oc?.chopped?.length || 0);
+ // nghe lại thấy lẹm → sửa vết cắt, dựng lại nền (tối đa 2 lần; mỗi lần ~1,5 phút cho clip 45 s)
+ while (repair && bad(rb.overcut)) {
+ const next = await repair(rb.overcut);
+ if (!next) break;
+ edl = next;
+ fs.writeFileSync(edlFile, JSON.stringify(edl, null, 1));
+ (checks.overcutBefore ||= []).push(rb.overcut);
+ log(' dựng lại nền sau khi sửa lẹm chữ');
+ await preview();
+ rb = await renderBase({ edlFile, base, draft, R });
+ }
+ if (bad(rb.overcut)) {
+ const left = [...(rb.overcut.lost || []), ...(rb.overcut.chopped || [])].map((x) => `"${x.word}" ở ${x.at} s`).join(', ');
+ warnings.push(`còn lẹm chữ (cần người xem lại): ${left}`);
+ edl.notes = `${edl.notes ? edl.notes + ' ' : ''}Nghe lại bản cắt còn thấy lẹm chữ (cần người xem lại): ${left}.`;
+ fs.writeFileSync(edlFile, JSON.stringify(edl, null, 1));
+ }
+ return finishRender({ dir, edl, edlFile, base, rb, draft, R, outName });
+}
+
+/**
+ * Render nền 1 lượt + nghe lại bản cắt (lumedit render). check=false: không nghe lại (chỉnh tay không đổi phần cắt).
+ * Mã hoá: NVENC nếu có (edit/encoder.mjs, FX_VCODEC_ARGS), lỗi thì làm lại bằng libx264.
+ */
+async function renderBase({ edlFile, base, draft, R, check = true }) {
+ const { log, timings, checks, step } = R;
+ const enc = await pickEncoder();
+ const rb = await step('render nền', async (pg) => {
+ const go = (kind) => runLumedit(['render', edlFile, '--out', base, ...(draft ? ['--draft-captions'] : []), ...(check ? [] : ['--no-check'])], {
+ env: kind === 'gpu' ? { FX_VCODEC_ARGS: JSON.stringify(videoArgs('gpu', { quality: 18 })) } : {},
+ onProgress: (p) => {
+ if (p.step === 'render') { pg(Math.round(p.pct * 0.6), `${p.done}/${p.total} khung`); if (p.pct % 25 === 0) log(` render ${p.pct}% (${p.done}/${p.total})`); }
+ else { pg(65, 'nghe lại bản cắt'); log(` ${p.step}${p.note ? ': ' + p.note : ''}`); }
+ },
+ });
+ let r = await go(enc.kind);
+ if (!r.ok && enc.kind === 'gpu') { log(` render nền bằng NVENC lỗi (${String(r.error).split(/\r?\n/).pop()}), làm lại bằng libx264`); r = await go('cpu'); r.kind = 'cpu'; }
+ if (!r.ok) throw new Error('render nền lỗi: ' + r.error);
+ return { ...r.result, encoder: r.kind || enc.kind };
+ });
+ timings['render nền (vẽ khung)'] = rb.seconds.render;
+ if (rb.seconds.overcut_check !== undefined) timings['kiểm lẹm chữ (nghe lại)'] = rb.seconds.overcut_check;
+ (checks.encoders ||= {}).base = rb.encoder === 'gpu' ? 'h264_nvenc' : 'libx264';
+ if (check) { checks.overcut = rb.overcut; log(` lẹm chữ: ${rb.overcut?.verdict}`); }
+ saveSig(path.dirname(base), 'base', baseSig(readJson(edlFile), draft));
+ saveSig(path.dirname(base), 'baseSeconds', rb.seconds_out);
+ return rb;
+}
+
+/**
+ * Tiếng động theo giây bản ra. Câu móc lặp lại (repeat): tiếng nằm trong khoảng móc phát cả ở đầu clip lẫn chỗ cũ;
+ * tiếng riêng của câu móc (hook.sfx, vd "boom") chỉ phát ở đầu clip.
+ */
+export function outputSfx(edl) {
+ const tl = timelineOf(edl); const H = edl.hook;
+ const out = edl.sfx.map((s) => ({ t: toOutputNearest(tl, s.at), name: s.name, gainDb: s.gainDb }));
+ if (H?.repeat) for (const s of edl.sfx) if (s.at >= H.start && s.at <= H.end) out.push({ t: s.at - H.start, name: s.name, gainDb: s.gainDb });
+ if (H?.sfx) out.push({ t: Math.max(0, H.sfx.at - H.start), name: H.sfx.name, gainDb: H.sfx.gainDb });
+ return out.sort((a, b) => a.t - b.t);
+}
+
+/**
+ * Bước 6–9: phụ đề, tiếng, ghép, kiểm. reuse.layer / reuse.mix: dùng lại lớp chữ / bản trộn tiếng của lượt trước
+ * (chỉnh tay chỉ đổi nhạc thì không render lại chữ, chỉ đổi chữ thì không trộn lại tiếng). qc=false: bỏ qc-check.
+ */
+async function finishRender({ dir, edl, edlFile, base, rb, draft, R, outName, reuse = {}, qc = true }) {
+ const { log, timings, checks, warnings, step } = R;
+ const layerFile = path.join(dir, LAYER.file);
+ const mixFile = path.join(dir, 'audio', 'mix.wav');
+ // dùng lại chỉ khi chữ ký khớp đúng EDL hiện tại (lượt trước hỏng giữa chừng thì file cũ không khớp → dựng lại)
+ const lSig = layerSig(edl, draft); const mSig = mixSig(edl);
+
+ let overlay = null;
+ const hasLayer = () => (edl.graphics || []).length > 0 || (!draft && edl.captions.words.length > 0);
+ if (reuse.layer !== false && sigOk(dir, 'layer', lSig) && (!hasLayer() || fs.existsSync(layerFile))) {
+ overlay = hasLayer() ? layerFile : null; log(' phụ đề: dùng lại lớp chữ lượt trước (không đổi)');
+ } else await step('phụ đề', async (pg) => {
+ fs.rmSync(layerFile, { force: true, recursive: true });
+ if (!hasLayer()) { pg(100, draft ? 'phụ đề nháp đã vẽ trong nền' : 'không có chữ'); saveSig(dir, 'layer', lSig); return; }
+ let accent; let style = null;
+ try { style = loadStyle(edl.style); accent = style.graphics?.accent; } catch { /* kiểu đã bị xoá: màu mặc định */ }
+ const sc = writeCaptionScene(edl, path.join(dir, 'captions'), { captions: !draft, accent, style });
+ checks.captions = { cards: sc.cards, graphics: sc.graphics, overlaps: 0, box: sc.box, safeZone: 'trong 120–960 px, đáy ≤ 80% khung', quote: sc.quote, hookText: sc.hookText, ticker: sc.ticker, layer: LAYER.name };
+ overlay = await renderCaptionLayer(path.join(dir, 'captions'), layerFile, { log, onPct: (p) => pg(p, 'HyperFrames'), format: LAYER.hf });
+ saveSig(dir, 'layer', lSig);
+ });
+
+ const duration = rb.seconds_out;
+ let mix;
+ if (reuse.mix !== false && sigOk(dir, 'mix', mSig) && fs.existsSync(mixFile)) { mix = { wav: mixFile }; log(' tiếng: dùng lại bản trộn lượt trước (không đổi)'); }
+ else {
+ mix = await step('tiếng', () => buildEditMix({
+ base, duration, workDir: path.join(dir, 'audio'), lufs: edl.output.lufs, log,
+ sfx: edl.audio?.sfxOff ? [] : outputSfx(edl), music: edl.music, voiceGainDb: edl.audio?.voiceGainDb || 0,
+ }));
+ saveSig(dir, 'mix', mSig);
+ }
+
+ const out = path.join(dir, outName);
+ const enc = await pickEncoder();
+ // hình bản ra = nền + lớp chữ: cả hai không đổi so với bản trước (chỉ chỉnh tiếng) → chép luồng hình của bản trước, không mã hoá lại
+ const sigs = readJson(sigFile(dir), {});
+ const vSig = sha([sigs.base || null, lSig, !!overlay]);
+ const prevVideo = sigs.video === vSig && sigs.videoFile && sigs.videoFile !== outName && fs.existsSync(path.join(dir, sigs.videoFile)) ? path.join(dir, sigs.videoFile) : null;
+ await step('ghép', async () => {
+ const tmp = out.replace(/\.mp4$/, '.part.mp4');
+ const mux = (kind) => {
+ if (kind === 'reuse') {
+ return run('ffmpeg', ['-hide_banner', '-y', '-i', prevVideo, '-i', mix.wav, '-map', '0:v:0', '-c:v', 'copy', '-map', '1:a:0', '-c:a', 'aac', '-b:a', '192k', '-ar', '48000', '-ac', '2',
+ '-shortest', '-movflags', '+faststart', tmp], { timeoutMs: 60 * 60e3 });
+ }
+ const args = ['-hide_banner', '-y', '-i', base];
+ if (overlay) args.push(...layerInput(LAYER, overlay));
+ args.push('-i', mix.wav);
+ const ai = overlay ? 2 : 1;
+ if (overlay) args.push('-filter_complex', '[0:v][1:v]overlay=0:0:format=auto:eof_action=pass,format=yuv420p[v]', '-map', '[v]', ...videoArgs(kind, { quality: 18 }), '-pix_fmt', 'yuv420p', '-r', String(OUT.fps));
+ else args.push('-map', '0:v:0', '-c:v', 'copy');
+ args.push('-map', `${ai}:a:0`, '-c:a', 'aac', '-b:a', '192k', '-ar', '48000', '-ac', '2', '-shortest', '-movflags', '+faststart', tmp);
+ return run('ffmpeg', args, { timeoutMs: 60 * 60e3 });
+ };
+ let kind = prevVideo ? 'reuse' : overlay ? enc.kind : 'copy';
+ if (prevVideo) log(` ghép: hình không đổi, chép luồng hình của ${path.basename(prevVideo)} (không mã hoá lại)`);
+ let r = await mux(kind);
+ if (r.code !== 0 && kind === 'reuse') { kind = overlay ? enc.kind : 'copy'; r = await mux(kind); }
+ if (r.code !== 0 && kind === 'gpu') { log(` ghép bằng NVENC lỗi (${r.out.trim().split(/\r?\n/).pop()}), làm lại bằng libx264`); kind = 'cpu'; r = await mux('cpu'); }
+ if (r.code !== 0) throw new Error('ghép lỗi: ' + r.out.trim().split(/\r?\n/).slice(-3).join(' | '));
+ (checks.encoders ||= {}).mux = kind === 'gpu' ? 'h264_nvenc' : kind === 'cpu' ? 'libx264' : kind === 'reuse' ? 'chép hình bản trước' : 'copy';
+ fs.renameSync(tmp, out);
+ saveSig(dir, 'video', vSig); saveSig(dir, 'videoFile', outName);
+ });
+
+ await step('kiểm', async () => {
+ const pr = await run('ffprobe', ['-v', 'error', '-show_entries', 'stream=codec_type,codec_name,width,height,r_frame_rate:format=duration,size', '-of', 'json', out]);
+ const j = JSON.parse(pr.out);
+ const vs = j.streams.find((s) => s.codec_type === 'video'); const as = j.streams.find((s) => s.codec_type === 'audio');
+ checks.file = { width: vs.width, height: vs.height, fps: vs.r_frame_rate, video: vs.codec_name, audio: as?.codec_name || null, duration: +Number(j.format.duration).toFixed(2), bytes: Number(j.format.size) || null };
+ checks.file.ok = vs.width === OUT.width && vs.height === OUT.height && vs.r_frame_rate === '30/1' && !!as;
+ const loud = await measureLoudness(out);
+ checks.loudness = { lufs: +loud.lufs.toFixed(1), truePeak: +loud.truePeak.toFixed(1), ok: Math.abs(loud.lufs - OUT.lufs) <= 1 && loud.truePeak <= -1 };
+ const n = 16; const d = checks.file.duration;
+ const sel = Array.from({ length: n }, (_, k) => `eq(n\\,${Math.floor(((k + 0.5) / n) * d * OUT.fps)})`).join('+');
+ await run('ffmpeg', ['-hide_banner', '-y', '-i', out, '-vf', `select='${sel}',scale=270:480,tile=4x4:padding=6:color=0x181818`, '-frames:v', '1', '-q:v', '3', path.join(dir, 'preview-final.jpg')]);
+ if (qc) {
+ const q = await runLumedit(['qc', out, '--out', path.join(dir, 'qc.json')]);
+ if (q.ok) {
+ checks.qc = { verdict: q.result.verdict, fails: q.result.findings.filter((f) => f.level === 'fail').map((f) => `${f.check}: ${f.what}`), warns: q.result.findings.filter((f) => f.level === 'warn').map((f) => `${f.check}: ${f.what}`) };
+ } else warnings.push('qc-check lỗi: ' + q.error);
+ }
+ log(` file ${checks.file.width}×${checks.file.height} ${checks.file.fps} ${checks.file.duration} s · ${checks.loudness.lufs} LUFS / ${checks.loudness.truePeak} dBTP · qc ${qc ? checks.qc?.verdict || '?' : 'bỏ qua (chỉnh tay)'}`);
+ for (const f of checks.qc?.fails || []) log(` qc FAIL ${f}`);
+ });
+ timings.total = +Object.entries(timings).filter(([k]) => !k.includes('(') && k !== 'total').reduce((s, [, v]) => s + v, 0).toFixed(1);
+ log(`XONG ${out} (${timings.total} s)`);
+ return { out, edl: edlFile };
+}
+
+/**
+ * Sửa bằng lời: không phân tích lại. Ra out-r<n>.mp4 mới; EDL cũ → versions/edl-<n>.json.
+ * opts: {log?, progress?}. Trả như editVideo (+ revision).
+ */
+export async function reviseEdit(id, instruction, opts = {}) {
+ const dir = editDir(id);
+ const R = runner(dir, opts);
+ const { log, timings, checks, warnings, step } = R;
+ const result = { ok: false, id, dir, revision: null, timings, checks, warnings };
+ let backup = null;
+ try {
+ instruction = String(instruction || '').trim();
+ if (!instruction) throw new Error('thiếu lời sửa');
+ if (instruction.length > 1000) throw new Error('lời sửa quá dài (tối đa 1000 ký tự)');
+ const state = readJson(path.join(dir, 'state.json'));
+ const ing = readJson(path.join(dir, 'ingest.json'));
+ const analysis = readJson(path.join(dir, 'analysis.json'));
+ const curEdl = readJson(path.join(dir, 'edl.json'));
+ if (!state || !ing || !analysis || !curEdl) throw new Error('bản dựng này chưa xong lần đầu (thiếu state/ingest/analysis/edl)');
+ const style = { ...loadStyle(state.style), sfxNames: SFX_NAMES, hesitations: new Set(analysis.hesitations || []) };
+ const words = wordList(analysis);
+ const n = (state.revisions?.length || 0) + 1;
+ log(`sửa lần ${n}: "${instruction}"`);
+ const rev = await step('LLM lập EDL', () => proposeRevision({
+ words, edl: curEdl, proposal: state.proposal, style: applyOverrides(style, state.overrides), overrides: state.overrides, instruction, names: state.names, log,
+ exclude: new Set(state.exclude || []),
+ }));
+ const newCuts = rev.cutsOut.flatMap((c) => outputCutToSource(timelineOf(curEdl), c.start, c.end, words));
+ log(` LLM: ${rev.notes || '(không ghi chú)'}${newCuts.length ? ` · cắt thêm ${newCuts.map((c) => `${c.start.toFixed(2)}–${c.end.toFixed(2)} s nguồn`).join(', ')}` : ''}`);
+ // giữ bản cũ
+ const vdir = path.join(dir, 'versions');
+ fs.mkdirSync(vdir, { recursive: true });
+ backup = path.join(vdir, `edl-${n}.json`);
+ fs.copyFileSync(path.join(dir, 'edl.json'), backup);
+ const next = { ...state, proposal: rev.proposal, overrides: rev.overrides, extraCuts: [...(state.extraCuts || []), ...newCuts] };
+ if (!fs.existsSync(ing.proxy.file)) {
+ // proxy bị dọn sau lượt trước (jobs.cleanupEdit): dựng lại từ nguồn, cùng thông số → cùng file (x264 tất định),
+ // nên cache chữ/mặt (proxy.words.json, proxy.face.json) dùng lại, không chép lời lại
+ if (!fs.existsSync(ing.source.file)) throw new Error('không còn file nguồn ' + ing.source.file);
+ const t = Date.now();
+ await makeProxy(ing.source.file, ing.info, ing.proxy.file, { log, encoder: ing.encoder || 'cpu' });
+ log(` dựng lại proxy từ nguồn: ${((Date.now() - t) / 1000).toFixed(1)} s`);
+ }
+ const edl = await buildEdl({ id, dir, ing, analysis, words, style, state: next, checks, warnings, log });
+ const outName = `out-r${n}.mp4`;
+ next.revisions = [...(state.revisions || []), { n, instruction, notes: rev.notes, at: new Date().toISOString(), previous: state.out || 'out.mp4', out: outName }];
+ const repair = cutRepairer({ id, dir, ing, analysis, words, style, state: next, checks, warnings, log });
+ const r = await renderEdl({ dir, edl, draft: state.draft, R, outName, repair });
+ next.out = outName;
+ fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify(next, null, 1));
+ Object.assign(result, r, { ok: true, revision: next.revisions[next.revisions.length - 1] });
+ } catch (e) {
+ result.error = e.message;
+ log('LỖI: ' + e.message);
+ // lỗi giữa chừng: trả edl.json về bản trước lần sửa (state.json chỉ ghi khi render xong nên vẫn là bản cũ)
+ if (backup && fs.existsSync(backup)) fs.copyFileSync(backup, path.join(dir, 'edl.json'));
+ }
+ const prevResult = readJson(path.join(dir, 'result.json'), {});
+ fs.writeFileSync(path.join(dir, 'result.json'), JSON.stringify({ ...prevResult, ...(result.ok ? result : {}), lastRevise: { ok: result.ok, error: result.error || null, at: new Date().toISOString() } }, null, 2));
+ return result;
+}
+
+// cho script kiểm thử: dựng lại EDL + render từ state.json đã có (không gọi LLM, không phân tích lại)
+// ---- chữ ký từng lớp (render.sig.json): lớp nào chưa đổi so với EDL hiện tại thì chỉnh tay dùng lại được -------------
+const sha = (x) => crypto.createHash('sha1').update(JSON.stringify(x)).digest('hex');
+/** Nền: phần cắt, móc, zoom, khung, đồ hoạ (kính mờ + thu khung vẽ trong nền), trích dẫn, phụ đề nháp (vẽ PIL trong nền). */
+export const baseSig = (edl, draft) => sha([edl.proxy.file, edl.keep, edl.hook, edl.zooms, edl.reframe, edl.graphics || [], edl.quote, draft ? edl.captions : null, !!draft]);
+/** Lớp chữ: phụ đề + đồ hoạ + chữ móc + trích dẫn trên trục bản ra. */
+export const layerSig = (edl, draft) => sha([LAYER.name, edl.style, edl.keep, edl.hook, edl.captions, edl.graphics || [], edl.hookText, edl.quote, !!draft]);
+/** Tiếng: giọng gốc (theo phần cắt) + nhạc + sfx + giọng/sfx chỉnh tay + LUFS. */
+export const mixSig = (edl) => sha([edl.keep, edl.hook, edl.audio, edl.music, edl.audio?.sfxOff ? [] : outputSfx(edl), edl.output.lufs]);
+const sigFile = (dir) => path.join(dir, 'render.sig.json');
+const sigOk = (dir, k, v) => readJson(sigFile(dir), {})[k] === v;
+function saveSig(dir, k, v) { const all = readJson(sigFile(dir), {}); all[k] = v; fs.writeFileSync(sigFile(dir), JSON.stringify(all, null, 1)); }
+
+/** Số giây của video nền (số khung / 30): độ dài bản trộn tiếng khi không render lại nền. */
+async function baseSeconds(base) {
+ const r = await run('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-count_packets', '-show_entries', 'stream=nb_read_packets', '-of', 'csv=p=0', base]);
+ const n = parseInt(r.out, 10);
+ if (!Number.isFinite(n) || n <= 0) throw new Error('không đọc được video nền ' + path.basename(base));
+ return +(n / OUT.fps).toFixed(3);
+}
+
+/**
+ * Chỉnh tay (edit/manual.mjs): không LLM, không phân tích lại, chỉ dựng lại lớp cần thiết —
+ * xoá zoom → render nền (không nghe lại); phụ đề/look/chữ nhấn/đồ hoạ → lớp chữ; nhạc/giọng/sfx → trộn tiếng; luôn ghép.
+ * Ra out-r<n>.mp4 mới, EDL cũ → versions/edl-<n>.json. patch đã qua parseManual. opts: {log?, progress?, uploads?}.
+ */
+export async function manualEdit(id, patch, opts = {}) {
+ const dir = editDir(id);
+ const R = runner(dir, opts);
+ const { log, checks, warnings } = R;
+ const result = { ok: false, id, dir, revision: null, timings: R.timings, checks, warnings };
+ let backup = null;
+ try {
+ const state = readJson(path.join(dir, 'state.json'));
+ const ing = readJson(path.join(dir, 'ingest.json'));
+ const curEdl = readJson(path.join(dir, 'edl.json'));
+ if (!state || !ing || !curEdl) throw new Error('bản dựng này chưa xong lần đầu (thiếu state/ingest/edl)');
+ let style = null;
+ try { style = loadStyle(state.style); } catch { /* kiểu đã bị xoá: mặc định nhạc −22 dB */ }
+ const ap = applyPatch(curEdl, state, patch, { dir, style, uploads: opts.uploads || {} });
+ const n = (state.revisions?.length || 0) + 1;
+ log(`chỉnh tay lần ${n}: ${ap.summary.join('; ')}`);
+ for (const w of ap.warnings) { log(' ' + w); warnings.push(w); }
+ const edl = ap.edl;
+ const base = path.join(dir, 'base.mp4');
+ // nền chỉ dựng lại khi phần vẽ trong nền đổi (zoom, đồ hoạ có kính mờ) hoặc thiếu/không khớp chữ ký
+ const redoBase = !fs.existsSync(base) || !sigOk(dir, 'base', baseSig(edl, state.draft));
+ if (ap.redo.base && !redoBase) log(' nền: không đổi, dùng lại');
+ const v = validateEdl(edl, { sfxNames: SFX_NAMES, checkFiles: false });
+ if (!v.ok) throw Object.assign(new Error('EDL sau chỉnh tay không hợp lệ: ' + v.errors.slice(0, 4).map((e) => `${e.code} ${e.path}: ${e.msg}`).join('; ')), { code: 400 });
+ if (edl.music && !fs.existsSync(edl.music.file)) throw new Error('không thấy file nhạc ' + path.basename(edl.music.file));
+ const vdir = path.join(dir, 'versions');
+ fs.mkdirSync(vdir, { recursive: true });
+ backup = path.join(vdir, `edl-${n}.json`);
+ fs.copyFileSync(path.join(dir, 'edl.json'), backup);
+ const edlFile = path.join(dir, 'edl.json');
+ fs.writeFileSync(edlFile, JSON.stringify(edl, null, 1));
+ let rb;
+ if (redoBase) {
+ if (!fs.existsSync(ing.proxy.file)) {
+ if (!fs.existsSync(ing.source.file)) throw new Error('không còn file nguồn ' + ing.source.file);
+ const t = Date.now();
+ await makeProxy(ing.source.file, ing.info, ing.proxy.file, { log, encoder: ing.encoder || 'cpu' });
+ R.timings['dựng lại proxy'] = +((Date.now() - t) / 1000).toFixed(1); // proxy bị dọn sau lượt trước (jobs.cleanupEdit)
+ log(` dựng lại proxy từ nguồn: ${R.timings['dựng lại proxy']} s`);
+ }
+ rb = await renderBase({ edlFile, base, draft: state.draft, R, check: false });
+ } else rb = { seconds_out: readJson(sigFile(dir), {}).baseSeconds || await baseSeconds(base) };
+ // lớp chữ / bản trộn dùng lại khi chữ ký khớp EDL mới (nền đổi vì zoom thì tiếng gốc vẫn y hệt → trộn cũ dùng được)
+ const reuse = {};
+ const outName = `out-r${n}.mp4`;
+ const r = await finishRender({ dir, edl, edlFile, base, rb, draft: state.draft, R, outName, reuse, qc: false });
+ const next = {
+ ...state, manual: ap.manual, music: ap.music, out: outName,
+ revisions: [...(state.revisions || []), { n, manual: true, instruction: ap.summary.join('; '), notes: ap.warnings.join('; '), at: new Date().toISOString(), previous: state.out || 'out.mp4', out: outName, seconds: R.timings.total }],
+ };
+ fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify(next, null, 1));
+ Object.assign(result, r, { ok: true, revision: next.revisions[next.revisions.length - 1] });
+ } catch (e) {
+ result.error = e.message;
+ log('LỖI: ' + e.message);
+ if (backup && fs.existsSync(backup)) fs.copyFileSync(backup, path.join(dir, 'edl.json'));
+ }
+ const prevResult = readJson(path.join(dir, 'result.json'), {});
+ // giữ checks/timings của lần dựng đầy đủ (qc, lẹm chữ…), cập nhật phần file/tiếng/thời gian của bản mới
+ const merged = result.ok ? { ...prevResult, out: result.out, edl: result.edl, checks: { ...prevResult.checks, ...checks }, lastManual: { timings: R.timings, warnings } } : prevResult;
+ fs.writeFileSync(path.join(dir, 'result.json'), JSON.stringify({ ...merged, lastRevise: { ok: result.ok, manual: true, error: result.error || null, at: new Date().toISOString() } }, null, 2));
+ return result;
+}
+
+export const _internal = { buildEdl, renderEdl, runner };
diff --git a/edit/studio-media.mjs b/edit/studio-media.mjs
new file mode 100644
index 0000000..0476637
--- /dev/null
+++ b/edit/studio-media.mjs
@@ -0,0 +1,117 @@
+// Phương tiện cho Studio (timeline trình edit): dải ảnh khung (sprite) của từng bản ra và đỉnh sóng của bài nhạc.
+// Sinh bằng ffmpeg, cache theo bản: strip-<out>.jpg + strip-<out>.json trong edits/<id>/, đỉnh sóng giữ trong RAM
+// theo (file, mtime). Chỉ đọc file trong thư mục edit (tên file kiểm bằng regex, không nhận đường dẫn).
+import fs from 'node:fs';
+import path from 'node:path';
+import { spawn } from 'node:child_process';
+import { MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';
+
+export const OUT_RE = /^out(-r\d{1,4})?\.mp4$/;
+const TILE_W = 54; const TILE_H = 96; // 9:16
+const MAX_TILES = 240;
+const httpErr = (code, msg) => Object.assign(new Error(msg), { code });
+
+function ff(args, { binary = false, timeoutMs = 120000 } = {}) {
+ return new Promise((resolve, reject) => {
+ const p = spawn('ffmpeg', ['-hide_banner', '-loglevel', 'error', ...args], { windowsHide: true });
+ const out = []; let err = '';
+ const timer = setTimeout(() => { p.kill('SIGKILL'); reject(new Error('ffmpeg quá thời gian')); }, timeoutMs);
+ p.stdout.on('data', (d) => out.push(d));
+ p.stderr.on('data', (d) => { err += d; if (err.length > 4000) err = err.slice(-4000); });
+ p.on('error', (e) => { clearTimeout(timer); reject(e); });
+ p.on('close', (code) => {
+ clearTimeout(timer);
+ if (code !== 0) reject(new Error('ffmpeg lỗi: ' + err.trim().split(/\r?\n/).pop()));
+ else resolve(binary ? Buffer.concat(out) : Buffer.concat(out).toString('utf8'));
+ });
+ });
+}
+
+async function durationOf(file) {
+ const r = await new Promise((resolve) => {
+ const p = spawn('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', file], { windowsHide: true });
+ let o = ''; p.stdout.on('data', (d) => { o += d; }); p.on('close', () => resolve(o)); p.on('error', () => resolve(''));
+ });
+ const d = parseFloat(r);
+ if (!Number.isFinite(d) || d <= 0) throw httpErr(422, 'không đọc được độ dài ' + path.basename(file));
+ return d;
+}
+
+const pending = new Map();
+/** Dải ảnh khung của 1 bản ra: {url, n, every, tileW, tileH, seconds}. Sinh 1 lần (ffmpeg fps + tile), lần sau đọc cache. */
+export function stripOf(dir, id, out) {
+ if (!OUT_RE.test(String(out))) throw httpErr(400, 'tên bản ra không hợp lệ');
+ const video = path.join(dir, out);
+ if (!fs.existsSync(video)) throw httpErr(404, 'không thấy ' + out);
+ const base = 'strip-' + out.replace(/\.mp4$/, '');
+ const jpg = path.join(dir, base + '.jpg'); const meta = path.join(dir, base + '.json');
+ const url = (m) => ({ ...m, url: `/edits/${id}/${base}.jpg?v=${Math.round(fs.statSync(jpg).mtimeMs)}` });
+ try {
+ const m = JSON.parse(fs.readFileSync(meta, 'utf8'));
+ if (fs.existsSync(jpg) && fs.statSync(jpg).mtimeMs >= fs.statSync(video).mtimeMs - 1) return Promise.resolve(url(m));
+ } catch { /* chưa có */ }
+ const key = jpg;
+ if (pending.has(key)) return pending.get(key);
+ const job = (async () => {
+ const seconds = await durationOf(video);
+ const n = Math.max(1, Math.min(MAX_TILES, Math.ceil(seconds / 0.5)));
+ const every = seconds / n;
+ const tmp = jpg + '.part.jpg';
+ // mỗi ô lấy khung ở giữa khoảng của nó; tile 1 hàng n cột
+ await ff(['-y', '-i', video, '-vf', `fps=1/${every.toFixed(4)}:start_time=${(every / 2).toFixed(4)},scale=${TILE_W}:${TILE_H}:force_original_aspect_ratio=increase,crop=${TILE_W}:${TILE_H},tile=${n}x1`, '-frames:v', '1', '-q:v', '5', tmp]);
+ fs.renameSync(tmp, jpg);
+ const m = { n, every: +every.toFixed(4), tileW: TILE_W, tileH: TILE_H, seconds: +seconds.toFixed(3) };
+ fs.writeFileSync(meta, JSON.stringify(m));
+ return url(m);
+ })().finally(() => pending.delete(key));
+ pending.set(key, job);
+ return job;
+}
+
+const NAME_RE = /^music(-[a-z0-9-]{1,30})?\.(wav|mp3|m4a|aac|ogg|flac|opus)$|^music-up-\d{1,4}\.(mp3|wav|m4a|aac|ogg|flac|opus)$/;
+/** Tên file nhạc trong thư mục edit cho 1 nguồn chỉnh tay ('keep' = nhạc của bản hiện tại). Nhạc tổng hợp chưa có thì sinh. */
+export function musicFileFor(dir, source, currentFile) {
+ const s = String(source || '');
+ if (s === 'keep') {
+ if (!currentFile) throw httpErr(404, 'bản này không có nhạc');
+ const name = path.basename(currentFile);
+ if (path.resolve(path.dirname(currentFile)) !== path.resolve(dir) || !NAME_RE.test(name)) throw httpErr(404, 'nhạc của bản này nằm ngoài thư mục edit');
+ return name;
+ }
+ let m = /^synth:([a-z0-9-]{1,30})$/.exec(s);
+ if (m) {
+ if (!MUSIC_STYLES.includes(m[1])) throw httpErr(400, `không có nhạc tổng hợp "${m[1]}"`);
+ const name = `music-${m[1]}.wav`;
+ if (!fs.existsSync(path.join(dir, name))) writeMusic(m[1], path.join(dir, name), 60, 1);
+ return name;
+ }
+ m = /^upload:(music-up-\d{1,4}\.(mp3|wav|m4a|aac|ogg|flac|opus))$/.exec(s);
+ if (m) { if (!fs.existsSync(path.join(dir, m[1]))) throw httpErr(404, 'chưa tải lên ' + m[1]); return m[1]; }
+ throw httpErr(400, 'nguồn nhạc không hợp lệ');
+}
+export const isMusicName = (n) => NAME_RE.test(String(n));
+
+const waves = new Map(); // file|mtime → {rate, peaks, seconds}
+export const WAVE_RATE = 25; // đỉnh mỗi giây
+/** Đỉnh sóng (0..1, trị tuyệt đối lớn nhất mỗi 1/25 s) của 1 file nhạc trong thư mục edit. */
+export async function waveOf(dir, name) {
+ if (!NAME_RE.test(name)) throw httpErr(400, 'tên nhạc không hợp lệ');
+ const f = path.join(dir, name);
+ const st = fs.statSync(f);
+ const key = `${f}|${st.mtimeMs}`;
+ if (waves.has(key)) return waves.get(key);
+ const sr = 4000;
+ const pcm = await ff(['-i', f, '-ac', '1', '-ar', String(sr), '-t', '600', '-f', 's16le', '-acodec', 'pcm_s16le', 'pipe:1'], { binary: true });
+ const n = Math.floor(pcm.length / 2); const per = sr / WAVE_RATE;
+ const peaks = [];
+ let top = 1;
+ for (let i = 0; i < n; i += per) {
+ let mx = 0;
+ for (let j = i; j < Math.min(n, i + per); j++) { const v = Math.abs(pcm.readInt16LE(j * 2)); if (v > mx) mx = v; }
+ peaks.push(mx); if (mx > top) top = mx;
+ }
+ const r = { rate: WAVE_RATE, seconds: +(n / sr).toFixed(3), peaks: peaks.map((x) => Math.round((x / top) * 100) / 100) };
+ if (waves.size > 30) waves.delete(waves.keys().next().value);
+ waves.set(key, r);
+ return r;
+}
diff --git a/edit/test/studio-check.mjs b/edit/test/studio-check.mjs
new file mode 100644
index 0000000..6aa6c12
--- /dev/null
+++ b/edit/test/studio-check.mjs
@@ -0,0 +1,126 @@
+#!/usr/bin/env node
+// Kiểm phần API mở rộng cho Studio (edit/manual.mjs + edit/http.mjs + edit/studio-media.mjs):
+// zoom thêm/sửa (giây bản ra, không chồng), đồ hoạ dời/giãn giờ + sửa ô chữ/số (kiểu khớp, ≥ 1,5 s), giữ qua dựng lại,
+// view có look css / vết cắt / ô đồ hoạ. Có cổng thì kiểm REST: manual?rev, strip, wave, tên file lạ, Origin lạ.
+// node edit/test/studio-check.mjs [port] [editId đã dựng xong]
+import http from 'node:http';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { parseManual, applyPatch, applyManual, manualView } from '../manual.mjs';
+import { validateEdl } from '../edl.mjs';
+
+let fails = 0;
+const check = (ok, what) => { console.log(`${ok ? 'PASS' : 'FAIL'} ${what}`); if (!ok) fails++; };
+const throws = (f, code, re) => { try { f(); return false; } catch (e) { return (code == null || e.code === code) && (!re || re.test(e.message)); } };
+
+// ---- schema ----
+check(!throws(() => parseManual({ zooms: { add: [{ at: 2, dur: 1, scale: 1.1, kind: 'push' }] } })), 'zoom add hợp lệ qua');
+check(throws(() => parseManual({ zooms: { add: [{ at: 2, dur: 1, scale: 2, kind: 'push' }] } }), 400, /scale/), 'zoom scale 2 (trần 1,6) → 400');
+check(throws(() => parseManual({ zooms: { add: [{ at: 2, dur: 1, scale: 1.1, kind: 'spin' }] } }), 400), 'zoom kiểu lạ → 400');
+check(throws(() => parseManual({ zooms: { set: [{ n: 0, x: 1 }] } }), 400), 'zoom set khoá lạ → 400');
+check(throws(() => parseManual({ graphics: { set: [{ id: 'g1', data: { html: '<b>' } }] } }), 400), 'đồ hoạ: ô lạ (html) → 400');
+check(throws(() => parseManual({ graphics: { set: [{ id: 'g1', data: { title: 'x'.repeat(31) } }] } }), 400), 'đồ hoạ: tiêu đề > 30 ký tự → 400');
+check(throws(() => parseManual({ graphics: { set: [{ id: 'g1', data: { rows: [{ k: 12, label: 'a' }] } }] } }), 400), 'đồ hoạ: dòng số 12 → 400');
+
+// ---- EDL giả: 2 đoạn giữ, 2 zoom, 2 đồ hoạ ----
+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'lumedit-studio-'));
+const words = Array.from({ length: 24 }, (_, i) => ({ i, w: `chữ${i}`, start: 1 + i * 0.5, end: 1.4 + i * 0.5 })).filter((w) => w.end <= 7 || w.start >= 8);
+const edl = {
+ version: 1, id: 't', createdAt: new Date().toISOString(), style: 'sach-gon',
+ source: { file: 'x.mp4', sha256: '0'.repeat(64), size: 1, duration: 20, startTime: 0, fps: 30, vfr: false, rotation: 0, width: 1920, height: 1080, codec: 'h264', hdr: false, hasAudio: true },
+ proxy: { file: 'x.mov', width: 1920, height: 1080, fps: 30, audioRate: 48000 },
+ output: { width: 1080, height: 1920, fps: 30, audioRate: 48000, lufs: -14 },
+ keep: [{ start: 0.5, end: 7 }, { start: 8, end: 13.5 }], removed: [{ start: 7, end: 8, reason: 'pause', words: '' }], reframe: { mode: 'center' },
+ zooms: [{ at: 1.2, dur: 1, scale: 1.2, kind: 'punch' }, { at: 9, dur: 1.5, scale: 1.1, kind: 'push' }],
+ captions: { style: 'sach-gon', renderer: 'hyperframes', maxWords: 3, position: 'lower', words, highlights: [1] },
+ sfx: [], music: null,
+ graphics: [
+ { id: 'g1', type: 'spec_table', start: 2, end: 5, estimate: false, data: { at: 2.05, title: 'Giá', unit: 'triệu', rows: [{ label: 'A', value: '15', at: 3 }, { label: 'B', value: '22', at: 4 }] }, box: { x: 120, y: 200, w: 840, h: 300, scale: 1 }, face: null, squeeze: null },
+ { id: 'g2', type: 'price_tag', start: 9.5, end: 11.5, estimate: false, data: { at: 9.55, value: 9.5, prefix: '', suffix: 'triệu', label: 'RTX' }, box: { x: 230, y: 600, w: 620, h: 240, scale: 1 }, face: null, squeeze: null },
+ ],
+ hook: null, hookText: null, quote: null, audio: { crossfadeMs: 20, keepSourceAudio: true },
+};
+check(validateEdl(edl, { checkFiles: false }).ok, 'EDL giả hợp lệ');
+const state = { style: 'sach-gon', draft: false };
+// bản ra: [0.5–7] → 0–6.5, [8–13.5] → 6.5–12
+const v = manualView(edl, state);
+check(JSON.stringify(v.cuts) === '[6.5]', `vết cắt bản ra: ${JSON.stringify(v.cuts)}`);
+check(v.captions.looks.every((l) => l.css && l.css.font && l.css.size > 0 && l.css.cy > 0), 'mỗi look có css (font, cỡ, cy) cho lớp xem trước');
+check(v.graphics[0].data.rows[1].value === '22' && v.graphics[0].data.at === undefined && v.graphics[0].box?.w === 840, 'đồ hoạ trong view: ô chữ/số + box, không lộ mốc nội bộ');
+
+// zoom thêm ở giây bản ra 7.0 (= nguồn 8.5), sửa zoom 0, xoá zoom 1
+const a = applyPatch(edl, state, parseManual({ zooms: { add: [{ at: 7, dur: 1, scale: 1.15, kind: 'punch' }], set: [{ n: 0, scale: 1.3, dur: 0.8 }], remove: [1] } }), { dir: tmp });
+check(a.edl.zooms.length === 2 && a.edl.zooms[1].at === 8.5 && a.edl.zooms[0].scale === 1.3 && a.edl.zooms[0].dur === 0.8, `zoom: thêm 7 s bản ra → 8,5 s nguồn, sửa zoom 0, xoá zoom 1 (${JSON.stringify(a.edl.zooms)})`);
+check(a.redo.base && !a.redo.layer && !a.redo.mix, 'zoom đổi → chỉ dựng lại nền');
+check(throws(() => applyPatch(edl, state, parseManual({ zooms: { add: [{ at: 0.9, dur: 1, scale: 1.1, kind: 'push' }] } }), { dir: tmp }), 400, /chồng/), 'zoom mới chồng zoom cũ → 400');
+check(throws(() => applyPatch(edl, state, parseManual({ zooms: { add: [{ at: 11.9, dur: 1, scale: 1.1, kind: 'push' }] } }), { dir: tmp }), 400, /cuối/), 'zoom chạy quá cuối video → 400');
+check(throws(() => applyPatch(edl, state, parseManual({ zooms: { set: [{ n: 5, scale: 1.1 }] } }), { dir: tmp }), 400), 'sửa zoom không có → 400');
+
+// đồ hoạ: dời g1 sang 3–6 s bản ra, sửa ô; giãn g2
+const b = applyPatch(edl, state, parseManual({ graphics: { set: [{ id: 'g1', start: 3, end: 6, data: { title: 'Giá mới', rows: [{ k: 0, value: '16' }] } }, { id: 'g2', end: 11.5 }] } }), { dir: tmp });
+const g1 = b.edl.graphics.find((g) => g.id === 'g1'); const g2 = b.edl.graphics.find((g) => g.id === 'g2');
+check(g1.start === 3.5 && g1.end === 6.5 && g1.data.title === 'Giá mới' && g1.data.rows[0].value === '16', `dời g1 3–6 s bản ra → ${g1.start}–${g1.end} s nguồn, sửa tiêu đề + ô`);
+check(g1.data.rows[0].at > g1.data.at && g1.data.rows[1].at <= g1.end && g1.data.at >= g1.start, 'mốc dòng trong đồ hoạ dời theo, nằm trong khoảng mới');
+check(g2.end === 13 && b.redo.base && b.redo.layer, `giãn g2 tới 11,5 s bản ra (nguồn ${g2.end}); dời giờ → nền + lớp chữ`);
+check(validateEdl(b.edl, { checkFiles: false }).ok, 'EDL sau dời đồ hoạ hợp lệ');
+check(throws(() => applyPatch(edl, state, parseManual({ graphics: { set: [{ id: 'g1', start: 3, end: 4 }] } }), { dir: tmp }), 400, /1.5/), 'đồ hoạ < 1,5 s → 400');
+check(throws(() => applyPatch(edl, state, parseManual({ graphics: { set: [{ id: 'g2', data: { value: 'mười' } }] } }), { dir: tmp }), 400, /số/), 'ô số nhận chữ → 400');
+check(throws(() => applyPatch(edl, state, parseManual({ graphics: { set: [{ id: 'g1', data: { text: 'x' } }] } }), { dir: tmp }), 400, /không có ô/), 'ô không có ở loại đồ hoạ này → 400');
+check(throws(() => applyPatch(edl, state, parseManual({ graphics: { set: [{ id: 'g9', end: 9 }] } }), { dir: tmp }), 400), 'đồ hoạ không có → 400');
+const c = applyPatch(edl, state, parseManual({ graphics: { set: [{ id: 'g2', data: { value: '10,5' } }] } }), { dir: tmp });
+check(c.edl.graphics[1].data.value === 10.5 && c.redo.layer, 'ô số nhận "10,5" → 10.5, chỉ đổi chữ → lớp chữ');
+
+// dựng lại EDL (sửa bằng lời): giữ zoom thêm/sửa/xoá + đồ hoạ dời/sửa
+const man = { ...a.manual, ...b.manual };
+const rebuilt = JSON.parse(JSON.stringify(edl));
+applyManual(rebuilt, man);
+check(rebuilt.zooms.length === 2 && rebuilt.zooms.some((z) => z.at === 8.5 && z.kind === 'punch') && rebuilt.zooms.some((z) => z.scale === 1.3), 'dựng lại: giữ zoom thêm + zoom sửa, bỏ zoom đã xoá');
+const rg = rebuilt.graphics.find((g) => g.id === 'g1');
+check(rg.start === 3.5 && rg.end === 6.5 && rg.data.title === 'Giá mới', 'dựng lại: giữ đồ hoạ đã dời + sửa chữ');
+fs.rmSync(tmp, { recursive: true, force: true });
+
+// ---- REST ----
+const PORT = Number(process.argv[2]); const ID = process.argv[3];
+if (PORT) {
+ const HOST = `127.0.0.1:${PORT}`;
+ const req = ({ method = 'GET', p, headers = {}, body }) => new Promise((resolve) => {
+ const r = http.request({ host: '127.0.0.1', port: PORT, method, path: p, headers: { Host: HOST, ...headers } }, (res) => {
+ let d = ''; res.on('data', (x) => { d += x; }); res.on('end', () => resolve({ code: res.statusCode, body: d, type: res.headers['content-type'] }));
+ });
+ r.on('error', (e) => resolve({ code: -1, body: e.message }));
+ r.end(body);
+ });
+ let r = await req({ p: '/api/edits/khong-co/strip' }); check(r.code === 404, `strip id lạ → 404 (${r.code})`);
+ r = await req({ p: '/api/edits/khong-co/wave' }); check(r.code === 404, `wave id lạ → 404 (${r.code})`);
+ if (ID) {
+ r = await req({ p: `/api/edits/${ID}/manual?rev=0` });
+ const v0 = r.code === 200 ? JSON.parse(r.body) : null;
+ check(!!v0 && v0.rev === 0 && v0.readOnly === true && /out\.mp4/.test(v0.media.out || ''), `manual?rev=0 → bản gốc, chỉ đọc (${r.code})`);
+ r = await req({ p: `/api/edits/${ID}/manual` });
+ const vl = JSON.parse(r.body);
+ check(vl.rev === vl.latest && !vl.readOnly && Array.isArray(vl.versions) && vl.versions.length === vl.latest + 1, `manual mới nhất r${vl.latest}, ${vl.versions.length} bản`);
+ r = await req({ p: `/api/edits/${ID}/manual?rev=999` }); check(r.code === 404, `rev không có → 404 (${r.code})`);
+ r = await req({ p: `/api/edits/${ID}/manual?rev=-1` }); check(r.code === 404, `rev âm → 404 (${r.code})`);
+ r = await req({ p: `/api/edits/${ID}/strip?out=${encodeURIComponent(vl.media.outName)}` });
+ const s = r.code === 200 ? JSON.parse(r.body) : null;
+ check(!!s && s.n > 0 && s.every > 0 && /^\/edits\//.test(s.url), `strip ${vl.media.outName}: ${s?.n} ô, ${s?.every} s/ô`);
+ if (s) { r = await req({ p: s.url.split('?')[0] }); check(r.code === 200 && r.type === 'image/jpeg', `ảnh strip phục vụ được (${r.code} ${r.type})`); }
+ r = await req({ p: `/api/edits/${ID}/strip?out=..%2F..%2Fx.mp4` }); check(r.code === 400, `strip out có ../ → 400 (${r.code})`);
+ r = await req({ p: `/api/edits/${ID}/strip?out=job.json` }); check(r.code === 400, `strip out không phải bản ra → 400 (${r.code})`);
+ r = await req({ p: `/api/edits/${ID}/wave?src=synth:chill` });
+ const w = r.code === 200 ? JSON.parse(r.body) : null;
+ check(!!w && w.rate === 25 && w.peaks.length > 100 && Math.max(...w.peaks) <= 1 && /music-chill\.wav/.test(w.url), `wave synth:chill: ${w?.peaks.length} đỉnh, ${w?.seconds} s`);
+ r = await req({ p: `/api/edits/${ID}/wave?src=../../etc/passwd` }); check(r.code === 400, `wave nguồn lạ → 400 (${r.code})`);
+ r = await req({ p: `/api/edits/${ID}/wave?file=job.json&src=x` }); check(r.code === 400, `wave file lạ không được đọc → 400 (${r.code})`);
+ r = await req({ p: `/edits/${ID}/job.json` }); check(r.code === 404, `/edits/<id>/job.json không phục vụ (${r.code})`);
+ r = await req({ p: `/edits/${ID}/state.json` }); check(r.code === 404, `/edits/<id>/state.json không phục vụ (${r.code})`);
+ r = await req({ method: 'HEAD', p: `/edits/${ID}/base.mp4` }); check(r.code === 200 || r.code === 404, `base.mp4 phục vụ được khi có (${r.code})`);
+ r = await req({ method: 'POST', p: `/api/edits/${ID}/manual`, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ zooms: { add: [{ at: 0.01, dur: 8, scale: 1.1, kind: 'push' }, { at: 0.02, dur: 8, scale: 1.1, kind: 'push' }] } }) });
+ check(r.code === 400, `zoom thêm chồng nhau → 400 đồng bộ, không xếp hàng (${r.code})`);
+ r = await req({ method: 'POST', p: `/api/edits/${ID}/manual`, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ graphics: { set: [{ id: 'khong-co', end: 3 }] } }) });
+ check(r.code === 400, `đồ hoạ không có → 400 (${r.code})`);
+ }
+}
+console.log(fails ? `\n${fails} FAIL` : '\nTẤT CẢ PASS');
+process.exit(fails ? 1 : 0);
diff --git a/server/server.mjs b/server/server.mjs
index 500dd42..17d490b 100644
--- a/server/server.mjs
+++ b/server/server.mjs
@@ -1,393 +1,393 @@
-// Server API + UI. Chỉ bind 127.0.0.1:4400. Không framework.
-import http from 'node:http';
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { spawn } from 'node:child_process';
-import {
- ROOT, JOBS, TEMPLATES, loadCatalog, templateName, createJob, runJob, renderJob, readJob, listJobs, readLog, markStale,
- dueJobs, resolveMode, submitScene, previewJob, createJobs, MAX_BATCH,
-} from '../generator/jobs.mjs';
-import { findClaude } from '../generator/claude.mjs';
-import { rewriteScript, resolveRewriteEngine, REWRITE_MAX_CHARS } from '../generator/rewrite.mjs';
-import { config } from '../generator/config.mjs';
-import { reAudio, listVersions, audioBusy, saveAudioSpec } from '../generator/audio-job.mjs';
-import { audioOptions, normalizeAudioPrefs, voiceEngine, sampleTextFor } from '../engine/audio/prefs.mjs';
-import { MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';
-import { synthVoice } from '../engine/audio/voice.mjs';
-import { handleEditRoute, initEdits } from '../edit/http.mjs';
-import { handleVoiceRoute, initVoices } from './voices-http.mjs';
-import { handlePackRoute } from '../packs/http.mjs';
-import { listTemplates, resolveTemplate, parsePackRef, BUILTIN_TEMPLATE_RE } from '../packs/registry.mjs';
-import { originOk } from '../edit/http.mjs';
-import { isCloneVoice, cloneRef } from '../engine/audio/voice-store.mjs';
-import { handleDraftRoute, initDrafts } from '../packs/drafts-http.mjs';
-
-const AUDIO_SAMPLES = path.join(ROOT, 'engine', 'audio', 'samples');
-/** File nghe thử (cache trong engine/audio/samples/, chỉ sinh khi chưa có). Trả đường dẫn tuyệt đối. */
-async function audioPreviewFile(q) {
- const style = q.get('style'), voice = q.get('voice');
- if (style) {
- if (!MUSIC_STYLES.includes(style)) throw new Error('style nhạc không có: ' + style);
- const f = path.join(AUDIO_SAMPLES, `music-${style}.wav`);
- if (!fs.existsSync(f)) { fs.mkdirSync(AUDIO_SAMPLES, { recursive: true }); writeMusic(style, f, 8, 1); }
- return f;
- }
- if (voice) {
- const { voice: v } = normalizeAudioPrefs({ voice });
- const text = String(q.get('text') || sampleTextFor(v)).trim().slice(0, 160);
- if (v === 'auto' || v === 'none') throw new Error('chọn 1 giọng cụ thể để nghe thử');
- // giọng nhân bản: câu nghe thử đã đọc sẵn lúc tạo giọng
- if (isCloneVoice(v) && !q.get('text')) { const f = path.join(path.dirname(cloneRef(v).wav), 'sample.wav'); if (fs.existsSync(f)) return f; }
- const ve = voiceEngine(v);
- const [r] = await synthVoice([{ t: 0, text }], path.join(AUDIO_SAMPLES, 'voices'), { engine: ve.engine, voice: ve.speaker, log: (l) => console.log('[audio] ' + l) });
- return r.file;
- }
- throw new Error('cần ?style=<nhạc> hoặc ?voice=<giọng>&text=...');
-}
-
-const HOST = '127.0.0.1';
-const PORT = Number(process.env.PORT) || 4400;
-const PUBLIC = path.join(path.dirname(fileURLToPath(import.meta.url)), 'public');
-const DEFAULT_MODE = process.env.VIDEOAI_MODE || 'auto';
-const ALLOWED_HOSTS = new Set([`127.0.0.1:${PORT}`, `localhost:${PORT}`]);
-// L9: trang chỉ chạy script của chính app (file ngoài, index.html không có script nội tuyến); chữ của gói không thành code được.
-const PAGE_CSP = "default-src 'self'; img-src 'self' data: blob:; media-src 'self' blob:; style-src 'self' 'unsafe-inline'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
-
-const MIME = {
- '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
- '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
- '.png': 'image/png', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.mp4': 'video/mp4', '.m4a': 'audio/mp4', '.wav': 'audio/wav', '.woff2': 'font/woff2', '.md': 'text/markdown; charset=utf-8',
-};
-
-// ---- hàng đợi: mỗi lúc chỉ 1 job chạy (render nặng) ----
-const queue = [];
-let busy = false;
-const queuedIds = new Set();
-/** Xếp 1 job vào hàng (không xếp trùng). */
-function enqueueJob(id, fn) {
- if (queuedIds.has(id)) return;
- queuedIds.add(id);
- enqueue(async () => { try { await fn(); } finally { queuedIds.delete(id); } });
-}
-function enqueue(fn) {
- queue.push(fn);
- pump();
-}
-async function pump() {
- if (busy) return;
- const fn = queue.shift();
- if (!fn) return;
- busy = true;
- try { await fn(); } catch (e) { console.error('[queue]', e); }
- busy = false;
- pump();
-}
-
-function send(res, code, body, type = 'application/json; charset=utf-8') {
- const data = typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body);
- res.writeHead(code, { 'Content-Type': type, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
- res.end(data);
-}
-
-/** Phục vụ file tĩnh trong baseDir (chặn ../), hỗ trợ Range cho video. */
-function serveFile(req, res, baseDir, rel) {
- const file = path.resolve(baseDir, '.' + path.sep + rel);
- if (!file.startsWith(path.resolve(baseDir) + path.sep)) return send(res, 403, { error: 'forbidden' });
- let st;
- try { st = fs.statSync(file); } catch { return send(res, 404, { error: 'không thấy file' }); }
- if (!st.isFile()) return send(res, 404, { error: 'không thấy file' });
- const type = MIME[path.extname(file).toLowerCase()] || 'application/octet-stream';
- const range = req.headers.range && /bytes=(\d*)-(\d*)/.exec(req.headers.range);
- const headers = { 'Content-Type': type, 'Accept-Ranges': 'bytes', 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' };
- if (type.startsWith('text/html')) headers['Content-Security-Policy'] = PAGE_CSP;
- if (range) {
- const start = range[1] ? Number(range[1]) : 0;
- const end = range[2] ? Math.min(Number(range[2]), st.size - 1) : st.size - 1;
- if (start >= st.size || start > end) { res.writeHead(416, { 'Content-Range': `bytes */${st.size}` }); return res.end(); }
- res.writeHead(206, { ...headers, 'Content-Range': `bytes ${start}-${end}/${st.size}`, 'Content-Length': end - start + 1 });
- return fs.createReadStream(file, { start, end }).pipe(res);
- }
- res.writeHead(200, { ...headers, 'Content-Length': st.size });
- if (req.method === 'HEAD') return res.end();
- fs.createReadStream(file).pipe(res);
-}
-
-function readBody(req, limit = 64 * 1024) {
- return new Promise((resolve, reject) => {
- let size = 0; const chunks = [];
- req.on('data', (c) => { size += c.length; if (size > limit) { reject(new Error('body quá lớn')); req.destroy(); } else chunks.push(c); });
- req.on('end', () => {
- try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')); } catch { reject(new Error('JSON không hợp lệ')); }
- });
- req.on('error', reject);
- });
-}
-
-// Ảnh/video minh hoạ mỗi mẫu, theo thứ tự ưu tiên:
-// ảnh: 1. site/dist/media/<id>.webp (poster video demo, sinh bởi site/build.mjs — không có trong repo)
-// 2. templates/thumbs/<id>.webp (khung keyframe 360×640 có sẵn trong repo; tạo bằng scripts/make-thumbs.mjs)
-// 3. khung video tham chiếu riêng trên máy (templates/ref/<id>/frames, tools/fetch_refs.py — không có trong repo)
-// 4. poster SVG tự dựng (/poster/<id>.svg) từ tên + nhóm của mẫu
-// video: demo (site/dist/media/<id>.mp4) → video tham chiếu riêng → không có
-const DEMO = path.join(ROOT, 'site', 'dist', 'media');
-const THUMBS = path.join(TEMPLATES, 'thumbs');
-// LUMREELS_NO_REF=1: bỏ qua templates/ref (giả lập máy vừa clone repo; dùng khi chụp ảnh docs).
-const USE_REF = process.env.LUMREELS_NO_REF !== '1';
-function templateList() {
- // gốc + gói (packs/registry.mjs). Mẫu gói: ảnh từ gói (/pack-thumbs/…) hoặc poster SVG; không có video demo.
- return listTemplates().map((t) => {
- if (t.source !== 'builtin') {
- const pr = parsePackRef(t.ref);
- const r = resolveTemplate(t.ref);
- return {
- id: t.ref, ref: t.ref, name: t.name, blurb: t.blurb || '', category: t.category, genre: t.genre || '', technique: t.technique || [],
- difficulty: t.difficulty, narration: !!t.narration, source: t.source, packId: t.packId, restricted: true, hasGuidance: true,
- thumb: r?.thumbFile ? `/pack-thumbs/${pr.packId}/template-${pr.slug}.webp` : `/poster/p/${pr.packId}/${pr.slug}.svg`,
- video: null, videoKind: null,
- };
- }
- const ref = path.join(TEMPLATES, 'ref', t.id);
- const refThumb = USE_REF && ['f_08.jpg', 'f_09.jpg', 'f_07.jpg'].find((f) => fs.existsSync(path.join(ref, 'frames', f)));
- const demo = fs.existsSync(path.join(DEMO, `${t.id}.mp4`));
- const demoPoster = fs.existsSync(path.join(DEMO, `${t.id}.webp`));
- const keyThumb = fs.existsSync(path.join(THUMBS, `${t.id}.webp`));
- const refVideo = USE_REF && fs.existsSync(path.join(ref, 'video.mp4'));
- return {
- id: t.id, ref: t.id, name: t.name, blurb: t.blurb || '', category: t.category, genre: t.genre, technique: t.technique,
- difficulty: t.difficulty, narration: t.narration, source: 'builtin', restricted: t.restricted,
- hasGuidance: t.hasGuidance,
- thumb: demoPoster ? `/demo/${t.id}.webp` : keyThumb ? `/thumbs/${t.id}.webp` : refThumb ? `/ref/${t.id}/frames/${refThumb}` : `/poster/${t.id}.svg`,
- video: demo ? `/demo/${t.id}.mp4` : refVideo ? `/ref/${t.id}/video.mp4` : null,
- videoKind: demo ? 'demo' : refVideo ? 'ref' : null,
- source: 'builtin',
- };
- });
-}
-
-/** Poster SVG cho mẫu chưa có video demo: nền gradient theo id, tên phong cách, nhóm. */
-const CAT_LABEL = { faceless: 'Faceless', ads: 'Quảng cáo', 'multi-style': 'Đa phong cách', 'viet-nam': 'Việt Nam hoá' };
-function posterSvg(t) {
- const n = BUILTIN_TEMPLATE_RE.test(t.id) ? Number(t.id) : [...String(t.id)].reduce((a, c) => (a * 31 + c.charCodeAt(0)) % 997, 7);
- const h1 = (n * 47) % 360, h2 = (h1 + 40 + (n % 5) * 12) % 360;
- const x = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
- // ngắt tên thành tối đa 4 dòng ~12 ký tự
- const words = String(t.name).split(/\s+/); const lines = [''];
- for (const w of words) { if ((lines.at(-1) + ' ' + w).trim().length > 12 && lines.at(-1)) lines.push(w); else lines[lines.length - 1] = (lines.at(-1) + ' ' + w).trim(); }
- const shown = lines.slice(0, 4);
- const tech = (t.technique || []).includes('three') ? '3D' : (t.technique || []).includes('webgl-shader') ? 'Shader' : '2D';
- return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 540 960" width="540" height="960">
-<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="hsl(${h1} 45% 22%)"/><stop offset="1" stop-color="hsl(${h2} 55% 12%)"/></linearGradient></defs>
-<rect width="540" height="960" fill="url(#g)"/>
-<circle cx="${380 + (n % 7) * 10}" cy="${260 + (n % 4) * 30}" r="170" fill="hsl(${h2} 70% 60% / .18)"/>
-<rect x="44" y="300" width="72" height="8" rx="4" fill="hsl(${h1} 80% 70%)"/>
-<text x="44" y="270" font-family="'Be Vietnam Pro',sans-serif" font-size="30" font-weight="600" fill="#fff" fill-opacity=".7">${BUILTIN_TEMPLATE_RE.test(t.id) ? '#' + x(t.id) : x(String(t.id).split('/')[1] || '')}</text>
-${shown.map((l, i) => `<text x="44" y="${390 + i * 74}" font-family="'Be Vietnam Pro',sans-serif" font-size="60" font-weight="800" fill="#fff">${x(l)}</text>`).join('\n')}
-<text x="44" y="880" font-family="'Be Vietnam Pro',sans-serif" font-size="28" font-weight="500" fill="#fff" fill-opacity=".75">${x(CAT_LABEL[t.category] || t.category)} · ${tech}</text>
-</svg>`;
-}
-
-function jobView(job, withLog = false) {
- const dir = path.join(JOBS, job.id);
- const has = (f) => fs.existsSync(path.join(dir, f));
- const v = {
- ...job,
- templateTitle: templateName(job.templateId) || job.templateTitle,
- queued: queue.length,
- versions: listVersions(job.id).map((v) => ({ ...v, url: `/jobs/${job.id}/${v.file}` })),
- audioBusy: audioBusy(job.id),
- links: {
- mp4: has('out.mp4') && job.status === 'done' ? `/jobs/${job.id}/out.mp4` : null,
- preview: has('preview.jpg') ? `/jobs/${job.id}/preview.jpg` : null,
- prompt: `/jobs/${job.id}/PROMPT.md`,
- brief: has('brief.json') ? `/jobs/${job.id}/brief.json` : null,
- },
- paths: { dir, prompt: path.join(dir, 'PROMPT.md'), scene: path.join(dir, 'scene', 'index.html') },
- };
- if (withLog) v.log = readLog(job.id, 120);
- return v;
-}
-
-/** Job vừa tạo: hẹn giờ thì để bộ hẹn giờ lo; manual chỉ chuyển sang waiting_agent; còn lại xếp hàng chạy. */
-async function startJob(job) {
- if (job.status === 'scheduled') return; // bộ hẹn giờ sẽ chạy khi tới giờ
- if (resolveMode(job.mode) === 'manual') await runJob(job.id);
- else enqueueJob(job.id, () => runJob(job.id));
-}
-
-/** Job dựng thử của nháp "Tạo mẫu từ video": xếp vào hàng đợi chung, trả job khi xong. */
-function draftTestRunner(id) {
- return new Promise((resolve) => {
- enqueueJob(id, async () => {
- try { resolve(await runJob(id, { force: true })); } catch (e) { console.error('[draft-test]', id, e.message); resolve(readJob(id)); }
- });
- });
-}
-
-let rewriteBusy = false;
-let rewriteLast = 0;
-
-const server = http.createServer(async (req, res) => {
- const url = new URL(req.url, `http://${HOST}`);
- const p = decodeURIComponent(url.pathname);
- // Chống DNS rebinding: chỉ nhận Host là 127.0.0.1/localhost đúng cổng.
- if (!ALLOWED_HOSTS.has(String(req.headers.host || '').toLowerCase())) return send(res, 421, { error: 'host không hợp lệ' });
- // Trang web lạ không gửi lệnh ghi vào được (tạo job, cài gói, xoá…): Origin phải là chính app (không có Origin = curl/agent cục bộ).
- if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method) && !originOk(req, ALLOWED_HOSTS)) {
- res.setHeader('Connection', 'close'); res.on('finish', () => req.destroy());
- return send(res, 403, { error: 'origin không hợp lệ' });
- }
- try {
- // ---- Gói mẫu .lumpack (packs/http.mjs) ----
- if (await handlePackRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS })) return;
- // ---- Edit video của bạn (edit/http.mjs) ----
- if (await handleEditRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS })) return;
- // ---- Giọng của tôi (server/voices-http.mjs) ----
- if (await handleVoiceRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS })) return;
- // ---- Tạo mẫu từ video (packs/drafts-http.mjs): job dựng thử đi qua hàng đợi chung ----
- if (await handleDraftRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS, runTest: draftTestRunner })) return;
- // ---- API ----
- if (p === '/api/templates' && req.method === 'GET') return send(res, 200, templateList());
- if (p === '/api/version' && req.method === 'GET') return send(res, 200, { version: PKG_VERSION, update: updateState });
- if (p === '/api/config' && req.method === 'GET') {
- return send(res, 200, { defaultMode: DEFAULT_MODE, autoResolves: resolveMode('auto'), claudeAvailable: !!findClaude(), apiAvailable: config.hasApiKey(), outputDir: !!config.outputDir(), rewriteEngine: resolveRewriteEngine() });
- }
- if (p === '/api/rewrite' && req.method === 'POST') {
- // Chống bấm liên tục: mỗi lúc 1 lượt, cách nhau ≥ 3 giây.
- if (rewriteBusy) return send(res, 429, { error: 'Đang viết lại 1 bản, chờ xong rồi bấm tiếp' });
- if (Date.now() - rewriteLast < 3000) return send(res, 429, { error: 'Bấm chậm lại chút (cách nhau 3 giây)' });
- const body = await readBody(req);
- if (String(body.content || '').length > REWRITE_MAX_CHARS) return send(res, 413, { error: `Nội dung quá dài (tối đa ${REWRITE_MAX_CHARS} ký tự)` });
- rewriteBusy = true;
- try {
- const r = await rewriteScript({ templateId: body.templateId, content: body.content, durationS: body.durationS });
- console.log(`[rewrite] mẫu ${r.templateId}, ${r.durationS}s, ${r.engine}${r.fallbackFrom ? ' (sau khi ' + r.fallbackFrom + ')' : ''}`);
- return send(res, 200, r);
- } catch (e) {
- return send(res, /chưa cấu hình AI/i.test(e.message) ? 503 : 422, { error: e.message });
- } finally {
- rewriteBusy = false; rewriteLast = Date.now();
- }
- }
- if (p === '/api/jobs' && req.method === 'GET') return send(res, 200, listJobs().map((j) => jobView(j)));
- if (p === '/api/jobs' && req.method === 'POST') {
- const body = await readBody(req);
- const job = createJob({ templateId: body.templateId, content: body.content, durationS: body.durationS, aspect: body.aspect, mode: body.mode || DEFAULT_MODE, model: body.model, runAt: body.runAt, source: body.source || 'web', audio: body.audio });
- await startJob(job);
- return send(res, 201, jobView(readJob(job.id), true));
- }
- if (p === '/api/jobs/batch' && req.method === 'POST') {
- // Chọn nhiều mẫu: 1 job / mẫu, cùng nội dung + tuỳ chọn. Kiểm cả lô trước, sai 1 id là từ chối hết.
- const body = await readBody(req);
- if (!Array.isArray(body.templateIds)) return send(res, 400, { error: 'templateIds phải là mảng id mẫu' });
- if (body.templateIds.length > MAX_BATCH) return send(res, 400, { error: `Tối đa ${MAX_BATCH} mẫu mỗi lô` });
- let jobs;
- try {
- jobs = createJobs({ templateIds: body.templateIds, content: body.content, durationS: body.durationS, aspect: body.aspect, mode: body.mode || DEFAULT_MODE, model: body.model, runAt: body.runAt, source: body.source || 'web', audio: body.audio });
- } catch (e) { return send(res, 400, { error: e.message, badIds: e.badIds || [] }); }
- for (const job of jobs) await startJob(job);
- console.log(`[batch] ${jobs.length} job: ${jobs.map((j) => j.templateId).join(', ')}`);
- return send(res, 201, { jobs: jobs.map((j) => jobView(readJob(j.id))) });
- }
- let ms = /^\/api\/jobs\/([\w-]+)\/scene$/.exec(p);
- if (ms && req.method === 'POST') {
- const body = await readBody(req, 2_500_000);
- if (body.audio !== undefined && body.audio !== null) await saveAudioSpec(ms[1], body.audio); // scene/audio.json (AUTHORING §9)
- const r = submitScene(ms[1], body.html, body.brief);
- return send(res, r.ok ? 200 : 422, r);
- }
- ms = /^\/api\/jobs\/([\w-]+)\/preview$/.exec(p);
- if (ms && req.method === 'POST') {
- const r = await previewJob(ms[1]);
- return send(res, r.ok ? 200 : 422, { ok: r.ok, errors: r.errors, preview: r.ok ? `/jobs/${ms[1]}/preview.jpg` : null });
- }
- let m = /^\/api\/jobs\/([\w-]+)$/.exec(p);
- if (m && req.method === 'GET') {
- const job = readJob(m[1]);
- return job ? send(res, 200, jobView(job, true)) : send(res, 404, { error: 'không thấy job' });
- }
- m = /^\/api\/jobs\/([\w-]+)\/render$/.exec(p);
- if (m && req.method === 'POST') {
- const job = readJob(m[1]);
- if (!job) return send(res, 404, { error: 'không thấy job' });
- enqueueJob(job.id, () => renderJob(job.id));
- return send(res, 202, jobView(job, true));
- }
- // ---- âm thanh ----
- if (p === '/api/audio/options' && req.method === 'GET') return send(res, 200, audioOptions());
- if (p === '/api/audio/preview' && req.method === 'GET') {
- const f = await audioPreviewFile(url.searchParams);
- return serveFile(req, res, path.dirname(f), path.basename(f));
- }
- m = /^\/api\/jobs\/([\w-]+)\/audio$/.exec(p);
- if (m && req.method === 'POST') {
- const job = readJob(m[1]);
- if (!job) return send(res, 404, { error: 'không thấy job' });
- if (job.status !== 'done' && !fs.existsSync(path.join(JOBS, job.id, 'out.mp4'))) return send(res, 409, { error: 'video chưa dựng xong' });
- if (audioBusy(job.id)) return send(res, 409, { error: 'đang trộn tiếng cho video này' });
- const body = await readBody(req);
- const prefs = { music: body.music, voice: body.voice, sfx: body.sfx };
- normalizeAudioPrefs({ ...prefs }); // kiểm sớm, sai thì 400
- reAudio(job.id, prefs).catch((e) => console.error('[audio]', job.id, e.message)); // chạy nền; UI hỏi lại GET /api/jobs/:id
- return send(res, 202, { ...jobView(readJob(job.id), true), audioBusy: true });
- }
- m = /^\/api\/jobs\/([\w-]+)\/versions$/.exec(p);
- if (m && req.method === 'GET') return send(res, 200, listVersions(m[1]).map((v) => ({ ...v, url: `/jobs/${m[1]}/${v.file}` })));
- if (p.startsWith('/api/')) return send(res, 404, { error: 'không có API này' });
-
- // ---- file ----
- if (req.method !== 'GET' && req.method !== 'HEAD') return send(res, 405, { error: 'method' });
- if (p.startsWith('/ref/') && USE_REF) return serveFile(req, res, path.join(TEMPLATES, 'ref'), p.slice(5));
- m = /^\/demo\/(\d{3}\.(?:mp4|webp))$/.exec(p);
- if (m) return serveFile(req, res, DEMO, m[1]);
- m = /^\/thumbs\/(\d{3}\.webp)$/.exec(p);
- if (m) return serveFile(req, res, THUMBS, m[1]);
- m = /^\/poster\/(\d{3})\.svg$/.exec(p);
- if (m) {
- const t = loadCatalog().find((x) => x.id === m[1]);
- return t ? send(res, 200, posterSvg(t), 'image/svg+xml; charset=utf-8') : send(res, 404, { error: 'không thấy mẫu' });
- }
- m = /^\/poster\/p\/([a-z0-9.-]{5,49})\/([a-z][a-z0-9-]{1,31})\.svg$/.exec(p);
- if (m) {
- const r = parsePackRef(`${m[1]}/${m[2]}`) && resolveTemplate(`${m[1]}/${m[2]}`);
- return r ? send(res, 200, posterSvg({ id: r.ref, name: r.meta.name, category: r.meta.category, technique: r.meta.technique }), 'image/svg+xml; charset=utf-8') : send(res, 404, { error: 'không thấy mẫu' });
- }
- m = /^\/jobs\/([\w-]+)\/(versions\/out-\d{1,4}\.mp4)$/.exec(p);
- if (m) return serveFile(req, res, path.join(JOBS, m[1]), m[2]);
- m = /^\/jobs\/([\w-]+)\/(out\.mp4|preview\.jpg|PROMPT\.md|brief\.json)$/.exec(p);
- if (m) return serveFile(req, res, path.join(JOBS, m[1]), m[2]);
- if (p.startsWith('/fonts/')) return serveFile(req, res, path.join(ROOT, 'engine', 'fonts'), p.slice(7));
- return serveFile(req, res, PUBLIC, p === '/' ? 'index.html' : p.slice(1));
- } catch (e) {
- return send(res, 400, { error: e.message });
- }
-});
-
-markStale();
-initEdits(); // edit đang chạy dở khi server tắt → báo lỗi để bấm lại
-initVoices(); // giọng nhân bản đang xử lý dở → báo lỗi
-initDrafts(); // nháp "Tạo mẫu từ video" đang chạy dở → báo lỗi
-// Job queued còn sót (server tắt trước khi kịp chạy) → chạy lại.
-for (const j of listJobs()) if (j.status === 'queued' && resolveMode(j.mode) !== 'manual') enqueueJob(j.id, () => runJob(j.id));
-// Bộ hẹn giờ: 15 giây kiểm 1 lần, job tới giờ thì xếp hàng chạy.
-function tick() { for (const j of dueJobs()) enqueueJob(j.id, () => runJob(j.id, { force: true })); }
-setInterval(tick, 15000);
-tick();
-
-// Kiểm bản mới trên GitHub (chạy nền, không chặn app): lúc khởi động và 6 giờ/lần. Giao diện đọc qua /api/version.
-const PKG_VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
-let updateState = null;
-function checkUpdateBg() {
- if (process.env.LUMREELS_SKIP_UPDATE === '1') return;
- const p = spawn(process.execPath, [fileURLToPath(new URL('../scripts/update.mjs', import.meta.url)), '--json'], { windowsHide: true });
- let out = '';
- p.stdout.on('data', (d) => { out += d; });
- p.on('error', () => {});
- p.on('close', () => { try { updateState = JSON.parse(out); } catch { /* bỏ qua */ } });
-}
-setTimeout(checkUpdateBg, 3000);
-setInterval(checkUpdateBg, 6 * 3600 * 1000).unref();
-
-server.listen(PORT, HOST, () => {
- console.log(`LumReels: http://${HOST}:${PORT} (chế độ mặc định: ${DEFAULT_MODE} → ${resolveMode(DEFAULT_MODE)}; OUTPUT_DIR ${config.outputDir() ? 'có' : 'chưa đặt'})`);
-});
+// Server API + UI. Chỉ bind 127.0.0.1:4400. Không framework.
+import http from 'node:http';
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { spawn } from 'node:child_process';
+import {
+ ROOT, JOBS, TEMPLATES, loadCatalog, templateName, createJob, runJob, renderJob, readJob, listJobs, readLog, markStale,
+ dueJobs, resolveMode, submitScene, previewJob, createJobs, MAX_BATCH,
+} from '../generator/jobs.mjs';
+import { findClaude } from '../generator/claude.mjs';
+import { rewriteScript, resolveRewriteEngine, REWRITE_MAX_CHARS } from '../generator/rewrite.mjs';
+import { config } from '../generator/config.mjs';
+import { reAudio, listVersions, audioBusy, saveAudioSpec } from '../generator/audio-job.mjs';
+import { audioOptions, normalizeAudioPrefs, voiceEngine, sampleTextFor } from '../engine/audio/prefs.mjs';
+import { MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';
+import { synthVoice } from '../engine/audio/voice.mjs';
+import { handleEditRoute, initEdits } from '../edit/http.mjs';
+import { handleVoiceRoute, initVoices } from './voices-http.mjs';
+import { handlePackRoute } from '../packs/http.mjs';
+import { listTemplates, resolveTemplate, parsePackRef, BUILTIN_TEMPLATE_RE } from '../packs/registry.mjs';
+import { originOk } from '../edit/http.mjs';
+import { isCloneVoice, cloneRef } from '../engine/audio/voice-store.mjs';
+import { handleDraftRoute, initDrafts } from '../packs/drafts-http.mjs';
+
+const AUDIO_SAMPLES = path.join(ROOT, 'engine', 'audio', 'samples');
+/** File nghe thử (cache trong engine/audio/samples/, chỉ sinh khi chưa có). Trả đường dẫn tuyệt đối. */
+async function audioPreviewFile(q) {
+ const style = q.get('style'), voice = q.get('voice');
+ if (style) {
+ if (!MUSIC_STYLES.includes(style)) throw new Error('style nhạc không có: ' + style);
+ const f = path.join(AUDIO_SAMPLES, `music-${style}.wav`);
+ if (!fs.existsSync(f)) { fs.mkdirSync(AUDIO_SAMPLES, { recursive: true }); writeMusic(style, f, 8, 1); }
+ return f;
+ }
+ if (voice) {
+ const { voice: v } = normalizeAudioPrefs({ voice });
+ const text = String(q.get('text') || sampleTextFor(v)).trim().slice(0, 160);
+ if (v === 'auto' || v === 'none') throw new Error('chọn 1 giọng cụ thể để nghe thử');
+ // giọng nhân bản: câu nghe thử đã đọc sẵn lúc tạo giọng
+ if (isCloneVoice(v) && !q.get('text')) { const f = path.join(path.dirname(cloneRef(v).wav), 'sample.wav'); if (fs.existsSync(f)) return f; }
+ const ve = voiceEngine(v);
+ const [r] = await synthVoice([{ t: 0, text }], path.join(AUDIO_SAMPLES, 'voices'), { engine: ve.engine, voice: ve.speaker, log: (l) => console.log('[audio] ' + l) });
+ return r.file;
+ }
+ throw new Error('cần ?style=<nhạc> hoặc ?voice=<giọng>&text=...');
+}
+
+const HOST = '127.0.0.1';
+const PORT = Number(process.env.PORT) || 4400;
+const PUBLIC = path.join(path.dirname(fileURLToPath(import.meta.url)), 'public');
+const DEFAULT_MODE = process.env.VIDEOAI_MODE || 'auto';
+const ALLOWED_HOSTS = new Set([`127.0.0.1:${PORT}`, `localhost:${PORT}`]);
+// L9: trang chỉ chạy script của chính app (file ngoài, index.html không có script nội tuyến); chữ của gói không thành code được.
+const PAGE_CSP = "default-src 'self'; img-src 'self' data: blob:; media-src 'self' blob:; style-src 'self' 'unsafe-inline'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
+
+const MIME = {
+ '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
+ '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
+ '.png': 'image/png', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.mp4': 'video/mp4', '.m4a': 'audio/mp4', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.aac': 'audio/aac', '.ogg': 'audio/ogg', '.opus': 'audio/ogg', '.flac': 'audio/flac', '.woff2': 'font/woff2', '.md': 'text/markdown; charset=utf-8',
+};
+
+// ---- hàng đợi: mỗi lúc chỉ 1 job chạy (render nặng) ----
+const queue = [];
+let busy = false;
+const queuedIds = new Set();
+/** Xếp 1 job vào hàng (không xếp trùng). */
+function enqueueJob(id, fn) {
+ if (queuedIds.has(id)) return;
+ queuedIds.add(id);
+ enqueue(async () => { try { await fn(); } finally { queuedIds.delete(id); } });
+}
+function enqueue(fn) {
+ queue.push(fn);
+ pump();
+}
+async function pump() {
+ if (busy) return;
+ const fn = queue.shift();
+ if (!fn) return;
+ busy = true;
+ try { await fn(); } catch (e) { console.error('[queue]', e); }
+ busy = false;
+ pump();
+}
+
+function send(res, code, body, type = 'application/json; charset=utf-8') {
+ const data = typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body);
+ res.writeHead(code, { 'Content-Type': type, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
+ res.end(data);
+}
+
+/** Phục vụ file tĩnh trong baseDir (chặn ../), hỗ trợ Range cho video. */
+function serveFile(req, res, baseDir, rel) {
+ const file = path.resolve(baseDir, '.' + path.sep + rel);
+ if (!file.startsWith(path.resolve(baseDir) + path.sep)) return send(res, 403, { error: 'forbidden' });
+ let st;
+ try { st = fs.statSync(file); } catch { return send(res, 404, { error: 'không thấy file' }); }
+ if (!st.isFile()) return send(res, 404, { error: 'không thấy file' });
+ const type = MIME[path.extname(file).toLowerCase()] || 'application/octet-stream';
+ const range = req.headers.range && /bytes=(\d*)-(\d*)/.exec(req.headers.range);
+ const headers = { 'Content-Type': type, 'Accept-Ranges': 'bytes', 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' };
+ if (type.startsWith('text/html')) headers['Content-Security-Policy'] = PAGE_CSP;
+ if (range) {
+ const start = range[1] ? Number(range[1]) : 0;
+ const end = range[2] ? Math.min(Number(range[2]), st.size - 1) : st.size - 1;
+ if (start >= st.size || start > end) { res.writeHead(416, { 'Content-Range': `bytes */${st.size}` }); return res.end(); }
+ res.writeHead(206, { ...headers, 'Content-Range': `bytes ${start}-${end}/${st.size}`, 'Content-Length': end - start + 1 });
+ return fs.createReadStream(file, { start, end }).pipe(res);
+ }
+ res.writeHead(200, { ...headers, 'Content-Length': st.size });
+ if (req.method === 'HEAD') return res.end();
+ fs.createReadStream(file).pipe(res);
+}
+
+function readBody(req, limit = 64 * 1024) {
+ return new Promise((resolve, reject) => {
+ let size = 0; const chunks = [];
+ req.on('data', (c) => { size += c.length; if (size > limit) { reject(new Error('body quá lớn')); req.destroy(); } else chunks.push(c); });
+ req.on('end', () => {
+ try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')); } catch { reject(new Error('JSON không hợp lệ')); }
+ });
+ req.on('error', reject);
+ });
+}
+
+// Ảnh/video minh hoạ mỗi mẫu, theo thứ tự ưu tiên:
+// ảnh: 1. site/dist/media/<id>.webp (poster video demo, sinh bởi site/build.mjs — không có trong repo)
+// 2. templates/thumbs/<id>.webp (khung keyframe 360×640 có sẵn trong repo; tạo bằng scripts/make-thumbs.mjs)
+// 3. khung video tham chiếu riêng trên máy (templates/ref/<id>/frames, tools/fetch_refs.py — không có trong repo)
+// 4. poster SVG tự dựng (/poster/<id>.svg) từ tên + nhóm của mẫu
+// video: demo (site/dist/media/<id>.mp4) → video tham chiếu riêng → không có
+const DEMO = path.join(ROOT, 'site', 'dist', 'media');
+const THUMBS = path.join(TEMPLATES, 'thumbs');
+// LUMREELS_NO_REF=1: bỏ qua templates/ref (giả lập máy vừa clone repo; dùng khi chụp ảnh docs).
+const USE_REF = process.env.LUMREELS_NO_REF !== '1';
+function templateList() {
+ // gốc + gói (packs/registry.mjs). Mẫu gói: ảnh từ gói (/pack-thumbs/…) hoặc poster SVG; không có video demo.
+ return listTemplates().map((t) => {
+ if (t.source !== 'builtin') {
+ const pr = parsePackRef(t.ref);
+ const r = resolveTemplate(t.ref);
+ return {
+ id: t.ref, ref: t.ref, name: t.name, blurb: t.blurb || '', category: t.category, genre: t.genre || '', technique: t.technique || [],
+ difficulty: t.difficulty, narration: !!t.narration, source: t.source, packId: t.packId, restricted: true, hasGuidance: true,
+ thumb: r?.thumbFile ? `/pack-thumbs/${pr.packId}/template-${pr.slug}.webp` : `/poster/p/${pr.packId}/${pr.slug}.svg`,
+ video: null, videoKind: null,
+ };
+ }
+ const ref = path.join(TEMPLATES, 'ref', t.id);
+ const refThumb = USE_REF && ['f_08.jpg', 'f_09.jpg', 'f_07.jpg'].find((f) => fs.existsSync(path.join(ref, 'frames', f)));
+ const demo = fs.existsSync(path.join(DEMO, `${t.id}.mp4`));
+ const demoPoster = fs.existsSync(path.join(DEMO, `${t.id}.webp`));
+ const keyThumb = fs.existsSync(path.join(THUMBS, `${t.id}.webp`));
+ const refVideo = USE_REF && fs.existsSync(path.join(ref, 'video.mp4'));
+ return {
+ id: t.id, ref: t.id, name: t.name, blurb: t.blurb || '', category: t.category, genre: t.genre, technique: t.technique,
+ difficulty: t.difficulty, narration: t.narration, source: 'builtin', restricted: t.restricted,
+ hasGuidance: t.hasGuidance,
+ thumb: demoPoster ? `/demo/${t.id}.webp` : keyThumb ? `/thumbs/${t.id}.webp` : refThumb ? `/ref/${t.id}/frames/${refThumb}` : `/poster/${t.id}.svg`,
+ video: demo ? `/demo/${t.id}.mp4` : refVideo ? `/ref/${t.id}/video.mp4` : null,
+ videoKind: demo ? 'demo' : refVideo ? 'ref' : null,
+ source: 'builtin',
+ };
+ });
+}
+
+/** Poster SVG cho mẫu chưa có video demo: nền gradient theo id, tên phong cách, nhóm. */
+const CAT_LABEL = { faceless: 'Faceless', ads: 'Quảng cáo', 'multi-style': 'Đa phong cách', 'viet-nam': 'Việt Nam hoá' };
+function posterSvg(t) {
+ const n = BUILTIN_TEMPLATE_RE.test(t.id) ? Number(t.id) : [...String(t.id)].reduce((a, c) => (a * 31 + c.charCodeAt(0)) % 997, 7);
+ const h1 = (n * 47) % 360, h2 = (h1 + 40 + (n % 5) * 12) % 360;
+ const x = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+ // ngắt tên thành tối đa 4 dòng ~12 ký tự
+ const words = String(t.name).split(/\s+/); const lines = [''];
+ for (const w of words) { if ((lines.at(-1) + ' ' + w).trim().length > 12 && lines.at(-1)) lines.push(w); else lines[lines.length - 1] = (lines.at(-1) + ' ' + w).trim(); }
+ const shown = lines.slice(0, 4);
+ const tech = (t.technique || []).includes('three') ? '3D' : (t.technique || []).includes('webgl-shader') ? 'Shader' : '2D';
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 540 960" width="540" height="960">
+<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="hsl(${h1} 45% 22%)"/><stop offset="1" stop-color="hsl(${h2} 55% 12%)"/></linearGradient></defs>
+<rect width="540" height="960" fill="url(#g)"/>
+<circle cx="${380 + (n % 7) * 10}" cy="${260 + (n % 4) * 30}" r="170" fill="hsl(${h2} 70% 60% / .18)"/>
+<rect x="44" y="300" width="72" height="8" rx="4" fill="hsl(${h1} 80% 70%)"/>
+<text x="44" y="270" font-family="'Be Vietnam Pro',sans-serif" font-size="30" font-weight="600" fill="#fff" fill-opacity=".7">${BUILTIN_TEMPLATE_RE.test(t.id) ? '#' + x(t.id) : x(String(t.id).split('/')[1] || '')}</text>
+${shown.map((l, i) => `<text x="44" y="${390 + i * 74}" font-family="'Be Vietnam Pro',sans-serif" font-size="60" font-weight="800" fill="#fff">${x(l)}</text>`).join('\n')}
+<text x="44" y="880" font-family="'Be Vietnam Pro',sans-serif" font-size="28" font-weight="500" fill="#fff" fill-opacity=".75">${x(CAT_LABEL[t.category] || t.category)} · ${tech}</text>
+</svg>`;
+}
+
+function jobView(job, withLog = false) {
+ const dir = path.join(JOBS, job.id);
+ const has = (f) => fs.existsSync(path.join(dir, f));
+ const v = {
+ ...job,
+ templateTitle: templateName(job.templateId) || job.templateTitle,
+ queued: queue.length,
+ versions: listVersions(job.id).map((v) => ({ ...v, url: `/jobs/${job.id}/${v.file}` })),
+ audioBusy: audioBusy(job.id),
+ links: {
+ mp4: has('out.mp4') && job.status === 'done' ? `/jobs/${job.id}/out.mp4` : null,
+ preview: has('preview.jpg') ? `/jobs/${job.id}/preview.jpg` : null,
+ prompt: `/jobs/${job.id}/PROMPT.md`,
+ brief: has('brief.json') ? `/jobs/${job.id}/brief.json` : null,
+ },
+ paths: { dir, prompt: path.join(dir, 'PROMPT.md'), scene: path.join(dir, 'scene', 'index.html') },
+ };
+ if (withLog) v.log = readLog(job.id, 120);
+ return v;
+}
+
+/** Job vừa tạo: hẹn giờ thì để bộ hẹn giờ lo; manual chỉ chuyển sang waiting_agent; còn lại xếp hàng chạy. */
+async function startJob(job) {
+ if (job.status === 'scheduled') return; // bộ hẹn giờ sẽ chạy khi tới giờ
+ if (resolveMode(job.mode) === 'manual') await runJob(job.id);
+ else enqueueJob(job.id, () => runJob(job.id));
+}
+
+/** Job dựng thử của nháp "Tạo mẫu từ video": xếp vào hàng đợi chung, trả job khi xong. */
+function draftTestRunner(id) {
+ return new Promise((resolve) => {
+ enqueueJob(id, async () => {
+ try { resolve(await runJob(id, { force: true })); } catch (e) { console.error('[draft-test]', id, e.message); resolve(readJob(id)); }
+ });
+ });
+}
+
+let rewriteBusy = false;
+let rewriteLast = 0;
+
+const server = http.createServer(async (req, res) => {
+ const url = new URL(req.url, `http://${HOST}`);
+ const p = decodeURIComponent(url.pathname);
+ // Chống DNS rebinding: chỉ nhận Host là 127.0.0.1/localhost đúng cổng.
+ if (!ALLOWED_HOSTS.has(String(req.headers.host || '').toLowerCase())) return send(res, 421, { error: 'host không hợp lệ' });
+ // Trang web lạ không gửi lệnh ghi vào được (tạo job, cài gói, xoá…): Origin phải là chính app (không có Origin = curl/agent cục bộ).
+ if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method) && !originOk(req, ALLOWED_HOSTS)) {
+ res.setHeader('Connection', 'close'); res.on('finish', () => req.destroy());
+ return send(res, 403, { error: 'origin không hợp lệ' });
+ }
+ try {
+ // ---- Gói mẫu .lumpack (packs/http.mjs) ----
+ if (await handlePackRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS })) return;
+ // ---- Edit video của bạn (edit/http.mjs) ----
+ if (await handleEditRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS })) return;
+ // ---- Giọng của tôi (server/voices-http.mjs) ----
+ if (await handleVoiceRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS })) return;
+ // ---- Tạo mẫu từ video (packs/drafts-http.mjs): job dựng thử đi qua hàng đợi chung ----
+ if (await handleDraftRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS, runTest: draftTestRunner })) return;
+ // ---- API ----
+ if (p === '/api/templates' && req.method === 'GET') return send(res, 200, templateList());
+ if (p === '/api/version' && req.method === 'GET') return send(res, 200, { version: PKG_VERSION, update: updateState });
+ if (p === '/api/config' && req.method === 'GET') {
+ return send(res, 200, { defaultMode: DEFAULT_MODE, autoResolves: resolveMode('auto'), claudeAvailable: !!findClaude(), apiAvailable: config.hasApiKey(), outputDir: !!config.outputDir(), rewriteEngine: resolveRewriteEngine() });
+ }
+ if (p === '/api/rewrite' && req.method === 'POST') {
+ // Chống bấm liên tục: mỗi lúc 1 lượt, cách nhau ≥ 3 giây.
+ if (rewriteBusy) return send(res, 429, { error: 'Đang viết lại 1 bản, chờ xong rồi bấm tiếp' });
+ if (Date.now() - rewriteLast < 3000) return send(res, 429, { error: 'Bấm chậm lại chút (cách nhau 3 giây)' });
+ const body = await readBody(req);
+ if (String(body.content || '').length > REWRITE_MAX_CHARS) return send(res, 413, { error: `Nội dung quá dài (tối đa ${REWRITE_MAX_CHARS} ký tự)` });
+ rewriteBusy = true;
+ try {
+ const r = await rewriteScript({ templateId: body.templateId, content: body.content, durationS: body.durationS });
+ console.log(`[rewrite] mẫu ${r.templateId}, ${r.durationS}s, ${r.engine}${r.fallbackFrom ? ' (sau khi ' + r.fallbackFrom + ')' : ''}`);
+ return send(res, 200, r);
+ } catch (e) {
+ return send(res, /chưa cấu hình AI/i.test(e.message) ? 503 : 422, { error: e.message });
+ } finally {
+ rewriteBusy = false; rewriteLast = Date.now();
+ }
+ }
+ if (p === '/api/jobs' && req.method === 'GET') return send(res, 200, listJobs().map((j) => jobView(j)));
+ if (p === '/api/jobs' && req.method === 'POST') {
+ const body = await readBody(req);
+ const job = createJob({ templateId: body.templateId, content: body.content, durationS: body.durationS, aspect: body.aspect, mode: body.mode || DEFAULT_MODE, model: body.model, runAt: body.runAt, source: body.source || 'web', audio: body.audio });
+ await startJob(job);
+ return send(res, 201, jobView(readJob(job.id), true));
+ }
+ if (p === '/api/jobs/batch' && req.method === 'POST') {
+ // Chọn nhiều mẫu: 1 job / mẫu, cùng nội dung + tuỳ chọn. Kiểm cả lô trước, sai 1 id là từ chối hết.
+ const body = await readBody(req);
+ if (!Array.isArray(body.templateIds)) return send(res, 400, { error: 'templateIds phải là mảng id mẫu' });
+ if (body.templateIds.length > MAX_BATCH) return send(res, 400, { error: `Tối đa ${MAX_BATCH} mẫu mỗi lô` });
+ let jobs;
+ try {
+ jobs = createJobs({ templateIds: body.templateIds, content: body.content, durationS: body.durationS, aspect: body.aspect, mode: body.mode || DEFAULT_MODE, model: body.model, runAt: body.runAt, source: body.source || 'web', audio: body.audio });
+ } catch (e) { return send(res, 400, { error: e.message, badIds: e.badIds || [] }); }
+ for (const job of jobs) await startJob(job);
+ console.log(`[batch] ${jobs.length} job: ${jobs.map((j) => j.templateId).join(', ')}`);
+ return send(res, 201, { jobs: jobs.map((j) => jobView(readJob(j.id))) });
+ }
+ let ms = /^\/api\/jobs\/([\w-]+)\/scene$/.exec(p);
+ if (ms && req.method === 'POST') {
+ const body = await readBody(req, 2_500_000);
+ if (body.audio !== undefined && body.audio !== null) await saveAudioSpec(ms[1], body.audio); // scene/audio.json (AUTHORING §9)
+ const r = submitScene(ms[1], body.html, body.brief);
+ return send(res, r.ok ? 200 : 422, r);
+ }
+ ms = /^\/api\/jobs\/([\w-]+)\/preview$/.exec(p);
+ if (ms && req.method === 'POST') {
+ const r = await previewJob(ms[1]);
+ return send(res, r.ok ? 200 : 422, { ok: r.ok, errors: r.errors, preview: r.ok ? `/jobs/${ms[1]}/preview.jpg` : null });
+ }
+ let m = /^\/api\/jobs\/([\w-]+)$/.exec(p);
+ if (m && req.method === 'GET') {
+ const job = readJob(m[1]);
+ return job ? send(res, 200, jobView(job, true)) : send(res, 404, { error: 'không thấy job' });
+ }
+ m = /^\/api\/jobs\/([\w-]+)\/render$/.exec(p);
+ if (m && req.method === 'POST') {
+ const job = readJob(m[1]);
+ if (!job) return send(res, 404, { error: 'không thấy job' });
+ enqueueJob(job.id, () => renderJob(job.id));
+ return send(res, 202, jobView(job, true));
+ }
+ // ---- âm thanh ----
+ if (p === '/api/audio/options' && req.method === 'GET') return send(res, 200, audioOptions());
+ if (p === '/api/audio/preview' && req.method === 'GET') {
+ const f = await audioPreviewFile(url.searchParams);
+ return serveFile(req, res, path.dirname(f), path.basename(f));
+ }
+ m = /^\/api\/jobs\/([\w-]+)\/audio$/.exec(p);
+ if (m && req.method === 'POST') {
+ const job = readJob(m[1]);
+ if (!job) return send(res, 404, { error: 'không thấy job' });
+ if (job.status !== 'done' && !fs.existsSync(path.join(JOBS, job.id, 'out.mp4'))) return send(res, 409, { error: 'video chưa dựng xong' });
+ if (audioBusy(job.id)) return send(res, 409, { error: 'đang trộn tiếng cho video này' });
+ const body = await readBody(req);
+ const prefs = { music: body.music, voice: body.voice, sfx: body.sfx };
+ normalizeAudioPrefs({ ...prefs }); // kiểm sớm, sai thì 400
+ reAudio(job.id, prefs).catch((e) => console.error('[audio]', job.id, e.message)); // chạy nền; UI hỏi lại GET /api/jobs/:id
+ return send(res, 202, { ...jobView(readJob(job.id), true), audioBusy: true });
+ }
+ m = /^\/api\/jobs\/([\w-]+)\/versions$/.exec(p);
+ if (m && req.method === 'GET') return send(res, 200, listVersions(m[1]).map((v) => ({ ...v, url: `/jobs/${m[1]}/${v.file}` })));
+ if (p.startsWith('/api/')) return send(res, 404, { error: 'không có API này' });
+
+ // ---- file ----
+ if (req.method !== 'GET' && req.method !== 'HEAD') return send(res, 405, { error: 'method' });
+ if (p.startsWith('/ref/') && USE_REF) return serveFile(req, res, path.join(TEMPLATES, 'ref'), p.slice(5));
+ m = /^\/demo\/(\d{3}\.(?:mp4|webp))$/.exec(p);
+ if (m) return serveFile(req, res, DEMO, m[1]);
+ m = /^\/thumbs\/(\d{3}\.webp)$/.exec(p);
+ if (m) return serveFile(req, res, THUMBS, m[1]);
+ m = /^\/poster\/(\d{3})\.svg$/.exec(p);
+ if (m) {
+ const t = loadCatalog().find((x) => x.id === m[1]);
+ return t ? send(res, 200, posterSvg(t), 'image/svg+xml; charset=utf-8') : send(res, 404, { error: 'không thấy mẫu' });
+ }
+ m = /^\/poster\/p\/([a-z0-9.-]{5,49})\/([a-z][a-z0-9-]{1,31})\.svg$/.exec(p);
+ if (m) {
+ const r = parsePackRef(`${m[1]}/${m[2]}`) && resolveTemplate(`${m[1]}/${m[2]}`);
+ return r ? send(res, 200, posterSvg({ id: r.ref, name: r.meta.name, category: r.meta.category, technique: r.meta.technique }), 'image/svg+xml; charset=utf-8') : send(res, 404, { error: 'không thấy mẫu' });
+ }
+ m = /^\/jobs\/([\w-]+)\/(versions\/out-\d{1,4}\.mp4)$/.exec(p);
+ if (m) return serveFile(req, res, path.join(JOBS, m[1]), m[2]);
+ m = /^\/jobs\/([\w-]+)\/(out\.mp4|preview\.jpg|PROMPT\.md|brief\.json)$/.exec(p);
+ if (m) return serveFile(req, res, path.join(JOBS, m[1]), m[2]);
+ if (p.startsWith('/fonts/')) return serveFile(req, res, path.join(ROOT, 'engine', 'fonts'), p.slice(7));
+ return serveFile(req, res, PUBLIC, p === '/' ? 'index.html' : p.slice(1));
+ } catch (e) {
+ return send(res, 400, { error: e.message });
+ }
+});
+
+markStale();
+initEdits(); // edit đang chạy dở khi server tắt → báo lỗi để bấm lại
+initVoices(); // giọng nhân bản đang xử lý dở → báo lỗi
+initDrafts(); // nháp "Tạo mẫu từ video" đang chạy dở → báo lỗi
+// Job queued còn sót (server tắt trước khi kịp chạy) → chạy lại.
+for (const j of listJobs()) if (j.status === 'queued' && resolveMode(j.mode) !== 'manual') enqueueJob(j.id, () => runJob(j.id));
+// Bộ hẹn giờ: 15 giây kiểm 1 lần, job tới giờ thì xếp hàng chạy.
+function tick() { for (const j of dueJobs()) enqueueJob(j.id, () => runJob(j.id, { force: true })); }
+setInterval(tick, 15000);
+tick();
+
+// Kiểm bản mới trên GitHub (chạy nền, không chặn app): lúc khởi động và 6 giờ/lần. Giao diện đọc qua /api/version.
+const PKG_VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
+let updateState = null;
+function checkUpdateBg() {
+ if (process.env.LUMREELS_SKIP_UPDATE === '1') return;
+ const p = spawn(process.execPath, [fileURLToPath(new URL('../scripts/update.mjs', import.meta.url)), '--json'], { windowsHide: true });
+ let out = '';
+ p.stdout.on('data', (d) => { out += d; });
+ p.on('error', () => {});
+ p.on('close', () => { try { updateState = JSON.parse(out); } catch { /* bỏ qua */ } });
+}
+setTimeout(checkUpdateBg, 3000);
+setInterval(checkUpdateBg, 6 * 3600 * 1000).unref();
+
+server.listen(PORT, HOST, () => {
+ console.log(`LumReels: http://${HOST}:${PORT} (chế độ mặc định: ${DEFAULT_MODE} → ${resolveMode(DEFAULT_MODE)}; OUTPUT_DIR ${config.outputDir() ? 'có' : 'chưa đặt'})`);
+});