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.
Edit video: chỉnh tay sau khi AI edit xong + mã hoá GPU (NVENC)
Lumtek799d7063b78a
diff --git a/docs/CHI-TIET.md b/docs/CHI-TIET.mdindex 9ce60e2..a318d84 100644--- a/docs/CHI-TIET.md+++ b/docs/CHI-TIET.md@@ -88,16 +88,17 @@ video ─ edit/ingest.mjs : ffprobe đủ (xoay, VFR, HDR, start_time) + SHA-2preview-final.jpg (lưới 16 khung bản ra) → result.json```- **EDL** (`edit/edl.schema.json`, nguồn sự thật là zod trong `edit/edl.mjs`; `node edit/edl.mjs <edl.json>` để kiểm): `version`, `source` (sha256, xoay, VFR, HDR…), `proxy`, `output`, `keep[]` (đoạn giữ, giây nguồn), `removed[]` (lý do + chữ bị bỏ), `reframe`, `zooms[]`, `captions{style, renderer, maxWords, position, words[], highlights[]}`, `sfx[]`, `music`, `audio{crossfadeMs: 20, keepSourceAudio}`. Mọi mốc là **giây của nguồn**.-- Mã AskEditor (MIT) chép vào `edit/askeditor/` (chỉ lõi + clean-cut/captions/qc-check); chỗ sửa ghi trong `edit/askeditor/VENDORED.md`. Python luôn chạy với `-X utf8` (Windows cp1252 làm vỡ chữ Việt). Biến: `LUMEDIT_WHISPER` (mặc định `large-v3`), `FX_DEVICE` (`auto|cuda|cpu`), `EDIT_MODEL` (model Claude, mặc định Sonnet), `LUMEDIT_PYTHON` (Python dùng để tạo venv).+- Mã AskEditor (MIT) chép vào `edit/askeditor/` (chỉ lõi + clean-cut/captions/qc-check); chỗ sửa ghi trong `edit/askeditor/VENDORED.md`. Python luôn chạy với `-X utf8` (Windows cp1252 làm vỡ chữ Việt). Biến: `LUMEDIT_WHISPER` (mặc định `large-v3`), `FX_DEVICE` (`auto|cuda|cpu`; thiết bị whisper thật ghi trong log bước phân tích và `checks.whisperDevice`), `LUMREELS_ENCODER` (`auto|gpu|cpu`, mặc định `auto`: có NVENC thì proxy, nền và bước ghép mã hoá `h264_nvenc`, lỗi thì tự quay về libx264; `edit/encoder.mjs`), `LUMREELS_CAPTION_LAYER` (`png|webm|webm-fast|mov`, mặc định `png`: chuỗi PNG RGBA, nhanh hơn WebM VP9 ~30%), `EDIT_MODEL` (model Claude, mặc định Sonnet), `LUMEDIT_PYTHON` (Python dùng để tạo venv).- Clip thử tổng hợp (khi chưa có clip người thật): `node edit/test/make-synth.mjs edits/_synth/synth.mp4 [--wide]` (nối hình + giọng sạch của vài job, chèn 1 khoảng lặng 1,6 s và 1 câu nói dở rồi nói lại; ghi kèm `.truth.json`).- **Giao diện**: tab "Edit video của bạn" cạnh "Dựng từ mẫu": kéo thả video (≤ 2 GB), chọn kiểu, nhạc (tổng hợp có sẵn hoặc tải file), ô "tên riêng" (AI dùng để sửa chữ máy nghe sai, ngoài các tên này chỉ sửa chữ vô nghĩa rõ ràng), ô dặn thêm, bản nháp; thanh tiến độ theo 9 bước, video ra, **danh sách chữ AI đã sửa** để người xem lại, ô sửa bằng lời + nút Render lại, các lần sửa, nhật ký. Chưa cài `edit/setup.mjs` thì tab hiện lệnh cài.- **REST** (`edit/http.mjs`, cùng chống DNS rebinding qua Host như các route khác, thêm chặn `Origin` lạ cho lệnh ghi):- `GET /api/edit-options` (đã cài chưa, kiểu edit, nhạc) · `GET /api/edits` · `POST /api/edits` multipart (`video` ≤ 2 GB, `music`?, `style`, `musicStyle`?, `content`?, `names`?, `draft`?; ghi thẳng ra `edits/<id>/source.*`, không giữ trong RAM) hoặc JSON `{path, style, music?, content?, names?, draft?}` khi gọi từ máy · `GET /api/edits/:id` (trạng thái, bước, %, log, `fixes`, `revisions`, `checks`) · `POST /api/edits/:id/revise {instruction}` · `DELETE /api/edits/:id` (xoá hẳn; đang chạy → 409) · file `/edits/:id/(out.mp4|out-r<n>.mp4|preview.jpg|preview-final.jpg|edl.json)`.+ `GET /api/edit-options` (đã cài chưa, kiểu edit, nhạc) · `GET /api/edits` · `POST /api/edits` multipart (`video` ≤ 2 GB, `music`?, `style`, `musicStyle`?, `content`?, `names`?, `draft`?; ghi thẳng ra `edits/<id>/source.*`, không giữ trong RAM) hoặc JSON `{path, style, music?, content?, names?, draft?}` khi gọi từ máy · `GET /api/edits/:id` (trạng thái, bước, %, log, `fixes`, `revisions`, `checks`) · `POST /api/edits/:id/revise {instruction}` · `GET /api/edits/:id/manual` (bảng chỉnh tay) · `POST /api/edits/:id/manual` (bản vá JSON, xem dưới) · `POST /api/edits/:id/music` (multipart `music` ≤ 200 MB → `{file, name}`) · `DELETE /api/edits/:id` (xoá hẳn; đang chạy → 409) · file `/edits/:id/(out.mp4|out-r<n>.mp4|preview.jpg|preview-final.jpg|edl.json)`.Upload: phải có `Content-Length`, ổ đĩa phải trống ≥ 5× cỡ upload (507 nếu không), mỗi lúc nhận 1 upload (429), bộ đệm multipart luôn ≤ 64 KB + 1 chunk (trước dấu phân cách đầu, đầu phần, trường chữ, sau dấu kết thúc; quá thì 400 và đóng kết nối); lỗi nào sau khi đã ghi file cũng xoá cả thư mục `edits/<id>`. Video và nhạc được ffprobe ngay khi tạo (không có hình/tiếng, < 1 s, > 30 phút → 422) trước khi chạy whisper/LLM.- **Hàng chờ**: mỗi lúc 1 edit chạy trên cả máy (khoá `edits/.edit.lock` tạo độc quyền `wx`, có pid; khoá của tiến trình đã chết được gỡ dưới khoá phụ `.edit.lock.break` cũng `wx`, nên 2 tiến trình không thể cùng gỡ/cùng giữ). Hồ sơ `edits/<id>/job.json`: `queued → running → done | error`, `step/pct`. Mỗi lần đọc job (UI, REST, MCP, CLI): job `queued/running` mà pid đã chết → tự chuyển `error` (dựng lần đầu) hoặc `done` + `reviseError` (lần sửa), kèm lý do.-- **Dọn đĩa**: xong mỗi lượt (được hay lỗi) xoá `proxy.mov`, `base.mp4`, `captions.webm`, `captions/lib`, `audio/`; giữ nguồn, `edl.json`, `out*.mp4`, `captions/index.html`, log và các JSON nhỏ (phân tích, chép lời, mặt). Sửa bằng lời dựng lại proxy từ nguồn (~5 s; cùng thông số nên ra đúng file cũ, cache chữ/mặt dùng lại). Xoá hẳn: nút "Xoá bản dựng này" trên UI, `DELETE /api/edits/:id`, `node cli.mjs edit-rm <id>`.+- **Dọn đĩa**: xong mỗi lượt (được hay lỗi) xoá `proxy.mov`, `captions/lib`, `audio/` trừ `mix.wav`; giữ nguồn, `edl.json`, `out*.mp4`, `base.mp4` (nền), lớp chữ (`captions-png/`), `audio/mix.wav`, `captions/index.html`, log và các JSON nhỏ (phân tích, chép lời, mặt) — chỉnh tay dùng lại nền/lớp chữ/bản trộn khi chữ ký trong `render.sig.json` khớp. Sửa bằng lời dựng lại proxy từ nguồn (~5 s; cùng thông số nên ra đúng file cũ, cache chữ/mặt dùng lại). Xoá hẳn: nút "Xoá bản dựng này" trên UI, `DELETE /api/edits/:id`, `node cli.mjs edit-rm <id>`.- **Đã cài chưa** (`setupStatus`): python trong venv + dấu `edit/.venv/.lumedit-ready.json` do setup ghi sau khi import thử đủ gói, kèm danh sách file phải còn (model whisper, model mặt/người, font). Thiếu gì UI/REST/MCP báo đúng cái thiếu.- **Sửa bằng lời** (`reviseEdit`): LLM đọc lời chép kèm mốc giây BẢN HIỆN TẠI + đề xuất hiện tại → trả đề xuất mới, `cut_output` (giây bản hiện tại, code đổi sang giây nguồn theo keep và nới mép cho trọn chữ) và núm kiểu (`zoomScale`, `zoomMinGap`, `captionsMaxWords`, `musicGainDb`, `pause`, `sfxOff`). Code dựng lại EDL, render từ bước "xem trước". Mỗi lần sửa n ra file MỚI `out-r<n>.mp4` (Windows khoá file đang phát nên không ghi đè), bản trước giữ nguyên; EDL trước lần sửa n ở `versions/edl-<n>.json`; `state.json.out` = bản mới nhất. Lỗi giữa chừng → trả `edl.json` về bản trước. LLM sai 2 vòng → báo lỗi, bản cũ giữ nguyên.+- **Chỉnh tay** (`edit/manual.mjs`, `manualEdit`): không LLM. Bản vá JSON kiểm chặt (khoá lạ → 400): `captions {lines: [{start, end, text}] (giây BẢN RA, *chữ* = chữ nhấn), highlights: bool, look: id kiểu}`, `music {source: keep|none|synth:<tên>|upload:music-up-<n>.<đuôi>, gainDb −40…0, duck: bool, fadeOut 0…10, start giây bài nhạc}`, `voice {gainDb −12…12}`, `sfx {on}`, `zooms {remove: [số thứ tự]}`, `graphics {remove: [id]}`. Chỉ dựng lại lớp cần: phụ đề/look/chữ nhấn → lớp chữ + ghép; nhạc/giọng/sfx → trộn tiếng + ghép (không render hình); xoá zoom/đồ hoạ → nền (không nghe lại) + ghép. Ra `out-r<n>.mp4` như sửa bằng lời, EDL trước ở `versions/edl-<n>.json`; chỉnh tay lưu ở `state.manual` và được giữ khi sửa bằng lời (dòng phụ đề tay chỉ giữ khi phần cắt không đổi). Bản nháp (phụ đề PIL trong nền) không sửa phụ đề tay được (409).- **CLI**: `node cli.mjs edit <video> … [--names "Lumfin, …"]`, `edit-revise <id> "<lời>"` (hoặc `--file <f>`: MCP truyền lời sửa qua file, không qua argv), `edit-rm <id>`, `edit-show <id> [--json]`, `edit-run <id>`. **MCP**: `edit_video {path, style, music?, notes?, names?, draft?}` (chạy nền, trả editId), `revise_edit {editId, instruction}`, `get_edit {editId?}`.- **Phụ đề không chồng nhau**: luật thời gian nhóm chữ (giống nhau ở `captions-hf.mjs` và `lumedit.py`): nối khe < 0,4 s, tối thiểu 0,25 s nhưng không bao giờ quá điểm bắt đầu của nhóm sau, nhóm bị ép < 0,1 s gộp vào nhóm sau; kiểm `cardOverlaps` — có chồng là dừng. (Lỗi cũ: chữ nói nhanh 0,22 s bị kéo lên 0,25 s nên "TRÀ" đè "SỮA".)- **Tốc độ phụ đề HyperFrames** (đo trên 23,8 s, 80 nhóm): 1080p 61 s; `-w 10` 59 s; dựng ở 720p rồi phóng 51 s / 47 s (chữ mờ hơn, chưa dùng). Hướng tăng tốc thật (để sau): chỉ chụp khung có chuyển động (0,2 s đầu mỗi nhóm + khung đổi màu), giữ các khung tĩnh bằng ffmpeg.diff --git a/edit/askeditor/VENDORED.md b/edit/askeditor/VENDORED.mdindex 35ebfc8..0041418 100644--- a/edit/askeditor/VENDORED.md+++ b/edit/askeditor/VENDORED.md@@ -12,6 +12,8 @@- Khoá cache chữ (`model_key`) gồm model + ngôn ngữ, nên đổi model thì chép lại.- Không dùng câu mồi (`initial_prompt`) ngoài tiếng Anh (làm whisper bịa câu tiếng Việt).- Từ đệm tiếng Việt (ờ, ờm, ừm, ơ, hừm); câu whisper hay bịa ("hãy subscribe…", "ghiền mì gõ"…) bị bỏ ngay ở lượt nghe đầu.+ - Ghi thiết bị whisper thật (`DEVICE`: `cuda float16` hoặc `cpu int8 (lý do)`) vào cache chữ (`device`), để log Edit thấy khi GPU âm thầm rơi về CPU.2. `fx/core/text.py`: khi `FX_LANG=vi`, các mặt chữ Poppins (thiếu dấu Việt) vẽ bằng Be Vietnam Pro (OFL), do `node edit/setup.mjs` ghép từ `engine/fonts`.3. `fx/core/models.py`: thêm lệnh `fetch-vision` (chỉ tải model mặt/người; model giọng do `FX_WHISPER` lo).4. Mọi `read_text()` ghi rõ `encoding="utf-8"`. Ngoài ra LumReels luôn chạy Python với `-X utf8` / `PYTHONUTF8=1` vì Windows mặc định cp1252 làm vỡ chữ Việt ở các chỗ `write_text()`.+5. `fx/core/video.py`: `FrameWriter` đọc `FX_VCODEC_ARGS` (danh sách JSON tham số ffmpeg, vd `h264_nvenc`) thay cho libx264 khi Node đặt (`edit/encoder.mjs`); không đặt thì giữ libx264 như gốc.diff --git a/edit/askeditor/fx/core/video.py b/edit/askeditor/fx/core/video.pyindex 6b969ac..df75d71 100644--- a/edit/askeditor/fx/core/video.py+++ b/edit/askeditor/fx/core/video.py@@ -296,6 +296,20 @@ def mono(samples: np.ndarray, rate: int, to_rate: int = 16000) -> np.ndarray:return np.interp(pos, np.arange(len(x)), x).astype(np.float32)+def _video_codec(preset: str, crf: int) -> list[str]:+ """[LumReels] The encoder arguments: FX_VCODEC_ARGS (a JSON list from the Node side, e.g. h264_nvenc+ when the machine has one) replaces libx264, so the base render can use the GPU's encoder."""+ raw = os.environ.get("FX_VCODEC_ARGS", "").strip()+ if raw:+ try:+ args = json.loads(raw)+ if isinstance(args, list) and args and all(isinstance(a, str) for a in args):+ return args+ except ValueError:+ pass+ return ["-c:v", "libx264", "-preset", preset, "-crf", str(crf)]++class FrameWriter:"""Writes RGB frames to an MP4 (H.264, the clip's frame rate) with the given sound (AAC).@@ -335,7 +349,7 @@ class FrameWriter:cmd += ["-map", "1:a:0", "-c:a", "aac", "-b:a", f"{int(audio_kbps)}k"]cmd += ["-vf", "scale=out_color_matrix=bt709:out_range=tv,format=yuv420p",*(["-threads", THREADS] if THREADS.isdigit() else []),- "-c:v", "libx264", "-preset", preset, "-crf", str(crf), "-pix_fmt", "yuv420p",+ *_video_codec(preset, crf), "-pix_fmt", "yuv420p","-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-color_range", "tv","-movflags", "+faststart", "-map_metadata", "-1", "-fflags", "+bitexact","-flags:v", "+bitexact", "-flags:a", "+bitexact", str(self._partial)]diff --git a/edit/askeditor/fx/core/words.py b/edit/askeditor/fx/core/words.pyindex 727bf00..2a479dd 100644--- a/edit/askeditor/fx/core/words.py+++ b/edit/askeditor/fx/core/words.py@@ -184,6 +184,7 @@ def load(clip: str | os.PathLike, model: str = "small.en", refresh: bool = Falsedef _engine(model: str):+ global DEVICEfrom faster_whisper import WhisperModelfrom . import models@@ -191,6 +192,7 @@ def _engine(model: str):threads = max(1, min(8, (os.cpu_count() or 4)))override = os.environ.get("FX_WHISPER", "").strip()if not override:+ DEVICE = "cpu int8 (pack model)"return WhisperModel(str(models.speech_path(model)), device="cpu", compute_type="int8", cpu_threads=threads)device = os.environ.get("FX_DEVICE", "auto").strip().lower() or "auto"if device in ("auto", "cuda"):@@ -199,14 +201,26 @@ def _engine(model: str):if ctranslate2.get_cuda_device_count() > 0:cuda_libraries()- return WhisperModel(override, device="cuda", compute_type="float16", cpu_threads=threads)+ engine = WhisperModel(override, device="cuda", compute_type="float16", cpu_threads=threads)+ DEVICE = "cuda float16"+ return engine+ why = "no CUDA device"except Exception as e: # no CUDA libraries, an old driver, no room on the cardif device == "cuda":raise+ why = str(e)print(f"speech model: the GPU could not be used ({e}); using the CPU", file=sys.stderr)+ else:+ why = f"FX_DEVICE={device}"+ DEVICE = f"cpu int8 ({why})"return WhisperModel(override, device="cpu", compute_type="int8", cpu_threads=threads)+# [LumReels] Where the last engine of this process runs ("cuda float16" | "cpu int8 (why)"), written into the+# words cache so a silent fall back to the CPU shows in the edit's log.+DEVICE = ""++def model_key(model: str) -> str:"""[LumReels] What a words cache records as its model: the model and the language when they comefrom the environment, so changing either transcribes again."""@@ -281,6 +295,7 @@ def transcribe(clip: Path, model: str = "small.en") -> dict:"model": model_key(model),"source": dict(paths.source_signature(clip), seconds=round(info.duration, 3)),"seconds_to_transcribe": round(time.time() - started, 2),+ "device": DEVICE,"text": text,"words": to_json(words),}diff --git a/edit/audio.mjs b/edit/audio.mjsindex fb268b9..b47938f 100644--- a/edit/audio.mjs+++ b/edit/audio.mjs@@ -14,23 +14,27 @@ const ff = async (args, what, timeoutMs = 20 * 60e3) => {};/**- * base: video nền có tiếng gốc đã cắt. sfx: [{t (giây bản ra), name, gainDb}]. music: {file, gainDb, duckDb, fadeOut}|null.- * Trả {wav, lufs, truePeak, gainDb}.+ * base: video nền có tiếng gốc đã cắt. sfx: [{t (giây bản ra), name, gainDb}].+ * music: {file, gainDb, duckDb (0 = không hạ khi nói), fadeOut, start? (giây của bài nhạc ở đầu bản ra)}|null.+ * voiceGainDb: nâng/hạ giọng so với nhạc + sfx trước khi chuẩn độ lớn. Trả {wav, lufs, truePeak, gainDb}.*/-export async function buildEditMix({ base, duration, sfx = [], music = null, workDir, lufs = -14, log = console.log }) {+export async function buildEditMix({ base, duration, sfx = [], music = null, voiceGainDb = 0, workDir, lufs = -14, log = console.log }) {fs.mkdirSync(workDir, { recursive: true });const dlg = path.join(workDir, 'dialogue.wav');await ff(['-i', base, '-vn', '-ac', '2', '-ar', '48000', '-c:a', 'pcm_s16le', dlg], 'tách giọng gốc');const inputs = ['-i', dlg]; const chains = []; const mixIn = ['[dlg]'];- chains.push('[0:a]aformat=sample_fmts=fltp:sample_rates=48000:channel_layouts=stereo,asplit=2[dlg][key]');+ const vg = voiceGainDb ? `,volume=${voiceGainDb}dB` : '';+ chains.push(`[0:a]aformat=sample_fmts=fltp:sample_rates=48000:channel_layouts=stereo${vg},asplit=2[dlg][key]`);let k = 1;if (music) {inputs.push('-stream_loop', '-1', '-i', music.file);const fadeAt = Math.max(0, duration - music.fadeOut);// hạ nhạc khi có giọng: sidechain theo giọng gốc; ratio quy đổi gần đúng từ duckDbconst ratio = Math.min(20, Math.max(1.5, 1 + music.duckDb / 3));- chains.push(`[${k}:a]aformat=sample_fmts=fltp:sample_rates=48000:channel_layouts=stereo,atrim=0:${duration.toFixed(3)},asetpts=PTS-STARTPTS,volume=${music.gainDb}dB[mraw]`);- chains.push(`[mraw][key]sidechaincompress=threshold=0.015:ratio=${ratio.toFixed(1)}:attack=15:release=350:makeup=1[mduck]`);+ const st = Math.max(0, Number(music.start) || 0);+ chains.push(`[${k}:a]aformat=sample_fmts=fltp:sample_rates=48000:channel_layouts=stereo,atrim=${st.toFixed(3)}:${(st + duration).toFixed(3)},asetpts=PTS-STARTPTS,volume=${music.gainDb}dB[mraw]`);+ if (music.duckDb > 0) chains.push(`[mraw][key]sidechaincompress=threshold=0.015:ratio=${ratio.toFixed(1)}:attack=15:release=350:makeup=1[mduck]`);+ else chains.push('[mraw]anull[mduck]', '[key]anullsink');chains.push(`[mduck]afade=t=out:st=${fadeAt.toFixed(3)}:d=${music.fadeOut}[mus]`);mixIn.push('[mus]'); k++;} else {@@ -55,6 +59,6 @@ export async function buildEditMix({ base, duration, sfx = [], music = null, worawait ff(['-i', pre, '-af', `volume=${gainDb}dB,alimiter=limit=${Math.pow(10, -2.5 / 20).toFixed(4)}:attack=5:release=50:level=disabled`,'-c:a', 'pcm_s16le', '-ar', '48000', wav], 'chỉnh độ lớn');const after = await measureLoudness(wav);- log(`tiếng: trước ${m.lufs.toFixed(1)} LUFS → sau ${after.lufs.toFixed(1)} LUFS, đỉnh ${after.truePeak.toFixed(1)} dBTP${music ? ', có nhạc tự hạ khi nói' : ''}, ${sfx.length} tiếng động`);+ log(`tiếng: trước ${m.lufs.toFixed(1)} LUFS → sau ${after.lufs.toFixed(1)} LUFS, đỉnh ${after.truePeak.toFixed(1)} dBTP${music ? `, nhạc ${music.gainDb} dB${music.duckDb > 0 ? ' tự hạ khi nói' : ' không ducking'}${music.start ? ` từ giây ${music.start}` : ''}` : ''}${voiceGainDb ? `, giọng ${voiceGainDb > 0 ? '+' : ''}${voiceGainDb} dB` : ''}, ${sfx.length} tiếng động`);return { wav, lufs: after.lufs, truePeak: after.truePeak, gainDb };}diff --git a/edit/captions-hf.mjs b/edit/captions-hf.mjsindex 09afa12..da888d8 100644--- a/edit/captions-hf.mjs+++ b/edit/captions-hf.mjs@@ -27,6 +27,13 @@ function groupWords(words, maxWords) {/** Cùng luật với caption_cards trong edit/py/lumedit.py. */export function captionCards(edl) {const cap = edl.captions; const tl = timelineOf(edl); const H = edl.hook;+ // phụ đề chỉnh tay (giây bản ra, edit/manual.mjs): dùng nguyên dòng người dùng đặt, chỉ kiểm không đè nhau+ if (cap.lines) {+ const cards = cap.lines.map((l) => ({ start: l.start, end: l.end, words: l.words.map((w) => ({ w: w.w, i: -1, o: w.o, hl: w.hi })), wordOut: l.words.map((w) => Math.max(l.start, w.o)) }));+ const bad = cardOverlaps(cards);+ if (bad.length) throw new Error('phụ đề chỉnh tay chồng nhau: ' + bad.join('; '));+ return cards;+ }// mỗi chữ mang giây bản ra (o) của chính nó: chữ câu móc lặp lại có 2 chỗ trên bản raconst mk = (ws, map) => groupWords(ws, cap.maxWords).map((g) => ({ words: g.map((w) => ({ ...w, o: map(w.start) })), start: map(g[0].start), end: map(g[g.length - 1].end) }));const cards = mk(cap.words, (t) => toOutputNearest(tl, t)).sort((a, b) => a.start - b.start);@@ -161,7 +168,9 @@ export function writeCaptionScene(edl, sceneDir, { captions = true, accent, stylconst dur = Math.max(1 / OUT.fps, Math.round(outputDuration(tlk) * OUT.fps) / OUT.fps);let cards = captions && edl.captions.words.length ? captionCards(edl) : [];const gfx = (edl.graphics || []).length ? graphicsScene(edl, { accent: accent || look.hi, stepTracker: !!style?.graphics?.stepTracker, dur }) : null;- const hi = new Set(edl.captions.highlights);+ const hiSet = new Set(edl.captions.hiOff ? [] : edl.captions.highlights);+ // chữ nhấn: dòng chỉnh tay mang cờ hl riêng; tắt chữ nhấn (hiOff) thì không chữ nào nhấn+ const hi = { has: (i, wd) => !edl.captions.hiOff && (wd?.hl ?? hiSet.has(i)) };const x0 = Math.round(SAFE.x0 * OUT.width); const w = Math.round((SAFE.x1 - SAFE.x0) * OUT.width);const cy = Math.round(look.cy * OUT.height); const yMax = Math.round(SAFE.y1 * OUT.height);@@ -191,7 +200,7 @@ export function writeCaptionScene(edl, sceneDir, { captions = true, accent, stylsize = c.words.length === 1 ? Math.min(look.size, Math.floor(w / (longest * 0.5 + 0.5))) : look.size;}const inner = (t) => (look.enter === 'typewriter' ? [...t].map((ch) => `<i class="ch">${esc(ch)}</i>`).join('') : esc(t));- const spans = c.words.map((wd, k) => `<span class="w${hi.has(wd.i) ? ' hi' : ''}" id="c${ci}w${k}">${inner(text[k])}</span>`).join(' ');+ const spans = c.words.map((wd, k) => `<span class="w${hi.has(wd.i, wd) ? ' hi' : ''}" id="c${ci}w${k}">${inner(text[k])}</span>`).join(' ');return `<div class="card${ticker ? ' tk' : ''}" id="c${ci}" style="font-size:${size}px">${spans}</div>`;}).join('\n ');@@ -241,7 +250,7 @@ export function writeCaptionScene(edl, sceneDir, { captions = true, accent, stylif (look.karaoke && c.words.length > 1) {c.words.forEach((wd, k) => {const a = c.wordOut[k]; const b = k + 1 < c.words.length ? c.wordOut[k + 1] : c.end;- lines.push(`tl.set('#c${ci}w${k}', {color: '${look.hi}'}, ${a.toFixed(3)}); tl.set('#c${ci}w${k}', {color: '${hi.has(wd.i) ? look.hi : look.color}'}, ${b.toFixed(3)});`);+ lines.push(`tl.set('#c${ci}w${k}', {color: '${look.hi}'}, ${a.toFixed(3)}); tl.set('#c${ci}w${k}', {color: '${hi.has(wd.i, wd) ? look.hi : look.color}'}, ${b.toFixed(3)});`);});}lines.push(`tl.set('#c${ci}', {autoAlpha: 0}, ${c.end.toFixed(3)});`);@@ -352,10 +361,32 @@ ${gfx ? `<script src="./lib/runtime/scene.js"></script>return { duration: dur, cards: cards.length, graphics: (edl.graphics || []).length, box: { x0, x1: x0 + w, cy, yMax }, quote: !!qs, hookText: !!hookHtml, ticker: !!ticker };}-/** Render lớp chữ trong suốt → WebM VP9 alpha. */-export async function renderCaptionLayer(sceneDir, outWebm, { log = console.log, onPct } = {}) {+// Định dạng lớp chữ trong suốt (HyperFrames → ffmpeg chồng lên nền). LUMREELS_CAPTION_LAYER=png|webm|webm-fast|mov.+// Đo lớp chữ 32 s (967 khung) trên máy 20 luồng + RTX 3070 Ti, HF render / cỡ / ghép (overlay + NVENC):+// webm VP9 alpha 63,7 s / 0,9 MB / 5,7 s · webm --vp9-cpu-used 8 64,5 s (không nhanh hơn: chậm ở chụp khung, không ở VP9)+// mov ProRes 4444 55,7 s / 87 MB / 6,3 s · png (chuỗi PNG RGBA, không mã hoá video) 45,3 s / 33 MB / 5,9 s → mặc định png.+// Alpha: PNG không mất dữ liệu (VP9 alpha có mất), bản ghép png và webm giống nhau (SSIM 0,995, khác ở khung chữ đang mờ dần).+export const LAYERS = {+ webm: { name: 'webm', file: 'captions.webm', hf: ['--format', 'webm'], input: ['-c:v', 'libvpx-vp9'] },+ 'webm-fast': { name: 'webm-fast', file: 'captions.webm', hf: ['--format', 'webm', '--vp9-cpu-used', '8'], input: ['-c:v', 'libvpx-vp9'] },+ png: { name: 'png', file: 'captions-png', hf: ['--format', 'png-sequence'], input: null },+ mov: { name: 'mov', file: 'captions.mov', hf: ['--format', 'mov'], input: [] },+};+export const LAYER = LAYERS[String(process.env.LUMREELS_CAPTION_LAYER || '').trim().toLowerCase()] || LAYERS.png;++/** Tham số ffmpeg đọc lớp chữ (chuỗi PNG: mẫu tên file + số khung đầu). */+export function layerInput(layer, file) {+ if (layer.input) return [...layer.input, '-i', file];+ const files = fs.readdirSync(file).filter((f) => /\.png$/i.test(f)).sort();+ const m = /^(.*?)(\d+)(\.png)$/i.exec(files[0] || '');+ if (!m) throw new Error('lớp chữ PNG rỗng: ' + file);+ return ['-framerate', String(OUT.fps), '-start_number', String(Number(m[2])), '-i', path.join(file, `${m[1]}%0${m[2].length}d${m[3]}`)];+}++/** Render lớp chữ trong suốt (định dạng LAYER: WebM VP9 alpha / chuỗi PNG / ProRes 4444). */+export async function renderCaptionLayer(sceneDir, outWebm, { log = console.log, onPct, format = LAYER.hf } = {}) {let last = -1;- const r = await runHF(['render', sceneDir, '-o', outWebm, '--format', 'webm', '-f', String(OUT.fps), '-q', 'looks', '--quiet'], {+ const r = await runHF(['render', sceneDir, '-o', outWebm, ...format, '-f', String(OUT.fps), '-q', 'looks', '--quiet'], {onLine: (l) => {const m = /^@hf-progress (.*)$/.exec(l);if (m) { try { const p = JSON.parse(m[1]); onPct?.(p.pct); const b = Math.floor(p.pct / 20) * 20; if (b !== last) { last = b; log(`phụ đề HyperFrames ${p.pct}% ${p.code}`); } } catch { /* bỏ qua */ } }diff --git a/edit/edl.mjs b/edit/edl.mjsindex 390f636..1910912 100644--- a/edit/edl.mjs+++ b/edit/edl.mjs@@ -68,10 +68,17 @@ export const EdlSchema = z.object({maxWords: z.number().int().min(1).max(8), position: z.enum(['lower', 'middle']),words: z.array(z.object({ i: z.number().int().nonnegative(), w: z.string().min(1), start: sec, end: sec }).strict()),highlights: z.array(z.number().int().nonnegative()).describe('chỉ số i của chữ nhấn'),+ hiOff: z.boolean().default(false).describe('tắt mọi chữ nhấn (chỉnh tay)'),+ lines: z.array(z.object({+ start: sec, end: sec,+ words: z.array(z.object({ w: z.string().min(1).max(80), o: sec, hi: z.boolean() }).strict()).min(1).max(40),+ }).strict()).max(600).optional()+ .describe('dòng phụ đề chỉnh tay, GIÂY BẢN RA (thay cho nhóm chữ tự động; o: giây bản ra của từng chữ cho karaoke)'),}).strict(),sfx: z.array(z.object({ at: sec, name: z.string(), gainDb: z.number().min(-30).max(6) }).strict()),music: z.object({- file: z.string(), gainDb: z.number().min(-40).max(0), duckDb: z.number().min(0).max(30), fadeOut: z.number().min(0).max(10),+ file: z.string(), gainDb: z.number().min(-40).max(0), duckDb: z.number().min(0).max(30).describe('0: không hạ nhạc khi nói'), fadeOut: z.number().min(0).max(10),+ start: z.number().min(0).max(600).default(0).describe('giây của bài nhạc phát ở đầu bản ra'),}).strict().nullable(),graphics: z.array(GraphicSchema).default([]).describe('đồ hoạ bảng biểu (kiểu thong-tin-do-hoa)'),hook: z.object({@@ -86,7 +93,11 @@ export const EdlSchema = z.object({quote: z.object({start: sec, end: sec, dimTo: z.number().min(0.1).max(1), blurPx: z.number().min(0).max(30), dimIn: z.number().min(0.1).max(3),}).strict().nullable().default(null).describe('câu trích dẫn to giữa khung (giây nguồn); video tối + mờ trong lúc đó'),- audio: z.object({ crossfadeMs: z.number().min(5).max(80), keepSourceAudio: z.literal(true) }).strict(),+ audio: z.object({+ crossfadeMs: z.number().min(5).max(80), keepSourceAudio: z.literal(true),+ voiceGainDb: z.number().min(-12).max(12).default(0).describe('nâng/hạ giọng gốc so với nhạc (cả bản vẫn chuẩn về −14 LUFS)'),+ sfxOff: z.boolean().default(false).describe('tắt mọi tiếng động (giữ danh sách sfx)'),+ }).strict(),notes: z.string().optional(),}).strict();@@ -174,6 +185,11 @@ export function validateEdl(input, { sfxNames, checkFiles = true } = {}) {if (i && w.start < e.captions.words[i - 1].start - 1e-6) add('word-order', `captions.words.${i}`, 'chữ phải theo thứ tự thời gian');ids.add(w.i);});+ (e.captions.lines || []).forEach((l, i) => {+ if (l.end - l.start < 0.05) add('line-time', `captions.lines.${i}`, 'dòng phụ đề kết thúc trước khi bắt đầu');+ if (l.start > outDur + 0.05) add('line-out', `captions.lines.${i}`, `dòng phụ đề ở ${l.start} s, sau cuối bản ra (${outDur.toFixed(2)} s)`);+ if (i && l.start < e.captions.lines[i - 1].end - 1e-6) add('line-overlap', `captions.lines.${i}`, 'dòng phụ đề đè dòng trước');+ });e.captions.highlights.forEach((h, i) => { if (!ids.has(h)) add('highlight', `captions.highlights.${i}`, `chữ nhấn ${h} không có trong phụ đề`); });e.sfx.forEach((s, i) => {if (sfxNames && !sfxNames.includes(s.name)) add('sfx-name', `sfx.${i}`, `không có tiếng "${s.name}"`);diff --git a/edit/edl.schema.json b/edit/edl.schema.jsonindex f7b8937..21c3e98 100644--- a/edit/edl.schema.json+++ b/edit/edl.schema.json@@ -347,6 +347,63 @@"maximum": 9007199254740991},"description": "chỉ số i của chữ nhấn"+ },+ "hiOff": {+ "default": false,+ "description": "tắt mọi chữ nhấn (chỉnh tay)",+ "type": "boolean"+ },+ "lines": {+ "description": "dòng phụ đề chỉnh tay, GIÂY BẢN RA (thay cho nhóm chữ tự động; o: giây bản ra của từng chữ cho karaoke)",+ "maxItems": 600,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "start": {+ "type": "number",+ "minimum": 0+ },+ "end": {+ "type": "number",+ "minimum": 0+ },+ "words": {+ "minItems": 1,+ "maxItems": 40,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "w": {+ "type": "string",+ "minLength": 1,+ "maxLength": 80+ },+ "o": {+ "type": "number",+ "minimum": 0+ },+ "hi": {+ "type": "boolean"+ }+ },+ "required": [+ "w",+ "o",+ "hi"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "start",+ "end",+ "words"+ ],+ "additionalProperties": false+ }}},"required": [@@ -401,12 +458,20 @@"duckDb": {"type": "number","minimum": 0,- "maximum": 30+ "maximum": 30,+ "description": "0: không hạ nhạc khi nói"},"fadeOut": {"type": "number","minimum": 0,"maximum": 10+ },+ "start": {+ "default": 0,+ "description": "giây của bài nhạc phát ở đầu bản ra",+ "type": "number",+ "minimum": 0,+ "maximum": 600}},"required": [@@ -772,6 +837,18 @@"keepSourceAudio": {"type": "boolean","const": true+ },+ "voiceGainDb": {+ "default": 0,+ "description": "nâng/hạ giọng gốc so với nhạc (cả bản vẫn chuẩn về −14 LUFS)",+ "type": "number",+ "minimum": -12,+ "maximum": 12+ },+ "sfxOff": {+ "default": false,+ "description": "tắt mọi tiếng động (giữ danh sách sfx)",+ "type": "boolean"}},"required": [diff --git a/edit/encoder.mjs b/edit/encoder.mjsnew file mode 100644index 0000000..f8c3a3a--- /dev/null+++ b/edit/encoder.mjs@@ -0,0 +1,64 @@+// Chọn bộ mã hoá H.264 cho phần Edit: có NVENC (card NVIDIA, ffmpeg có h264_nvenc) thì dùng GPU, không thì libx264.+// LUMREELS_ENCODER=cpu|gpu|auto (mặc định auto). gpu mà máy không chạy được NVENC → vẫn quay về libx264 (có ghi lý do).+// Thử thật 1 lần mỗi tiến trình (mã hoá 8 khung 1080×1920), vì ffmpeg có h264_nvenc chưa chắc driver/card chạy được.+// Chất lượng: x264 CRF q ↔ NVENC VBR cq (q + 5), preset p6 (proxy p4), AQ không gian + thời gian, 3 B-frame làm tham chiếu.+// Đo trên bản ra 32 s 1080×1920 (so với bản lossless): x264 CRF 18 medium VMAF 90,48 / 18,0 MB / 6,3 s;+// NVENC cq 19 90,74 / 42,8 MB (gấp 2,4 lần cỡ) · cq 21 90,62 / 33,2 MB · cq 23 (p6) 90,51 / 26,2 MB / 5,4 s · cq 25 90,17 / 21,3 MB+// → cq = CRF + 5: cùng VMAF với x264 CRF 18, file to hơn ~45%. Lợi chính của NVENC là để CPU cho việc khác (vẽ khung, Chrome).+import { run } from '../engine/lib.mjs';++let probed = null; // Promise<{gpu: boolean, why: string}>++export const encoderMode = () => {+ const m = String(process.env.LUMREELS_ENCODER || 'auto').trim().toLowerCase();+ return ['cpu', 'gpu', 'auto'].includes(m) ? m : 'auto';+};++/** NVENC chạy được không (thử mã hoá thật). Kết quả giữ trong tiến trình. */+export function probeNvenc() {+ if (!probed) {+ probed = (async () => {+ const r = await run('ffmpeg', ['-hide_banner', '-v', 'error', '-f', 'lavfi', '-i', 'testsrc2=s=1080x1920:r=30', '-frames:v', '8',+ ...videoArgs('gpu', { quality: 18 }), '-pix_fmt', 'yuv420p', '-f', 'null', '-'], { timeoutMs: 30e3 });+ if (r.code === 0) return { gpu: true, why: 'h264_nvenc chạy được' };+ return { gpu: false, why: 'NVENC không chạy: ' + (r.out.trim().split(/\r?\n/).pop() || `mã ${r.code}`) };+ })();+ }+ return probed;+}++/** Bộ mã hoá nên dùng: {kind: 'gpu'|'cpu', why}. */+export async function pickEncoder() {+ const mode = encoderMode();+ if (mode === 'cpu') return { kind: 'cpu', why: 'LUMREELS_ENCODER=cpu' };+ const p = await probeNvenc();+ if (p.gpu) return { kind: 'gpu', why: mode === 'gpu' ? 'LUMREELS_ENCODER=gpu' : p.why };+ return { kind: 'cpu', why: p.why + (mode === 'gpu' ? ' (đã đặt gpu, quay về libx264)' : '') };+}++/**+ * Tham số ffmpeg mã hoá hình (không gồm -pix_fmt). quality: CRF kiểu x264 (16 proxy, 18 bản ra).+ * speed: 'fast' (proxy, ghép) | 'medium' (bản ra). gop: số khung giữa 2 khung khoá (tuỳ chọn).+ */+export function videoArgs(kind, { quality = 18, speed = 'medium', gop = null } = {}) {+ const g = gop ? ['-g', String(gop)] : [];+ if (kind === 'gpu') {+ return ['-c:v', 'h264_nvenc', '-preset', speed === 'fast' ? 'p4' : 'p6', '-tune', 'hq', '-rc', 'vbr', '-cq', String(quality + 5), '-b:v', '0',+ '-spatial-aq', '1', '-temporal-aq', '1', '-bf', '3', '-b_ref_mode', 'middle', '-rc-lookahead', '20', '-profile:v', 'high', ...g, ...(gop ? ['-forced-idr', '1'] : [])];+ }+ const x = ['-c:v', 'libx264', '-preset', speed === 'fast' ? 'veryfast' : 'medium', '-crf', String(quality), ...g];+ return gop ? [...x, '-keyint_min', String(gop), '-sc_threshold', '0'] : x;+}++/**+ * Chạy fn(kind) với bộ mã hoá đã chọn; GPU lỗi → chạy lại bằng libx264 (log lý do). Trả {result, kind}.+ */+export async function withEncoder(fn, { log = () => {}, what = 'mã hoá' } = {}) {+ const enc = await pickEncoder();+ if (enc.kind === 'gpu') {+ try { return { result: await fn('gpu'), kind: 'gpu' }; } catch (e) {+ log(` ${what}: NVENC lỗi (${String(e.message).slice(0, 200)}), làm lại bằng libx264`);+ }+ }+ return { result: await fn('cpu'), kind: 'cpu' };+}diff --git a/edit/env.mjs b/edit/env.mjsindex bbb5732..86e0e37 100644--- a/edit/env.mjs+++ b/edit/env.mjs@@ -75,13 +75,13 @@ export function pyEnv(extra = {}) {}/**- * Chạy `python -X utf8 edit/py/lumedit.py <args>`. onProgress nhận object của mỗi dòng "@progress".+ * Chạy `python -X utf8 edit/py/lumedit.py <args>`. onProgress nhận object của mỗi dòng "@progress". env: biến thêm (vd FX_VCODEC_ARGS).* Trả {ok, result, code, log}. result = JSON của dòng "@result" cuối cùng.*/-export function runLumedit(args, { onProgress, onLine, timeoutMs = 3 * 60 * 60 * 1000 } = {}) {+export function runLumedit(args, { onProgress, onLine, env = {}, timeoutMs = 3 * 60 * 60 * 1000 } = {}) {return new Promise((resolve) => {if (!venvReady()) return resolve({ ok: false, code: 3, error: 'Chưa cài môi trường Edit: chạy node edit/setup.mjs', log: '' });- const p = spawn(venvPython(), ['-X', 'utf8', LUMEDIT, ...args], { cwd: PACK, env: pyEnv(), windowsHide: true });+ const p = spawn(venvPython(), ['-X', 'utf8', LUMEDIT, ...args], { cwd: PACK, env: pyEnv(env), windowsHide: true });let log = ''; let buf = ''; let result = null;const timer = setTimeout(() => { log += '\n[lumedit] quá thời gian, dừng\n'; p.kill(); }, timeoutMs);const feed = (d) => {diff --git a/edit/http.mjs b/edit/http.mjsindex 6029772..208fe52 100644--- a/edit/http.mjs+++ b/edit/http.mjs@@ -8,6 +8,9 @@// 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)@@ -16,12 +19,13 @@ 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,+ 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 GBconst 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 tayconst 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']);@@ -140,6 +144,7 @@ function freeBytes(dir) {}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 }) {@@ -248,6 +253,67 @@ export async function handleEditRoute(req, res, p, { send, readBody, serveFile,} 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);diff --git a/edit/ingest.mjs b/edit/ingest.mjsindex a135b9b..8da7585 100644--- a/edit/ingest.mjs+++ b/edit/ingest.mjs@@ -4,6 +4,7 @@import fs from 'node:fs';import crypto from 'node:crypto';import { run } from '../engine/lib.mjs';+import { videoArgs, withEncoder } from './encoder.mjs';const num = (v) => (v === undefined || v === null || v === 'N/A' ? NaN : Number(v));const ratio = (s) => { const [a, b] = String(s || '0/1').split('/').map(Number); return b ? a / b : NaN; };@@ -54,7 +55,14 @@ async function hasZscale() {* Proxy CFR 30 fps. Cạnh ngắn tối đa 1080 (dọc: rộng ≤ 1080; ngang: cao ≤ 1080). HDR → tonemap về SDR BT.709* (cần ffmpeg có zscale). Nguồn không có tiếng → chèn tiếng lặng để mọi bước sau có luồng âm.*/-export async function makeProxy(file, info, out, { log = console.log } = {}) {+export async function makeProxy(file, info, out, { log = console.log, encoder = null } = {}) {+ // encoder: 'gpu' | 'cpu' (dựng lại proxy cho lần sửa: dùng đúng loại lần đầu để file ra giống hệt → cache chữ dùng lại)+ if (encoder) return { file: await proxyWith(encoder, file, info, out, log), encoder };+ const { result, kind } = await withEncoder((k) => proxyWith(k, file, info, out, log), { log, what: 'proxy' });+ return { file: result, encoder: kind };+}++async function proxyWith(kind, file, info, out, log) {const portrait = info.height >= info.width;const scale = portrait ? "scale='min(1080,iw)':-2:flags=lanczos" : "scale=-2:'min(1080,ih)':flags=lanczos";const vf = [];@@ -64,11 +72,13 @@ export async function makeProxy(file, info, out, { log = console.log } = {}) {}vf.push(scale, 'setsar=1', 'fps=30', 'format=yuv420p');// -ss/-itsoffset không dùng: ffmpeg tự trừ start_time khi ghi (avoid_negative_ts), xoay được áp tự động (autorotate).+ // GPU: chỉ mã hoá bằng NVENC. Giải mã vẫn CPU: đo 60 s nguồn 4K H.264, NVDEC + chép khung về RAM 9,3 s, CPU 3,9 s;+ // scale_cuda còn chậm hơn (13,1 s cả proxy). CPU giải mã + NVENC 5,9 s, CPU + libx264 veryfast 8,5 s.const args = ['-hide_banner', '-y', '-i', file];if (!info.hasAudio) args.push('-f', 'lavfi', '-i', 'anullsrc=r=48000:cl=stereo');args.push('-map', '0:v:0', '-map', info.hasAudio ? '0:a:0' : '1:a:0','-vf', vf.join(','), '-fps_mode', 'cfr',- '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '16', '-g', '30', '-keyint_min', '30', '-sc_threshold', '0',+ ...videoArgs(kind, { quality: 16, speed: 'fast', gop: 30 }), '-pix_fmt', 'yuv420p','-color_primaries', 'bt709', '-color_trc', 'bt709', '-colorspace', 'bt709','-c:a', 'pcm_s16le', '-ar', '48000', '-ac', '2','-t', String(info.duration), '-avoid_negative_ts', 'make_zero', '-movflags', '+faststart', out);@@ -83,11 +93,14 @@ export async function ingest(file, proxyOut, { log = console.log } = {}) {const info = await probeSource(file);if (!Number.isFinite(info.duration) || info.duration <= 0) throw new Error('không đọc được độ dài video');log(`nguồn: ${info.width}×${info.height} ${info.codec} ${info.fps.toFixed(2)} fps${info.vfr ? ' (VFR)' : ''}${info.rotation ? ` xoay ${info.rotation}°` : ''}${info.hdr ? ' HDR' : ''} · ${info.duration.toFixed(2)} s${info.hasAudio ? '' : ' · KHÔNG có tiếng'}`);- const [sha, proxyFile] = await Promise.all([sha256File(file), makeProxy(file, info, proxyOut, { log })]);+ const t = Date.now();+ const [sha, px] = await Promise.all([sha256File(file), makeProxy(file, info, proxyOut, { log })]);+ const proxyFile = px.file;+ log(`proxy: ${px.encoder === 'gpu' ? 'h264_nvenc' : 'libx264'} ${((Date.now() - t) / 1000).toFixed(1)} s`);const pr = await run('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=width,height', '-of', 'json', proxyFile]);const ps = JSON.parse(pr.out).streams[0];return {- info,+ info, encoder: px.encoder,source: {file, sha256: sha, size: fs.statSync(file).size, duration: +info.duration.toFixed(3), startTime: info.startTime,fps: +info.fps.toFixed(3), vfr: info.vfr, rotation: info.rotation, width: info.width, height: info.height,diff --git a/edit/jobs.mjs b/edit/jobs.mjsindex a9fb446..c815541 100644--- a/edit/jobs.mjs+++ b/edit/jobs.mjs@@ -3,7 +3,9 @@// đã 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, STEPS } from './pipeline.mjs';+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 { probeSource } from './ingest.mjs';@@ -40,7 +42,7 @@ function writeJob(id, patch) {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 (job.action === 'revise' && currentOut(job.id)) return writeJob(job.id, { status: 'done', reviseError: why + ' — bấm Render lại' });+ 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' });}@@ -81,15 +83,18 @@ export async function checkMedia(video, music) {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) {- 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`);- }+ 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.@@ -161,6 +166,8 @@ const onProgress = (id) => (p) => writeJob(id, { step: p.step, stepIndex: p.inde/*** 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);@@ -173,7 +180,9 @@ export function cleanupEdit(id) {fs.rmSync(f, { recursive: true, force: true });} catch { /* không có */ }};- for (const f of ['proxy.mov', 'base.mp4', 'base.words.json', 'base.face.json', 'captions.webm', 'audio', path.join('captions', 'lib'), 'qc.jpg', 'proxy.mov.part']) rm(f);+ 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;}@@ -243,6 +252,52 @@ export function reviseEditJob(id, instruction, { log = () => {} } = {}) {});}+/** 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);@@ -258,7 +313,8 @@ export function editView(id, { withLog = true, urlBase = `/edits/${id}` } = {})styleName: (() => { try { return loadStyle(job.style).name; } catch { return job.style; } })(),steps: STEPS,fixes: result.checks?.fixes || [],- revisions: state.revisions || [],+ 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 || [],diff --git a/edit/manual.mjs b/edit/manual.mjsnew file mode 100644index 0000000..00b1848--- /dev/null+++ b/edit/manual.mjs@@ -0,0 +1,296 @@+// 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 };diff --git a/edit/pipeline.mjs b/edit/pipeline.mjsindex 7a4377d..a7ea382 100644--- a/edit/pipeline.mjs+++ b/edit/pipeline.mjs@@ -23,8 +23,10 @@ import {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 } from './captions-hf.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, '');@@ -75,6 +77,7 @@ export async function editVideo(video, opts = {}) {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) => {@@ -82,9 +85,10 @@ export async function editVideo(video, opts = {}) {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 · mặt ${an.seconds.face} s (thấy mặt ${Math.round(an.data.face.found_share * 100)}% khung)`);+ 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);@@ -231,6 +235,7 @@ async function buildEdl({ id, dir, ing, analysis, words, style, state, checks, wconst 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ạiif (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);@@ -303,23 +308,32 @@ async function renderEdl({ dir, edl, draft, R, outName = 'out.mp4', repair = nulreturn finishRender({ dir, edl, edlFile, base, rb, draft, R, outName });}-/** Render nền 1 lượt + nghe lại bản cắt (lumedit render). */-async function renderBase({ edlFile, base, draft, R }) {+/**+ * 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 r = await runLumedit(['render', edlFile, '--out', base, ...(draft ? ['--draft-captions'] : [])], {+ 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;+ 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.overcut = rb.overcut;- log(` lẹm chữ: ${rb.overcut?.verdict}`);+ (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;}@@ -335,58 +349,94 @@ export function outputSfx(edl) {return out.sort((a, b) => a.t - b.t);}-/** Bước 6–9: phụ đề, tiếng, ghép, kiểm. */-async function finishRender({ dir, edl, edlFile, base, rb, draft, R, outName }) {+/**+ * 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;- await step('phụ đề', async (pg) => {- const hasGfx = (edl.graphics || []).length > 0;- if ((draft || !edl.captions.words.length) && !hasGfx) { pg(100, draft ? 'phụ đề nháp đã vẽ trong nền' : 'không có chữ'); return; }+ 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 };- overlay = await renderCaptionLayer(path.join(dir, 'captions'), path.join(dir, 'captions.webm'), { log, onPct: (p) => pg(p, 'HyperFrames') });+ 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 mix = await step('tiếng', () => buildEditMix({- base, duration: rb.seconds_out, workDir: path.join(dir, 'audio'), lufs: edl.output.lufs, log,- sfx: outputSfx(edl),- music: edl.music,- }));+ 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 args = ['-hide_banner', '-y', '-i', base];- if (overlay) args.push('-c:v', 'libvpx-vp9', '-i', 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]', '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', '-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);- const r = await run('ffmpeg', args, { timeoutMs: 60 * 60e3 });+ 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', '-of', 'json', out]);+ 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) };+ 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')]);- 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 ${checks.qc?.verdict || '?'}`);+ 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);@@ -434,7 +484,7 @@ export async function reviseEdit(id, instruction, opts = {}) {// nên cache chữ/mặt (proxy.words.json, proxy.face.json) dùng lại, không chép lời lạiif (!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 });+ 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 });@@ -457,4 +507,93 @@ export async function reviseEdit(id, instruction, opts = {}) {}// 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/py/lumedit.py b/edit/py/lumedit.pyindex a7d6bce..c5c757b 100644--- a/edit/py/lumedit.py+++ b/edit/py/lumedit.py@@ -57,6 +57,12 @@ def cmd_analyze(proxy: Path, out: Path) -> dict:progress("words", note=f"chép lời ({os.environ.get('FX_WHISPER') or 'small.en'}, {wordsmod.LANG})")ws = clip.wordst_words = time.time() - t0+ try: # where whisper ran (cuda float16 | cpu int8 (why)), recorded in the words cache by fx.core.words+ from fx.core import paths as pathsmod+ device = json.loads(pathsmod.beside(proxy.resolve(), "words.json").read_text(encoding="utf-8")).get("device") or "?"+ except (OSError, ValueError):+ device = "?"+ progress("words", note=f"whisper {device}")progress("quiet")quiet = clip.quietprogress("face")@@ -85,9 +91,10 @@ def cmd_analyze(proxy: Path, out: Path) -> dict:"hesitations": sorted(wordsmod.HESITATIONS),"model": wordsmod.model_key("small.en"), "lang": wordsmod.LANG,"seconds": {"words": round(t_words, 1), "face": round(t_face, 1), "total": round(time.time() - t0, 1)},+ "whisper_device": device,}out.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")- return {"out": str(out), "words": len(ws), "unsure": len(clip.unsure), "seconds": data["seconds"]}+ return {"out": str(out), "words": len(ws), "unsure": len(clip.unsure), "seconds": data["seconds"], "device": device}# ---- shared: the EDL as AskEditor objects ------------------------------------------------------------------diff --git a/edit/test/manual-check.mjs b/edit/test/manual-check.mjsnew file mode 100644index 0000000..2b409fd--- /dev/null+++ b/edit/test/manual-check.mjs@@ -0,0 +1,141 @@+#!/usr/bin/env node+// Kiểm chỉnh tay (edit/manual.mjs) — phần không cần server: schema chặt, dòng phụ đề (gộp/tách/đè), áp bản vá lên EDL+// (lớp nào phải dựng lại), giữ chỉnh tay khi dựng lại EDL. Có cổng thì kiểm thêm REST trên server đang chạy:+// schema sai → 400, Origin lạ → 403, id lạ → 404, Content-Type sai → 415, JSON hỏng → 400, nhạc tải lên sai định dạng → 415.+// node edit/test/manual-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, buildLines, lineTokens, lineText, applyPatch, applyManual, currentLines, cutSig } from '../manual.mjs';+import { validateEdl } from '../edl.mjs';+import { captionCards } from '../captions-hf.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({}), 400, /rỗng/), 'bản vá rỗng → 400');+check(throws(() => parseManual({ foo: 1 }), 400), 'khoá lạ ở gốc → 400');+check(throws(() => parseManual({ music: { gainDb: 5 } }), 400, /music\.gainDb/), 'nhạc +5 dB (trần 0) → 400 kèm đường dẫn trường');+check(throws(() => parseManual({ music: { source: '../../etc/passwd' } }), 400), 'nguồn nhạc là đường dẫn → 400');+check(throws(() => parseManual({ music: { source: 'upload:../x.mp3' } }), 400), 'upload có ../ → 400');+check(throws(() => parseManual({ captions: { lines: [{ start: 0, end: 1, text: 'a', x: 1 }] } }), 400), 'dòng có khoá lạ → 400');+check(throws(() => parseManual({ captions: { look: 'khong-co' } }), 400), 'look lạ → 400');+check(throws(() => parseManual({ zooms: { remove: [-1] } }), 400), 'zoom số âm → 400');+check(throws(() => parseManual({ voice: { gainDb: 40 } }), 400), 'giọng +40 dB → 400');+check(!throws(() => parseManual({ music: { gainDb: -28, duck: false } })), 'bản vá hợp lệ qua');++// ---- dòng phụ đề ----+check(JSON.stringify(lineTokens('*Giá* tăng *gấp đôi*')) === JSON.stringify([{ w: 'Giá', hi: true }, { w: 'tăng', hi: false }, { w: 'gấp', hi: true }, { w: 'đôi', hi: true }]), 'tách chữ nhấn *…*');+check(lineText([{ w: 'a', hi: true }, { w: 'b', hi: false }]) === '*a* b', 'ghép lại chữ nhấn');+const prev = [{ start: 0, end: 1, words: [{ w: 'xin', o: 0, hi: false }, { w: 'chào', o: 0.5, hi: false }] }];+const L = buildLines([{ start: 0, end: 1, text: 'xin *chào* mọi người' }], prev, 10);+check(L[0].words[1].o === 0.5 && L[0].words[1].hi && L[0].words[2].o > 0.5 && L[0].words[3].o < 1, 'giữ mốc chữ cũ, chữ mới chia đều trong dòng');+check(throws(() => buildLines([{ start: 0, end: 1, text: 'a' }, { start: 0.5, end: 2, text: 'b' }], [], 10), 400, /đè/), 'hai dòng đè nhau → 400');+check(throws(() => buildLines([{ start: 2, end: 2.05, text: 'a' }], [], 10), 400), 'dòng < 0,1 s → 400');+check(throws(() => buildLines([{ start: 12, end: 13, text: 'a' }], [], 10), 400, /sau cuối/), 'dòng sau cuối video → 400');+const sorted = buildLines([{ start: 3, end: 4, text: 'sau' }, { start: 1, end: 2, text: 'trước' }], [], 10);+check(sorted[0].words[0].w === 'trước', 'dòng gửi lộn thứ tự được xếp lại theo giờ');++// ---- áp lên EDL giả ----+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'lumedit-man-'));+const music = path.join(tmp, 'm.wav'); fs.writeFileSync(music, 'x');+const words = ['Giá', 'VGA', 'tăng', 'gấp', 'đôi.', 'Mua', 'ngay', 'đi.'].map((w, i) => ({ i, w, start: 1 + i * 0.5, end: 1.4 + i * 0.5 }));+const edl = {+ version: 1, id: 't', createdAt: new Date().toISOString(), style: 'sach-gon',+ source: { file: 'x.mp4', sha256: '0'.repeat(64), size: 1, duration: 10, 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: 6 }], removed: [], reframe: { mode: 'center' },+ zooms: [{ at: 1.2, dur: 1, scale: 1.2, kind: 'punch' }, { at: 3.1, dur: 1, scale: 1.1, kind: 'push' }],+ captions: { style: 'sach-gon', renderer: 'hyperframes', maxWords: 3, position: 'lower', words, highlights: [1] },+ sfx: [{ at: 1.2, name: 'whoosh', gainDb: -6 }],+ music: { file: music, gainDb: -22, duckDb: 10, fadeOut: 1.5 },+ graphics: [], hook: null, hookText: null, quote: null, audio: { crossfadeMs: 20, keepSourceAudio: true },+};+check(validateEdl(edl, { checkFiles: false }).ok, 'EDL cũ (chưa có trường chỉnh tay) vẫn hợp lệ');+const state = { style: 'sach-gon', music, draft: false };+const lines0 = currentLines(edl);+check(lines0.length >= 2 && lines0[0].words.some((w) => w.hi), 'dòng hiện tại lấy từ nhóm chữ tự động, có chữ nhấn');+// sửa chữ 2 dòng + gộp+const edited = lines0.map((l) => ({ start: l.start, end: l.end, text: lineText(l.words) }));+edited[0].text = 'Giá *card đồ hoạ*';+edited[1].text = edited[1].text + ' nhé';+const a = applyPatch(edl, state, { captions: { lines: edited }, music: { gainDb: -28, duck: false }, zooms: { remove: [0] } }, { dir: tmp });+check(a.redo.layer && a.redo.mix && a.redo.base, 'sửa chữ + nhạc + xoá zoom → dựng lại lớp chữ, tiếng, nền');+check(a.edl.music.gainDb === -28 && a.edl.music.duckDb === 0, 'nhạc −28 dB, tắt ducking (duckDb 0)');+check(a.edl.zooms.length === 1 && a.edl.zooms[0].at === 3.1, 'xoá đúng zoom số 0');+check(validateEdl(a.edl, { checkFiles: false }).ok, 'EDL sau chỉnh tay hợp lệ');+const cards = captionCards(a.edl);+check(cards[0].words.map((w) => w.w).join(' ') === 'Giá card đồ hoạ' && cards[0].words[1].hl === true, 'lớp chữ dùng dòng chỉnh tay (chữ + nhấn)');+const b = applyPatch(edl, state, { music: { gainDb: -30 } }, { dir: tmp });+check(!b.redo.layer && !b.redo.base && b.redo.mix, 'chỉ đổi nhạc → chỉ trộn lại tiếng');+const c = applyPatch(edl, state, { captions: { highlights: false } }, { dir: tmp });+check(c.redo.layer && !c.redo.mix && c.edl.captions.hiOff, 'tắt chữ nhấn → chỉ lớp chữ');+check(throws(() => applyPatch(edl, state, { music: { gainDb: -22 } }, { dir: tmp }), 400, /không có gì khác/), 'bản vá giống hệt bản đang có → 400');+check(throws(() => applyPatch(edl, state, { zooms: { remove: [5] } }, { dir: tmp }), 400), 'xoá zoom không có → 400');+check(throws(() => applyPatch(edl, state, { music: { source: 'upload:music-up-1.mp3' } }, { dir: tmp }), 400, /chưa tải/), 'nhạc tải lên chưa có → 400');+check(throws(() => applyPatch(edl, { ...state, draft: true }, { captions: { highlights: false } }, { dir: tmp }), 409), 'bản nháp: sửa phụ đề → 409');+const none = applyPatch(edl, state, { music: { source: 'none' } }, { dir: tmp });+check(none.edl.music === null && none.music === null, 'bỏ nhạc');+const syn = applyPatch(edl, state, { music: { source: 'synth:chill' } }, { dir: tmp });+check(syn.edl.music && fs.existsSync(syn.edl.music.file) && syn.edl.music.start === 0, 'đổi sang nhạc tổng hợp chill (file sinh ra)');+// dựng lại EDL (sửa bằng lời): giữ chỉnh tay+const rebuilt = JSON.parse(JSON.stringify(edl));+const w1 = applyManual(rebuilt, a.manual);+check(rebuilt.captions.lines && rebuilt.music.duckDb === 0 && rebuilt.zooms.length === 1 && !w1.length, 'dựng lại cùng phần cắt: giữ dòng chỉnh tay, nhạc, zoom đã xoá');+const recut = JSON.parse(JSON.stringify(edl)); recut.keep = [{ start: 0.5, end: 4 }];+const w2 = applyManual(recut, a.manual);+check(!recut.captions.lines && w2.length === 1 && cutSig(recut) !== a.manual.lines.sig, 'phần cắt đổi: bỏ dòng chỉnh tay (mốc cũ sai), có cảnh báo');+fs.rmSync(tmp, { recursive: true, force: true });++// ---- REST (server đang chạy) ----+const PORT = Number(process.argv[2]);+const ID = process.argv[3];+if (PORT) {+ const HOST = `127.0.0.1:${PORT}`;+ const req = ({ method = 'POST', 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 }));+ });+ r.on('error', (e) => resolve({ code: -1, body: e.message }));+ r.end(body);+ });+ const json = { 'Content-Type': 'application/json' };+ let r = await req({ p: '/api/edits/khong-co-dau/manual', headers: json, body: '{"voice":{"gainDb":2}}' });+ check(r.code === 404, `id lạ → 404 (${r.code})`);+ r = await req({ method: 'GET', p: '/api/edits/khong-co-dau/manual' });+ check(r.code === 404, `GET id lạ → 404 (${r.code})`);+ r = await req({ p: '/api/edits/..%2F..%2Fetc/manual', headers: json, body: '{}' });+ check(r.code === 404, `id có ../ → 404 (${r.code})`);+ r = await req({ p: `/api/edits/${ID || 'x'}/manual`, headers: { ...json, Origin: 'https://evil.example' }, body: '{"voice":{"gainDb":2}}' });+ check(r.code === 403, `Origin lạ → 403 (${r.code})`);+ r = await req({ p: `/api/edits/${ID || 'x'}/music`, headers: { Origin: 'https://evil.example', 'Content-Type': 'multipart/form-data; boundary=x', 'Content-Length': '10' }, body: '0123456789' });+ check(r.code === 403, `tải nhạc với Origin lạ → 403 (${r.code})`);+ if (ID) {+ r = await req({ p: `/api/edits/${ID}/manual`, headers: { 'Content-Type': 'text/plain' }, body: '{"voice":{"gainDb":2}}' });+ check(r.code === 415, `Content-Type không phải JSON → 415 (${r.code})`);+ r = await req({ p: `/api/edits/${ID}/manual`, headers: json, body: '{"voice":' });+ check(r.code === 400, `JSON hỏng → 400 (${r.code})`);+ r = await req({ p: `/api/edits/${ID}/manual`, headers: json, body: '{"music":{"gainDb":12}}' });+ check(r.code === 400 && /music\.gainDb/.test(r.body), `schema sai (nhạc +12 dB) → 400 có tên trường (${r.code})`);+ r = await req({ p: `/api/edits/${ID}/manual`, headers: json, body: '{"zooms":{"remove":[999]}}' });+ check(r.code === 400, `xoá zoom không có → 400 đồng bộ, không 202 (${r.code})`);+ r = await req({ p: `/api/edits/${ID}/manual`, headers: json, body: '[1,2]' });+ check(r.code === 400, `bản vá là mảng → 400 (${r.code})`);+ r = await req({ method: 'GET', p: `/api/edits/${ID}/manual` });+ const v = r.code === 200 ? JSON.parse(r.body) : null;+ check(!!v && Array.isArray(v.captions.lines) && typeof v.duration === 'number', `GET manual → 200 có dòng phụ đề (${r.code}, ${v?.captions.lines.length} dòng)`);+ const B = 'mUsIcB0uNd';+ const mp = Buffer.from(`--${B}\r\nContent-Disposition: form-data; name="music"; filename="x.exe"\r\n\r\nMZ\r\n--${B}--\r\n`);+ r = await req({ p: `/api/edits/${ID}/music`, headers: { 'Content-Type': `multipart/form-data; boundary=${B}`, 'Content-Length': String(mp.length) }, body: mp });+ check(r.code === 415, `tải nhạc đuôi .exe → 415 (${r.code})`);+ const bad = Buffer.from(`--${B}\r\nContent-Disposition: form-data; name="music"; filename="x.mp3"\r\n\r\nkhong phai mp3\r\n--${B}--\r\n`);+ r = await req({ p: `/api/edits/${ID}/music`, headers: { 'Content-Type': `multipart/form-data; boundary=${B}`, 'Content-Length': String(bad.length) }, body: bad });+ check(r.code === 422, `tải "mp3" hỏng → 422 và xoá file (${r.code})`);+ }+}+console.log(fails ? `\n${fails} FAIL` : '\nTẤT CẢ PASS');+process.exit(fails ? 1 : 0);diff --git a/server/public/edit-panel.css b/server/public/edit-panel.cssindex 157d403..af7fc29 100644--- a/server/public/edit-panel.css+++ b/server/public/edit-panel.css@@ -116,3 +116,73 @@.ed-danger button { color: var(--bad); border-color: color-mix(in srgb, var(--bad) 40%, var(--line)); min-height: 44px; }.ed-danger button:hover { border-color: var(--bad); }.sty:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }++/* ---- chỉnh tay (phụ đề / nhạc & tiếng / zoom & đồ hoạ) ---- */+.ed-man { margin-top: 16px; padding-top: 14px; border-top: 1px solid var(--line); }+.ed-man h4 { margin: 0 0 8px; font-size: 14px; color: var(--ink-2); font-weight: 600; }+.ed-man h5 { margin: 12px 0 6px; font-size: 13px; color: var(--ink-3); font-weight: 600; text-transform: uppercase; letter-spacing: .04em; }+.ed-mtabs { display: flex; gap: 4px; padding: 4px; border-radius: 12px; background: var(--bg); border: 1px solid var(--line); }+.ed-mtabs [role="tab"] { flex: 1; min-height: 44px; padding: 0 8px; border: 0; border-radius: 9px; background: transparent; color: var(--ink-2); font: 600 14px/1.2 var(--sans); cursor: pointer; }+.ed-mtabs [role="tab"][aria-selected="true"] { background: var(--panel-2); color: var(--ink); box-shadow: inset 0 -2px 0 var(--accent); }+.ed-mtabs [role="tab"]:focus-visible, .ed-man button:focus-visible, .ed-man input:focus-visible, .ed-man select:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.ed-mpanel { padding: 12px 0 4px; }+.ed-mpanel[hidden] { display: none; }+.ed-mrow { display: flex; gap: 10px; align-items: center; margin: 6px 0; }+.ed-mlab { flex: 0 0 auto; min-width: 96px; font-size: 14px; color: var(--ink-2); }+.ed-mrow select, .ed-mrow .ed-in { flex: 1; min-width: 0; }+.ed-mhint { margin: 2px 0 8px; font-size: 13px; }+.ed-num { width: 84px; flex: 0 0 auto; padding: 0 8px; font: 500 14px var(--mono); font-variant-numeric: tabular-nums; }+.ed-lines { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; max-height: 460px; overflow-y: auto; overscroll-behavior: contain; }+.ed-lines li { display: grid; grid-template-columns: 64px minmax(0, 1fr) auto; grid-template-areas: "tm text text" "tm time act"; gap: 6px 8px; align-items: center; padding: 8px; border-radius: 12px; border: 1px solid var(--line); background: var(--bg); transition: border-color .15s, background .15s; }+.ed-lines li.none { display: block; color: var(--ink-3); font-size: 14px; }+.ed-lines li.now { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 7%, var(--bg)); }+.ed-lines li.bad { border-color: var(--bad); }+.ed-lines .ed-tm { grid-area: tm; align-self: stretch; }+.ed-lines .ed-ltext { grid-area: text; min-height: 44px; font-size: 15px; }+.ed-ltime { grid-area: time; display: flex; align-items: center; gap: 6px; flex-wrap: wrap; color: var(--ink-3); }+.ed-ltime .ed-in { min-height: 44px; }+.ed-lact { display: flex; gap: 4px; }+.ed-lines .ed-lact { grid-area: act; }+.ed-lact button, .ed-mx { min-height: 44px; min-width: 44px; padding: 0 10px; border-radius: 9px; border: 1px solid var(--line); background: var(--panel-2); color: var(--ink-2); font-size: 13px; cursor: pointer; }+.ed-lact button:hover:not(:disabled), .ed-mx:hover { color: var(--ink); border-color: var(--ink-3); }+.ed-lact button:disabled { opacity: .4; cursor: not-allowed; }+.ed-lact .del { font-size: 18px; color: var(--bad); }+.ed-lerr { grid-column: 1 / -1; font-size: 13px; color: var(--bad); }+.ed-tm { min-height: 44px; min-width: 56px; padding: 0 6px; border-radius: 9px; border: 1px solid var(--line); background: var(--panel-2); color: var(--accent); font: 600 13px var(--mono); font-variant-numeric: tabular-nums; cursor: pointer; }+.ed-tm:hover { border-color: var(--accent); }+.ed-slider { display: grid; gap: 4px; margin: 8px 0; }+.ed-slider[hidden] { display: none; }+.ed-man label[for] { display: flex; justify-content: space-between; gap: 8px; font-size: 14px; color: var(--ink-2); }+.ed-man label.ed-mlab { display: block; }+.ed-man output { font: 600 14px var(--mono); font-variant-numeric: tabular-nums; color: var(--ink); }+.ed-man input[type="range"] { width: 100%; min-height: 32px; accent-color: var(--accent); }+.ed-fxlist { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }+.ed-fxlist li { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; gap: 8px; align-items: center; padding: 6px 8px; border-radius: 12px; border: 1px solid var(--line); background: var(--bg); font-size: 14px; }+.ed-fxlist li.none { display: block; color: var(--ink-3); }+.ed-fxlist li.gone span { text-decoration: line-through; color: var(--ink-3); }+.ed-fxlist li.gone { border-style: dashed; }+.ed-mx[aria-pressed="true"] { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 40%, var(--line)); }+.ed-mbar { position: sticky; bottom: 0; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 10px; padding: 10px 0 4px; background: var(--panel); }+.ed-mdirty { flex: 1 1 160px; font-size: 13px; color: var(--ink-3); }+.ed-mdirty.bad { color: var(--bad); }+.ed-mreset { min-height: 44px; padding: 0 14px; border-radius: 10px; border: 1px solid var(--line); background: transparent; color: var(--ink-2); cursor: pointer; }+.ed-mapply { min-height: 44px; padding: 0 20px; border-radius: 10px; border: 0; background: var(--accent); color: var(--accent-ink); font-weight: 700; cursor: pointer; }+.ed-mreset:disabled, .ed-mapply:disabled { opacity: .45; cursor: not-allowed; }+.ed-hist li.man .tag { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 12px; background: var(--panel-2); border: 1px solid var(--line); color: var(--accent); }+.ed-hist li.orig { color: var(--ink-3); }+/* màn hẹp: nút Dựng của form nằm cố định ở đáy → thanh Áp dụng dính ngay trên nó */+@media (max-width: 900px) {+ .ed-mbar { bottom: calc(84px + env(safe-area-inset-bottom)); z-index: 4; gap: 6px 8px; padding: 6px 0; box-shadow: 0 -10px 16px -12px rgba(0,0,0,.6); }+ .ed-mdirty { flex-basis: 100%; }+ .ed-mapply { flex: 1; }+}+@media (max-width: 480px) {+ .ed-mlab { min-width: 0; }+ .ed-mrow { flex-wrap: wrap; }+ .ed-mrow .ed-mlab { flex-basis: 100%; }+ .ed-lines { max-height: none; }+ .ed-lines li { grid-template-columns: 56px minmax(0, 1fr); grid-template-areas: "tm text" "tm time" "tm act"; }+ .ed-lines .ed-lact { justify-self: start; }+ .ed-num { width: 72px; }+}+@media (prefers-reduced-motion: reduce) { .ed-lines li { transition: none; } }diff --git a/server/public/edit-panel.js b/server/public/edit-panel.jsindex 62b1695..1e18f7c 100644--- a/server/public/edit-panel.js+++ b/server/public/edit-panel.js@@ -252,13 +252,13 @@$('#edId').textContent = `${viewStyleName(v)} · ${v.id}`;const st = $('#edStatus');st.className = 'st ' + (v.status === 'done' ? 'done' : v.status === 'error' ? 'error' : 'run');- st.textContent = busy ? t(v.status === 'queued' ? 'ed.waitTurn' : v.action === 'revise' ? 'ed.revising' : 'ed.st.running') : stLabel(v.status);- // bước+ st.textContent = busy ? t(v.status === 'queued' ? 'ed.waitTurn' : v.action === 'revise' ? 'ed.revising' : v.action === 'manual' ? 'man.running' : 'ed.st.running') : stLabel(v.status);+ // bước (sửa bằng lời bắt đầu từ "LLM lập EDL"; chỉnh tay từ "render nền" hoặc "phụ đề")const steps = v.steps || [];- const from = v.action === 'revise' ? 2 : 0;+ const from = v.action === 'revise' ? 2 : v.action === 'manual' ? (v.stepFrom ?? 4) : 0;$('#edSteps').innerHTML = steps.map((s, i) => {let cls = '';- if (i < from && v.action === 'revise') cls = 'done';+ if (i < from) cls = 'done';else if (v.status === 'done') cls = 'done';else if (busy && i < v.stepIndex) cls = 'done';else if (busy && i === v.stepIndex) cls = 'now';@@ -307,7 +307,10 @@$('#edRevise').hidden = !(v.links?.out || v.status === 'done');const revs = v.revisions || [];$('#edHist').hidden = !revs.length;- $('#edHistList').innerHTML = revs.map((r) => `<li>"${esc(r.instruction)}"${r.notes ? ` — ${esc(r.notes)}` : ''}</li>`).join('');+ const play = (u) => (u ? ` <a href="${esc(u)}" target="_blank" rel="noopener">${esc(t('man.watch'))}</a>` : '');+ $('#edHistList').innerHTML = (v.originalUrl && revs.length ? `<li class="orig">${esc(t('man.original'))}${play(v.originalUrl)}</li>` : '')+ + revs.map((r) => `<li${r.manual ? ' class="man"' : ''}>${r.manual ? `<span class="tag">${esc(t('man.tag'))}</span> ${esc(r.instruction)}` : `"${esc(r.instruction)}"`}${r.notes ? ` — ${esc(r.notes)}` : ''}${r.manual && r.seconds ? ` · ${esc(t('man.took', { s: Math.round(r.seconds) }))}` : ''}${play(r.url)}</li>`).join('');+ Man.onView(v, busy);$('#edLog').textContent = (v.log || []).join('\n');}@@ -336,6 +339,248 @@$('#edReviseForm').addEventListener('submit', (e) => { e.preventDefault(); revise($('#edReviseText').value.trim()); });$('#edPresets').addEventListener('click', (e) => { const b = e.target.closest('button'); if (b) $('#edReviseText').value = b.textContent; $('#edReviseText').focus(); });+ // ---- chỉnh tay (GET/POST /api/edits/:id/manual, POST /api/edits/:id/music) ------------------------------------+ // Bảng dòng phụ đề (giây bản ra), nhạc, giọng, sfx, zoom, đồ hoạ. Sửa trong trang (bản nháp cục bộ), bấm Áp dụng+ // thì gửi một bản vá chỉ gồm phần đã đổi; server dựng lại lớp cần thiết ra out-r<n>.mp4.+ const Man = (() => {+ const M = { id: null, outKey: null, orig: null, cur: null, loading: false };+ const clone = (x) => JSON.parse(JSON.stringify(x));+ const sec = (x) => (Math.round(x * 100) / 100).toFixed(2);+ const db = (x) => `${x > 0 ? '+' : ''}${x} dB`;+ const video = () => $('#edMedia video');+ const isBusy = () => !!state.view && ['queued', 'running'].includes(state.view.status);++ async function load(id) {+ M.loading = true;+ try {+ const r = await fetch(`/api/edits/${encodeURIComponent(id)}/manual`);+ const j = await r.json().catch(() => ({}));+ if (!r.ok) throw new Error(j.error || 'HTTP ' + r.status);+ if (id !== M.id) return;+ M.orig = j; M.cur = clone(j); $('#edManErr').textContent = '';+ paint();+ } catch (e) { if (id === M.id) $('#edManErr').textContent = t('man.loadErr', { e: I.srv(e.message) }); } finally { M.loading = false; paintDirty(); }+ }+ // gọi mỗi lần vẽ bản edit: tải lại khi đổi bản hoặc có video ra mới+ function onView(v, busy) {+ const ready = v.status === 'done' && !!v.links?.out;+ if (v.id !== M.id) { M.id = v.id; M.orig = M.cur = null; M.outKey = null; $('#edManErr').textContent = ''; }+ $('#edMan').hidden = !M.orig && !ready;+ if (M.orig) paintDirty();+ if (!ready || busy) return;+ const key = `${v.id}|${v.links.out}`;+ if (key === M.outKey) return;+ M.outKey = key; load(v.id);+ }++ // ---- vẽ ----+ const musicLabel = (name) => (!name ? '' : name.startsWith('synth:') ? t('man.synth', { id: name.slice(6) }) : name);+ function paint() {+ const c = M.cur; if (!c) return;+ $('#edMan').hidden = false;+ $('#edManLook').innerHTML = c.captions.looks.map((l) => `<option value="${esc(l.id)}">${esc(I.lang === 'en' ? l.nameEn : l.name)}</option>`).join('');+ $('#edManLook').value = c.captions.look;+ $('#edManHi').checked = c.captions.highlights;+ $('#edManDraft').hidden = !c.draft;+ $('#edManLook').disabled = !!c.draft; $('#edManHi').disabled = !!c.draft;+ paintLines();+ const mu = c.music;+ const opts = [];+ if (M.orig.music.on) opts.push(`<option value="keep">${esc(t('man.musicKeep', { name: musicLabel(M.orig.music.name) }))}</option>`);+ opts.push(`<option value="none">${esc(t('ed.noMusic'))}</option>`);+ for (const s of mu.synth) opts.push(`<option value="synth:${esc(s)}">${esc(t('man.synth', { id: s }))}</option>`);+ for (const u of mu.uploads) opts.push(`<option value="upload:${esc(u.file)}">${esc(t('man.uploaded', { name: u.name }))}</option>`);+ opts.push(`<option value="file">${esc(t('ed.musicFile'))}</option>`);+ $('#edManMusic').innerHTML = opts.join('');+ $('#edManMusic').value = mu.source || (M.orig.music.on ? 'keep' : 'none');+ $('#edManGain').value = mu.gainDb; $('#edManDuck').checked = mu.duck; $('#edManFade').value = mu.fadeOut; $('#edManStart').value = mu.start;+ $('#edManVoice').value = c.voice.gainDb;+ $('#edManSfx').checked = c.sfx.on; $('#edManSfx').disabled = !c.sfx.count;+ $('#edManSfxL').textContent = t('man.sfx', { n: c.sfx.count });+ paintAudioOut();+ const rm = (on, what) => `<button type="button" class="ed-mx" aria-pressed="${on}" aria-label="${esc(on ? t('man.undoN', { what }) : t('man.removeN', { what }))}">${esc(on ? t('man.undo') : t('man.remove'))}</button>`;+ $('#edManZooms').innerHTML = c.zooms.length ? c.zooms.map((z) => `<li data-n="${z.n}" class="${z.gone ? 'gone' : ''}"><button type="button" class="ed-tm" data-t="${z.at}" aria-label="${esc(t('man.jump', { s: sec(z.at) }))}">${sec(z.at)}</button><span>${esc(t('man.zoomKind', { kind: z.kind, scale: z.scale.toFixed(2) }))}</span>${rm(!!z.gone, `zoom ${sec(z.at)} s`)}</li>`).join('') : `<li class="none">${esc(t('man.noZoom'))}</li>`;+ $('#edManGfx').innerHTML = c.graphics.length ? c.graphics.map((g) => `<li data-id="${esc(g.id)}" class="${g.gone ? 'gone' : ''}"><button type="button" class="ed-tm" data-t="${g.at}" aria-label="${esc(t('man.jump', { s: sec(g.at) }))}">${sec(g.at)}</button><span>${esc(g.type)}${g.title ? ` · ${esc(String(g.title).slice(0, 40))}` : ''}</span>${rm(!!g.gone, `${g.type} ${sec(g.at)} s`)}</li>`).join('') : `<li class="none">${esc(t('man.noGfx'))}</li>`;+ paintDirty();+ }+ function paintAudioOut() {+ $('#edManGainV').textContent = db(Number($('#edManGain').value));+ $('#edManFadeV').textContent = `${Number($('#edManFade').value)} s`;+ $('#edManVoiceV').textContent = db(Number($('#edManVoice').value));+ $('#edManMusicBox').hidden = $('#edManMusic').value === 'none';+ if (M.cur) M.cur.music.source = $('#edManMusic').value;+ }+ function lineErrors(lines) {+ const bad = new Map();+ lines.forEach((l, k) => {+ if (!(l.end - l.start >= 0.1)) bad.set(k, t('man.errShort'));+ else if (l.start >= M.cur.duration) bad.set(k, t('man.errAfter', { d: sec(M.cur.duration) }));+ else if (k && l.start < lines[k - 1].end - 1e-6) bad.set(k, t('man.errOverlap'));+ else if (!l.text.replace(/\*/g, '').trim()) bad.set(k, t('man.errEmpty'));+ });+ return bad;+ }+ function paintLines() {+ const c = M.cur; const lines = c.captions.lines;+ const bad = lineErrors(lines);+ const dis = c.draft ? ' disabled' : '';+ $('#edLines').innerHTML = lines.length ? lines.map((l, k) => `<li data-k="${k}"${bad.has(k) ? ' class="bad"' : ''}>+ <button type="button" class="ed-tm" data-t="${l.start}" aria-label="${esc(t('man.jump', { s: sec(l.start) }))}">${sec(l.start)}</button>+ <input class="ed-in ed-ltext" value="${esc(l.text)}" maxlength="200" aria-label="${esc(t('man.lineText', { n: k + 1 }))}"${dis} />+ <span class="ed-ltime">+ <input class="ed-in ed-num" data-f="start" type="number" step="0.05" min="0" inputmode="decimal" value="${sec(l.start)}" aria-label="${esc(t('man.lineStart', { n: k + 1 }))}"${dis} />+ <span aria-hidden="true">→</span>+ <input class="ed-in ed-num" data-f="end" type="number" step="0.05" min="0" inputmode="decimal" value="${sec(l.end)}" aria-label="${esc(t('man.lineEnd', { n: k + 1 }))}"${dis} />+ </span>+ <span class="ed-lact">+ <button type="button" data-a="split" aria-label="${esc(t('man.splitN', { n: k + 1 }))}"${dis}>${esc(t('man.split'))}</button>+ <button type="button" data-a="merge" aria-label="${esc(t('man.mergeN', { n: k + 1 }))}"${k + 1 < lines.length ? dis : ' disabled'}>${esc(t('man.merge'))}</button>+ <button type="button" data-a="del" class="del" aria-label="${esc(t('man.delN', { n: k + 1 }))}"${dis}>×</button>+ </span>+ ${bad.has(k) ? `<span class="ed-lerr">${esc(bad.get(k))}</span>` : ''}+ </li>`).join('') : `<li class="none">${esc(t('man.noLines'))}</li>`;+ }++ // ---- bản vá = phần khác bản đang có ----+ function patch() {+ const o = M.orig; const c = M.cur; if (!o || !c) return {};+ const p = {}; const cap = {};+ const ls = (x) => JSON.stringify(x.map((l) => [Math.round(l.start * 100), Math.round(l.end * 100), l.text.trim()]));+ if (ls(o.captions.lines) !== ls(c.captions.lines)) cap.lines = c.captions.lines.map((l) => ({ start: +sec(l.start), end: +sec(l.end), text: l.text.trim() }));+ if (o.captions.highlights !== c.captions.highlights) cap.highlights = c.captions.highlights;+ if (o.captions.look !== c.captions.look) cap.look = c.captions.look;+ if (Object.keys(cap).length) p.captions = cap;+ const mu = {}; const src0 = o.music.on ? 'keep' : 'none'; const src = c.music.source || src0;+ if (src !== src0) mu.source = src;+ if (src !== 'none') {+ for (const k of ['gainDb', 'duck', 'fadeOut', 'start']) if (c.music[k] !== o.music[k] || mu.source) mu[k] = c.music[k];+ }+ if (Object.keys(mu).length) p.music = mu;+ if (c.voice.gainDb !== o.voice.gainDb) p.voice = { gainDb: c.voice.gainDb };+ if (c.sfx.on !== o.sfx.on) p.sfx = { on: c.sfx.on };+ const zr = c.zooms.filter((z) => z.gone).map((z) => z.n); if (zr.length) p.zooms = { remove: zr };+ const gr = c.graphics.filter((g) => g.gone).map((g) => g.id); if (gr.length) p.graphics = { remove: gr };+ return p;+ }+ function paintDirty() {+ const p = patch(); const n = Object.values(p).reduce((s, v) => s + Object.keys(v).length, 0);+ const bad = M.cur ? lineErrors(M.cur.captions.lines).size : 0;+ const what = [...new Set([(p.captions || p.graphics) && t('man.wCap'), (p.music || p.voice || p.sfx) && t('man.wAud'), (p.zooms || p.graphics) && t('man.wBase')].filter(Boolean))];+ const el = $('#edManDirty');+ el.textContent = bad ? t('man.fixFirst', { n: bad }) : n ? t('man.dirty', { n, what: what.join(' + ') }) : t('man.clean');+ el.classList.toggle('bad', !!bad);+ $('#edManApply').disabled = !n || !!bad || isBusy() || M.loading;+ $('#edManApply').textContent = isBusy() && state.view?.action === 'manual' ? t('man.applying') : t('man.apply');+ $('#edManReset').disabled = !n || isBusy();+ }++ // ---- sự kiện ----+ const tabsEl = [...document.querySelectorAll('.ed-mtabs [role="tab"]')];+ function pickTab(b, focus) {+ tabsEl.forEach((x) => { const on = x === b; x.setAttribute('aria-selected', String(on)); x.tabIndex = on ? 0 : -1; $('#' + x.getAttribute('aria-controls')).hidden = !on; });+ if (focus) b.focus();+ }+ tabsEl.forEach((b) => b.addEventListener('click', () => pickTab(b)));+ $('.ed-mtabs').addEventListener('keydown', (e) => {+ const i = tabsEl.indexOf(document.activeElement); if (i < 0) return;+ const step = { ArrowRight: 1, ArrowLeft: -1 }[e.key];+ if (step) { e.preventDefault(); pickTab(tabsEl[(i + step + tabsEl.length) % tabsEl.length], true); }+ });+ // bấm mốc giờ → video nhảy tới đúng giây (dòng phụ đề, zoom, đồ hoạ)+ $('#edMan').addEventListener('click', (e) => {+ const tm = e.target.closest('.ed-tm'); if (!tm) return;+ const v = video(); if (!v) return;+ v.currentTime = Math.max(0, Number(tm.dataset.t) + 0.02);+ v.play().catch(() => {});+ });+ $('#edLines').addEventListener('input', (e) => {+ const li = e.target.closest('li[data-k]'); if (!li || !M.cur) return;+ const l = M.cur.captions.lines[Number(li.dataset.k)];+ if (e.target.classList.contains('ed-ltext')) l.text = e.target.value;+ else if (e.target.dataset.f) { const x = Number(e.target.value); if (Number.isFinite(x)) l[e.target.dataset.f] = x; }+ const bad = lineErrors(M.cur.captions.lines);+ document.querySelectorAll('#edLines li[data-k]').forEach((x) => {+ const k = Number(x.dataset.k); x.classList.toggle('bad', bad.has(k));+ let er = x.querySelector('.ed-lerr');+ if (bad.has(k)) { if (!er) { er = document.createElement('span'); er.className = 'ed-lerr'; x.append(er); } er.textContent = bad.get(k); } else er?.remove();+ const tb = x.querySelector('.ed-tm'); const ln = M.cur.captions.lines[k];+ if (tb && ln) { tb.dataset.t = ln.start; tb.textContent = sec(ln.start); }+ });+ paintDirty();+ });+ $('#edLines').addEventListener('click', (e) => {+ const b = e.target.closest('button[data-a]'); if (!b || !M.cur) return;+ const lines = M.cur.captions.lines; const k = Number(b.closest('li').dataset.k); const l = lines[k];+ if (b.dataset.a === 'del') lines.splice(k, 1);+ else if (b.dataset.a === 'merge' && lines[k + 1]) { const n = lines[k + 1]; lines.splice(k, 2, { start: l.start, end: n.end, text: `${l.text} ${n.text}`.trim() }); }+ else if (b.dataset.a === 'split') {+ const ws = l.text.trim().split(/\s+/);+ if (ws.length < 2) { $('#edManErr').textContent = t('man.cantSplit'); return; }+ const cut = Math.ceil(ws.length / 2); const a = ws.slice(0, cut).join(' '); const z = ws.slice(cut).join(' ');+ const mid = Math.round((l.start + (l.end - l.start) * (a.length / (a.length + z.length))) * 100) / 100;+ lines.splice(k, 1, { start: l.start, end: mid, text: a }, { start: mid, end: l.end, text: z });+ }+ $('#edManErr').textContent = '';+ paintLines(); paintDirty();+ $(`#edLines li[data-k="${Math.min(k, lines.length - 1)}"] .ed-ltext`)?.focus();+ });+ // dòng đang phát sáng lên theo giờ video+ $('#edMedia').addEventListener('timeupdate', (e) => {+ if (!M.cur || e.target.tagName !== 'VIDEO') return;+ const tt = e.target.currentTime;+ document.querySelectorAll('#edLines li[data-k]').forEach((x) => {+ const l = M.cur.captions.lines[Number(x.dataset.k)];+ x.classList.toggle('now', !!l && tt >= l.start && tt < l.end);+ });+ }, true);+ $('#edManLook').addEventListener('change', (e) => { M.cur.captions.look = e.target.value; paintDirty(); });+ $('#edManHi').addEventListener('change', (e) => { M.cur.captions.highlights = e.target.checked; paintDirty(); });+ const num = (id, f) => $(id).addEventListener('input', (e) => { const x = Number(e.target.value); if (Number.isFinite(x) && M.cur) f(x); paintAudioOut(); paintDirty(); });+ num('#edManGain', (x) => { M.cur.music.gainDb = x; });+ num('#edManFade', (x) => { M.cur.music.fadeOut = x; });+ num('#edManStart', (x) => { M.cur.music.start = Math.min(600, Math.max(0, x)); });+ num('#edManVoice', (x) => { M.cur.voice.gainDb = x; });+ $('#edManDuck').addEventListener('change', (e) => { M.cur.music.duck = e.target.checked; paintDirty(); });+ $('#edManSfx').addEventListener('change', (e) => { M.cur.sfx.on = e.target.checked; paintDirty(); });+ let musicPrev = null;+ $('#edManMusic').addEventListener('focus', (e) => { musicPrev = e.target.value; });+ $('#edManMusic').addEventListener('change', (e) => {+ if (e.target.value === 'file') { e.target.value = musicPrev || M.cur.music.source || 'keep'; $('#edManMusicFile').click(); return; }+ musicPrev = e.target.value;+ paintAudioOut(); paintDirty();+ });+ $('#edManMusicFile').addEventListener('change', async (e) => {+ const f = e.target.files[0]; e.target.value = '';+ if (!f || !M.id) return;+ const msg = $('#edManMusicMsg'); msg.textContent = t('man.uploading', { name: f.name, size: fmtMB(f.size) });+ const fd = new FormData(); fd.append('music', f, f.name);+ try {+ const r = await fetch(`/api/edits/${encodeURIComponent(M.id)}/music`, { method: 'POST', body: fd });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) throw new Error(j.error || 'HTTP ' + r.status);+ for (const x of [M.cur, M.orig]) x.music.uploads.push({ file: j.file, name: j.name });+ M.cur.music.source = `upload:${j.file}`;+ msg.textContent = t('man.uploadOk', { name: j.name });+ paint();+ } catch (err) { msg.textContent = t('man.uploadErr', { e: I.srv(err.message) }); }+ });+ const toggleGone = (list, li, find) => { const x = list.find(find); if (x) x.gone = !x.gone; paint(); li && $(`#${li}`)?.focus(); };+ $('#edManZooms').addEventListener('click', (e) => { const b = e.target.closest('.ed-mx'); if (b) toggleGone(M.cur.zooms, null, (x) => x.n === Number(b.closest('li').dataset.n)); });+ $('#edManGfx').addEventListener('click', (e) => { const b = e.target.closest('.ed-mx'); if (b) toggleGone(M.cur.graphics, null, (x) => x.id === b.closest('li').dataset.id); });+ $('#edManReset').addEventListener('click', () => { if (M.orig) { M.cur = clone(M.orig); $('#edManErr').textContent = ''; $('#edManMusicMsg').textContent = ''; paint(); } });+ $('#edManApply').addEventListener('click', async () => {+ const p = patch(); if (!M.id || !Object.keys(p).length) return;+ $('#edManApply').disabled = true; $('#edManErr').textContent = '';+ try {+ const r = await fetch(`/api/edits/${encodeURIComponent(M.id)}/manual`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(p) });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) { $('#edManErr').textContent = I.srv(j.error || t('err.status', { s: r.status })); paintDirty(); return; }+ render(j); poll();+ } catch { $('#edManErr').textContent = t('man.sendFail'); paintDirty(); }+ });+ return { onView, repaint: () => { if (M.cur) paint(); } };+ })();+// Đổi VI/EN: vẽ lại phần JS sinh (chữ tĩnh do i18n.js đổi). Lỗi/ghi chú server giữ nguyên.window.addEventListener('lumreels:lang', () => {if (state.noServer) $('#edSetupText').textContent = t('ed.noServer');@@ -347,6 +592,7 @@if (state.list) renderList();document.querySelectorAll('.ed-item').forEach((b) => b.classList.toggle('sel', b.dataset.id === state.current));if (state.view) render(state.view);+ Man.repaint();});renderDrop();diff --git a/server/public/i18n.js b/server/public/i18n.jsindex 49cda82..6fe4462 100644--- a/server/public/i18n.js+++ b/server/public/i18n.js@@ -329,6 +329,68 @@'ed.noOvercut': 'không lẹm chữ','ed.sendFail': 'Không gửi được lời sửa.','ed.confirmDel': 'Xoá hẳn bản dựng này (video ra, EDL, file đã tải lên)? Không lấy lại được.',+ 'man.h': 'Chỉnh tay',+ 'man.tabCap': 'Phụ đề',+ 'man.tabAud': 'Nhạc & tiếng',+ 'man.tabFx': 'Zoom & đồ hoạ',+ 'man.look': 'Kiểu chữ',+ 'man.hi': 'Chữ nhấn (chữ trong *sao* đổi màu)',+ 'man.capHint': 'Bấm mốc giờ để video nhảy tới dòng đó. Bọc *chữ* để nhấn.',+ 'man.draftNote': 'Bản nháp vẽ phụ đề thẳng vào nền nên chưa sửa tay được. Bỏ "nháp" rồi dựng lại.',+ 'man.music': 'Nhạc',+ 'man.musicKeep': 'Giữ nhạc đang dùng ({name})',+ 'man.synth': 'Nhạc tổng hợp: {id}',+ 'man.uploaded': 'Đã tải: {name}',+ 'man.uploading': 'Đang tải {name} ({size})…',+ 'man.uploadOk': 'Đã tải lên {name}. Bấm Áp dụng để trộn lại tiếng.',+ 'man.uploadErr': 'Tải nhạc chưa được: {e}',+ 'man.musicGain': 'Âm lượng nhạc',+ 'man.duck': 'Ducking: nhạc nhỏ lại khi có tiếng nói',+ 'man.fade': 'Fade out cuối',+ 'man.start': 'Nhạc bắt đầu từ giây',+ 'man.voice': 'Âm lượng giọng (so với nhạc)',+ 'man.loudHint': 'Cả bản luôn chuẩn về −14 LUFS: tăng giọng tức là nhạc và tiếng động nhỏ đi tương đối.',+ 'man.sfx': (v) => `Tiếng động (sfx)${v.n ? ` · ${v.n} tiếng` : ' · bản này không có'}`,+ 'man.zooms': 'Zoom',+ 'man.gfx': 'Đồ hoạ',+ 'man.zoomKind': (v) => `${v.kind === 'punch' ? 'Zoom giật' : 'Zoom đẩy'} ×${v.scale}`,+ 'man.noZoom': 'Bản này không có zoom.',+ 'man.noGfx': 'Bản này không có đồ hoạ.',+ 'man.noLines': 'Bản này không có phụ đề.',+ 'man.remove': 'Xoá',+ 'man.undo': 'Giữ lại',+ 'man.removeN': 'Xoá {what}',+ 'man.undoN': 'Giữ lại {what}',+ 'man.jump': 'Nhảy tới giây {s}',+ 'man.lineText': 'Chữ dòng {n}',+ 'man.lineStart': 'Giây bắt đầu dòng {n}',+ 'man.lineEnd': 'Giây kết thúc dòng {n}',+ 'man.split': 'Tách',+ 'man.merge': 'Gộp ↓',+ 'man.splitN': 'Tách dòng {n} làm đôi',+ 'man.mergeN': 'Gộp dòng {n} với dòng sau',+ 'man.delN': 'Xoá dòng {n}',+ 'man.cantSplit': 'Dòng chỉ có 1 chữ, không tách được.',+ 'man.errShort': 'Dòng phải dài ít nhất 0,1 giây (kết thúc sau bắt đầu).',+ 'man.errAfter': 'Bắt đầu sau cuối video ({d} s).',+ 'man.errOverlap': 'Đè lên dòng trước: dời giờ bắt đầu ra sau.',+ 'man.errEmpty': 'Dòng trống: gõ chữ hoặc xoá dòng.',+ 'man.fixFirst': (v) => `Sửa ${v.n} dòng báo đỏ trước khi áp dụng.`,+ 'man.dirty': (v) => `${v.n} thay đổi · dựng lại: ${v.what}`,+ 'man.clean': 'Chưa có thay đổi.',+ 'man.wCap': 'lớp chữ',+ 'man.wAud': 'tiếng',+ 'man.wBase': 'nền',+ 'man.reset': 'Bỏ thay đổi',+ 'man.apply': 'Áp dụng',+ 'man.applying': 'Đang dựng…',+ 'man.running': 'Đang dựng bản chỉnh tay',+ 'man.loadErr': 'Không tải được phần chỉnh tay: {e}',+ 'man.sendFail': 'Không gửi được phần chỉnh tay.',+ 'man.tag': 'Chỉnh tay',+ 'man.took': 'dựng {s} giây',+ 'man.watch': 'Xem',+ 'man.original': 'Bản đầu tiên','ed.styleHint': '{n} kiểu · cuộn để xem hết','ed.styleAria': (v) => `${v.name}: ${v.summary}`,'ed.setupText': 'Phần Edit video cần thêm Python, model chép lời và model nhận mặt. Bấm Cài ngay, LumReels tự cài hết (chỉ làm một lần).',@@ -678,6 +740,68 @@'ed.noOvercut': 'no clipped words','ed.sendFail': "Couldn't send your change.",'ed.confirmDel': 'Delete this edit for good (output video, EDL, uploaded files)? This cannot be undone.',+ 'man.h': 'Manual edit',+ 'man.tabCap': 'Captions',+ 'man.tabAud': 'Music & sound',+ 'man.tabFx': 'Zoom & graphics',+ 'man.look': 'Caption look',+ 'man.hi': 'Highlights (words in *stars* get the accent colour)',+ 'man.capHint': 'Tap a time to jump the video there. Wrap a *word* to highlight it.',+ 'man.draftNote': "A draft burns captions into the picture, so they can't be edited by hand. Turn off \"draft\" and edit again.",+ 'man.music': 'Music',+ 'man.musicKeep': 'Keep current music ({name})',+ 'man.synth': 'Built-in music: {id}',+ 'man.uploaded': 'Uploaded: {name}',+ 'man.uploading': 'Uploading {name} ({size})…',+ 'man.uploadOk': 'Uploaded {name}. Press Apply to remix the sound.',+ 'man.uploadErr': "Couldn't upload the music: {e}",+ 'man.musicGain': 'Music volume',+ 'man.duck': 'Ducking: music dips while someone speaks',+ 'man.fade': 'Fade out at the end',+ 'man.start': 'Music starts at second',+ 'man.voice': 'Voice volume (vs. music)',+ 'man.loudHint': 'The whole mix is always normalised to −14 LUFS: a louder voice means relatively quieter music and effects.',+ 'man.sfx': (v) => `Sound effects (sfx)${v.n ? ` · ${v.n}` : ' · none in this edit'}`,+ 'man.zooms': 'Zooms',+ 'man.gfx': 'Graphics',+ 'man.zoomKind': (v) => `${v.kind === 'punch' ? 'Punch zoom' : 'Push zoom'} ×${v.scale}`,+ 'man.noZoom': 'This edit has no zooms.',+ 'man.noGfx': 'This edit has no graphics.',+ 'man.noLines': 'This edit has no captions.',+ 'man.remove': 'Remove',+ 'man.undo': 'Keep',+ 'man.removeN': 'Remove {what}',+ 'man.undoN': 'Keep {what}',+ 'man.jump': 'Jump to {s} s',+ 'man.lineText': 'Text of line {n}',+ 'man.lineStart': 'Start of line {n} (seconds)',+ 'man.lineEnd': 'End of line {n} (seconds)',+ 'man.split': 'Split',+ 'man.merge': 'Merge ↓',+ 'man.splitN': 'Split line {n} in two',+ 'man.mergeN': 'Merge line {n} with the next',+ 'man.delN': 'Delete line {n}',+ 'man.cantSplit': 'This line has one word; nothing to split.',+ 'man.errShort': 'A line must last at least 0.1 s (end after start).',+ 'man.errAfter': 'Starts after the end of the video ({d} s).',+ 'man.errOverlap': 'Overlaps the line before: move its start later.',+ 'man.errEmpty': 'Empty line: type something or delete it.',+ 'man.fixFirst': (v) => `Fix ${v.n} line${S(v.n)} marked red before applying.`,+ 'man.dirty': (v) => `${v.n} change${S(v.n)} · redo: ${v.what}`,+ 'man.clean': 'No changes yet.',+ 'man.wCap': 'caption layer',+ 'man.wAud': 'sound',+ 'man.wBase': 'picture',+ 'man.reset': 'Discard changes',+ 'man.apply': 'Apply',+ 'man.applying': 'Rendering…',+ 'man.running': 'Rendering manual edit',+ 'man.loadErr': "Couldn't load manual editing: {e}",+ 'man.sendFail': "Couldn't send the manual edit.",+ 'man.tag': 'Manual',+ 'man.took': 'took {s} s',+ 'man.watch': 'Watch',+ 'man.original': 'First version','ed.styleHint': '{n} styles · scroll to see them all','ed.styleAria': (v) => `${v.name}: ${v.summary}`,'ed.setupText': 'Video editing needs Python, a speech-to-text model and a face model. Click Install now and LumReels sets everything up (one time only).',diff --git a/server/public/index.html b/server/public/index.htmlindex f30b2fb..e36e478 100644--- a/server/public/index.html+++ b/server/public/index.html@@ -198,6 +198,61 @@</form><div class="ed-presets" id="edPresets"><button type="button" data-i18n="ed.p1">bỏ 3 giây đầu</button><button type="button" data-i18n="ed.p2">zoom ít lại</button><button type="button" data-i18n="ed.p3">nhạc nhỏ lại</button><button type="button" data-i18n="ed.p4">phụ đề 2 chữ một lần</button></div></div>+ <section class="ed-man" id="edMan" hidden aria-labelledby="edManH">+ <h4 id="edManH" data-i18n="man.h">Chỉnh tay</h4>+ <div class="ed-mtabs" role="tablist" aria-label="Chỉnh tay" data-i18n-aria="man.h">+ <button type="button" role="tab" id="edMtCap" aria-controls="edMpCap" aria-selected="true" data-i18n="man.tabCap">Phụ đề</button>+ <button type="button" role="tab" id="edMtAud" aria-controls="edMpAud" aria-selected="false" tabindex="-1" data-i18n="man.tabAud">Nhạc & tiếng</button>+ <button type="button" role="tab" id="edMtFx" aria-controls="edMpFx" aria-selected="false" tabindex="-1" data-i18n="man.tabFx">Zoom & đồ hoạ</button>+ </div>+ <div role="tabpanel" id="edMpCap" aria-labelledby="edMtCap" class="ed-mpanel">+ <div class="ed-mrow">+ <label class="ed-mlab" for="edManLook" data-i18n="man.look">Kiểu chữ</label>+ <select class="ed-in" id="edManLook"></select>+ </div>+ <label class="ed-check"><input type="checkbox" id="edManHi" /> <span data-i18n="man.hi">Chữ nhấn (chữ trong *sao* đổi màu)</span></label>+ <p class="hint ed-mhint" data-i18n="man.capHint">Bấm mốc giờ để video nhảy tới dòng đó. Bọc *chữ* để nhấn.</p>+ <p class="hint" id="edManDraft" hidden data-i18n="man.draftNote">Bản nháp vẽ phụ đề thẳng vào nền nên chưa sửa tay được. Bỏ "nháp" rồi dựng lại.</p>+ <ol class="ed-lines" id="edLines"></ol>+ </div>+ <div role="tabpanel" id="edMpAud" aria-labelledby="edMtAud" class="ed-mpanel" hidden>+ <div class="ed-mrow">+ <label class="ed-mlab" for="edManMusic" data-i18n="man.music">Nhạc</label>+ <select class="ed-in" id="edManMusic"></select>+ <input type="file" id="edManMusicFile" accept="audio/*,.mp3,.wav,.m4a,.aac,.ogg,.flac,.opus" hidden />+ </div>+ <div class="ed-file" id="edManMusicMsg" aria-live="polite"></div>+ <div class="ed-slider" id="edManMusicBox">+ <label for="edManGain"><span data-i18n="man.musicGain">Âm lượng nhạc</span> <output id="edManGainV" for="edManGain"></output></label>+ <input type="range" id="edManGain" min="-40" max="0" step="1" />+ <label class="ed-check"><input type="checkbox" id="edManDuck" /> <span data-i18n="man.duck">Ducking: nhạc nhỏ lại khi có tiếng nói</span></label>+ <label for="edManFade"><span data-i18n="man.fade">Fade out cuối</span> <output id="edManFadeV" for="edManFade"></output></label>+ <input type="range" id="edManFade" min="0" max="10" step="0.5" />+ <div class="ed-mrow">+ <label class="ed-mlab" for="edManStart" data-i18n="man.start">Nhạc bắt đầu từ giây</label>+ <input class="ed-in ed-num" id="edManStart" type="number" min="0" max="600" step="0.5" inputmode="decimal" />+ </div>+ </div>+ <div class="ed-slider">+ <label for="edManVoice"><span data-i18n="man.voice">Âm lượng giọng (so với nhạc)</span> <output id="edManVoiceV" for="edManVoice"></output></label>+ <input type="range" id="edManVoice" min="-12" max="12" step="1" />+ </div>+ <p class="hint" data-i18n="man.loudHint">Cả bản luôn chuẩn về −14 LUFS: tăng giọng tức là nhạc và tiếng động nhỏ đi tương đối.</p>+ <label class="ed-check"><input type="checkbox" id="edManSfx" /> <span id="edManSfxL">Tiếng động (sfx)</span></label>+ </div>+ <div role="tabpanel" id="edMpFx" aria-labelledby="edMtFx" class="ed-mpanel" hidden>+ <h5 data-i18n="man.zooms">Zoom</h5>+ <ul class="ed-fxlist" id="edManZooms"></ul>+ <h5 data-i18n="man.gfx">Đồ hoạ</h5>+ <ul class="ed-fxlist" id="edManGfx"></ul>+ </div>+ <div class="errmsg" id="edManErr" role="alert"></div>+ <div class="ed-mbar">+ <span class="ed-mdirty" id="edManDirty" aria-live="polite"></span>+ <button type="button" class="ed-mreset" id="edManReset" data-i18n="man.reset">Bỏ thay đổi</button>+ <button type="button" class="ed-mapply" id="edManApply" data-i18n="man.apply">Áp dụng</button>+ </div>+ </section><div class="ed-hist" id="edHist" hidden><h4 data-i18n="ed.histH">Các lần sửa</h4><ol id="edHistList"></ol></div><details class="log"><summary data-i18n="ed.log">Nhật ký</summary><pre id="edLog"></pre></details><div class="links ed-danger"><button type="button" id="edDelete" data-i18n="ed.delete">Xoá bản dựng này</button></div>