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.

25.8 KB
Raw Blame
// 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, ratio?, musicStyle?, content?, names?, draft?, target?)
//                                        hoặc JSON {path, style, ratio?, music?(đường dẫn|tên nhạc tổng hợp), content?, names?, draft?, target?}
//                                        ratio: 9:16 (mặc định) · 16:9 · 4:3 · 3:4
//   GET    /api/edits/:id             → trạng thái, tiến độ, log, chữ LLM đã sửa, các lần sửa
//   POST   /api/edits/from-reel      → {job}: Sửa tiếp trong Studio 1 reel đã dựng (giữ nguyên, tách track giọng/nhạc nếu còn)
//   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';
import { previewGraphics } from './manual.mjs';
import { prepareReel, ReelImportSchema } from './reel.mjs';
import { graphicsScene, GFX_RUNTIME } from './graphics.mjs';
import { loadStyle } from './planner.mjs';
import { lookOf } from './captions-hf.mjs';
import { withFrame } from './edl.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)
  // hàm vẽ đồ hoạ (GFX_RUNTIME) cho khung xem trước của Studio: file JS tĩnh (CSP script-src 'self', không eval)
  if (p === '/edit-runtime/gfx.js' && (req.method === 'GET' || req.method === 'HEAD')) {
    res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' });
    res.end(req.method === 'HEAD' ? undefined : `${GFX_RUNTIME}
window.gfxRender = gfxRender;
`);
    return true;
  }
  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, ratio: fields.ratio, 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, ratio: body.ratio, 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;
  }
  // ---- "Sửa tiếp trong Studio" từ 1 reel đã dựng (tab Dựng từ mẫu): edit giữ nguyên, tách track nếu reel còn tiếng riêng ----
  if (p === '/api/edits/from-reel' && req.method === 'POST') {
    const ready = editReady();
    if (!ready.ready) { send(res, 503, { error: ready.note }); return true; }
    let body;
    try { body = await readBody(req, 4 * 1024); } catch { send(res, 400, { error: 'JSON không hợp lệ' }); return true; }
    const r = ReelImportSchema.safeParse(body);
    if (!r.success) { send(res, 400, { error: 'cần {job: "<id video>"}' }); return true; }
    const id = newEditId(); const dir = editDir(id);
    try {
      fs.mkdirSync(dir, { recursive: true });
      const pr = await prepareReel(r.data.job, dir);
      // giữ tỉ lệ của reel (job dựng từ mẫu 16:9 → bản edit 16:9, khung không cắt)
      const job = await createEdit({ id, video: pr.video, sourceName: pr.sourceName, style: 'sach-gon', ratio: pr.reel.aspect || '9:16', music: pr.music, musicName: pr.musicName, noMusic: !pr.music,
        content: pr.reel.content, llm: 'off', keepAll: true, reel: { ...pr.reel, split: pr.split }, script: pr.script, musicGainDb: pr.musicGainDb });
      runEditJob(job.id).catch((e) => console.error('[edit reel]', job.id, e.message));
      send(res, 202, editView(job.id));
    } catch (e) {
      try { fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, 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: cảnh xem trước đồ hoạ (cùng HTML/CSS với lớp HyperFrames) ----
  m = /^\/api\/edits\/([\w-]+)\/gfx-preview$/.exec(p);
  if (m && req.method === 'POST') {
    let body;
    try { body = await readBody(req, 128 * 1024); } catch { sendAndClose(res, req, send, 400, { error: 'JSON không hợp lệ' }); return true; }
    try {
      if (!ID_RE.test(m[1]) || !readEditJob(m[1])) throw httpErr(404, 'không thấy edit');
      const edl = JSON.parse(fs.readFileSync(path.join(editDir(m[1]), 'edl.json'), 'utf8'));
      let accent; try { accent = loadStyle(edl.style).graphics?.accent; } catch { /* kiểu đã xoá */ }
      send(res, 200, withFrame(edl, () => previewGraphics(edl, body, { accent: accent || lookOf(edl.captions.style).hi, graphicsScene })));
    } catch (e) { send(res, Number.isInteger(e.code) ? e.code : 422, { error: e.message }); }
    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|preview-clean\.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;
}