Skip to content

Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.

Sửa tiếp trong Studio cho reel đã dựng + cắt bỏ đoạn trên track Video

Lumtek69d9746d4834
diff --git a/edit/edl.mjs b/edit/edl.mjs
index 1910912..0ac744b 100644
--- a/edit/edl.mjs
+++ b/edit/edl.mjs
@@ -1,223 +1,224 @@
-// EDL của LumReels Edit (bản 1): một file JSON mô tả trọn bản dựng từ 1 video nguồn.
-// - Mọi mốc thời gian là GIÂY CỦA NGUỒN (timestamp thật, trừ start_time), không phải giây của bản ra.
-// Video điện thoại (VFR, xoay, HEVC, HDR) được chuẩn hoá trước thành proxy CFR 30 fps cùng trục thời gian
-// (proxy t = nguồn PTS − start_time), nên mốc trong EDL đọc thẳng được trên proxy.
-// - Bản ra: hình snap theo khung 30 fps, tiếng snap theo mẫu 48 kHz; âm gốc đi qua mọi vết cắt, nối crossfade 20 ms.
-// Nguồn sự thật của schema là zod ở đây; `node edit/edl.mjs --schema` ghi ra edl.schema.json.
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { z } from 'zod';
-import { graphicsErrors } from './graphics.mjs';
-
-export const EDL_VERSION = 1;
-export const OUT = { width: 1080, height: 1920, fps: 30, audioRate: 48000, lufs: -14 };
-export const REMOVE_REASONS = ['pause', 'filler', 'retake', 'false-start', 'aside', 'edge', 'by-hand', 'trim'];
-export const SAFE = { x0: 120 / 1080, x1: 960 / 1080, y0: 0.10, y1: 0.80 }; // vùng an toàn Reels/Shorts/TikTok
-
-const sec = z.number().finite().min(0);
-const span = z.object({ start: sec, end: sec }).strict();
-
-// lớp đồ hoạ thông tin (edit/graphics.mjs). Mốc là giây nguồn; data.at và at của từng dòng/cột/điểm cũng là giây nguồn.
-const item = z.object({ at: sec }).passthrough();
-export const GraphicSchema = z.object({
- id: z.string(),
- type: z.enum(['counter', 'bar_chart', 'compare', 'spec_table', 'checklist', 'price_tag', 'sticker', 'line_chart', 'title_card']),
- start: sec, end: sec,
- estimate: z.boolean().describe('có số suy ra, không nói thẳng → đồ hoạ ghi "ước tính"'),
- data: z.object({ at: sec, items: z.array(item).optional(), points: z.array(item).optional(), rows: z.array(item).optional() }).passthrough(),
- box: z.object({ x: z.number(), y: z.number(), w: z.number().positive(), h: z.number().positive(), scale: z.number().min(0.3).max(1) }).strict().nullable()
- .describe('vị trí trên khung bản ra (px), đã né mặt'),
- face: z.array(z.number()).length(4).nullable().describe('hợp khung mặt bản ra lúc đồ hoạ hiện (+lề, đã tính push), để kiểm không đè'),
- squeeze: z.object({ scale: z.number().min(0.5).max(1), anchorY: z.number().min(0).max(OUT.height) }).strict().nullable().default(null)
- .describe('thu cả khung hình quanh (giữa, anchorY) trong lúc đồ hoạ hiện — cận mặt, không đủ chỗ phía trên'),
-}).strict();
-
-export const EdlSchema = z.object({
- version: z.literal(EDL_VERSION),
- id: z.string().min(1),
- createdAt: z.string(),
- style: z.string().min(1).describe('id thẻ kiểu edit (edit-styles/<id>.md)'),
- source: z.object({
- file: z.string(), sha256: z.string().regex(/^[0-9a-f]{64}$/), size: z.number().int().nonnegative(),
- duration: sec, startTime: z.number().describe('start_time của nguồn, đã trừ khi làm proxy'),
- fps: z.number().positive().describe('avg_frame_rate'), vfr: z.boolean(),
- rotation: z.number().describe('độ xoay trong metadata, đã áp vào proxy'),
- width: z.number().int().positive().describe('chiều ngang khi hiển thị (sau xoay)'), height: z.number().int().positive(),
- codec: z.string(), hdr: z.boolean(), hasAudio: z.boolean(),
- }).strict(),
- proxy: z.object({
- file: z.string(), width: z.number().int().positive(), height: z.number().int().positive(),
- fps: z.literal(30), audioRate: z.literal(48000),
- }).strict(),
- output: z.object({
- width: z.literal(OUT.width), height: z.literal(OUT.height), fps: z.literal(OUT.fps),
- audioRate: z.literal(OUT.audioRate), lufs: z.number().min(-30).max(-8),
- }).strict(),
- keep: z.array(span).min(1).describe('đoạn nguồn được giữ, theo thứ tự, không chồng nhau'),
- removed: z.array(span.extend({ reason: z.enum(REMOVE_REASONS), words: z.string().default('') }).strict())
- .describe('đoạn bị bỏ, để người xem lại và đặt lại'),
- reframe: z.object({ mode: z.enum(['face', 'center', 'fill', 'none']) }).strict(),
- zooms: z.array(z.object({
- at: sec.describe('giây nguồn lúc zoom chạm'), dur: z.number().min(0.2).max(8),
- scale: z.number().min(1).max(1.6), kind: z.enum(['punch', 'push']),
- word: z.number().int().nonnegative().optional(),
- }).strict()),
- captions: z.object({
- style: z.string(), renderer: z.enum(['hyperframes', 'pil']),
- maxWords: z.number().int().min(1).max(8), position: z.enum(['lower', 'middle']),
- words: z.array(z.object({ i: z.number().int().nonnegative(), w: z.string().min(1), start: sec, end: sec }).strict()),
- highlights: z.array(z.number().int().nonnegative()).describe('chỉ số i của chữ nhấn'),
- hiOff: z.boolean().default(false).describe('tắt mọi chữ nhấn (chỉnh tay)'),
- lines: z.array(z.object({
- start: sec, end: sec,
- words: z.array(z.object({ w: z.string().min(1).max(80), o: sec, hi: z.boolean() }).strict()).min(1).max(40),
- }).strict()).max(600).optional()
- .describe('dòng phụ đề chỉnh tay, GIÂY BẢN RA (thay cho nhóm chữ tự động; o: giây bản ra của từng chữ cho karaoke)'),
- }).strict(),
- sfx: z.array(z.object({ at: sec, name: z.string(), gainDb: z.number().min(-30).max(6) }).strict()),
- music: z.object({
- file: z.string(), gainDb: z.number().min(-40).max(0), duckDb: z.number().min(0).max(30).describe('0: không hạ nhạc khi nói'), fadeOut: z.number().min(0).max(10),
- start: z.number().min(0).max(600).default(0).describe('giây của bài nhạc phát ở đầu bản ra'),
- }).strict().nullable(),
- graphics: z.array(GraphicSchema).default([]).describe('đồ hoạ bảng biểu (kiểu thong-tin-do-hoa)'),
- hook: z.object({
- start: sec, end: sec,
- repeat: z.boolean().describe('true: câu móc vẫn phát lại ở chỗ cũ; false: đã trừ khỏi keep'),
- flash: z.boolean().describe('chớp trắng 2 khung ở chỗ nối móc → clip'),
- sfx: z.object({ name: z.string(), at: sec.describe('giây nguồn (trong khoảng móc)'), gainDb: z.number().min(-30).max(6) }).strict().nullable(),
- }).strict().nullable().default(null)
- .describe('câu móc kéo lên đầu: bản ra = [hook] + keep[]; mọi mốc bản ra của keep dời thêm (end − start)'),
- hookText: z.object({ text: z.string().min(1).max(40), until: z.number().min(0.5).max(5) }).strict().nullable().default(null)
- .describe('chữ móc to ở 0 → until giây bản ra (chữ nhấn trong *…*)'),
- quote: z.object({
- start: sec, end: sec, dimTo: z.number().min(0.1).max(1), blurPx: z.number().min(0).max(30), dimIn: z.number().min(0.1).max(3),
- }).strict().nullable().default(null).describe('câu trích dẫn to giữa khung (giây nguồn); video tối + mờ trong lúc đó'),
- audio: z.object({
- crossfadeMs: z.number().min(5).max(80), keepSourceAudio: z.literal(true),
- voiceGainDb: z.number().min(-12).max(12).default(0).describe('nâng/hạ giọng gốc so với nhạc (cả bản vẫn chuẩn về −14 LUFS)'),
- sfxOff: z.boolean().default(false).describe('tắt mọi tiếng động (giữ danh sách sfx)'),
- }).strict(),
- notes: z.string().optional(),
-}).strict();
-
-// ---- ánh xạ thời gian nguồn → bản ra -------------------------------------------------------------------
-// Các hàm dưới nhận `keep` (mảng đoạn giữ). Có câu móc (edl.hook) thì truyền timelineOf(edl): cùng mảng keep, kèm
-// thuộc tính .hook — bản ra = [hook] + keep, mọi mốc của keep dời thêm hookDur. Mốc nằm cả trong keep lẫn trong
-// hook (repeat) thì lấy chỗ trong keep; mốc chỉ có trong hook (repeat: false) thì về 0 … hookDur.
-export const hookDur = (keep) => (keep?.hook ? keep.hook.end - keep.hook.start : 0);
-/** Mảng keep của EDL (bản sao) mang theo .hook để các hàm ánh xạ biết câu móc ở đầu bản ra. */
-export function timelineOf(edl) {
- const k = edl.keep.map((x) => ({ start: x.start, end: x.end }));
- if (edl.hook) Object.defineProperty(k, 'hook', { value: { ...edl.hook }, enumerable: false });
- return k;
-}
-const inHook = (keep, t) => !!keep?.hook && t >= keep.hook.start - 1e-9 && t <= keep.hook.end + 1e-9;
-export function outputDuration(keep) { return hookDur(keep) + keep.reduce((s, k) => s + (k.end - k.start), 0); }
-/** Giây nguồn → giây bản ra; null nếu rơi vào đoạn bỏ. */
-export function toOutput(keep, t) {
- let acc = hookDur(keep);
- for (const k of keep) {
- if (t < k.start - 1e-9) break;
- if (t <= k.end + 1e-9) return acc + (t - k.start);
- acc += k.end - k.start;
- }
- return inHook(keep, t) ? t - keep.hook.start : null;
-}
-/** Như toOutput nhưng mốc rơi vào đoạn bỏ thì dời về mép giữ gần nhất. */
-export function toOutputNearest(keep, t) {
- const got = toOutput(keep, t);
- if (got !== null) return got;
- let best = 0; let bd = Infinity; let acc = hookDur(keep);
- for (const k of keep) {
- for (const [src, o] of [[k.start, acc], [k.end, acc + k.end - k.start]]) {
- if (Math.abs(src - t) < bd) { bd = Math.abs(src - t); best = o; }
- }
- acc += k.end - k.start;
- }
- return best;
-}
-export const inKeep = (keep, t) => keep.some((k) => t >= k.start - 1e-6 && t <= k.end + 1e-6) || inHook(keep, t);
-
-/**
- * Kiểm EDL: schema + luật thời gian. Trả {ok, errors:[{code, path, msg}], edl}.
- * opts.sfxNames: tên sfx hợp lệ; opts.checkFiles: kiểm file nguồn/nhạc có thật.
- */
-export function validateEdl(input, { sfxNames, checkFiles = true } = {}) {
- const errors = [];
- const add = (code, p, msg) => errors.push({ code, path: p, msg });
- const parsed = EdlSchema.safeParse(input);
- if (!parsed.success) {
- for (const i of parsed.error.issues) add('schema', i.path.join('.'), i.message);
- return { ok: false, errors };
- }
- const e = parsed.data;
- const dur = e.source.duration;
- const tl = timelineOf(e);
- const frame = 1 / e.output.fps;
- e.keep.forEach((k, i) => {
- if (k.end - k.start < frame) add('keep-short', `keep.${i}`, `đoạn giữ ${k.start}–${k.end} ngắn hơn 1 khung`);
- if (k.end > dur + 0.05) add('keep-out', `keep.${i}`, `đoạn giữ vượt quá độ dài nguồn (${dur.toFixed(2)} s)`);
- if (i && k.start < e.keep[i - 1].end - 1e-6) add('keep-overlap', `keep.${i}`, `đoạn giữ chồng/ngược thứ tự với đoạn trước`);
- });
- if (e.hook) {
- const h = e.hook; const hd = h.end - h.start;
- if (hd < 0.3 || hd > 6) add('hook-len', 'hook', `câu móc dài ${hd.toFixed(2)} s (cần 0,3–6 s)`);
- if (h.end > dur + 0.05) add('hook-out', 'hook', 'câu móc vượt quá độ dài nguồn');
- if (h.sfx && (h.sfx.at < h.start - 1e-6 || h.sfx.at > h.end + 1e-6)) add('hook-sfx', 'hook.sfx', 'tiếng của câu móc nằm ngoài câu móc');
- if (h.sfx && sfxNames && !sfxNames.includes(h.sfx.name)) add('sfx-name', 'hook.sfx', `không có tiếng "${h.sfx.name}"`);
- if (!h.repeat && e.keep.some((k) => k.start < h.end - 1e-3 && k.end > h.start + 1e-3)) add('hook-overlap', 'hook', 'câu móc không lặp lại (repeat: false) mà vẫn nằm trong keep');
- }
- if (e.quote) {
- if (e.quote.end <= e.quote.start) add('quote', 'quote', 'câu trích dẫn kết thúc trước khi bắt đầu');
- else if (!inKeep(tl, e.quote.start) || !inKeep(tl, e.quote.end)) add('quote-cut', 'quote', 'câu trích dẫn rơi vào đoạn bị bỏ');
- }
- const outDur = outputDuration(tl);
- if (outDur < 1) add('too-short', 'keep', `bản ra chỉ ${outDur.toFixed(2)} s`);
- e.zooms.forEach((zm, i) => {
- if (!inKeep(tl, zm.at)) add('zoom-cut', `zooms.${i}`, `zoom ở ${zm.at} s rơi vào đoạn bị bỏ`);
- if (i && zm.at < e.zooms[i - 1].at) add('zoom-order', `zooms.${i}`, 'zoom phải theo thứ tự thời gian');
- });
- const ids = new Set();
- e.captions.words.forEach((w, i) => {
- if (w.end < w.start) add('word-time', `captions.words.${i}`, `chữ "${w.w}" kết thúc trước khi bắt đầu`);
- if (!inKeep(tl, (w.start + w.end) / 2)) add('word-cut', `captions.words.${i}`, `chữ "${w.w}" ở ${w.start} s nằm trong đoạn bị bỏ`);
- if (i && w.start < e.captions.words[i - 1].start - 1e-6) add('word-order', `captions.words.${i}`, 'chữ phải theo thứ tự thời gian');
- ids.add(w.i);
- });
- (e.captions.lines || []).forEach((l, i) => {
- if (l.end - l.start < 0.05) add('line-time', `captions.lines.${i}`, 'dòng phụ đề kết thúc trước khi bắt đầu');
- if (l.start > outDur + 0.05) add('line-out', `captions.lines.${i}`, `dòng phụ đề ở ${l.start} s, sau cuối bản ra (${outDur.toFixed(2)} s)`);
- if (i && l.start < e.captions.lines[i - 1].end - 1e-6) add('line-overlap', `captions.lines.${i}`, 'dòng phụ đề đè dòng trước');
- });
- e.captions.highlights.forEach((h, i) => { if (!ids.has(h)) add('highlight', `captions.highlights.${i}`, `chữ nhấn ${h} không có trong phụ đề`); });
- e.sfx.forEach((s, i) => {
- if (sfxNames && !sfxNames.includes(s.name)) add('sfx-name', `sfx.${i}`, `không có tiếng "${s.name}"`);
- if (!inKeep(tl, s.at)) add('sfx-cut', `sfx.${i}`, `tiếng "${s.name}" ở ${s.at} s rơi vào đoạn bị bỏ`);
- });
- for (const g of graphicsErrors(e)) errors.push(g);
- if (checkFiles) {
- if (!fs.existsSync(e.proxy.file)) add('file', 'proxy.file', `không thấy proxy ${e.proxy.file}`);
- if (e.music && !fs.existsSync(e.music.file)) add('file', 'music.file', `không thấy file nhạc ${e.music.file}`);
- }
- return { ok: errors.length === 0, errors, edl: e };
-}
-
-export function writeJsonSchema(file = path.join(path.dirname(fileURLToPath(import.meta.url)), 'edl.schema.json')) {
- const schema = z.toJSONSchema(EdlSchema, { target: 'draft-2020-12', io: 'input' });
- schema.$id = 'https://reels.lumtek.net/schema/edl-v1.json';
- schema.title = 'LumReels Edit EDL v1';
- schema.description = 'Bản dựng từ 1 video nguồn. Mọi mốc thời gian là giây của nguồn (đã trừ start_time).';
- fs.writeFileSync(file, JSON.stringify(schema, null, 2) + '\n');
- return file;
-}
-
-if (path.resolve(process.argv[1] || '') === fileURLToPath(import.meta.url)) {
- const a = process.argv.slice(2);
- if (a[0] === '--schema') console.log(writeJsonSchema());
- else if (a[0]) {
- const r = validateEdl(JSON.parse(fs.readFileSync(a[0], 'utf8')));
- console.log(r.ok ? 'EDL hợp lệ' : r.errors.map((x) => `${x.code} ${x.path}: ${x.msg}`).join('\n'));
- process.exit(r.ok ? 0 : 1);
- } else console.log('node edit/edl.mjs --schema | <edl.json>');
-}
+// EDL của LumReels Edit (bản 1): một file JSON mô tả trọn bản dựng từ 1 video nguồn.
+// - Mọi mốc thời gian là GIÂY CỦA NGUỒN (timestamp thật, trừ start_time), không phải giây của bản ra.
+// Video điện thoại (VFR, xoay, HEVC, HDR) được chuẩn hoá trước thành proxy CFR 30 fps cùng trục thời gian
+// (proxy t = nguồn PTS − start_time), nên mốc trong EDL đọc thẳng được trên proxy.
+// - Bản ra: hình snap theo khung 30 fps, tiếng snap theo mẫu 48 kHz; âm gốc đi qua mọi vết cắt, nối crossfade 20 ms.
+// Nguồn sự thật của schema là zod ở đây; `node edit/edl.mjs --schema` ghi ra edl.schema.json.
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { z } from 'zod';
+import { graphicsErrors } from './graphics.mjs';
+
+export const EDL_VERSION = 1;
+export const OUT = { width: 1080, height: 1920, fps: 30, audioRate: 48000, lufs: -14 };
+export const REMOVE_REASONS = ['pause', 'filler', 'retake', 'false-start', 'aside', 'edge', 'by-hand', 'trim'];
+export const SAFE = { x0: 120 / 1080, x1: 960 / 1080, y0: 0.10, y1: 0.80 }; // vùng an toàn Reels/Shorts/TikTok
+
+const sec = z.number().finite().min(0);
+const span = z.object({ start: sec, end: sec }).strict();
+
+// lớp đồ hoạ thông tin (edit/graphics.mjs). Mốc là giây nguồn; data.at và at của từng dòng/cột/điểm cũng là giây nguồn.
+const item = z.object({ at: sec }).passthrough();
+export const GraphicSchema = z.object({
+ id: z.string(),
+ type: z.enum(['counter', 'bar_chart', 'compare', 'spec_table', 'checklist', 'price_tag', 'sticker', 'line_chart', 'title_card']),
+ start: sec, end: sec,
+ estimate: z.boolean().describe('có số suy ra, không nói thẳng → đồ hoạ ghi "ước tính"'),
+ data: z.object({ at: sec, items: z.array(item).optional(), points: z.array(item).optional(), rows: z.array(item).optional() }).passthrough(),
+ box: z.object({ x: z.number(), y: z.number(), w: z.number().positive(), h: z.number().positive(), scale: z.number().min(0.3).max(1) }).strict().nullable()
+ .describe('vị trí trên khung bản ra (px), đã né mặt'),
+ face: z.array(z.number()).length(4).nullable().describe('hợp khung mặt bản ra lúc đồ hoạ hiện (+lề, đã tính push), để kiểm không đè'),
+ squeeze: z.object({ scale: z.number().min(0.5).max(1), anchorY: z.number().min(0).max(OUT.height) }).strict().nullable().default(null)
+ .describe('thu cả khung hình quanh (giữa, anchorY) trong lúc đồ hoạ hiện — cận mặt, không đủ chỗ phía trên'),
+}).strict();
+
+export const EdlSchema = z.object({
+ version: z.literal(EDL_VERSION),
+ id: z.string().min(1),
+ createdAt: z.string(),
+ style: z.string().min(1).describe('id thẻ kiểu edit (edit-styles/<id>.md)'),
+ source: z.object({
+ file: z.string(), sha256: z.string().regex(/^[0-9a-f]{64}$/), size: z.number().int().nonnegative(),
+ duration: sec, startTime: z.number().describe('start_time của nguồn, đã trừ khi làm proxy'),
+ fps: z.number().positive().describe('avg_frame_rate'), vfr: z.boolean(),
+ rotation: z.number().describe('độ xoay trong metadata, đã áp vào proxy'),
+ width: z.number().int().positive().describe('chiều ngang khi hiển thị (sau xoay)'), height: z.number().int().positive(),
+ codec: z.string(), hdr: z.boolean(), hasAudio: z.boolean(),
+ }).strict(),
+ proxy: z.object({
+ file: z.string(), width: z.number().int().positive(), height: z.number().int().positive(),
+ fps: z.literal(30), audioRate: z.literal(48000),
+ }).strict(),
+ output: z.object({
+ width: z.literal(OUT.width), height: z.literal(OUT.height), fps: z.literal(OUT.fps),
+ audioRate: z.literal(OUT.audioRate), lufs: z.number().min(-30).max(-8),
+ }).strict(),
+ keep: z.array(span).min(1).describe('đoạn nguồn được giữ, theo thứ tự, không chồng nhau'),
+ removed: z.array(span.extend({ reason: z.enum(REMOVE_REASONS), words: z.string().default('') }).strict())
+ .describe('đoạn bị bỏ, để người xem lại và đặt lại'),
+ reframe: z.object({ mode: z.enum(['face', 'center', 'fill', 'none']) }).strict(),
+ zooms: z.array(z.object({
+ at: sec.describe('giây nguồn lúc zoom chạm'), dur: z.number().min(0.2).max(8),
+ scale: z.number().min(1).max(1.6), kind: z.enum(['punch', 'push']),
+ word: z.number().int().nonnegative().optional(),
+ }).strict()),
+ captions: z.object({
+ style: z.string(), renderer: z.enum(['hyperframes', 'pil']),
+ maxWords: z.number().int().min(1).max(8), position: z.enum(['lower', 'middle']),
+ words: z.array(z.object({ i: z.number().int().nonnegative(), w: z.string().min(1), start: sec, end: sec }).strict()),
+ highlights: z.array(z.number().int().nonnegative()).describe('chỉ số i của chữ nhấn'),
+ hiOff: z.boolean().default(false).describe('tắt mọi chữ nhấn (chỉnh tay)'),
+ off: z.boolean().default(false).describe('không vẽ phụ đề (reel nhập vào: chữ đã nằm trong cảnh); vẫn giữ chữ để bật lại'),
+ lines: z.array(z.object({
+ start: sec, end: sec,
+ words: z.array(z.object({ w: z.string().min(1).max(80), o: sec, hi: z.boolean() }).strict()).min(1).max(40),
+ }).strict()).max(600).optional()
+ .describe('dòng phụ đề chỉnh tay, GIÂY BẢN RA (thay cho nhóm chữ tự động; o: giây bản ra của từng chữ cho karaoke)'),
+ }).strict(),
+ sfx: z.array(z.object({ at: sec, name: z.string(), gainDb: z.number().min(-30).max(6) }).strict()),
+ music: z.object({
+ file: z.string(), gainDb: z.number().min(-40).max(0), duckDb: z.number().min(0).max(30).describe('0: không hạ nhạc khi nói'), fadeOut: z.number().min(0).max(10),
+ start: z.number().min(0).max(600).default(0).describe('giây của bài nhạc phát ở đầu bản ra'),
+ }).strict().nullable(),
+ graphics: z.array(GraphicSchema).default([]).describe('đồ hoạ bảng biểu (kiểu thong-tin-do-hoa)'),
+ hook: z.object({
+ start: sec, end: sec,
+ repeat: z.boolean().describe('true: câu móc vẫn phát lại ở chỗ cũ; false: đã trừ khỏi keep'),
+ flash: z.boolean().describe('chớp trắng 2 khung ở chỗ nối móc → clip'),
+ sfx: z.object({ name: z.string(), at: sec.describe('giây nguồn (trong khoảng móc)'), gainDb: z.number().min(-30).max(6) }).strict().nullable(),
+ }).strict().nullable().default(null)
+ .describe('câu móc kéo lên đầu: bản ra = [hook] + keep[]; mọi mốc bản ra của keep dời thêm (end − start)'),
+ hookText: z.object({ text: z.string().min(1).max(40), until: z.number().min(0.5).max(5) }).strict().nullable().default(null)
+ .describe('chữ móc to ở 0 → until giây bản ra (chữ nhấn trong *…*)'),
+ quote: z.object({
+ start: sec, end: sec, dimTo: z.number().min(0.1).max(1), blurPx: z.number().min(0).max(30), dimIn: z.number().min(0.1).max(3),
+ }).strict().nullable().default(null).describe('câu trích dẫn to giữa khung (giây nguồn); video tối + mờ trong lúc đó'),
+ audio: z.object({
+ crossfadeMs: z.number().min(5).max(80), keepSourceAudio: z.literal(true),
+ voiceGainDb: z.number().min(-12).max(12).default(0).describe('nâng/hạ giọng gốc so với nhạc (cả bản vẫn chuẩn về −14 LUFS)'),
+ sfxOff: z.boolean().default(false).describe('tắt mọi tiếng động (giữ danh sách sfx)'),
+ }).strict(),
+ notes: z.string().optional(),
+}).strict();
+
+// ---- ánh xạ thời gian nguồn → bản ra -------------------------------------------------------------------
+// Các hàm dưới nhận `keep` (mảng đoạn giữ). Có câu móc (edl.hook) thì truyền timelineOf(edl): cùng mảng keep, kèm
+// thuộc tính .hook — bản ra = [hook] + keep, mọi mốc của keep dời thêm hookDur. Mốc nằm cả trong keep lẫn trong
+// hook (repeat) thì lấy chỗ trong keep; mốc chỉ có trong hook (repeat: false) thì về 0 … hookDur.
+export const hookDur = (keep) => (keep?.hook ? keep.hook.end - keep.hook.start : 0);
+/** Mảng keep của EDL (bản sao) mang theo .hook để các hàm ánh xạ biết câu móc ở đầu bản ra. */
+export function timelineOf(edl) {
+ const k = edl.keep.map((x) => ({ start: x.start, end: x.end }));
+ if (edl.hook) Object.defineProperty(k, 'hook', { value: { ...edl.hook }, enumerable: false });
+ return k;
+}
+const inHook = (keep, t) => !!keep?.hook && t >= keep.hook.start - 1e-9 && t <= keep.hook.end + 1e-9;
+export function outputDuration(keep) { return hookDur(keep) + keep.reduce((s, k) => s + (k.end - k.start), 0); }
+/** Giây nguồn → giây bản ra; null nếu rơi vào đoạn bỏ. */
+export function toOutput(keep, t) {
+ let acc = hookDur(keep);
+ for (const k of keep) {
+ if (t < k.start - 1e-9) break;
+ if (t <= k.end + 1e-9) return acc + (t - k.start);
+ acc += k.end - k.start;
+ }
+ return inHook(keep, t) ? t - keep.hook.start : null;
+}
+/** Như toOutput nhưng mốc rơi vào đoạn bỏ thì dời về mép giữ gần nhất. */
+export function toOutputNearest(keep, t) {
+ const got = toOutput(keep, t);
+ if (got !== null) return got;
+ let best = 0; let bd = Infinity; let acc = hookDur(keep);
+ for (const k of keep) {
+ for (const [src, o] of [[k.start, acc], [k.end, acc + k.end - k.start]]) {
+ if (Math.abs(src - t) < bd) { bd = Math.abs(src - t); best = o; }
+ }
+ acc += k.end - k.start;
+ }
+ return best;
+}
+export const inKeep = (keep, t) => keep.some((k) => t >= k.start - 1e-6 && t <= k.end + 1e-6) || inHook(keep, t);
+
+/**
+ * Kiểm EDL: schema + luật thời gian. Trả {ok, errors:[{code, path, msg}], edl}.
+ * opts.sfxNames: tên sfx hợp lệ; opts.checkFiles: kiểm file nguồn/nhạc có thật.
+ */
+export function validateEdl(input, { sfxNames, checkFiles = true } = {}) {
+ const errors = [];
+ const add = (code, p, msg) => errors.push({ code, path: p, msg });
+ const parsed = EdlSchema.safeParse(input);
+ if (!parsed.success) {
+ for (const i of parsed.error.issues) add('schema', i.path.join('.'), i.message);
+ return { ok: false, errors };
+ }
+ const e = parsed.data;
+ const dur = e.source.duration;
+ const tl = timelineOf(e);
+ const frame = 1 / e.output.fps;
+ e.keep.forEach((k, i) => {
+ if (k.end - k.start < frame) add('keep-short', `keep.${i}`, `đoạn giữ ${k.start}–${k.end} ngắn hơn 1 khung`);
+ if (k.end > dur + 0.05) add('keep-out', `keep.${i}`, `đoạn giữ vượt quá độ dài nguồn (${dur.toFixed(2)} s)`);
+ if (i && k.start < e.keep[i - 1].end - 1e-6) add('keep-overlap', `keep.${i}`, `đoạn giữ chồng/ngược thứ tự với đoạn trước`);
+ });
+ if (e.hook) {
+ const h = e.hook; const hd = h.end - h.start;
+ if (hd < 0.3 || hd > 6) add('hook-len', 'hook', `câu móc dài ${hd.toFixed(2)} s (cần 0,3–6 s)`);
+ if (h.end > dur + 0.05) add('hook-out', 'hook', 'câu móc vượt quá độ dài nguồn');
+ if (h.sfx && (h.sfx.at < h.start - 1e-6 || h.sfx.at > h.end + 1e-6)) add('hook-sfx', 'hook.sfx', 'tiếng của câu móc nằm ngoài câu móc');
+ if (h.sfx && sfxNames && !sfxNames.includes(h.sfx.name)) add('sfx-name', 'hook.sfx', `không có tiếng "${h.sfx.name}"`);
+ if (!h.repeat && e.keep.some((k) => k.start < h.end - 1e-3 && k.end > h.start + 1e-3)) add('hook-overlap', 'hook', 'câu móc không lặp lại (repeat: false) mà vẫn nằm trong keep');
+ }
+ if (e.quote) {
+ if (e.quote.end <= e.quote.start) add('quote', 'quote', 'câu trích dẫn kết thúc trước khi bắt đầu');
+ else if (!inKeep(tl, e.quote.start) || !inKeep(tl, e.quote.end)) add('quote-cut', 'quote', 'câu trích dẫn rơi vào đoạn bị bỏ');
+ }
+ const outDur = outputDuration(tl);
+ if (outDur < 1) add('too-short', 'keep', `bản ra chỉ ${outDur.toFixed(2)} s`);
+ e.zooms.forEach((zm, i) => {
+ if (!inKeep(tl, zm.at)) add('zoom-cut', `zooms.${i}`, `zoom ở ${zm.at} s rơi vào đoạn bị bỏ`);
+ if (i && zm.at < e.zooms[i - 1].at) add('zoom-order', `zooms.${i}`, 'zoom phải theo thứ tự thời gian');
+ });
+ const ids = new Set();
+ e.captions.words.forEach((w, i) => {
+ if (w.end < w.start) add('word-time', `captions.words.${i}`, `chữ "${w.w}" kết thúc trước khi bắt đầu`);
+ if (!inKeep(tl, (w.start + w.end) / 2)) add('word-cut', `captions.words.${i}`, `chữ "${w.w}" ở ${w.start} s nằm trong đoạn bị bỏ`);
+ if (i && w.start < e.captions.words[i - 1].start - 1e-6) add('word-order', `captions.words.${i}`, 'chữ phải theo thứ tự thời gian');
+ ids.add(w.i);
+ });
+ (e.captions.lines || []).forEach((l, i) => {
+ if (l.end - l.start < 0.05) add('line-time', `captions.lines.${i}`, 'dòng phụ đề kết thúc trước khi bắt đầu');
+ if (l.start > outDur + 0.05) add('line-out', `captions.lines.${i}`, `dòng phụ đề ở ${l.start} s, sau cuối bản ra (${outDur.toFixed(2)} s)`);
+ if (i && l.start < e.captions.lines[i - 1].end - 1e-6) add('line-overlap', `captions.lines.${i}`, 'dòng phụ đề đè dòng trước');
+ });
+ e.captions.highlights.forEach((h, i) => { if (!ids.has(h)) add('highlight', `captions.highlights.${i}`, `chữ nhấn ${h} không có trong phụ đề`); });
+ e.sfx.forEach((s, i) => {
+ if (sfxNames && !sfxNames.includes(s.name)) add('sfx-name', `sfx.${i}`, `không có tiếng "${s.name}"`);
+ if (!inKeep(tl, s.at)) add('sfx-cut', `sfx.${i}`, `tiếng "${s.name}" ở ${s.at} s rơi vào đoạn bị bỏ`);
+ });
+ for (const g of graphicsErrors(e)) errors.push(g);
+ if (checkFiles) {
+ if (!fs.existsSync(e.proxy.file)) add('file', 'proxy.file', `không thấy proxy ${e.proxy.file}`);
+ if (e.music && !fs.existsSync(e.music.file)) add('file', 'music.file', `không thấy file nhạc ${e.music.file}`);
+ }
+ return { ok: errors.length === 0, errors, edl: e };
+}
+
+export function writeJsonSchema(file = path.join(path.dirname(fileURLToPath(import.meta.url)), 'edl.schema.json')) {
+ const schema = z.toJSONSchema(EdlSchema, { target: 'draft-2020-12', io: 'input' });
+ schema.$id = 'https://reels.lumtek.net/schema/edl-v1.json';
+ schema.title = 'LumReels Edit EDL v1';
+ schema.description = 'Bản dựng từ 1 video nguồn. Mọi mốc thời gian là giây của nguồn (đã trừ start_time).';
+ fs.writeFileSync(file, JSON.stringify(schema, null, 2) + '\n');
+ return file;
+}
+
+if (path.resolve(process.argv[1] || '') === fileURLToPath(import.meta.url)) {
+ const a = process.argv.slice(2);
+ if (a[0] === '--schema') console.log(writeJsonSchema());
+ else if (a[0]) {
+ const r = validateEdl(JSON.parse(fs.readFileSync(a[0], 'utf8')));
+ console.log(r.ok ? 'EDL hợp lệ' : r.errors.map((x) => `${x.code} ${x.path}: ${x.msg}`).join('\n'));
+ process.exit(r.ok ? 0 : 1);
+ } else console.log('node edit/edl.mjs --schema | <edl.json>');
+}
diff --git a/edit/edl.schema.json b/edit/edl.schema.json
index 21c3e98..972a6c6 100644
--- a/edit/edl.schema.json
+++ b/edit/edl.schema.json
@@ -353,6 +353,11 @@
"description": "tắt mọi chữ nhấn (chỉnh tay)",
"type": "boolean"
},
+ "off": {
+ "default": false,
+ "description": "không vẽ phụ đề (reel nhập vào: chữ đã nằm trong cảnh); vẫn giữ chữ để bật lại",
+ "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,
diff --git a/edit/http.mjs b/edit/http.mjs
index 3be897c..f3f76d4 100644
--- a/edit/http.mjs
+++ b/edit/http.mjs
@@ -7,6 +7,7 @@
// POST /api/edits → multipart (video ≤ 2 GB, music?, style, musicStyle?, content?, names?, draft?, target?)
// hoặc JSON {path, style, music?(đường dẫn|tên nhạc tổng hợp), content?, names?, draft?, target?}
// GET /api/edits/:id → trạng thái, tiến độ, log, chữ LLM đã sửa, các lần sửa
+// POST /api/edits/from-reel → {job}: Sửa tiếp trong Studio 1 reel đã dựng (giữ nguyên, tách track giọng/nhạc nếu còn)
// POST /api/edits/:id/revise → {instruction}: LLM sửa EDL theo lời, render lại, không phân tích lại
// GET /api/edits/:id/manual → những gì chỉnh tay được: dòng phụ đề (giây bản ra), nhạc, giọng, sfx, zoom, đồ hoạ
// POST /api/edits/:id/manual → JSON bản vá (edit/manual.mjs ManualSchema, kiểm chặt): dựng lại phần cần thiết → out-r<n>.mp4
@@ -27,6 +28,7 @@ import {
import { installStatus, startInstall } from './setup-run.mjs';
import { stripOf, waveOf, musicFileFor, isMusicName } from './studio-media.mjs';
import { previewGraphics } from './manual.mjs';
+import { prepareReel, ReelImportSchema } from './reel.mjs';
import { graphicsScene, GFX_RUNTIME } from './graphics.mjs';
import { loadStyle } from './planner.mjs';
import { lookOf } from './captions-hf.mjs';
@@ -248,6 +250,28 @@ window.gfxRender = gfxRender;
}
return true;
}
+ // ---- "Sửa tiếp trong Studio" từ 1 reel đã dựng (tab Dựng từ mẫu): edit giữ nguyên, tách track nếu reel còn tiếng riêng ----
+ if (p === '/api/edits/from-reel' && req.method === 'POST') {
+ const ready = editReady();
+ if (!ready.ready) { send(res, 503, { error: ready.note }); return true; }
+ let body;
+ try { body = await readBody(req, 4 * 1024); } catch { send(res, 400, { error: 'JSON không hợp lệ' }); return true; }
+ const r = ReelImportSchema.safeParse(body);
+ if (!r.success) { send(res, 400, { error: 'cần {job: "<id video>"}' }); return true; }
+ const id = newEditId(); const dir = editDir(id);
+ try {
+ fs.mkdirSync(dir, { recursive: true });
+ const pr = await prepareReel(r.data.job, dir);
+ const job = await createEdit({ id, video: pr.video, sourceName: pr.sourceName, style: 'sach-gon', music: pr.music, musicName: pr.musicName, noMusic: !pr.music,
+ content: pr.reel.content, llm: 'off', keepAll: true, reel: { ...pr.reel, split: pr.split }, script: pr.script, musicGainDb: pr.musicGainDb });
+ runEditJob(job.id).catch((e) => console.error('[edit reel]', job.id, e.message));
+ send(res, 202, editView(job.id));
+ } catch (e) {
+ try { fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }); } catch { /* bỏ qua */ }
+ send(res, Number.isInteger(e.code) ? e.code : 422, { error: e.message });
+ }
+ return true;
+ }
let m = /^\/api\/edits\/([\w-]+)$/.exec(p);
if (m && req.method === 'GET') {
const v = ID_RE.test(m[1]) && editView(m[1]);
diff --git a/edit/jobs.mjs b/edit/jobs.mjs
index 9a27b0b..1b71a9c 100644
--- a/edit/jobs.mjs
+++ b/edit/jobs.mjs
@@ -123,6 +123,7 @@ export async function createEdit(input) {
source: video, sourceName: input.sourceName || path.basename(video), sourceSeconds: +info.duration.toFixed(2),
style, music, musicName: input.musicName || (music ? path.basename(music) : null),
content, names: parseNames(input.names), draft: !!input.draft, llm: input.llm === 'off' ? 'off' : 'on', target, noMusic: !music && !!input.noMusic,
+ ...(input.keepAll ? { keepAll: true, reel: input.reel || null, script: String(input.script || '').slice(0, 4000), musicGainDb: Number.isFinite(input.musicGainDb) ? input.musicGainDb : null } : {}),
createdAt: new Date().toISOString(), error: null, out: null, pid: process.pid,
});
}
@@ -224,7 +225,7 @@ export async function runEditJob(id, { log = () => {} } = {}) {
let r;
try {
r = await editVideo(job.source, {
- id, style: job.style, music: job.music, noMusic: !!job.noMusic, content: job.content, names: job.names, draft: job.draft, llm: job.llm, target: job.target, log, progress: onProgress(id),
+ id, style: job.style, music: job.music, noMusic: !!job.noMusic, keepAll: !!job.keepAll, script: job.script, musicGainDb: job.musicGainDb, reel: job.reel, content: job.content, names: job.names, draft: job.draft, llm: job.llm, target: job.target, log, progress: onProgress(id),
});
} catch (e) { r = { ok: false, id, error: e.message }; }
const freed = cleanupEdit(id);
@@ -299,6 +300,8 @@ export function manualState(id, rev = null) {
const cleanOk = n === latest && has(CLEAN) && sig.clean === cleanSig(edl);
const mf = edl.music?.file && path.dirname(path.resolve(edl.music.file)) === path.resolve(dir) && isMusicName(path.basename(edl.music.file)) ? path.basename(edl.music.file) : null;
v.rev = n; v.latest = latest; v.readOnly = n !== latest;
+ const job = readEditJob(id);
+ v.reel = job?.reel || null; v.keepAll = !!job?.keepAll;
v.media = {
out: outOf(n) && has(outOf(n)) ? url(outOf(n)) : null, outName: outOf(n) || null,
base: baseOk ? url('base.mp4') : null, clean: cleanOk ? url(CLEAN) : null, music: mf && has(mf) ? url(mf) : null, musicFile: mf && has(mf) ? mf : null,
diff --git a/edit/manual.mjs b/edit/manual.mjs
index dcd35ea..5a5a1f9 100644
--- a/edit/manual.mjs
+++ b/edit/manual.mjs
@@ -10,6 +10,7 @@ import { MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';
import { captionCards, cardOverlaps, LOOKS, captionTop } from './captions-hf.mjs';
import { outputDuration, timelineOf, toOutputNearest, inKeep, hookDur, validateEdl, OUT } from './edl.mjs';
import { outputToSource, layoutGraphics, MIN_GRAPHIC } from './graphics.mjs';
+import { applyExtraCuts, outputCutToSource } from './planner.mjs';
export const LOOK_IDS = Object.keys(LOOKS);
export const MAX_LINES = 600;
@@ -40,6 +41,7 @@ export const ManualSchema = 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(),
+ show: z.boolean().optional(),
}).strict().optional(),
music: z.object({
source: z.union([
@@ -53,6 +55,8 @@ export const ManualSchema = z.object({
start: z.number().finite().min(0).max(600).optional(),
}).strict().optional(),
voice: z.object({ gainDb: z.number().finite().min(-12).max(12) }).strict().optional(),
+ // cắt bỏ đoạn trên track video: khoảng GIÂY BẢN RA của bản hiện tại (Studio: chọn vùng → Xoá, hoặc S tách clip rồi xoá)
+ cuts: z.object({ remove: z.array(z.object({ start: sec, end: sec }).strict()).min(1).max(50) }).strict().optional(),
sfx: z.object({ on: z.boolean() }).strict().optional(),
zooms: z.object({
remove: z.array(z.number().int().min(0).max(999)).max(200).optional(),
@@ -192,13 +196,14 @@ export function manualView(edl, state, { lookNames = {}, uploads = {} } = {}) {
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));
+ const syn = m && /music-([a-z0-9-]+)\.wav$/.exec(m.file);
+ const musicName = !m ? null : man.musicName || (/music-reel\.wav$/.test(m.file) ? 'reel' : syn && MUSIC_STYLES.includes(syn[1]) ? `synth:${syn[1]}` : path.basename(m.file));
return {
duration: dur, draft: !!state.draft, cuts: cutsOf(edl),
captions: {
// wo: giây bản ra của từng chữ (karaoke xem trước)
lines: currentLines(edl).map((l) => ({ start: l.start, end: l.end, text: lineText(l.words), wo: l.words.map((w) => w.o) })),
- edited: !!edl.captions.lines, highlights: !edl.captions.hiOff, look: edl.captions.style,
+ edited: !!edl.captions.lines, highlights: !edl.captions.hiOff, look: edl.captions.style, show: !edl.captions.off,
looks: LOOK_IDS.map((id) => ({ id, name: lookNames[id]?.name || id, nameEn: lookNames[id]?.nameEn || lookNames[id]?.name || id, hi: LOOKS[id].hi, css: lookCss(LOOKS[id]) })),
},
music: {
@@ -373,6 +378,57 @@ export function previewGraphics(edl, body, { accent, graphicsScene }) {
return { css: sc.css, html: sc.html, data: sc.data, ids: list.map((g) => g.id) };
}
+// ---- cắt bỏ đoạn trên track video (giây bản ra) -----------------------------------------------------------------------
+/**
+ * Trừ các khoảng bản ra khỏi EDL: keep (giây nguồn, không bám chữ — người dùng chọn đúng chỗ), dòng phụ đề chỉnh tay dời
+ * theo (dòng nằm trọn trong chỗ cắt thì bỏ), zoom / sfx / đồ hoạ / trích dẫn rơi vào chỗ cắt thì bỏ. Trả các khoảng nguồn
+ * (để lưu state.extraCuts: sửa bằng lời / dựng lại vẫn giữ chỗ cắt).
+ */
+function applyCuts(edl, list, { man, redo, summary, warnings }) {
+ const tl = timelineOf(edl); const dur = outputDuration(tl); const hd = hookDur(tl);
+ const rs = [];
+ for (const [a, b] of list.map((c) => [Math.max(0, Math.min(c.start, c.end)), Math.min(dur, Math.max(c.start, c.end))]).filter(([a, b]) => b - a >= 1 / 30).sort((x, y) => x[0] - y[0])) {
+ const m = rs[rs.length - 1]; if (m && a <= m[1] + 1e-3) m[1] = Math.max(m[1], b); else rs.push([a, b]);
+ }
+ if (!rs.length) throw httpErr(400, 'khoảng cắt rỗng (ngắn hơn 1 khung)');
+ const total = rs.reduce((s, [a, b]) => s + b - a, 0);
+ if (dur - total < 1) throw httpErr(400, `cắt xong chỉ còn ${(dur - total).toFixed(2)} s (cần ≥ 1 s)`);
+ if (hd > 0 && rs.some(([a]) => a < hd - 1e-3)) throw httpErr(400, `chưa cắt được trong câu móc đầu video (0–${hd.toFixed(2)} s)`);
+ const src = rs.flatMap(([a, b]) => outputCutToSource(tl, a, b, []));
+ // dời giây bản ra: điểm nằm trong chỗ cắt dồn về mép trái chỗ cắt
+ const shift = (o) => { let s = 0; for (const [a, b] of rs) { if (o >= b) s += b - a; else if (o > a) return a - s; else break; } return o - s; };
+ const prevLines = edl.captions.lines ? currentLines(edl) : null;
+ const before = { zooms: edl.zooms.length, gfx: (edl.graphics || []).length };
+ const cut = applyExtraCuts(edl, src);
+ Object.assign(edl, cut);
+ const tl2 = timelineOf(edl); const dur2 = outputDuration(tl2);
+ const inK = (t) => inKeep(tl2, t);
+ if (prevLines) {
+ const lines = [];
+ for (const l of prevLines) {
+ const a = r2(shift(l.start)); const b = r2(Math.min(dur2, shift(l.end)));
+ if (b - a < 0.1) continue;
+ let p = a;
+ const words = l.words.map((w) => { const o = r2(Math.max(p, Math.min(b - 0.02, shift(w.o)))); p = o; return { ...w, o }; });
+ lines.push({ start: a, end: b, words });
+ }
+ edl.captions.lines = lines;
+ man.lines = { sig: cutSig(edl), lines };
+ }
+ const gone = (edl.graphics || []).filter((g) => !inK(g.data?.at ?? g.start) || toOutputNearest(tl2, g.end) - toOutputNearest(tl2, g.start) < MIN_GRAPHIC - 1e-3);
+ if (gone.length) {
+ edl.graphics = edl.graphics.filter((g) => !gone.includes(g));
+ man.graphicsRemoved = [...new Set([...(man.graphicsRemoved || []), ...gone.map((g) => g.id)])];
+ }
+ if (edl.quote && (!inK(edl.quote.start) || !inK(edl.quote.end))) edl.quote = null;
+ const lostZ = before.zooms - edl.zooms.length;
+ if (lostZ) warnings.push(`${lostZ} zoom nằm trong chỗ cắt, bỏ`);
+ if (gone.length) warnings.push(`${gone.length} đồ hoạ nằm trong chỗ cắt, bỏ (${gone.map((g) => g.type).join(', ')})`);
+ redo.base = true; redo.layer = true; redo.mix = true;
+ summary.push(`cắt bỏ ${rs.length} đoạn (${rs.map(([a, b]) => `${a.toFixed(1)}–${b.toFixed(1)} s`).join(', ')}; −${total.toFixed(1)} s)`);
+ return src.map((c) => ({ start: +c.start.toFixed(3), end: +c.end.toFixed(3) }));
+}
+
// ---- á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},
@@ -414,6 +470,11 @@ export function applyPatch(edlIn, state, patch, { dir, style = null, uploads = {
}
}
+ if (patch.captions?.show !== undefined && !!edl.captions.off === patch.captions.show) {
+ if (draft) throw httpErr(409, 'bản nháp vẽ phụ đề thẳng vào nền: dựng lại bản chính rồi mới bật/tắt phụ đề');
+ edl.captions.off = !patch.captions.show; man.capsOff = edl.captions.off; redo.layer = true;
+ summary.push(patch.captions.show ? 'bật phụ đề' : 'tắt phụ đề');
+ }
if (patch.graphics?.set?.length) applyGraphicsSet(edl, patch.graphics.set, { dur, dir, style, man, redo, summary, warnings });
if (patch.graphics?.remove?.length) {
const ids = new Set(patch.graphics.remove);
@@ -484,8 +545,10 @@ export function applyPatch(edlIn, state, patch, { dir, style = null, uploads = {
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');
}
+ let extraCuts = null;
+ if (patch.cuts?.remove?.length) extraCuts = applyCuts(edl, patch.cuts.remove, { man, redo, summary, warnings });
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 };
+ return { edl, manual: man, music, redo, summary, warnings, extraCuts };
}
/**
@@ -496,6 +559,7 @@ export function applyManual(edl, man) {
const warnings = [];
if (!man) return warnings;
if (man.look && LOOKS[man.look]) edl.captions.style = man.look;
+ if (man.capsOff !== undefined) edl.captions.off = !!man.capsOff;
if (man.hiOff) edl.captions.hiOff = true;
if (man.lines) {
if (man.lines.sig === cutSig(edl)) edl.captions.lines = man.lines.lines;
diff --git a/edit/pipeline.mjs b/edit/pipeline.mjs
index 2eb115c..f073591 100644
--- a/edit/pipeline.mjs
+++ b/edit/pipeline.mjs
@@ -27,6 +27,7 @@ import { writeCaptionScene, writeGraphicScene, renderCaptionLayer, captionTop, L
import { buildEditMix } from './audio.mjs';
import { pickEncoder, videoArgs } from './encoder.mjs';
import { applyPatch, applyManual } from './manual.mjs';
+import { scriptFixes } from './reel.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, '');
@@ -89,16 +90,17 @@ export async function editVideo(video, opts = {}) {
return { ...r.result, data: JSON.parse(fs.readFileSync(analysisFile, 'utf8')) };
});
log(` ${an.words} chữ chắc + ${an.unsure} chữ không chắc · whisper ${an.seconds.words} s (${an.device || '?'}) · mặt ${an.seconds.face} s (thấy mặt ${Math.round(an.data.face.found_share * 100)}% khung)`);
- if (!an.words) throw new Error('không nghe được lời nào trong video');
+ if (!an.words && !opts.keepAll) throw new Error('không nghe được lời nào trong video');
const words = wordList(an.data);
style.hesitations = new Set(an.data.hesitations || []);
// độ dài: --target của người dùng, không có thì theo thẻ kiểu (style.target; nguồn đã ngắn thì bỏ qua như cũ)
const target = Number(opts.target) > 0 ? Math.round(Number(opts.target)) : Number(style.target) > 0 ? Math.round(style.target) : null;
if (!(Number(opts.target) > 0) && target) log(` độ dài theo kiểu: ${target} s${style.maxSec ? ` (trần ${style.maxSec} s)` : ''}`);
- const llmOn = (opts.llm || 'on') !== 'off';
+ const llmOn = (opts.llm || 'on') !== 'off' && !opts.keepAll;
let selection = null;
- const plan = await step('LLM lập EDL', async (pg) => {
+ // nhập từ reel (giữ nguyên): không LLM, không cắt; chữ whisper sửa theo lời đọc TTS của reel
+ const plan = opts.keepAll ? { proposal: { drop: [], highlights: [], zooms: [], sfx: [], fixes: scriptFixes(words, opts.script), notes: 'Nhập từ reel: giữ nguyên, không tự cắt, không tự thêm phụ đề' }, warnings: [], rounds: 0, graphics: [] } : await step('LLM lập EDL', async (pg) => {
if (target && !llmOn) warnings.push('--target cần LLM: bỏ qua (LLM tắt)');
else if (target && ing.source.duration < target * 1.15) log(` nguồn ${ing.source.duration.toFixed(0)} s đã gần ${target} s: không chọn đoạn`);
else if (target) {
@@ -138,6 +140,7 @@ export async function editVideo(video, opts = {}) {
draft: !!opts.draft, llm: opts.llm || 'on', proposal: plan.proposal, overrides: {}, extraCuts: [], revisions: [],
target, segments: selection?.segments || null, exclude: selection ? [...selection.exclude] : [], graphics: plan.graphics || [],
figures: plan.figures || [], units: plan.units || [], cutRepairs: [],
+ ...(opts.keepAll ? { keepAll: true, reel: opts.reel || null, musicGainDb: Number.isFinite(opts.musicGainDb) ? opts.musicGainDb : null } : {}),
};
fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify(state, null, 1));
let edl = await buildEdl({ id, dir, ing, analysis: an.data, words, style, state, checks, warnings, log });
@@ -168,6 +171,18 @@ export async function editVideo(video, opts = {}) {
return result;
}
+/**
+ * Reel nhập vào (giữ nguyên): giữ trọn nguồn, không zoom/sfx/móc/trích dẫn tự động, phụ đề TẮT (chữ đã nằm trong cảnh;
+ * người dùng bật trong Studio), khung không cắt (reel đã 9:16), nhạc của reel ở đúng âm lượng cũ.
+ */
+function keepWhole(edl, ing, state) {
+ const d = ing.source.duration;
+ const e = { ...edl, keep: [{ start: 0, end: +d.toFixed(3) }], removed: [], zooms: [], sfx: [], hook: null, hookText: null, quote: null, graphics: [], reframe: { mode: 'center' } };
+ e.captions = { ...edl.captions, off: true };
+ if (e.music && Number.isFinite(state.musicGainDb)) e.music = { ...e.music, gainDb: state.musicGainDb };
+ return e;
+}
+
/**
* Số trên đồ hoạ (kế hoạch theo chỉ số chữ): điền đơn vị người nói dùng (ngay sau số hoặc câu xung quanh), nghe lại
* riêng từng chỗ có số (lumedit hear), số không chắc thì không in lên đồ hoạ. Trả {graphics, figures, units}.
@@ -232,6 +247,7 @@ async function buildEdl({ id, dir, ing, analysis, words, style, state, checks, w
let edl = compileEdl({ id, ingestRes: ing, analysis, words, proposal: state.proposal, style: st, music: state.music, draft: state.draft,
exclude: state.exclude || [], graphics: state.graphics || [], restore: state.cutRepairs || [] });
const gw = edl._warnings || []; delete edl._warnings;
+ if (state.keepAll) edl = keepWhole(edl, ing, state);
const kept = gw.filter((w) => w.startsWith('không bỏ '));
edl.notes = edlNotes(edl.notes, state) + (kept.length ? ` Code giữ lại (nói liền, cắt sẽ vào giữa từ): ${kept.map((w) => w.slice('không bỏ '.length)).join('; ')}.` : '');
edl = applyExtraCuts(edl, state.extraCuts);
@@ -457,7 +473,8 @@ async function finishRender({ dir, edl, edlFile, base, rb, draft, R, outName, re
// 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, comb); const mSig = mixSig(edl);
const capEdl = comb ? edl : { ...edl, graphics: [] };
- const hasLayer = () => (comb && (edl.graphics || []).length > 0) || (!draft && (edl.captions.words.length > 0 || !!edl.hookText || !!edl.quote));
+ const capsOn = !draft && !edl.captions.off;
+ const hasLayer = () => (comb && (edl.graphics || []).length > 0) || (capsOn && (edl.captions.words.length > 0 || !!edl.hookText || !!edl.quote));
const capFresh = reuse.layer !== false && sigOk(dir, 'layer', lSig) && (!hasLayer() || fs.existsSync(layerFile));
// lớp riêng từng đồ hoạ: chỉ khoảng nó hiện, chữ ký riêng (sửa 1 đồ hoạ không render lại phụ đề / đồ hoạ khác)
const gl = comb ? [] : (edl.graphics || []).map((g) => {
@@ -475,7 +492,7 @@ async function finishRender({ dir, edl, edlFile, base, rb, draft, R, outName, re
if (!capFresh) {
if (!hasLayer()) { fs.rmSync(layerFile, { force: true, recursive: true }); overlay = null; saveSig(dir, 'layer', lSig); }
else {
- const sc = writeCaptionScene(capEdl, path.join(dir, 'captions'), { captions: !draft, accent, style });
+ const sc = writeCaptionScene(capEdl, path.join(dir, 'captions'), { captions: capsOn, accent, style });
checks.captions = { cards: sc.cards, graphics: (edl.graphics || []).length, 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, gfxLayers: comb ? 0 : gl.length };
const metaFile = path.join(dir, 'captions.meta.json');
const prev = readJson(metaFile);
@@ -743,7 +760,7 @@ export async function manualEdit(id, patch, opts = {}) {
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,
+ ...state, manual: ap.manual, music: ap.music, out: outName, ...(ap.extraCuts?.length ? { extraCuts: [...(state.extraCuts || []), ...ap.extraCuts] } : {}),
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));
diff --git a/edit/reel.mjs b/edit/reel.mjs
new file mode 100644
index 0000000..5d7efd7
--- /dev/null
+++ b/edit/reel.mjs
@@ -0,0 +1,96 @@
+// "Sửa tiếp trong Studio": nhập 1 reel đã dựng xong (tab Dựng từ mẫu, jobs/<id>/) thành 1 bản Edit kiểu "giữ nguyên":
+// không LLM cắt, không tự thêm phụ đề (chữ đã nằm trong cảnh), vẫn chép lời (whisper) để có khối chữ nếu người dùng bật
+// phụ đề, chữ sửa theo chính lời đọc (TTS) của reel. Reel còn giữ tiếng riêng (out.silent.mp4 + scene/audio.json + audio/)
+// thì nhập TÁCH TRACK: nguồn = hình không tiếng + giọng/tiếng động (trộn lại không nhạc), nhạc = file nhạc của reel → chỉnh
+// được âm lượng / thay bài thật. Không có thì nhập out.mp4 nguyên (nhạc đã trộn sẵn).
+import fs from 'node:fs';
+import path from 'node:path';
+import { z } from 'zod';
+import { jobDir, readJob } from '../generator/jobs.mjs';
+import { buildMix } from '../engine/audio/mix.mjs';
+import { run } from '../engine/lib.mjs';
+
+const httpErr = (code, msg) => Object.assign(new Error(msg), { code });
+export const ReelImportSchema = z.object({ job: z.string().regex(/^[\w-]{1,80}$/) }).strict();
+
+/** Chuẩn hoá để so chữ whisper với lời đọc: thường, bỏ dấu, bỏ dấu câu. */
+const norm = (w) => String(w).toLowerCase().normalize('NFD').replace(/\p{M}/gu, '').replace(/đ/g, 'd').replace(/[^\p{L}\p{N}]/gu, '');
+const strip = (w) => String(w).replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, '');
+
+/**
+ * Sửa chữ whisper theo lời đọc thật (kịch bản TTS): dóng hàng 2 dãy chữ (quy hoạch động, khớp khi giống sau chuẩn hoá),
+ * chữ whisper thế chỗ 1-1 cho chữ kịch bản (khác chữ) hoặc chỉ sai dấu/hoa → fix {word, text}. words: [{i, w}].
+ */
+export function scriptFixes(words, script) {
+ const S = String(script || '').split(/\s+/).map(strip).filter(Boolean);
+ const W = words.map((w) => ({ i: w.i, w: strip(w.w) })).filter((w) => w.w);
+ const n = W.length; const m = S.length;
+ if (!n || !m || n * m > 4e6) return [];
+ const D = Array.from({ length: n + 1 }, () => new Int32Array(m + 1));
+ for (let i = 0; i <= n; i++) D[i][0] = i;
+ for (let j = 0; j <= m; j++) D[0][j] = j;
+ for (let i = 1; i <= n; i++) {
+ for (let j = 1; j <= m; j++) {
+ const sub = norm(W[i - 1].w) === norm(S[j - 1]) ? 0 : 1;
+ D[i][j] = Math.min(D[i - 1][j - 1] + sub, D[i - 1][j] + 1, D[i][j - 1] + 1);
+ }
+ }
+ const fixes = [];
+ let i = n; let j = m;
+ while (i > 0 && j > 0) {
+ const sub = norm(W[i - 1].w) === norm(S[j - 1]) ? 0 : 1;
+ if (D[i][j] === D[i - 1][j - 1] + sub) {
+ const w = W[i - 1]; const s = S[j - 1];
+ if (w.w !== s) fixes.push({ word: w.i, text: s });
+ i--; j--;
+ } else if (D[i][j] === D[i - 1][j] + 1) i--; else j--;
+ }
+ return fixes.reverse();
+}
+
+/**
+ * Chuẩn bị file cho bản Edit từ reel (chưa chạy pipeline). Trả {video, sourceName, music, musicName, musicGainDb,
+ * script, reel, split}. dir: thư mục edit mới (đã tạo).
+ */
+export async function prepareReel(jobId, dir, { log = () => {} } = {}) {
+ const job = readJob(jobId);
+ if (!job) throw httpErr(404, 'không thấy video ' + jobId);
+ if (job.status !== 'done') throw httpErr(409, 'video này chưa dựng xong');
+ const jd = jobDir(jobId);
+ const out = path.join(jd, job.output?.mp4 || 'out.mp4');
+ if (!fs.existsSync(out)) throw httpErr(409, 'video này không còn file MP4');
+ let spec = null; try { spec = JSON.parse(fs.readFileSync(path.join(jd, 'scene', 'audio.json'), 'utf8')); } catch { /* reel không có tiếng tách */ }
+ const silent = path.join(jd, 'out.silent.mp4');
+ const script = (spec?.voice?.lines || []).slice().sort((a, b) => a.t - b.t).map((l) => String(l.text || '').trim()).filter(Boolean).join(' ').slice(0, 4000);
+ const title = String(job.templateTitle || job.templateId || jobId).slice(0, 80);
+ const reel = { id: jobId, title, templateId: job.templateId || null, mp4: `/jobs/${jobId}/${path.basename(out)}`, content: String(job.content || '').slice(0, 400) };
+ const base = { sourceName: `${title} · ${jobId}.mp4`, script, reel };
+ const musicFile = spec?.music ? fs.readdirSync(path.join(jd, 'audio')).find((f) => f.startsWith(`music-${spec.music.style}-`) && f.endsWith('.wav')) : null;
+ if (!fs.existsSync(silent) || !spec) {
+ log('reel không còn tiếng tách: nhập MP4 nguyên (nhạc đã trộn sẵn)');
+ return { ...base, video: out, music: null, musicName: null, musicGainDb: null, split: false };
+ }
+ // giọng + tiếng động, không nhạc: trộn lại từ file giọng đã có (chép thư mục audio để dùng cache giọng, không đọc lại TTS)
+ const work = path.join(dir, 'reel-audio');
+ fs.cpSync(path.join(jd, 'audio'), work, { recursive: true });
+ for (const f of ['mix.wav', 'premix.wav']) fs.rmSync(path.join(work, f), { force: true });
+ const r0 = await run('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', silent]);
+ const duration = parseFloat(r0.out);
+ if (!(duration > 0)) throw httpErr(422, 'không đọc được độ dài video reel');
+ let voiceWav = null;
+ if (spec.voice?.lines?.length || spec.sfx?.length) {
+ const mix = await buildMix(path.join(jd, 'scene'), { duration, workDir: work, log, spec: { ...spec, music: null }, seedKey: jobId });
+ voiceWav = mix.wav;
+ }
+ const video = path.join(dir, 'reel.mp4');
+ const args = ['-hide_banner', '-y', '-i', silent];
+ if (voiceWav) args.push('-i', voiceWav); else args.push('-f', 'lavfi', '-t', String(duration), '-i', 'anullsrc=r=48000:cl=stereo');
+ args.push('-map', '0:v:0', '-map', '1:a:0', '-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-shortest', '-movflags', '+faststart', video);
+ const r = await run('ffmpeg', args);
+ if (r.code !== 0) throw httpErr(422, 'ghép hình + giọng của reel lỗi: ' + r.out.trim().split(/\r?\n/).pop());
+ let music = null;
+ if (musicFile) { music = path.join(dir, 'music-reel.wav'); fs.copyFileSync(path.join(jd, 'audio', musicFile), music); }
+ const gain = spec.music ? (spec.music.gain ?? (spec.voice?.lines?.length ? -12 : -6)) : null;
+ fs.rmSync(work, { recursive: true, force: true });
+ return { ...base, video, music, musicName: music ? `nhạc của reel (${spec.music.style})` : null, musicGainDb: gain == null ? null : Math.max(-40, Math.min(0, gain)), split: true };
+}
diff --git a/edit/studio-media.mjs b/edit/studio-media.mjs
index 0476637..7402e51 100644
--- a/edit/studio-media.mjs
+++ b/edit/studio-media.mjs
@@ -1,117 +1,117 @@
-// Phương tiện cho Studio (timeline trình edit): dải ảnh khung (sprite) của từng bản ra và đỉnh sóng của bài nhạc.
-// Sinh bằng ffmpeg, cache theo bản: strip-<out>.jpg + strip-<out>.json trong edits/<id>/, đỉnh sóng giữ trong RAM
-// theo (file, mtime). Chỉ đọc file trong thư mục edit (tên file kiểm bằng regex, không nhận đường dẫn).
-import fs from 'node:fs';
-import path from 'node:path';
-import { spawn } from 'node:child_process';
-import { MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';
-
-export const OUT_RE = /^out(-r\d{1,4})?\.mp4$/;
-const TILE_W = 54; const TILE_H = 96; // 9:16
-const MAX_TILES = 240;
-const httpErr = (code, msg) => Object.assign(new Error(msg), { code });
-
-function ff(args, { binary = false, timeoutMs = 120000 } = {}) {
- return new Promise((resolve, reject) => {
- const p = spawn('ffmpeg', ['-hide_banner', '-loglevel', 'error', ...args], { windowsHide: true });
- const out = []; let err = '';
- const timer = setTimeout(() => { p.kill('SIGKILL'); reject(new Error('ffmpeg quá thời gian')); }, timeoutMs);
- p.stdout.on('data', (d) => out.push(d));
- p.stderr.on('data', (d) => { err += d; if (err.length > 4000) err = err.slice(-4000); });
- p.on('error', (e) => { clearTimeout(timer); reject(e); });
- p.on('close', (code) => {
- clearTimeout(timer);
- if (code !== 0) reject(new Error('ffmpeg lỗi: ' + err.trim().split(/\r?\n/).pop()));
- else resolve(binary ? Buffer.concat(out) : Buffer.concat(out).toString('utf8'));
- });
- });
-}
-
-async function durationOf(file) {
- const r = await new Promise((resolve) => {
- const p = spawn('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', file], { windowsHide: true });
- let o = ''; p.stdout.on('data', (d) => { o += d; }); p.on('close', () => resolve(o)); p.on('error', () => resolve(''));
- });
- const d = parseFloat(r);
- if (!Number.isFinite(d) || d <= 0) throw httpErr(422, 'không đọc được độ dài ' + path.basename(file));
- return d;
-}
-
-const pending = new Map();
-/** Dải ảnh khung của 1 bản ra: {url, n, every, tileW, tileH, seconds}. Sinh 1 lần (ffmpeg fps + tile), lần sau đọc cache. */
-export function stripOf(dir, id, out) {
- if (!OUT_RE.test(String(out))) throw httpErr(400, 'tên bản ra không hợp lệ');
- const video = path.join(dir, out);
- if (!fs.existsSync(video)) throw httpErr(404, 'không thấy ' + out);
- const base = 'strip-' + out.replace(/\.mp4$/, '');
- const jpg = path.join(dir, base + '.jpg'); const meta = path.join(dir, base + '.json');
- const url = (m) => ({ ...m, url: `/edits/${id}/${base}.jpg?v=${Math.round(fs.statSync(jpg).mtimeMs)}` });
- try {
- const m = JSON.parse(fs.readFileSync(meta, 'utf8'));
- if (fs.existsSync(jpg) && fs.statSync(jpg).mtimeMs >= fs.statSync(video).mtimeMs - 1) return Promise.resolve(url(m));
- } catch { /* chưa có */ }
- const key = jpg;
- if (pending.has(key)) return pending.get(key);
- const job = (async () => {
- const seconds = await durationOf(video);
- const n = Math.max(1, Math.min(MAX_TILES, Math.ceil(seconds / 0.5)));
- const every = seconds / n;
- const tmp = jpg + '.part.jpg';
- // mỗi ô lấy khung ở giữa khoảng của nó; tile 1 hàng n cột
- await ff(['-y', '-i', video, '-vf', `fps=1/${every.toFixed(4)}:start_time=${(every / 2).toFixed(4)},scale=${TILE_W}:${TILE_H}:force_original_aspect_ratio=increase,crop=${TILE_W}:${TILE_H},tile=${n}x1`, '-frames:v', '1', '-q:v', '5', tmp]);
- fs.renameSync(tmp, jpg);
- const m = { n, every: +every.toFixed(4), tileW: TILE_W, tileH: TILE_H, seconds: +seconds.toFixed(3) };
- fs.writeFileSync(meta, JSON.stringify(m));
- return url(m);
- })().finally(() => pending.delete(key));
- pending.set(key, job);
- return job;
-}
-
-const NAME_RE = /^music(-[a-z0-9-]{1,30})?\.(wav|mp3|m4a|aac|ogg|flac|opus)$|^music-up-\d{1,4}\.(mp3|wav|m4a|aac|ogg|flac|opus)$/;
-/** Tên file nhạc trong thư mục edit cho 1 nguồn chỉnh tay ('keep' = nhạc của bản hiện tại). Nhạc tổng hợp chưa có thì sinh. */
-export function musicFileFor(dir, source, currentFile) {
- const s = String(source || '');
- if (s === 'keep') {
- if (!currentFile) throw httpErr(404, 'bản này không có nhạc');
- const name = path.basename(currentFile);
- if (path.resolve(path.dirname(currentFile)) !== path.resolve(dir) || !NAME_RE.test(name)) throw httpErr(404, 'nhạc của bản này nằm ngoài thư mục edit');
- return name;
- }
- let m = /^synth:([a-z0-9-]{1,30})$/.exec(s);
- if (m) {
- if (!MUSIC_STYLES.includes(m[1])) throw httpErr(400, `không có nhạc tổng hợp "${m[1]}"`);
- const name = `music-${m[1]}.wav`;
- if (!fs.existsSync(path.join(dir, name))) writeMusic(m[1], path.join(dir, name), 60, 1);
- return name;
- }
- m = /^upload:(music-up-\d{1,4}\.(mp3|wav|m4a|aac|ogg|flac|opus))$/.exec(s);
- if (m) { if (!fs.existsSync(path.join(dir, m[1]))) throw httpErr(404, 'chưa tải lên ' + m[1]); return m[1]; }
- throw httpErr(400, 'nguồn nhạc không hợp lệ');
-}
-export const isMusicName = (n) => NAME_RE.test(String(n));
-
-const waves = new Map(); // file|mtime → {rate, peaks, seconds}
-export const WAVE_RATE = 25; // đỉnh mỗi giây
-/** Đỉnh sóng (0..1, trị tuyệt đối lớn nhất mỗi 1/25 s) của 1 file nhạc trong thư mục edit. */
-export async function waveOf(dir, name) {
- if (!NAME_RE.test(name)) throw httpErr(400, 'tên nhạc không hợp lệ');
- const f = path.join(dir, name);
- const st = fs.statSync(f);
- const key = `${f}|${st.mtimeMs}`;
- if (waves.has(key)) return waves.get(key);
- const sr = 4000;
- const pcm = await ff(['-i', f, '-ac', '1', '-ar', String(sr), '-t', '600', '-f', 's16le', '-acodec', 'pcm_s16le', 'pipe:1'], { binary: true });
- const n = Math.floor(pcm.length / 2); const per = sr / WAVE_RATE;
- const peaks = [];
- let top = 1;
- for (let i = 0; i < n; i += per) {
- let mx = 0;
- for (let j = i; j < Math.min(n, i + per); j++) { const v = Math.abs(pcm.readInt16LE(j * 2)); if (v > mx) mx = v; }
- peaks.push(mx); if (mx > top) top = mx;
- }
- const r = { rate: WAVE_RATE, seconds: +(n / sr).toFixed(3), peaks: peaks.map((x) => Math.round((x / top) * 100) / 100) };
- if (waves.size > 30) waves.delete(waves.keys().next().value);
- waves.set(key, r);
- return r;
-}
+// Phương tiện cho Studio (timeline trình edit): dải ảnh khung (sprite) của từng bản ra và đỉnh sóng của bài nhạc.
+// Sinh bằng ffmpeg, cache theo bản: strip-<out>.jpg + strip-<out>.json trong edits/<id>/, đỉnh sóng giữ trong RAM
+// theo (file, mtime). Chỉ đọc file trong thư mục edit (tên file kiểm bằng regex, không nhận đường dẫn).
+import fs from 'node:fs';
+import path from 'node:path';
+import { spawn } from 'node:child_process';
+import { MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';
+
+export const OUT_RE = /^out(-r\d{1,4})?\.mp4$/;
+const TILE_W = 54; const TILE_H = 96; // 9:16
+const MAX_TILES = 240;
+const httpErr = (code, msg) => Object.assign(new Error(msg), { code });
+
+function ff(args, { binary = false, timeoutMs = 120000 } = {}) {
+ return new Promise((resolve, reject) => {
+ const p = spawn('ffmpeg', ['-hide_banner', '-loglevel', 'error', ...args], { windowsHide: true });
+ const out = []; let err = '';
+ const timer = setTimeout(() => { p.kill('SIGKILL'); reject(new Error('ffmpeg quá thời gian')); }, timeoutMs);
+ p.stdout.on('data', (d) => out.push(d));
+ p.stderr.on('data', (d) => { err += d; if (err.length > 4000) err = err.slice(-4000); });
+ p.on('error', (e) => { clearTimeout(timer); reject(e); });
+ p.on('close', (code) => {
+ clearTimeout(timer);
+ if (code !== 0) reject(new Error('ffmpeg lỗi: ' + err.trim().split(/\r?\n/).pop()));
+ else resolve(binary ? Buffer.concat(out) : Buffer.concat(out).toString('utf8'));
+ });
+ });
+}
+
+async function durationOf(file) {
+ const r = await new Promise((resolve) => {
+ const p = spawn('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', file], { windowsHide: true });
+ let o = ''; p.stdout.on('data', (d) => { o += d; }); p.on('close', () => resolve(o)); p.on('error', () => resolve(''));
+ });
+ const d = parseFloat(r);
+ if (!Number.isFinite(d) || d <= 0) throw httpErr(422, 'không đọc được độ dài ' + path.basename(file));
+ return d;
+}
+
+const pending = new Map();
+/** Dải ảnh khung của 1 bản ra: {url, n, every, tileW, tileH, seconds}. Sinh 1 lần (ffmpeg fps + tile), lần sau đọc cache. */
+export function stripOf(dir, id, out) {
+ if (!OUT_RE.test(String(out))) throw httpErr(400, 'tên bản ra không hợp lệ');
+ const video = path.join(dir, out);
+ if (!fs.existsSync(video)) throw httpErr(404, 'không thấy ' + out);
+ const base = 'strip-' + out.replace(/\.mp4$/, '');
+ const jpg = path.join(dir, base + '.jpg'); const meta = path.join(dir, base + '.json');
+ const url = (m) => ({ ...m, url: `/edits/${id}/${base}.jpg?v=${Math.round(fs.statSync(jpg).mtimeMs)}` });
+ try {
+ const m = JSON.parse(fs.readFileSync(meta, 'utf8'));
+ if (fs.existsSync(jpg) && fs.statSync(jpg).mtimeMs >= fs.statSync(video).mtimeMs - 1) return Promise.resolve(url(m));
+ } catch { /* chưa có */ }
+ const key = jpg;
+ if (pending.has(key)) return pending.get(key);
+ const job = (async () => {
+ const seconds = await durationOf(video);
+ const n = Math.max(1, Math.min(MAX_TILES, Math.ceil(seconds / 0.5)));
+ const every = seconds / n;
+ const tmp = jpg + '.part.jpg';
+ // mỗi ô lấy khung ở giữa khoảng của nó; tile 1 hàng n cột
+ await ff(['-y', '-i', video, '-vf', `tpad=stop_mode=clone:stop_duration=${(every + 0.5).toFixed(2)},fps=1/${every.toFixed(4)}:start_time=${(every / 2).toFixed(4)},scale=${TILE_W}:${TILE_H}:force_original_aspect_ratio=increase,crop=${TILE_W}:${TILE_H},tile=${n}x1`, '-frames:v', '1', '-q:v', '5', tmp]);
+ fs.renameSync(tmp, jpg);
+ const m = { n, every: +every.toFixed(4), tileW: TILE_W, tileH: TILE_H, seconds: +seconds.toFixed(3) };
+ fs.writeFileSync(meta, JSON.stringify(m));
+ return url(m);
+ })().finally(() => pending.delete(key));
+ pending.set(key, job);
+ return job;
+}
+
+const NAME_RE = /^music(-[a-z0-9-]{1,30})?\.(wav|mp3|m4a|aac|ogg|flac|opus)$|^music-up-\d{1,4}\.(mp3|wav|m4a|aac|ogg|flac|opus)$/;
+/** Tên file nhạc trong thư mục edit cho 1 nguồn chỉnh tay ('keep' = nhạc của bản hiện tại). Nhạc tổng hợp chưa có thì sinh. */
+export function musicFileFor(dir, source, currentFile) {
+ const s = String(source || '');
+ if (s === 'keep') {
+ if (!currentFile) throw httpErr(404, 'bản này không có nhạc');
+ const name = path.basename(currentFile);
+ if (path.resolve(path.dirname(currentFile)) !== path.resolve(dir) || !NAME_RE.test(name)) throw httpErr(404, 'nhạc của bản này nằm ngoài thư mục edit');
+ return name;
+ }
+ let m = /^synth:([a-z0-9-]{1,30})$/.exec(s);
+ if (m) {
+ if (!MUSIC_STYLES.includes(m[1])) throw httpErr(400, `không có nhạc tổng hợp "${m[1]}"`);
+ const name = `music-${m[1]}.wav`;
+ if (!fs.existsSync(path.join(dir, name))) writeMusic(m[1], path.join(dir, name), 60, 1);
+ return name;
+ }
+ m = /^upload:(music-up-\d{1,4}\.(mp3|wav|m4a|aac|ogg|flac|opus))$/.exec(s);
+ if (m) { if (!fs.existsSync(path.join(dir, m[1]))) throw httpErr(404, 'chưa tải lên ' + m[1]); return m[1]; }
+ throw httpErr(400, 'nguồn nhạc không hợp lệ');
+}
+export const isMusicName = (n) => NAME_RE.test(String(n));
+
+const waves = new Map(); // file|mtime → {rate, peaks, seconds}
+export const WAVE_RATE = 25; // đỉnh mỗi giây
+/** Đỉnh sóng (0..1, trị tuyệt đối lớn nhất mỗi 1/25 s) của 1 file nhạc trong thư mục edit. */
+export async function waveOf(dir, name) {
+ if (!NAME_RE.test(name)) throw httpErr(400, 'tên nhạc không hợp lệ');
+ const f = path.join(dir, name);
+ const st = fs.statSync(f);
+ const key = `${f}|${st.mtimeMs}`;
+ if (waves.has(key)) return waves.get(key);
+ const sr = 4000;
+ const pcm = await ff(['-i', f, '-ac', '1', '-ar', String(sr), '-t', '600', '-f', 's16le', '-acodec', 'pcm_s16le', 'pipe:1'], { binary: true });
+ const n = Math.floor(pcm.length / 2); const per = sr / WAVE_RATE;
+ const peaks = [];
+ let top = 1;
+ for (let i = 0; i < n; i += per) {
+ let mx = 0;
+ for (let j = i; j < Math.min(n, i + per); j++) { const v = Math.abs(pcm.readInt16LE(j * 2)); if (v > mx) mx = v; }
+ peaks.push(mx); if (mx > top) top = mx;
+ }
+ const r = { rate: WAVE_RATE, seconds: +(n / sr).toFixed(3), peaks: peaks.map((x) => Math.round((x / top) * 100) / 100) };
+ if (waves.size > 30) waves.delete(waves.keys().next().value);
+ waves.set(key, r);
+ return r;
+}
diff --git a/edit/test/studio-check.mjs b/edit/test/studio-check.mjs
index 4901c10..6aaae5c 100644
--- a/edit/test/studio-check.mjs
+++ b/edit/test/studio-check.mjs
@@ -8,6 +8,7 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { parseManual, applyPatch, applyManual, manualView, changedLines } from '../manual.mjs';
+import { scriptFixes, ReelImportSchema } from '../reel.mjs';
import { baseSig, cleanSig, glassItems, gfxWindow, gfxSig, dirtyRanges } from '../pipeline.mjs';
import { validateEdl } from '../edl.mjs';
@@ -125,6 +126,41 @@ fs.rmSync(tmp, { recursive: true, force: true });
check(dirtyRanges(prev, many) === null, 'đổi > 55% thời lượng → render cả lớp');
}
+// ---- mục 9: cắt bỏ đoạn trên track video, bật/tắt phụ đề, sửa chữ theo kịch bản reel ----
+{
+ const e9 = JSON.parse(JSON.stringify(edl));
+ // bản ra: [0.5–7] → 0–6.5, [8–13.5] → 6.5–12; dòng chỉnh tay để kiểm dời giờ
+ const v9 = manualView(e9, state);
+ const lines9 = v9.captions.lines.map((l) => ({ start: l.start, end: l.end, text: l.text }));
+ const base9 = applyPatch(e9, state, parseManual({ captions: { lines: lines9.map((l, k) => (k === 0 ? { ...l, text: l.text + ' a' } : l)) } }), { dir: os.tmpdir() }).edl;
+ const lv = manualView(base9, state).captions.lines;
+ const c = applyPatch(base9, state, parseManual({ cuts: { remove: [{ start: 2, end: 3 }] } }), { dir: os.tmpdir() });
+ const tl9 = c.edl.keep.map((k) => [k.start, k.end]);
+ check(JSON.stringify(tl9) === JSON.stringify([[0.5, 2.5], [3.5, 7], [8, 13.5]]), `cắt 2–3 s bản ra → keep ${JSON.stringify(tl9)}`);
+ check(c.redo.base && c.redo.layer && c.redo.mix && JSON.stringify(c.extraCuts) === JSON.stringify([{ start: 2.5, end: 3.5 }]), `cắt → dựng lại nền + chữ + tiếng; lưu khoảng nguồn ${JSON.stringify(c.extraCuts)}`);
+ const after = manualView(c.edl, state);
+ check(Math.abs(after.duration - 11) < 0.01, `bản ra 12 → ${after.duration} s`);
+ const l0 = lv.find((l) => l.start >= 3); const l1 = after.captions.lines.find((l) => l.text === l0.text);
+ check(!!l1 && Math.abs(l1.start - (l0.start - 1)) < 0.02, `dòng phụ đề sau chỗ cắt dời lên 1 s (${l0.start} → ${l1?.start})`);
+ const lc = lv[2]; const c2 = applyPatch(base9, state, parseManual({ cuts: { remove: [{ start: lc.start, end: lc.end }] } }), { dir: os.tmpdir() });
+ const after2 = manualView(c2.edl, state); const inside = 1;
+ check(!after2.captions.lines.some((l) => l.text === lc.text) && after2.captions.lines.length === lv.length - inside, `dòng nằm trọn trong chỗ cắt bị bỏ (${lv.length} → ${after2.captions.lines.length}, bỏ dòng \"${lc.text}\")`);
+ check(validateEdl(c.edl, { checkFiles: false }).ok, 'EDL sau cắt hợp lệ');
+ check(throws(() => applyPatch(e9, state, parseManual({ cuts: { remove: [{ start: 0, end: 11.5 }] } }), { dir: os.tmpdir() }), 400, /còn/), 'cắt gần hết (còn < 1 s) → 400');
+ check(throws(() => parseManual({ cuts: { remove: [] } }), 400), 'cuts rỗng → 400');
+ check(throws(() => parseManual({ cuts: { remove: [{ start: 1, end: 2, x: 1 }] } }), 400), 'cuts khoá lạ → 400');
+ const re = JSON.parse(JSON.stringify(edl)); applyManual(re, c.manual);
+ const off = applyPatch(e9, state, parseManual({ captions: { show: false } }), { dir: os.tmpdir() });
+ check(off.edl.captions.off === true && off.redo.layer && !off.redo.base && manualView(off.edl, state).captions.show === false, 'tắt phụ đề → captions.off, chỉ lớp chữ');
+ const on = applyPatch(off.edl, state, parseManual({ captions: { show: true } }), { dir: os.tmpdir() });
+ check(on.edl.captions.off === false && /bật phụ đề/.test(on.summary.join()), 'bật lại phụ đề');
+ const re2 = JSON.parse(JSON.stringify(edl)); applyManual(re2, off.manual);
+ check(re2.captions.off === true, 'dựng lại giữ trạng thái tắt phụ đề');
+ const fx = scriptFixes([{ i: 0, w: 'Go' }, { i: 1, w: 'chu.' }, { i: 2, w: 'Chọn' }, { i: 3, w: 'mẫu' }, { i: 4, w: 'reo' }, { i: 5, w: 'video.' }], 'Gõ chữ. Chọn mẫu. Ra video.');
+ check(JSON.stringify(fx) === JSON.stringify([{ word: 0, text: 'Gõ' }, { word: 1, text: 'chữ' }, { word: 4, text: 'Ra' }]), `sửa chữ whisper theo lời đọc reel: ${JSON.stringify(fx)}`);
+ check(ReelImportSchema.safeParse({ job: '../x' }).success === false && ReelImportSchema.safeParse({ job: 'abc-1', x: 1 }).success === false, 'nhập reel: id lạ / khoá lạ → từ chối');
+}
+
// ---- REST ----
const PORT = Number(process.argv[2]); const ID = process.argv[3];
if (PORT) {
@@ -163,6 +199,10 @@ if (PORT) {
r = await req({ method: 'HEAD', p: `/edits/${ID}/base.mp4` }); check(r.code === 200 || r.code === 404, `base.mp4 phục vụ được khi có (${r.code})`);
r = await req({ method: 'POST', p: `/api/edits/${ID}/manual`, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ zooms: { add: [{ at: 0.01, dur: 8, scale: 1.1, kind: 'push' }, { at: 0.02, dur: 8, scale: 1.1, kind: 'push' }] } }) });
check(r.code === 400, `zoom thêm chồng nhau → 400 đồng bộ, không xếp hàng (${r.code})`);
+ r = await req({ method: 'POST', p: '/api/edits/from-reel', headers: { 'Content-Type': 'application/json' }, body: '{"job":"../../etc"}' }); check(r.code === 400, `nhập reel: id có ../ → 400 (${r.code})`);
+ r = await req({ method: 'POST', p: '/api/edits/from-reel', headers: { 'Content-Type': 'application/json' }, body: '{"job":"khong-co-video"}' }); check(r.code === 404, `nhập reel: video không có → 404 (${r.code})`);
+ r = await req({ method: 'POST', p: '/api/edits/from-reel', headers: { 'Content-Type': 'application/json', Origin: 'https://evil.example' }, body: '{"job":"x"}' }); check(r.code === 403, `nhập reel từ Origin lạ → 403 (${r.code})`);
+ r = await req({ method: 'POST', p: `/api/edits/${ID}/manual`, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ cuts: { remove: [{ start: 0, end: 3600 }] } }) }); check(r.code === 400, `cắt hết video → 400 đồng bộ (${r.code})`);
r = await req({ method: 'POST', p: `/api/edits/${ID}/manual`, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ graphics: { set: [{ id: 'khong-co', end: 3 }] } }) });
check(r.code === 400, `đồ hoạ không có → 400 (${r.code})`);
}
diff --git a/server/public/app.js b/server/public/app.js
index 29e5449..f46ec89 100644
--- a/server/public/app.js
+++ b/server/public/app.js
@@ -1,584 +1,585 @@
-// UI 1 trang: lưới mẫu, ô nội dung, danh sách job. Không framework. Chữ giao diện lấy từ i18n.js (window.I18N).
-(() => {
- const $ = (s, el = document) => el.querySelector(s);
- const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
- const I = window.I18N;
- const t = (k, v) => I.t(k, v);
- const status = (s) => (['scheduled', 'queued', 'generating', 'waiting_agent', 'previewing', 'rendering', 'done', 'error'].includes(s) ? t('st.' + s) : s);
- const RUNNING = ['queued', 'generating', 'previewing', 'rendering'];
- const CATS = ['faceless', 'ads', 'multi-style', 'viet-nam'];
- const catName = (c) => (CATS.includes(c) ? t('cat.' + c) : c);
- // Nhãn nguồn của mẫu (L13): gốc / của tôi (tự tạo) / cộng đồng (gói nhập). Chữ của gói chỉ vào textContent (L9).
- const SOURCES = ['builtin', 'local', 'pack'];
- const srcOf = (x) => (SOURCES.includes(x?.source) ? x.source : 'builtin');
- const srcLabel = (x) => t('src.' + srcOf(x));
- /** Tạo phần tử: props {class, text, attrs:{}, data:{}}; con là phần tử hoặc chuỗi (thành nút chữ). */
- function h(tag, props = {}, ...kids) {
- const el = document.createElement(tag);
- if (props.class) el.className = props.class;
- if (props.text != null) el.textContent = props.text;
- for (const [k, v] of Object.entries(props.attrs || {})) if (v != null && v !== false) el.setAttribute(k, v === true ? '' : String(v));
- for (const [k, v] of Object.entries(props.data || {})) el.dataset[k] = String(v);
- for (const c of kids.flat()) if (c != null && c !== false) el.append(c instanceof Node ? c : document.createTextNode(String(c)));
- return el;
- }
- const srcBadge = (x) => h('span', { class: 'src src-' + srcOf(x), text: srcLabel(x) });
- const modeLabel = (m) => ({ auto: t('modeLabel.auto'), api: 'Claude API', claude: 'Claude Code', manual: t('modeLabel.manual') }[m]);
- const fmtTime = (iso) => new Date(iso).toLocaleString(I.locale, { hour: '2-digit', minute: '2-digit', day: '2-digit', month: '2-digit', year: 'numeric' });
- // datetime-local trả giờ máy không múi giờ → đổi sang ISO có múi giờ để server hiểu đúng.
- const runAtValue = () => { const v = $('#runAt').value; return v ? new Date(v).toISOString() : undefined; };
-
- // Thời lượng: số giây (90, 90s) hoặc phút:giây (1:30). Cùng luật với generator/jobs.mjs parseDuration.
- const DUR_MIN = 3, DUR_MAX = 600;
- function parseDur(v) {
- const s0 = String(v ?? '').trim().toLowerCase().replace(/\s+/g, '');
- if (!s0) return { error: t('dur.errEmpty') };
- let m, s;
- if ((m = /^(\d{1,4})(?:s|giây|giay)?$/.exec(s0))) s = Number(m[1]);
- else if ((m = /^(\d{1,2}):([0-5]\d)$/.exec(s0))) s = Number(m[1]) * 60 + Number(m[2]);
- else if ((m = /^(\d{1,2})(?:m|p|phút|phut)$/.exec(s0))) s = Number(m[1]) * 60;
- else return { error: t('dur.errFmt') };
- if (s < DUR_MIN) return { error: t('dur.errMin') };
- if (s > DUR_MAX) return { error: t('dur.errMax') };
- return { s };
- }
- const fmtDur = (s) => (s < 60 ? `${s}s` : `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`);
- // Khoảng thời gian ước tính: "40–120 giây", "4–11 phút", "2–5 giờ"… (đơn vị theo đầu trên)
- const dec = (x) => x.toFixed(1).replace('.', t('num.dec'));
- const fmtRange = (a, b) => (b < 120 ? `${Math.round(a)}–${Math.round(b)} ${t('unit.sec')}`
- : b < 7200 ? `${Math.max(1, Math.round(a / 60))}–${Math.round(b / 60)} ${t('unit.min')}` : `${dec(a / 3600)}–${dec(b / 3600)} ${t('unit.hour')}`);
- const durS = () => parseDur($('#duration').value).s;
-
- let templates = [];
- let templatesState = 'loading'; // loading | ok | error
- // Mẫu đang chọn (theo thứ tự bấm). Chế độ thường: tối đa 1. "Chọn nhiều mẫu": tối đa MAX_PICK, mỗi mẫu 1 job.
- const MAX_PICK = 12;
- let picks = [];
- let multi = false;
- const one = () => (picks.length === 1 ? picks[0] : null);
- const pickIndex = (id) => picks.findIndex((x) => x.id === id);
- let cat = '';
- let srcFilter = ''; // '' | 'local' | 'pack' (chip "Của tôi" / "Cộng đồng")
- let pollTimer = null;
- const JOB_PAGE = 6;
- let showAll = false;
- let allJobsCount = 0;
-
- // ---------- bản mới ----------
- let update = null;
- function renderUpdate() {
- const box = $('#update-banner');
- const u = update;
- if (!box || !u) return;
- const tx = box.querySelector('.ub-text');
- tx.textContent = '';
- // u.changes[0] là tiêu đề commit (dữ liệu git), giữ nguyên
- tx.append(t('update.text', { n: u.behind, first: u.changes && u.changes[0] ? u.changes[0] : '' }));
- const c = document.createElement('code'); c.textContent = 'npm start';
- tx.append(c, t('update.after'));
- }
- async function checkVersion(retry = 3) {
- let d;
- try { d = await (await fetch('/api/version')).json(); } catch { return; }
- const u = d && d.update;
- if (!u) { if (retry > 0) setTimeout(() => checkVersion(retry - 1), 8000); return; }
- const box = $('#update-banner');
- if (!box || !u.ok || !u.behind) return;
- const key = 'lumreels-hide-update-' + (u.upstream || '') + '-' + u.behind;
- try { if (localStorage.getItem(key)) return; } catch { /* bỏ qua */ }
- update = u;
- renderUpdate();
- box.hidden = false;
- box.querySelector('.ub-close').onclick = () => { box.hidden = true; try { localStorage.setItem(key, '1'); } catch { /* bỏ qua */ } };
- }
- setTimeout(checkVersion, 1500);
-
- // ---------- mẫu ----------
- async function loadTemplates() {
- templatesState = 'loading'; renderGrid();
- try {
- templates = await (await fetch('/api/templates')).json();
- templatesState = 'ok';
- } catch {
- templatesState = 'error';
- }
- renderGrid();
- }
-
- // Mã hiện trên thẻ: mẫu gốc "045"; mẫu gói chỉ hiện slug (mã đầy đủ nằm trong aria-label / title).
- const shortId = (x) => (srcOf(x) === 'builtin' ? x.id : String(x.id).split('/').pop());
- const PLAY_SVG = 'M8 5v14l11-7z';
- function playIcon() {
- const ns = 'http://www.w3.org/2000/svg';
- const svg = document.createElementNS(ns, 'svg'); svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('aria-hidden', 'true');
- const path = document.createElementNS(ns, 'path'); path.setAttribute('d', PLAY_SVG); svg.append(path);
- return svg;
- }
- function tplCard(x) {
- const k = pickIndex(x.id);
- const card = h('div', {
- class: `tpl${x.hasGuidance ? '' : ' off'}${k >= 0 ? ' sel' : ''}`, data: { id: x.id },
- attrs: { role: 'button', tabindex: 0, 'aria-disabled': String(!x.hasGuidance), 'aria-pressed': String(k >= 0),
- 'aria-label': t('tpl.aria', { id: x.id, name: x.name, ready: x.hasGuidance, order: multi && k >= 0 ? k + 1 : 0 }) + ' · ' + srcLabel(x) },
- });
- if (multi && k >= 0) card.append(h('span', { class: 'order', text: k + 1, attrs: { 'aria-hidden': 'true' } }));
- // x.thumb do server ghép từ id/slug đã kiểm (/thumbs/045.webp, /pack-thumbs/<gói>/template-<slug>.webp, /poster/…)
- card.append(x.thumb ? h('img', { class: 'thumb', attrs: { src: x.thumb, alt: '', loading: 'lazy', decoding: 'async', width: 540, height: 960 } })
- : h('div', { class: 'thumb ph', text: t('tpl.noThumb') }));
- card.append(h('span', { class: 'badge' + (x.hasGuidance ? ' ready' : ''), text: t(x.hasGuidance ? 'tpl.ready' : 'tpl.noGuide') }));
- if (x.video) {
- const b = h('button', { class: 'play', data: { play: x.id }, attrs: { type: 'button', 'aria-label': t(x.videoKind === 'demo' ? 'tpl.playDemo' : 'tpl.playRef', { id: x.id }) } });
- b.append(playIcon());
- card.append(b);
- }
- card.append(h('div', { class: 'meta' },
- h('div', { class: 'id' }, srcBadge(x), h('span', { text: `${shortId(x)} · ${catName(x.category)}` })),
- h('div', { class: 't', text: x.name })));
- if (srcOf(x) !== 'builtin') card.title = x.id;
- return card;
- }
- function renderGrid() {
- const grid = $('#grid');
- if (templatesState !== 'ok') {
- grid.replaceChildren(h('div', { class: 'empty-grid', text: t(templatesState === 'error' ? 'grid.loadErr' : 'grid.loading') }));
- return;
- }
- const q = $('#q').value.trim().toLowerCase();
- const readyOnly = $('#readyOnly').checked;
- const list = templates.filter((x) => (!cat || x.category === cat) && (!srcFilter || srcOf(x) === srcFilter) && (!readyOnly || x.hasGuidance) &&
- (!q || `${x.name} ${x.genre} ${x.blurb}`.toLowerCase().includes(q) || String(x.id).includes(q)));
- const ready = templates.filter((x) => x.hasGuidance).length;
- $('#tplCount').textContent = t('pick.count', { ready, total: templates.length });
- if (!list.length) {
- const empty = h('div', { class: 'empty-grid', text: t(srcFilter && !q ? 'grid.emptySrc.' + srcFilter : 'grid.empty') });
- if (srcFilter && !q) empty.append(' ', h('button', { class: 'linkish', text: t('pack.importBtn'), data: { packImport: 1 }, attrs: { type: 'button' } }));
- grid.replaceChildren(empty);
- return;
- }
- const focusId = document.activeElement?.closest?.('#grid .tpl')?.dataset.id;
- grid.classList.toggle('multi', multi);
- grid.replaceChildren(...list.map(tplCard));
- if (focusId) [...grid.querySelectorAll('.tpl')].find((el) => el.dataset.id === focusId)?.focus({ preventScroll: true });
- }
-
- // Báo nhẹ (tự ẩn), vd chọn quá 12 mẫu.
- let noteTimer = null;
- function note(msg) {
- const el = $('#pickNote');
- el.textContent = msg;
- clearTimeout(noteTimer);
- if (msg) noteTimer = setTimeout(() => { el.textContent = ''; }, 4000);
- }
-
- function pick(id) {
- const x = templates.find((y) => y.id === id);
- if (!x || !x.hasGuidance) return;
- if (!multi) picks = [x];
- else {
- const k = pickIndex(id);
- if (k >= 0) picks.splice(k, 1);
- else if (picks.length >= MAX_PICK) { note(t('pick.max', { max: MAX_PICK })); return; }
- else picks.push(x);
- }
- note('');
- picksChanged();
- }
- function unpick(id) { const k = pickIndex(id); if (k >= 0) { picks.splice(k, 1); picksChanged(); } }
- function setMulti(on) {
- multi = on;
- $('#multiPick').checked = on;
- if (!on) picks = picks.slice(0, 1); // tắt: quay về chọn 1, giữ mẫu đầu tiên
- note('');
- picksChanged();
- }
-
- function picksChanged() {
- renderGrid();
- renderPicked();
- window.dispatchEvent(new Event('lumreels:picked'));
- updateWhen();
- updateGo();
- }
-
- function renderPicked() {
- const box = $('#picked');
- if (!picks.length) {
- box.className = 'picked empty';
- box.textContent = multi ? t('picked.noneMulti', { max: MAX_PICK }) : t('picked.none');
- return;
- }
- if (!multi) {
- const x = picks[0];
- box.className = 'picked';
- const info = h('div', {}, h('div', { class: 't' }, srcBadge(x), ` ${shortId(x)} · ${x.name}`), h('div', { class: 'd', text: x.blurb || x.genre || '' }));
- if (srcOf(x) !== 'builtin') info.append(h('div', { class: 'd lock', text: t('pack.lockedNote') }));
- box.replaceChildren(...(x.thumb ? [h('img', { attrs: { src: x.thumb, alt: '' } })] : []), info);
- return;
- }
- box.className = 'picked multi';
- const strip = h('ul', { class: 'strip', attrs: { 'aria-label': t('picked.strip') } }, picks.map((x, i) => h('li', { class: 'pk', attrs: { title: `${x.id} · ${x.name}` } },
- x.thumb ? h('img', { attrs: { src: x.thumb, alt: '' } }) : h('span', { class: 'ph' }),
- h('span', { class: 'n', text: i + 1, attrs: { 'aria-hidden': 'true' } }),
- h('button', { class: 'rm', text: '×', data: { unpick: x.id }, attrs: { type: 'button', 'aria-label': t('picked.remove', { id: x.id, name: x.name }) } }))));
- box.replaceChildren(
- h('div', { class: 'pm-head' }, h('span', { class: 't', text: t('picked.count', { n: picks.length }) }),
- h('button', { class: 'mini', text: t('picked.clear'), data: { clear: 1 }, attrs: { type: 'button' } })),
- strip);
- }
-
- let viewing = null;
- function viewerDesc(x) {
- return (x.videoKind === 'demo' ? t('viewer.demo') : x.videoKind === 'ref' ? t('viewer.ref') : '') + (x.blurb || '');
- }
- function openViewer(id) {
- const x = templates.find((y) => y.id === id);
- if (!x) return;
- viewing = x;
- $('#vTitle').textContent = `${x.id} · ${x.name}`;
- $('#vDesc').textContent = viewerDesc(x);
- const v = $('#vVideo');
- v.hidden = !x.video;
- if (x.video) { v.src = x.video; v.play().catch(() => {}); }
- $('#viewer').showModal();
- }
- function closeViewer() { const v = $('#vVideo'); v.pause(); v.removeAttribute('src'); v.load(); $('#viewer').close(); viewing = null; }
-
- // ---------- form ----------
- function updateGo() {
- const n = $('#content').value.length;
- $('#chars').textContent = n;
- const enough = $('#content').value.trim().length >= 10;
- const dur = !!durS();
- const ok = picks.length > 0 && enough && dur;
- $('#go').disabled = !ok;
- $('#go').title = !picks.length ? t('go.needTpl') : !enough ? t('go.needText') : !dur ? t('go.badDur') : '';
- const rw = $('#rewrite');
- const many = picks.length > 1;
- rw.disabled = !ok || many || rwBusy;
- rw.title = rwBusy ? t('rw.busy') : !picks.length ? t('rw.needOne') : many ? t('rw.onlyOne') : !enough ? t('rw.needText') : !dur ? t('go.badDur') : '';
- rw.querySelector('span').textContent = t(rwBusy ? 'rw.btnBusy' : 'rw.btn');
- const hint = $('#rwHint');
- hint.classList.toggle('bad', many);
- hint.textContent = many ? t('rw.hintMany', { n: picks.length }) : t('rw.hint');
- }
-
- // ---------- thời lượng ----------
- function updateDur() {
- const r = parseDur($('#duration').value);
- $('#duration').setAttribute('aria-invalid', r.error ? 'true' : 'false');
- document.querySelectorAll('.pre').forEach((b) => b.classList.toggle('on', Number(b.dataset.dur) === r.s));
- const hint = $('#durHint');
- hint.classList.toggle('bad', !!r.error);
- hint.textContent = r.error ? r.error + '.' : r.s >= 60 ? t('dur.eqLong', { s: r.s, f: fmtDur(r.s) }) : t('dur.eq', { s: r.s });
- const warn = $('#durWarn');
- if (r.s > 60) {
- warn.hidden = false;
- warn.textContent = t('dur.warn', { f: fmtDur(r.s), range: fmtRange(r.s / 8 * 20, r.s / 8 * 60), scenes: Math.round(r.s / 8) });
- } else warn.hidden = true;
- updateGo();
- }
-
- // ---------- viết lại kịch bản ----------
- let rwBusy = false;
- let rwResult = null; // bản AI vừa viết, chưa dùng
- let rwUndo = null; // nội dung trước khi bấm "Dùng bản này"
- let rwView = null; // hàm vẽ lại ô kết quả (đổi ngôn ngữ thì gọi lại)
- function rwShow(cls, html) { const b = $('#rwBox'); b.className = 'rw ' + cls; b.innerHTML = html; b.hidden = !html; }
- function rwSet(fn) { rwView = fn; if (fn) fn(); else rwShow('', ''); }
- async function rewrite() {
- const selected = one();
- if (rwBusy || !selected) return;
- const dur = durS();
- rwBusy = true; rwResult = null;
- const btn = $('#rewrite');
- btn.classList.add('busy');
- updateGo();
- rwSet(() => rwShow('load', esc(t('rw.loading', { id: selected.id, d: fmtDur(dur) }))));
- const ctl = new AbortController();
- const timer = setTimeout(() => ctl.abort(), 100_000);
- try {
- const r = await fetch('/api/rewrite', {
- method: 'POST', headers: { 'Content-Type': 'application/json' }, signal: ctl.signal,
- body: JSON.stringify({ templateId: selected.id, content: $('#content').value, durationS: dur }),
- });
- const j = await r.json().catch(() => ({}));
- if (!r.ok) throw new Error(j.error || t('err.status', { s: r.status }));
- rwResult = j;
- const eng = j.engine === 'api' ? 'Claude API' : 'Claude Code';
- const cost = j.usage?.costUSD != null ? ` · ≈ $${Number(j.usage.costUSD).toFixed(3)}` : '';
- rwSet(() => rwShow('', `<div class="rw-h"><span>${esc(t('rw.title', { id: j.templateId, d: fmtDur(j.durationS) }))}</span><span class="eng">${eng}${cost}</span></div>
- <pre id="rwScript">${esc(j.script)}</pre>
- ${j.notes ? `<div class="rw-n">${esc(j.notes)}</div>` : ''}
- ${j.fallbackFrom ? `<div class="rw-n">${esc(t('rw.fallback', { why: j.fallbackFrom }))}</div>` : ''}
- <div class="rw-a"><button type="button" class="use" data-rw="use">${esc(t('rw.use'))}</button><button type="button" data-rw="drop">${esc(t('rw.drop'))}</button></div>`));
- } catch (e) {
- const msg = e.name === 'AbortError' ? null : e.message;
- rwSet(() => rwShow('err-box', esc(msg ?? t('rw.timeout'))));
- } finally {
- clearTimeout(timer);
- rwBusy = false;
- btn.classList.remove('busy');
- updateGo();
- }
- }
- $('#rwBox').addEventListener('click', (e) => {
- const a = e.target.closest('[data-rw]')?.dataset.rw;
- if (!a) return;
- if (a === 'use' && rwResult) {
- rwUndo = $('#content').value;
- $('#content').value = rwResult.script.slice(0, 4000);
- rwResult = null;
- rwSet(() => rwShow('', `<div class="rw-h"><span>${esc(t('rw.replaced'))}</span></div><div class="rw-a"><button type="button" data-rw="undo">${esc(t('rw.undo'))}</button><button type="button" data-rw="close">${esc(t('rw.close'))}</button></div>`));
- } else if (a === 'undo' && rwUndo !== null) {
- $('#content').value = rwUndo; rwUndo = null;
- rwSet(null);
- } else { rwResult = null; rwSet(null); }
- updateGo();
- });
-
- async function submit() {
- $('#formErr').textContent = '';
- const btn = $('#go');
- if (!picks.length) return;
- btn.disabled = true; btn.classList.add('busy'); btn.querySelector('span').textContent = t('go.sending');
- const batch = picks.length > 1;
- const common = { content: $('#content').value, durationS: durS(), mode: $('#mode').value, model: $('#model').value, runAt: runAtValue(), audio: window.LumAudio?.value() };
- try {
- const r = await fetch(batch ? '/api/jobs/batch' : '/api/jobs', {
- method: 'POST', headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(batch ? { templateIds: picks.map((x) => x.id), ...common } : { templateId: picks[0].id, ...common }),
- });
- const j = await r.json();
- if (!r.ok) throw new Error(j.error || t('form.jobErr'));
- const created = batch ? j.jobs : [j];
- if (created.length > JOB_PAGE) showAll = true; // cả lô đều hiện trong danh sách
- await loadJobs();
- document.getElementById('job-' + created[0].id)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
- } catch (e) {
- $('#formErr').textContent = e.message + t('form.retry');
- } finally {
- btn.classList.remove('busy'); updateWhen(); updateGo();
- }
- }
-
- // ---------- jobs ----------
- async function loadJobs() {
- let jobs = [];
- try { jobs = await (await fetch('/api/jobs')).json(); } catch { return; }
- // log chi tiết cho job đang chạy
- allJobsCount = jobs.length;
- const detailed = await Promise.all(jobs.slice(0, showAll ? 60 : JOB_PAGE).map(async (j) =>
- (RUNNING.includes(j.status) || j.status === 'error' || j.status === 'waiting_agent')
- ? (await fetch('/api/jobs/' + j.id)).json().catch(() => j) : j));
- renderJobs(detailed);
- clearTimeout(pollTimer);
- if (jobs.some((j) => RUNNING.includes(j.status))) pollTimer = setTimeout(loadJobs, 2000);
- else if (jobs.some((j) => j.status === 'scheduled')) pollTimer = setTimeout(loadJobs, 10000);
- }
-
- function renderJobs(jobs) {
- const box = $('#jobs');
- if (!jobs.length) {
- box.innerHTML = `<div class="no-jobs">${t('jobs.empty')}</div>`;
- return;
- }
- // giữ video đang phát, không vẽ lại job không đổi (chữ ký có ngôn ngữ: đổi VI/EN thì vẽ lại chữ)
- const prev = new Map([...box.querySelectorAll('.job')].map((el) => [el.id, el.dataset.sig]));
- const rows = jobs.map((j) => {
- const sig = `${j.status}|${j.updatedAt}|${I.lang}`;
- if (prev.get('job-' + j.id) === sig && j.status === 'done') return null;
- return { id: j.id, sig, html: jobHtml(j) };
- });
- const frag = [];
- jobs.forEach((j, i) => {
- const h = rows[i];
- if (!h) frag.push(document.getElementById('job-' + j.id));
- else {
- const d = document.createElement('div'); d.innerHTML = h.html.trim(); const el = d.firstChild; el.dataset.sig = h.sig;
- // tên mẫu có thể là chữ của gói (L9): chỉ textContent
- const tt = el.querySelector('.tt'); if (tt) tt.textContent = t('job.tpl', { id: j.templateId, name: j.templateTitle || '' }) + (j.templateSource && j.templateSource !== 'builtin' ? ' · ' + t('src.' + (j.templateSource === 'local' ? 'local' : 'pack')) : '');
- frag.push(el);
- }
- });
- if (allJobsCount > frag.length) {
- const more = document.createElement('button');
- more.className = 'more'; more.type = 'button'; more.dataset.sig = 'more';
- more.textContent = showAll ? t('jobs.less') : t('jobs.more', { n: allJobsCount - frag.length });
- more.addEventListener('click', () => { showAll = !showAll; loadJobs(); });
- frag.push(more);
- } else if (showAll && allJobsCount > JOB_PAGE) {
- const less = document.createElement('button'); less.className = 'more'; less.type = 'button'; less.textContent = t('jobs.less');
- less.addEventListener('click', () => { showAll = false; loadJobs(); }); frag.push(less);
- }
- box.replaceChildren(...frag);
- }
-
- function jobHtml(j) {
- const running = RUNNING.includes(j.status);
- const media = j.links?.mp4
- ? `<video src="${j.links.mp4}" controls playsinline preload="metadata"></video>`
- : j.links?.preview ? `<img src="${j.links.preview}?v=${encodeURIComponent(j.updatedAt)}" alt="${esc(t('job.previewAlt'))}">`
- : `<span>${esc(t(running ? 'job.building' : j.status === 'waiting_agent' ? 'job.waitScene' : 'job.noImage'))}</span>`;
- const last = (j.log || []).slice(-1)[0] || '';
- const out = j.output ? `${j.output.width}×${j.output.height} · ${j.output.fps} · ${Number(j.output.duration).toFixed(1)}s` : '';
- return `<article class="job" id="job-${j.id}">
- <div class="media">${media}</div>
- <div>
- <div class="head"><span class="st ${j.status} ${running ? 'run' : ''}">${esc(status(j.status))}</span>
- <span class="tt"></span></div>
- <div class="jid">${j.id} · ${fmtDur(j.durationS)} · ${esc(modeLabel(j.engine || j.mode) || j.mode)}${j.model && j.model.alias && (j.engine || j.mode) !== 'manual' ? ' · ' + esc(j.model.alias) : ''} ${out ? '· ' + out : ''}</div>
- ${j.status === 'scheduled' ? `<div class="cost">${esc(t('job.at', { t: fmtTime(j.runAt) }))}</div>` : ''}
- ${j.usage ? `<div class="cost">${esc(t('job.api', { i: (j.usage.inputTokens / 1000).toFixed(1), o: (j.usage.outputTokens / 1000).toFixed(1), c: j.usage.costUSD.toFixed(3) }))}</div>` : ''}
- ${j.output?.exported ? `<div class="cost">${esc(t('job.exported', { p: j.output.exported }))}</div>` : ''}
- <div class="content">${esc(j.content)}</div>
- ${running && last ? `<div class="jid">${esc(last)}</div>` : ''}
- ${j.status === 'error' ? `<div class="errmsg">${esc(j.error || t('job.errUnknown'))}${esc(t('job.errTail'))}</div>` : ''}
- ${j.status === 'waiting_agent' ? `<div class="cmd">${esc(t('job.agent', { prompt: j.paths?.prompt, scene: j.paths?.scene, id: j.id }))}</div>` : ''}
- <div class="links">
- ${j.links?.mp4 ? `<a href="${j.links.mp4}" download>${esc(t('job.mp4'))}</a>` : ''}
- ${j.links?.preview ? `<a href="${j.links.preview}" target="_blank" rel="noopener">${esc(t('job.preview'))}</a>` : ''}
- <a href="${j.links?.prompt}" target="_blank" rel="noopener">Prompt</a>
- ${j.links?.brief ? `<a href="${j.links.brief}" target="_blank" rel="noopener">Brief</a>` : ''}
- ${['waiting_agent', 'error', 'done'].includes(j.status) ? `<button data-render="${j.id}">${esc(t(j.status === 'done' ? 'job.rerender' : 'job.render'))}</button>` : ''}
- </div>
- ${j.log?.length ? `<details class="log"><summary>${esc(t('job.log', { n: j.log.length }))}</summary><pre>${esc(j.log.join('\n'))}</pre></details>` : ''}
- </div>
- </article>`;
- }
-
- async function rerender(id) {
- await fetch(`/api/jobs/${id}/render`, { method: 'POST' });
- loadJobs();
- }
-
- // ---------- sự kiện ----------
- $('#grid').addEventListener('click', (e) => {
- const play = e.target.closest('[data-play]');
- if (play) { e.stopPropagation(); openViewer(play.dataset.play); return; }
- const card = e.target.closest('.tpl');
- if (card) pick(card.dataset.id);
- });
- $('#grid').addEventListener('keydown', (e) => {
- if ((e.key === 'Enter' || e.key === ' ') && e.target.classList.contains('tpl')) { e.preventDefault(); pick(e.target.dataset.id); }
- });
- $('#multiPick').addEventListener('change', (e) => setMulti(e.target.checked));
- $('#picked').addEventListener('click', (e) => {
- const rm = e.target.closest('[data-unpick]');
- if (rm) { unpick(rm.dataset.unpick); ($('#picked [data-unpick]') || $('#multiPick')).focus(); return; }
- if (e.target.closest('[data-clear]')) { picks = []; picksChanged(); $('#multiPick').focus(); }
- });
- $('#q').addEventListener('input', renderGrid);
- $('#readyOnly').addEventListener('change', renderGrid);
- function setChip(c) {
- cat = c.dataset.cat || '';
- srcFilter = c.dataset.src || '';
- document.querySelectorAll('.filters .chip').forEach((x) => { x.classList.toggle('on', x === c); x.setAttribute('aria-checked', x === c); });
- renderGrid();
- }
- document.querySelectorAll('.filters .chip').forEach((c) => c.addEventListener('click', () => setChip(c)));
- // packs-panel.js: cài/gỡ gói xong → tải lại lưới; "Xem trong lưới" → bật chip nguồn
- window.addEventListener('lumreels:packs', (e) => {
- const show = e.detail?.show;
- if (show) { const c = document.querySelector(`.filters .chip[data-src="${show === 'local' ? 'local' : 'pack'}"]`); if (c) setChip(c); }
- const removed = e.detail?.removed;
- if (removed) { picks = picks.filter((x) => !String(x.id).startsWith(removed + '/')); picksChanged(); }
- loadTemplates();
- });
- $('#content').addEventListener('input', updateGo);
- $('#rewrite').addEventListener('click', rewrite);
- $('#duration').addEventListener('input', updateDur);
- document.querySelectorAll('.pre').forEach((b) => b.addEventListener('click', () => { $('#duration').value = b.dataset.dur; updateDur(); }));
- $('#go').addEventListener('click', submit);
- $('#vClose').addEventListener('click', closeViewer);
- $('#viewer').addEventListener('cancel', (e) => { e.preventDefault(); closeViewer(); });
- $('#jobs').addEventListener('click', (e) => { const b = e.target.closest('[data-render]'); if (b) { b.disabled = true; rerender(b.dataset.render); } });
-
- function updateWhen() {
- const v = $('#runAt').value;
- const btn = $('#go').querySelector('span');
- if (!btn.closest('.busy')) btn.textContent = t(v ? 'go.schedule' : 'go.build', { n: picks.length });
- $('#clearAt').hidden = !v;
- }
- $('#runAt').addEventListener('input', updateWhen);
- $('#clearAt').addEventListener('click', () => { $('#runAt').value = ''; updateWhen(); });
- updateWhen();
-
- let cfg = {};
- const modeHint = () => {
- const m = $('#mode').value;
- $('#modeHint').textContent = {
- auto: t('mode.hintAuto', { m: modeLabel(cfg.autoResolves) || '…' }),
- api: t('mode.hintApi'),
- claude: t('mode.hintClaude'),
- manual: t('mode.hintManual'),
- }[m] + (cfg.outputDir ? t('mode.hintExport') : '');
- };
- $('#mode').addEventListener('change', modeHint);
- // Model: tự chọn = Opus cho mẫu 3D/shader, Sonnet cho mẫu 2D (rẻ hơn, đủ tốt cho DOM/SVG/Canvas)
- const MODEL_NAME = { opus: 'Opus', sonnet: 'Sonnet', haiku: 'Haiku' };
- const heavy = (x) => (x?.technique || []).some((y) => /three|webgl|shader/i.test(y));
- function modelHint() {
- if (picks.length > 1) return modelHintMany();
- const selected = one();
- const m = $('#model').value;
- const rec = selected ? (heavy(selected) ? 'opus' : 'sonnet') : null;
- const recTxt = rec ? t('model.rec', { heavy: heavy(selected), m: MODEL_NAME[rec] }) : t('model.pickFirst');
- const opt = $('#model').querySelector('[value=auto]');
- opt.textContent = rec ? t('model.autoRec', { m: MODEL_NAME[rec] }) : t('model.auto');
- const warn = m === 'haiku' && rec === 'opus' ? t('model.haikuWarn') : m !== 'auto' && rec && m !== rec ? t('model.override', { m: MODEL_NAME[m] }) : '';
- $('#modelHint').textContent = recTxt + warn + t('model.agentNote');
- }
- // Nhiều mẫu: "3 mẫu 2D → Sonnet, 1 mẫu 3D/shader → Opus" (mỗi job tự chọn theo mẫu của nó).
- function modelHintMany() {
- const m = $('#model').value;
- const nHeavy = picks.filter(heavy).length, nLight = picks.length - nHeavy;
- $('#model').querySelector('[value=auto]').textContent = t('model.autoMany');
- const parts = [];
- if (nLight) parts.push(t('model.manyLight', { n: nLight, m: MODEL_NAME.sonnet }));
- if (nHeavy) parts.push(t('model.manyHeavy', { n: nHeavy, m: MODEL_NAME.opus }));
- const txt = m === 'auto' ? t('model.manyAuto', { parts: parts.join(', ') })
- : t('model.manyFixed', { n: picks.length, m: MODEL_NAME[m], parts: parts.join(', ') }) + (m === 'haiku' && nHeavy ? t('model.haikuWarnMany') : '');
- $('#modelHint').textContent = txt + t('model.agentNote');
- }
- $('#model').addEventListener('change', modelHint);
- window.addEventListener('lumreels:picked', modelHint);
- modelHint();
- fetch('/api/config').then((r) => r.json()).then((c) => {
- cfg = c;
- $('#mode').value = c.defaultMode;
- if (!c.claudeAvailable) $('#mode').querySelector('[value=claude]').disabled = true;
- if (!c.apiAvailable) $('#mode').querySelector('[value=api]').disabled = true;
- modeHint();
- }).catch(() => {});
-
- // Đổi VI/EN: vẽ lại mọi chữ do JS sinh (chữ tĩnh trong HTML đã được i18n.js đổi).
- window.addEventListener('lumreels:lang', () => {
- renderGrid();
- renderPicked();
- updateDur(); // gọi luôn updateGo
- updateWhen();
- modeHint();
- modelHint();
- renderUpdate();
- if (rwView) rwView();
- if (viewing) $('#vDesc').textContent = viewerDesc(viewing);
- note(''); // báo nhẹ tự ẩn: bỏ luôn cho khỏi lẫn ngôn ngữ
- loadJobs();
- });
-
- // learn-panel.js vừa lưu 1 mẫu "Của tôi" → nạp lại danh sách, lọc Của tôi, chọn luôn mẫu đó
- window.addEventListener('lumreels:templates', async (e) => {
- await loadTemplates();
- const ref = e.detail?.pick;
- if (!ref) return;
- const chip = document.querySelector('.chip[data-cat="mine"]');
- if (chip) chip.click();
- if (multi) setMulti(false);
- pick(ref);
- document.querySelector(`#grid .tpl[data-id="${CSS.escape(ref)}"]`)?.scrollIntoView({ block: 'nearest' });
- });
-
- updateDur();
- loadTemplates();
- loadJobs();
-})();
+// UI 1 trang: lưới mẫu, ô nội dung, danh sách job. Không framework. Chữ giao diện lấy từ i18n.js (window.I18N).
+(() => {
+ const $ = (s, el = document) => el.querySelector(s);
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+ const I = window.I18N;
+ const t = (k, v) => I.t(k, v);
+ const status = (s) => (['scheduled', 'queued', 'generating', 'waiting_agent', 'previewing', 'rendering', 'done', 'error'].includes(s) ? t('st.' + s) : s);
+ const RUNNING = ['queued', 'generating', 'previewing', 'rendering'];
+ const CATS = ['faceless', 'ads', 'multi-style', 'viet-nam'];
+ const catName = (c) => (CATS.includes(c) ? t('cat.' + c) : c);
+ // Nhãn nguồn của mẫu (L13): gốc / của tôi (tự tạo) / cộng đồng (gói nhập). Chữ của gói chỉ vào textContent (L9).
+ const SOURCES = ['builtin', 'local', 'pack'];
+ const srcOf = (x) => (SOURCES.includes(x?.source) ? x.source : 'builtin');
+ const srcLabel = (x) => t('src.' + srcOf(x));
+ /** Tạo phần tử: props {class, text, attrs:{}, data:{}}; con là phần tử hoặc chuỗi (thành nút chữ). */
+ function h(tag, props = {}, ...kids) {
+ const el = document.createElement(tag);
+ if (props.class) el.className = props.class;
+ if (props.text != null) el.textContent = props.text;
+ for (const [k, v] of Object.entries(props.attrs || {})) if (v != null && v !== false) el.setAttribute(k, v === true ? '' : String(v));
+ for (const [k, v] of Object.entries(props.data || {})) el.dataset[k] = String(v);
+ for (const c of kids.flat()) if (c != null && c !== false) el.append(c instanceof Node ? c : document.createTextNode(String(c)));
+ return el;
+ }
+ const srcBadge = (x) => h('span', { class: 'src src-' + srcOf(x), text: srcLabel(x) });
+ const modeLabel = (m) => ({ auto: t('modeLabel.auto'), api: 'Claude API', claude: 'Claude Code', manual: t('modeLabel.manual') }[m]);
+ const fmtTime = (iso) => new Date(iso).toLocaleString(I.locale, { hour: '2-digit', minute: '2-digit', day: '2-digit', month: '2-digit', year: 'numeric' });
+ // datetime-local trả giờ máy không múi giờ → đổi sang ISO có múi giờ để server hiểu đúng.
+ const runAtValue = () => { const v = $('#runAt').value; return v ? new Date(v).toISOString() : undefined; };
+
+ // Thời lượng: số giây (90, 90s) hoặc phút:giây (1:30). Cùng luật với generator/jobs.mjs parseDuration.
+ const DUR_MIN = 3, DUR_MAX = 600;
+ function parseDur(v) {
+ const s0 = String(v ?? '').trim().toLowerCase().replace(/\s+/g, '');
+ if (!s0) return { error: t('dur.errEmpty') };
+ let m, s;
+ if ((m = /^(\d{1,4})(?:s|giây|giay)?$/.exec(s0))) s = Number(m[1]);
+ else if ((m = /^(\d{1,2}):([0-5]\d)$/.exec(s0))) s = Number(m[1]) * 60 + Number(m[2]);
+ else if ((m = /^(\d{1,2})(?:m|p|phút|phut)$/.exec(s0))) s = Number(m[1]) * 60;
+ else return { error: t('dur.errFmt') };
+ if (s < DUR_MIN) return { error: t('dur.errMin') };
+ if (s > DUR_MAX) return { error: t('dur.errMax') };
+ return { s };
+ }
+ const fmtDur = (s) => (s < 60 ? `${s}s` : `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`);
+ // Khoảng thời gian ước tính: "40–120 giây", "4–11 phút", "2–5 giờ"… (đơn vị theo đầu trên)
+ const dec = (x) => x.toFixed(1).replace('.', t('num.dec'));
+ const fmtRange = (a, b) => (b < 120 ? `${Math.round(a)}–${Math.round(b)} ${t('unit.sec')}`
+ : b < 7200 ? `${Math.max(1, Math.round(a / 60))}–${Math.round(b / 60)} ${t('unit.min')}` : `${dec(a / 3600)}–${dec(b / 3600)} ${t('unit.hour')}`);
+ const durS = () => parseDur($('#duration').value).s;
+
+ let templates = [];
+ let templatesState = 'loading'; // loading | ok | error
+ // Mẫu đang chọn (theo thứ tự bấm). Chế độ thường: tối đa 1. "Chọn nhiều mẫu": tối đa MAX_PICK, mỗi mẫu 1 job.
+ const MAX_PICK = 12;
+ let picks = [];
+ let multi = false;
+ const one = () => (picks.length === 1 ? picks[0] : null);
+ const pickIndex = (id) => picks.findIndex((x) => x.id === id);
+ let cat = '';
+ let srcFilter = ''; // '' | 'local' | 'pack' (chip "Của tôi" / "Cộng đồng")
+ let pollTimer = null;
+ const JOB_PAGE = 6;
+ let showAll = false;
+ let allJobsCount = 0;
+
+ // ---------- bản mới ----------
+ let update = null;
+ function renderUpdate() {
+ const box = $('#update-banner');
+ const u = update;
+ if (!box || !u) return;
+ const tx = box.querySelector('.ub-text');
+ tx.textContent = '';
+ // u.changes[0] là tiêu đề commit (dữ liệu git), giữ nguyên
+ tx.append(t('update.text', { n: u.behind, first: u.changes && u.changes[0] ? u.changes[0] : '' }));
+ const c = document.createElement('code'); c.textContent = 'npm start';
+ tx.append(c, t('update.after'));
+ }
+ async function checkVersion(retry = 3) {
+ let d;
+ try { d = await (await fetch('/api/version')).json(); } catch { return; }
+ const u = d && d.update;
+ if (!u) { if (retry > 0) setTimeout(() => checkVersion(retry - 1), 8000); return; }
+ const box = $('#update-banner');
+ if (!box || !u.ok || !u.behind) return;
+ const key = 'lumreels-hide-update-' + (u.upstream || '') + '-' + u.behind;
+ try { if (localStorage.getItem(key)) return; } catch { /* bỏ qua */ }
+ update = u;
+ renderUpdate();
+ box.hidden = false;
+ box.querySelector('.ub-close').onclick = () => { box.hidden = true; try { localStorage.setItem(key, '1'); } catch { /* bỏ qua */ } };
+ }
+ setTimeout(checkVersion, 1500);
+
+ // ---------- mẫu ----------
+ async function loadTemplates() {
+ templatesState = 'loading'; renderGrid();
+ try {
+ templates = await (await fetch('/api/templates')).json();
+ templatesState = 'ok';
+ } catch {
+ templatesState = 'error';
+ }
+ renderGrid();
+ }
+
+ // Mã hiện trên thẻ: mẫu gốc "045"; mẫu gói chỉ hiện slug (mã đầy đủ nằm trong aria-label / title).
+ const shortId = (x) => (srcOf(x) === 'builtin' ? x.id : String(x.id).split('/').pop());
+ const PLAY_SVG = 'M8 5v14l11-7z';
+ function playIcon() {
+ const ns = 'http://www.w3.org/2000/svg';
+ const svg = document.createElementNS(ns, 'svg'); svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('aria-hidden', 'true');
+ const path = document.createElementNS(ns, 'path'); path.setAttribute('d', PLAY_SVG); svg.append(path);
+ return svg;
+ }
+ function tplCard(x) {
+ const k = pickIndex(x.id);
+ const card = h('div', {
+ class: `tpl${x.hasGuidance ? '' : ' off'}${k >= 0 ? ' sel' : ''}`, data: { id: x.id },
+ attrs: { role: 'button', tabindex: 0, 'aria-disabled': String(!x.hasGuidance), 'aria-pressed': String(k >= 0),
+ 'aria-label': t('tpl.aria', { id: x.id, name: x.name, ready: x.hasGuidance, order: multi && k >= 0 ? k + 1 : 0 }) + ' · ' + srcLabel(x) },
+ });
+ if (multi && k >= 0) card.append(h('span', { class: 'order', text: k + 1, attrs: { 'aria-hidden': 'true' } }));
+ // x.thumb do server ghép từ id/slug đã kiểm (/thumbs/045.webp, /pack-thumbs/<gói>/template-<slug>.webp, /poster/…)
+ card.append(x.thumb ? h('img', { class: 'thumb', attrs: { src: x.thumb, alt: '', loading: 'lazy', decoding: 'async', width: 540, height: 960 } })
+ : h('div', { class: 'thumb ph', text: t('tpl.noThumb') }));
+ card.append(h('span', { class: 'badge' + (x.hasGuidance ? ' ready' : ''), text: t(x.hasGuidance ? 'tpl.ready' : 'tpl.noGuide') }));
+ if (x.video) {
+ const b = h('button', { class: 'play', data: { play: x.id }, attrs: { type: 'button', 'aria-label': t(x.videoKind === 'demo' ? 'tpl.playDemo' : 'tpl.playRef', { id: x.id }) } });
+ b.append(playIcon());
+ card.append(b);
+ }
+ card.append(h('div', { class: 'meta' },
+ h('div', { class: 'id' }, srcBadge(x), h('span', { text: `${shortId(x)} · ${catName(x.category)}` })),
+ h('div', { class: 't', text: x.name })));
+ if (srcOf(x) !== 'builtin') card.title = x.id;
+ return card;
+ }
+ function renderGrid() {
+ const grid = $('#grid');
+ if (templatesState !== 'ok') {
+ grid.replaceChildren(h('div', { class: 'empty-grid', text: t(templatesState === 'error' ? 'grid.loadErr' : 'grid.loading') }));
+ return;
+ }
+ const q = $('#q').value.trim().toLowerCase();
+ const readyOnly = $('#readyOnly').checked;
+ const list = templates.filter((x) => (!cat || x.category === cat) && (!srcFilter || srcOf(x) === srcFilter) && (!readyOnly || x.hasGuidance) &&
+ (!q || `${x.name} ${x.genre} ${x.blurb}`.toLowerCase().includes(q) || String(x.id).includes(q)));
+ const ready = templates.filter((x) => x.hasGuidance).length;
+ $('#tplCount').textContent = t('pick.count', { ready, total: templates.length });
+ if (!list.length) {
+ const empty = h('div', { class: 'empty-grid', text: t(srcFilter && !q ? 'grid.emptySrc.' + srcFilter : 'grid.empty') });
+ if (srcFilter && !q) empty.append(' ', h('button', { class: 'linkish', text: t('pack.importBtn'), data: { packImport: 1 }, attrs: { type: 'button' } }));
+ grid.replaceChildren(empty);
+ return;
+ }
+ const focusId = document.activeElement?.closest?.('#grid .tpl')?.dataset.id;
+ grid.classList.toggle('multi', multi);
+ grid.replaceChildren(...list.map(tplCard));
+ if (focusId) [...grid.querySelectorAll('.tpl')].find((el) => el.dataset.id === focusId)?.focus({ preventScroll: true });
+ }
+
+ // Báo nhẹ (tự ẩn), vd chọn quá 12 mẫu.
+ let noteTimer = null;
+ function note(msg) {
+ const el = $('#pickNote');
+ el.textContent = msg;
+ clearTimeout(noteTimer);
+ if (msg) noteTimer = setTimeout(() => { el.textContent = ''; }, 4000);
+ }
+
+ function pick(id) {
+ const x = templates.find((y) => y.id === id);
+ if (!x || !x.hasGuidance) return;
+ if (!multi) picks = [x];
+ else {
+ const k = pickIndex(id);
+ if (k >= 0) picks.splice(k, 1);
+ else if (picks.length >= MAX_PICK) { note(t('pick.max', { max: MAX_PICK })); return; }
+ else picks.push(x);
+ }
+ note('');
+ picksChanged();
+ }
+ function unpick(id) { const k = pickIndex(id); if (k >= 0) { picks.splice(k, 1); picksChanged(); } }
+ function setMulti(on) {
+ multi = on;
+ $('#multiPick').checked = on;
+ if (!on) picks = picks.slice(0, 1); // tắt: quay về chọn 1, giữ mẫu đầu tiên
+ note('');
+ picksChanged();
+ }
+
+ function picksChanged() {
+ renderGrid();
+ renderPicked();
+ window.dispatchEvent(new Event('lumreels:picked'));
+ updateWhen();
+ updateGo();
+ }
+
+ function renderPicked() {
+ const box = $('#picked');
+ if (!picks.length) {
+ box.className = 'picked empty';
+ box.textContent = multi ? t('picked.noneMulti', { max: MAX_PICK }) : t('picked.none');
+ return;
+ }
+ if (!multi) {
+ const x = picks[0];
+ box.className = 'picked';
+ const info = h('div', {}, h('div', { class: 't' }, srcBadge(x), ` ${shortId(x)} · ${x.name}`), h('div', { class: 'd', text: x.blurb || x.genre || '' }));
+ if (srcOf(x) !== 'builtin') info.append(h('div', { class: 'd lock', text: t('pack.lockedNote') }));
+ box.replaceChildren(...(x.thumb ? [h('img', { attrs: { src: x.thumb, alt: '' } })] : []), info);
+ return;
+ }
+ box.className = 'picked multi';
+ const strip = h('ul', { class: 'strip', attrs: { 'aria-label': t('picked.strip') } }, picks.map((x, i) => h('li', { class: 'pk', attrs: { title: `${x.id} · ${x.name}` } },
+ x.thumb ? h('img', { attrs: { src: x.thumb, alt: '' } }) : h('span', { class: 'ph' }),
+ h('span', { class: 'n', text: i + 1, attrs: { 'aria-hidden': 'true' } }),
+ h('button', { class: 'rm', text: '×', data: { unpick: x.id }, attrs: { type: 'button', 'aria-label': t('picked.remove', { id: x.id, name: x.name }) } }))));
+ box.replaceChildren(
+ h('div', { class: 'pm-head' }, h('span', { class: 't', text: t('picked.count', { n: picks.length }) }),
+ h('button', { class: 'mini', text: t('picked.clear'), data: { clear: 1 }, attrs: { type: 'button' } })),
+ strip);
+ }
+
+ let viewing = null;
+ function viewerDesc(x) {
+ return (x.videoKind === 'demo' ? t('viewer.demo') : x.videoKind === 'ref' ? t('viewer.ref') : '') + (x.blurb || '');
+ }
+ function openViewer(id) {
+ const x = templates.find((y) => y.id === id);
+ if (!x) return;
+ viewing = x;
+ $('#vTitle').textContent = `${x.id} · ${x.name}`;
+ $('#vDesc').textContent = viewerDesc(x);
+ const v = $('#vVideo');
+ v.hidden = !x.video;
+ if (x.video) { v.src = x.video; v.play().catch(() => {}); }
+ $('#viewer').showModal();
+ }
+ function closeViewer() { const v = $('#vVideo'); v.pause(); v.removeAttribute('src'); v.load(); $('#viewer').close(); viewing = null; }
+
+ // ---------- form ----------
+ function updateGo() {
+ const n = $('#content').value.length;
+ $('#chars').textContent = n;
+ const enough = $('#content').value.trim().length >= 10;
+ const dur = !!durS();
+ const ok = picks.length > 0 && enough && dur;
+ $('#go').disabled = !ok;
+ $('#go').title = !picks.length ? t('go.needTpl') : !enough ? t('go.needText') : !dur ? t('go.badDur') : '';
+ const rw = $('#rewrite');
+ const many = picks.length > 1;
+ rw.disabled = !ok || many || rwBusy;
+ rw.title = rwBusy ? t('rw.busy') : !picks.length ? t('rw.needOne') : many ? t('rw.onlyOne') : !enough ? t('rw.needText') : !dur ? t('go.badDur') : '';
+ rw.querySelector('span').textContent = t(rwBusy ? 'rw.btnBusy' : 'rw.btn');
+ const hint = $('#rwHint');
+ hint.classList.toggle('bad', many);
+ hint.textContent = many ? t('rw.hintMany', { n: picks.length }) : t('rw.hint');
+ }
+
+ // ---------- thời lượng ----------
+ function updateDur() {
+ const r = parseDur($('#duration').value);
+ $('#duration').setAttribute('aria-invalid', r.error ? 'true' : 'false');
+ document.querySelectorAll('.pre').forEach((b) => b.classList.toggle('on', Number(b.dataset.dur) === r.s));
+ const hint = $('#durHint');
+ hint.classList.toggle('bad', !!r.error);
+ hint.textContent = r.error ? r.error + '.' : r.s >= 60 ? t('dur.eqLong', { s: r.s, f: fmtDur(r.s) }) : t('dur.eq', { s: r.s });
+ const warn = $('#durWarn');
+ if (r.s > 60) {
+ warn.hidden = false;
+ warn.textContent = t('dur.warn', { f: fmtDur(r.s), range: fmtRange(r.s / 8 * 20, r.s / 8 * 60), scenes: Math.round(r.s / 8) });
+ } else warn.hidden = true;
+ updateGo();
+ }
+
+ // ---------- viết lại kịch bản ----------
+ let rwBusy = false;
+ let rwResult = null; // bản AI vừa viết, chưa dùng
+ let rwUndo = null; // nội dung trước khi bấm "Dùng bản này"
+ let rwView = null; // hàm vẽ lại ô kết quả (đổi ngôn ngữ thì gọi lại)
+ function rwShow(cls, html) { const b = $('#rwBox'); b.className = 'rw ' + cls; b.innerHTML = html; b.hidden = !html; }
+ function rwSet(fn) { rwView = fn; if (fn) fn(); else rwShow('', ''); }
+ async function rewrite() {
+ const selected = one();
+ if (rwBusy || !selected) return;
+ const dur = durS();
+ rwBusy = true; rwResult = null;
+ const btn = $('#rewrite');
+ btn.classList.add('busy');
+ updateGo();
+ rwSet(() => rwShow('load', esc(t('rw.loading', { id: selected.id, d: fmtDur(dur) }))));
+ const ctl = new AbortController();
+ const timer = setTimeout(() => ctl.abort(), 100_000);
+ try {
+ const r = await fetch('/api/rewrite', {
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, signal: ctl.signal,
+ body: JSON.stringify({ templateId: selected.id, content: $('#content').value, durationS: dur }),
+ });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error(j.error || t('err.status', { s: r.status }));
+ rwResult = j;
+ const eng = j.engine === 'api' ? 'Claude API' : 'Claude Code';
+ const cost = j.usage?.costUSD != null ? ` · ≈ $${Number(j.usage.costUSD).toFixed(3)}` : '';
+ rwSet(() => rwShow('', `<div class="rw-h"><span>${esc(t('rw.title', { id: j.templateId, d: fmtDur(j.durationS) }))}</span><span class="eng">${eng}${cost}</span></div>
+ <pre id="rwScript">${esc(j.script)}</pre>
+ ${j.notes ? `<div class="rw-n">${esc(j.notes)}</div>` : ''}
+ ${j.fallbackFrom ? `<div class="rw-n">${esc(t('rw.fallback', { why: j.fallbackFrom }))}</div>` : ''}
+ <div class="rw-a"><button type="button" class="use" data-rw="use">${esc(t('rw.use'))}</button><button type="button" data-rw="drop">${esc(t('rw.drop'))}</button></div>`));
+ } catch (e) {
+ const msg = e.name === 'AbortError' ? null : e.message;
+ rwSet(() => rwShow('err-box', esc(msg ?? t('rw.timeout'))));
+ } finally {
+ clearTimeout(timer);
+ rwBusy = false;
+ btn.classList.remove('busy');
+ updateGo();
+ }
+ }
+ $('#rwBox').addEventListener('click', (e) => {
+ const a = e.target.closest('[data-rw]')?.dataset.rw;
+ if (!a) return;
+ if (a === 'use' && rwResult) {
+ rwUndo = $('#content').value;
+ $('#content').value = rwResult.script.slice(0, 4000);
+ rwResult = null;
+ rwSet(() => rwShow('', `<div class="rw-h"><span>${esc(t('rw.replaced'))}</span></div><div class="rw-a"><button type="button" data-rw="undo">${esc(t('rw.undo'))}</button><button type="button" data-rw="close">${esc(t('rw.close'))}</button></div>`));
+ } else if (a === 'undo' && rwUndo !== null) {
+ $('#content').value = rwUndo; rwUndo = null;
+ rwSet(null);
+ } else { rwResult = null; rwSet(null); }
+ updateGo();
+ });
+
+ async function submit() {
+ $('#formErr').textContent = '';
+ const btn = $('#go');
+ if (!picks.length) return;
+ btn.disabled = true; btn.classList.add('busy'); btn.querySelector('span').textContent = t('go.sending');
+ const batch = picks.length > 1;
+ const common = { content: $('#content').value, durationS: durS(), mode: $('#mode').value, model: $('#model').value, runAt: runAtValue(), audio: window.LumAudio?.value() };
+ try {
+ const r = await fetch(batch ? '/api/jobs/batch' : '/api/jobs', {
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(batch ? { templateIds: picks.map((x) => x.id), ...common } : { templateId: picks[0].id, ...common }),
+ });
+ const j = await r.json();
+ if (!r.ok) throw new Error(j.error || t('form.jobErr'));
+ const created = batch ? j.jobs : [j];
+ if (created.length > JOB_PAGE) showAll = true; // cả lô đều hiện trong danh sách
+ await loadJobs();
+ document.getElementById('job-' + created[0].id)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ } catch (e) {
+ $('#formErr').textContent = e.message + t('form.retry');
+ } finally {
+ btn.classList.remove('busy'); updateWhen(); updateGo();
+ }
+ }
+
+ // ---------- jobs ----------
+ async function loadJobs() {
+ let jobs = [];
+ try { jobs = await (await fetch('/api/jobs')).json(); } catch { return; }
+ // log chi tiết cho job đang chạy
+ allJobsCount = jobs.length;
+ const detailed = await Promise.all(jobs.slice(0, showAll ? 60 : JOB_PAGE).map(async (j) =>
+ (RUNNING.includes(j.status) || j.status === 'error' || j.status === 'waiting_agent')
+ ? (await fetch('/api/jobs/' + j.id)).json().catch(() => j) : j));
+ renderJobs(detailed);
+ clearTimeout(pollTimer);
+ if (jobs.some((j) => RUNNING.includes(j.status))) pollTimer = setTimeout(loadJobs, 2000);
+ else if (jobs.some((j) => j.status === 'scheduled')) pollTimer = setTimeout(loadJobs, 10000);
+ }
+
+ function renderJobs(jobs) {
+ const box = $('#jobs');
+ if (!jobs.length) {
+ box.innerHTML = `<div class="no-jobs">${t('jobs.empty')}</div>`;
+ return;
+ }
+ // giữ video đang phát, không vẽ lại job không đổi (chữ ký có ngôn ngữ: đổi VI/EN thì vẽ lại chữ)
+ const prev = new Map([...box.querySelectorAll('.job')].map((el) => [el.id, el.dataset.sig]));
+ const rows = jobs.map((j) => {
+ const sig = `${j.status}|${j.updatedAt}|${I.lang}`;
+ if (prev.get('job-' + j.id) === sig && j.status === 'done') return null;
+ return { id: j.id, sig, html: jobHtml(j) };
+ });
+ const frag = [];
+ jobs.forEach((j, i) => {
+ const h = rows[i];
+ if (!h) frag.push(document.getElementById('job-' + j.id));
+ else {
+ const d = document.createElement('div'); d.innerHTML = h.html.trim(); const el = d.firstChild; el.dataset.sig = h.sig;
+ // tên mẫu có thể là chữ của gói (L9): chỉ textContent
+ const tt = el.querySelector('.tt'); if (tt) tt.textContent = t('job.tpl', { id: j.templateId, name: j.templateTitle || '' }) + (j.templateSource && j.templateSource !== 'builtin' ? ' · ' + t('src.' + (j.templateSource === 'local' ? 'local' : 'pack')) : '');
+ frag.push(el);
+ }
+ });
+ if (allJobsCount > frag.length) {
+ const more = document.createElement('button');
+ more.className = 'more'; more.type = 'button'; more.dataset.sig = 'more';
+ more.textContent = showAll ? t('jobs.less') : t('jobs.more', { n: allJobsCount - frag.length });
+ more.addEventListener('click', () => { showAll = !showAll; loadJobs(); });
+ frag.push(more);
+ } else if (showAll && allJobsCount > JOB_PAGE) {
+ const less = document.createElement('button'); less.className = 'more'; less.type = 'button'; less.textContent = t('jobs.less');
+ less.addEventListener('click', () => { showAll = false; loadJobs(); }); frag.push(less);
+ }
+ box.replaceChildren(...frag);
+ }
+
+ function jobHtml(j) {
+ const running = RUNNING.includes(j.status);
+ const media = j.links?.mp4
+ ? `<video src="${j.links.mp4}" controls playsinline preload="metadata"></video>`
+ : j.links?.preview ? `<img src="${j.links.preview}?v=${encodeURIComponent(j.updatedAt)}" alt="${esc(t('job.previewAlt'))}">`
+ : `<span>${esc(t(running ? 'job.building' : j.status === 'waiting_agent' ? 'job.waitScene' : 'job.noImage'))}</span>`;
+ const last = (j.log || []).slice(-1)[0] || '';
+ const out = j.output ? `${j.output.width}×${j.output.height} · ${j.output.fps} · ${Number(j.output.duration).toFixed(1)}s` : '';
+ return `<article class="job" id="job-${j.id}">
+ <div class="media">${media}</div>
+ <div>
+ <div class="head"><span class="st ${j.status} ${running ? 'run' : ''}">${esc(status(j.status))}</span>
+ <span class="tt"></span></div>
+ <div class="jid">${j.id} · ${fmtDur(j.durationS)} · ${esc(modeLabel(j.engine || j.mode) || j.mode)}${j.model && j.model.alias && (j.engine || j.mode) !== 'manual' ? ' · ' + esc(j.model.alias) : ''} ${out ? '· ' + out : ''}</div>
+ ${j.status === 'scheduled' ? `<div class="cost">${esc(t('job.at', { t: fmtTime(j.runAt) }))}</div>` : ''}
+ ${j.usage ? `<div class="cost">${esc(t('job.api', { i: (j.usage.inputTokens / 1000).toFixed(1), o: (j.usage.outputTokens / 1000).toFixed(1), c: j.usage.costUSD.toFixed(3) }))}</div>` : ''}
+ ${j.output?.exported ? `<div class="cost">${esc(t('job.exported', { p: j.output.exported }))}</div>` : ''}
+ <div class="content">${esc(j.content)}</div>
+ ${running && last ? `<div class="jid">${esc(last)}</div>` : ''}
+ ${j.status === 'error' ? `<div class="errmsg">${esc(j.error || t('job.errUnknown'))}${esc(t('job.errTail'))}</div>` : ''}
+ ${j.status === 'waiting_agent' ? `<div class="cmd">${esc(t('job.agent', { prompt: j.paths?.prompt, scene: j.paths?.scene, id: j.id }))}</div>` : ''}
+ <div class="links">
+ ${j.links?.mp4 ? `<a href="${j.links.mp4}" download>${esc(t('job.mp4'))}</a>` : ''}
+ ${j.links?.preview ? `<a href="${j.links.preview}" target="_blank" rel="noopener">${esc(t('job.preview'))}</a>` : ''}
+ <a href="${j.links?.prompt}" target="_blank" rel="noopener">Prompt</a>
+ ${j.links?.brief ? `<a href="${j.links.brief}" target="_blank" rel="noopener">Brief</a>` : ''}
+ ${j.status === 'done' && j.links?.mp4 ? `<button type="button" class="to-studio" data-studio="${j.id}">${esc(t('job.studio'))}</button>` : ''}
+ ${['waiting_agent', 'error', 'done'].includes(j.status) ? `<button data-render="${j.id}">${esc(t(j.status === 'done' ? 'job.rerender' : 'job.render'))}</button>` : ''}
+ </div>
+ ${j.log?.length ? `<details class="log"><summary>${esc(t('job.log', { n: j.log.length }))}</summary><pre>${esc(j.log.join('\n'))}</pre></details>` : ''}
+ </div>
+ </article>`;
+ }
+
+ async function rerender(id) {
+ await fetch(`/api/jobs/${id}/render`, { method: 'POST' });
+ loadJobs();
+ }
+
+ // ---------- sự kiện ----------
+ $('#grid').addEventListener('click', (e) => {
+ const play = e.target.closest('[data-play]');
+ if (play) { e.stopPropagation(); openViewer(play.dataset.play); return; }
+ const card = e.target.closest('.tpl');
+ if (card) pick(card.dataset.id);
+ });
+ $('#grid').addEventListener('keydown', (e) => {
+ if ((e.key === 'Enter' || e.key === ' ') && e.target.classList.contains('tpl')) { e.preventDefault(); pick(e.target.dataset.id); }
+ });
+ $('#multiPick').addEventListener('change', (e) => setMulti(e.target.checked));
+ $('#picked').addEventListener('click', (e) => {
+ const rm = e.target.closest('[data-unpick]');
+ if (rm) { unpick(rm.dataset.unpick); ($('#picked [data-unpick]') || $('#multiPick')).focus(); return; }
+ if (e.target.closest('[data-clear]')) { picks = []; picksChanged(); $('#multiPick').focus(); }
+ });
+ $('#q').addEventListener('input', renderGrid);
+ $('#readyOnly').addEventListener('change', renderGrid);
+ function setChip(c) {
+ cat = c.dataset.cat || '';
+ srcFilter = c.dataset.src || '';
+ document.querySelectorAll('.filters .chip').forEach((x) => { x.classList.toggle('on', x === c); x.setAttribute('aria-checked', x === c); });
+ renderGrid();
+ }
+ document.querySelectorAll('.filters .chip').forEach((c) => c.addEventListener('click', () => setChip(c)));
+ // packs-panel.js: cài/gỡ gói xong → tải lại lưới; "Xem trong lưới" → bật chip nguồn
+ window.addEventListener('lumreels:packs', (e) => {
+ const show = e.detail?.show;
+ if (show) { const c = document.querySelector(`.filters .chip[data-src="${show === 'local' ? 'local' : 'pack'}"]`); if (c) setChip(c); }
+ const removed = e.detail?.removed;
+ if (removed) { picks = picks.filter((x) => !String(x.id).startsWith(removed + '/')); picksChanged(); }
+ loadTemplates();
+ });
+ $('#content').addEventListener('input', updateGo);
+ $('#rewrite').addEventListener('click', rewrite);
+ $('#duration').addEventListener('input', updateDur);
+ document.querySelectorAll('.pre').forEach((b) => b.addEventListener('click', () => { $('#duration').value = b.dataset.dur; updateDur(); }));
+ $('#go').addEventListener('click', submit);
+ $('#vClose').addEventListener('click', closeViewer);
+ $('#viewer').addEventListener('cancel', (e) => { e.preventDefault(); closeViewer(); });
+ $('#jobs').addEventListener('click', (e) => { const b = e.target.closest('[data-render]'); if (b) { b.disabled = true; rerender(b.dataset.render); } });
+
+ function updateWhen() {
+ const v = $('#runAt').value;
+ const btn = $('#go').querySelector('span');
+ if (!btn.closest('.busy')) btn.textContent = t(v ? 'go.schedule' : 'go.build', { n: picks.length });
+ $('#clearAt').hidden = !v;
+ }
+ $('#runAt').addEventListener('input', updateWhen);
+ $('#clearAt').addEventListener('click', () => { $('#runAt').value = ''; updateWhen(); });
+ updateWhen();
+
+ let cfg = {};
+ const modeHint = () => {
+ const m = $('#mode').value;
+ $('#modeHint').textContent = {
+ auto: t('mode.hintAuto', { m: modeLabel(cfg.autoResolves) || '…' }),
+ api: t('mode.hintApi'),
+ claude: t('mode.hintClaude'),
+ manual: t('mode.hintManual'),
+ }[m] + (cfg.outputDir ? t('mode.hintExport') : '');
+ };
+ $('#mode').addEventListener('change', modeHint);
+ // Model: tự chọn = Opus cho mẫu 3D/shader, Sonnet cho mẫu 2D (rẻ hơn, đủ tốt cho DOM/SVG/Canvas)
+ const MODEL_NAME = { opus: 'Opus', sonnet: 'Sonnet', haiku: 'Haiku' };
+ const heavy = (x) => (x?.technique || []).some((y) => /three|webgl|shader/i.test(y));
+ function modelHint() {
+ if (picks.length > 1) return modelHintMany();
+ const selected = one();
+ const m = $('#model').value;
+ const rec = selected ? (heavy(selected) ? 'opus' : 'sonnet') : null;
+ const recTxt = rec ? t('model.rec', { heavy: heavy(selected), m: MODEL_NAME[rec] }) : t('model.pickFirst');
+ const opt = $('#model').querySelector('[value=auto]');
+ opt.textContent = rec ? t('model.autoRec', { m: MODEL_NAME[rec] }) : t('model.auto');
+ const warn = m === 'haiku' && rec === 'opus' ? t('model.haikuWarn') : m !== 'auto' && rec && m !== rec ? t('model.override', { m: MODEL_NAME[m] }) : '';
+ $('#modelHint').textContent = recTxt + warn + t('model.agentNote');
+ }
+ // Nhiều mẫu: "3 mẫu 2D → Sonnet, 1 mẫu 3D/shader → Opus" (mỗi job tự chọn theo mẫu của nó).
+ function modelHintMany() {
+ const m = $('#model').value;
+ const nHeavy = picks.filter(heavy).length, nLight = picks.length - nHeavy;
+ $('#model').querySelector('[value=auto]').textContent = t('model.autoMany');
+ const parts = [];
+ if (nLight) parts.push(t('model.manyLight', { n: nLight, m: MODEL_NAME.sonnet }));
+ if (nHeavy) parts.push(t('model.manyHeavy', { n: nHeavy, m: MODEL_NAME.opus }));
+ const txt = m === 'auto' ? t('model.manyAuto', { parts: parts.join(', ') })
+ : t('model.manyFixed', { n: picks.length, m: MODEL_NAME[m], parts: parts.join(', ') }) + (m === 'haiku' && nHeavy ? t('model.haikuWarnMany') : '');
+ $('#modelHint').textContent = txt + t('model.agentNote');
+ }
+ $('#model').addEventListener('change', modelHint);
+ window.addEventListener('lumreels:picked', modelHint);
+ modelHint();
+ fetch('/api/config').then((r) => r.json()).then((c) => {
+ cfg = c;
+ $('#mode').value = c.defaultMode;
+ if (!c.claudeAvailable) $('#mode').querySelector('[value=claude]').disabled = true;
+ if (!c.apiAvailable) $('#mode').querySelector('[value=api]').disabled = true;
+ modeHint();
+ }).catch(() => {});
+
+ // Đổi VI/EN: vẽ lại mọi chữ do JS sinh (chữ tĩnh trong HTML đã được i18n.js đổi).
+ window.addEventListener('lumreels:lang', () => {
+ renderGrid();
+ renderPicked();
+ updateDur(); // gọi luôn updateGo
+ updateWhen();
+ modeHint();
+ modelHint();
+ renderUpdate();
+ if (rwView) rwView();
+ if (viewing) $('#vDesc').textContent = viewerDesc(viewing);
+ note(''); // báo nhẹ tự ẩn: bỏ luôn cho khỏi lẫn ngôn ngữ
+ loadJobs();
+ });
+
+ // learn-panel.js vừa lưu 1 mẫu "Của tôi" → nạp lại danh sách, lọc Của tôi, chọn luôn mẫu đó
+ window.addEventListener('lumreels:templates', async (e) => {
+ await loadTemplates();
+ const ref = e.detail?.pick;
+ if (!ref) return;
+ const chip = document.querySelector('.chip[data-cat="mine"]');
+ if (chip) chip.click();
+ if (multi) setMulti(false);
+ pick(ref);
+ document.querySelector(`#grid .tpl[data-id="${CSS.escape(ref)}"]`)?.scrollIntoView({ block: 'nearest' });
+ });
+
+ updateDur();
+ loadTemplates();
+ loadJobs();
+})();
diff --git a/server/public/i18n.js b/server/public/i18n.js
index 4c98523..987d445 100644
--- a/server/public/i18n.js
+++ b/server/public/i18n.js
@@ -662,6 +662,24 @@
'cr.eta': 'Mất khoảng {m} phút',
'cr.delete': 'Xoá bản dựng {name}',
// ---- Studio (studio/*.js) ----
+ 'st.fromReel': 'Từ reel (giữ nguyên)',
+ 'st.reelMusic': 'Nhạc của reel',
+ 'st.reelLink': '↩ Reel: {title}',
+ 'st.reelBack': 'Quay về video reel này ở tab Dựng từ mẫu',
+ 'st.videoHint': 'Bấm track Video để chọn clip, kéo để chọn vùng; S tách clip tại đầu phát; Delete cắt bỏ đoạn đang chọn.',
+ 'st.videoPick': 'Chưa chọn đoạn nào trên track Video.',
+ 'st.cutThis': 'Cắt bỏ đoạn này',
+ 'st.restoreCut': 'Trả lại đoạn đã cắt',
+ 'st.splitClip': 'Tách clip tại đầu phát (S)',
+ 'st.cutDone': 'Đã đánh dấu cắt {a}–{b}. Xuất bản mới để áp dụng.',
+ 'st.noSplitHere': 'Không tách được ở đây (sát đầu/cuối hoặc trong chỗ đã cắt).',
+ 'st.cutsPending': (v) => `${v.n} chỗ cắt chờ xuất bản (−${v.s} s). Xem trước đã nhảy qua.`,
+ 'st.cutItem': 'Cắt {a}–{b}',
+ 'st.showCaps': 'Hiện phụ đề',
+ 'st.showCapsTip': 'Reel nhập vào đã có chữ trong cảnh nên phụ đề tắt sẵn; bật để vẽ thêm phụ đề từ lời đọc.',
+ 'job.studio': 'Sửa tiếp trong Studio',
+ 'job.studioBusy': 'Đang mở Studio…',
+ 'job.studioErr': 'Không mở được Studio: {e}',
'st.back': 'Quay lại danh sách',
'st.versions': 'Phiên bản',
'st.r0': 'gốc',
@@ -1405,6 +1423,24 @@
'cr.eta': 'Takes about {m} min',
'cr.delete': 'Delete edit {name}',
// ---- Studio (studio/*.js) ----
+ 'st.fromReel': 'From reel (kept as is)',
+ 'st.reelMusic': 'Reel music',
+ 'st.reelLink': '↩ Reel: {title}',
+ 'st.reelBack': 'Back to this reel in the From a template tab',
+ 'st.videoHint': 'Click the Video track to pick a clip, drag to pick a range; S splits the clip at the playhead; Delete cuts the selected part.',
+ 'st.videoPick': 'Nothing selected on the Video track.',
+ 'st.cutThis': 'Cut this part',
+ 'st.restoreCut': 'Restore this cut',
+ 'st.splitClip': 'Split clip at playhead (S)',
+ 'st.cutDone': 'Marked {a}–{b} to cut. Publish to apply.',
+ 'st.noSplitHere': 'Can’t split here (too close to the start/end or inside a cut).',
+ 'st.cutsPending': (v) => `${v.n} cut${v.n === 1 ? '' : 's'} waiting to publish (−${v.s} s). The preview already skips them.`,
+ 'st.cutItem': 'Cut {a}–{b}',
+ 'st.showCaps': 'Show captions',
+ 'st.showCapsTip': 'Imported reels already have text in the scene, so captions start off; turn on to add captions from the voice-over.',
+ 'job.studio': 'Keep editing in Studio',
+ 'job.studioBusy': 'Opening Studio…',
+ 'job.studioErr': 'Could not open Studio: {e}',
'st.back': 'Back to the list',
'st.versions': 'Versions',
'st.r0': 'orig',
diff --git a/server/public/index.html b/server/public/index.html
index 4fe038e..5ff8055 100644
--- a/server/public/index.html
+++ b/server/public/index.html
@@ -263,6 +263,7 @@
<script src="/app.js"></script>
<script type="module" src="/studio/create.js"></script>
<script type="module" src="/studio/studio.js"></script>
+<script type="module" src="/studio/from-reel.js"></script>
<script src="/packs-panel.js"></script>
<script src="/learn-panel.js"></script>
</body>
diff --git a/server/public/studio/create.css b/server/public/studio/create.css
index 034c003..a817394 100644
--- a/server/public/studio/create.css
+++ b/server/public/studio/create.css
@@ -205,4 +205,8 @@
.cr-go { margin-left: auto; height: 46px; }
}
@media (prefers-reduced-motion: reduce) { .ed-install-bar span { animation: none; width: 100%; opacity: .5; } .cr-bar i, .sty .pic, .btn { transition: none; } }
-.cr-back[hidden] { display: none; }
+.cr-back[hidden] { display: none; }
+
+/* tab Dựng từ mẫu: nút Sửa tiếp trong Studio + nháy thẻ khi quay về từ Studio */
+.job .links .to-studio { background: var(--accent-soft); color: var(--accent); border-color: rgba(255,107,44,.5); font-weight: 600; }
+.job.flash { box-shadow: 0 0 0 3px var(--accent); transition: box-shadow .3s; }
diff --git a/server/public/studio/create.js b/server/public/studio/create.js
index 45b9b49..e22ac67 100644
--- a/server/public/studio/create.js
+++ b/server/public/studio/create.js
@@ -32,7 +32,7 @@ document.addEventListener('keydown', (e) => {
});
window.addEventListener('hashchange', () => { if (location.hash === '#edit') show('edit'); });
// đóng Studio → về màn tạo mới, tải lại danh sách (có thể vừa xuất bản mới)
-window.addEventListener('lumreels:studio', (e) => { if (!e.detail.open) { show('edit'); if (S.opts) loadList(); } });
+window.addEventListener('lumreels:studio', (e) => { if (!e.detail.open && !/^#reel\//.test(location.hash)) { show('edit'); if (S.opts) loadList(); } });
// ---- nạp ----
async function init() {
diff --git a/server/public/studio/from-reel.js b/server/public/studio/from-reel.js
new file mode 100644
index 0000000..f96ff99
--- /dev/null
+++ b/server/public/studio/from-reel.js
@@ -0,0 +1,35 @@
+// Tab "Dựng từ mẫu": nút "Sửa tiếp trong Studio" trên thẻ video đã dựng xong → POST /api/edits/from-reel {job}
+// (edit/reel.mjs: giữ nguyên, tách track giọng/nhạc nếu reel còn tiếng riêng) rồi mở thẳng Studio #/edit/<id>.
+// Studio có link "↩ Reel" (#reel/<id>) quay về đúng thẻ video đó.
+import { $, t, I, postJSON } from './util.js';
+
+document.addEventListener('click', async (e) => {
+ const b = e.target.closest?.('[data-studio]'); if (!b || b.disabled) return;
+ e.preventDefault();
+ const label = b.textContent;
+ b.disabled = true; b.textContent = t('job.studioBusy');
+ try {
+ const j = await postJSON('/api/edits/from-reel', { job: b.dataset.studio });
+ location.hash = `#/edit/${encodeURIComponent(j.id)}`;
+ } catch (err) {
+ b.title = t('job.studioErr', { e: I.srv(err.message) });
+ b.textContent = label;
+ const card = b.closest('.job'); const box = card?.querySelector('.errmsg.studio') || document.createElement('div');
+ box.className = 'errmsg studio'; box.textContent = t('job.studioErr', { e: I.srv(err.message) });
+ if (card && !box.isConnected) b.closest('.links')?.after(box);
+ } finally { b.disabled = false; if (b.textContent === t('job.studioBusy')) b.textContent = label; }
+});
+
+function showReel() {
+ const m = /^#reel\/([\w-]{1,80})$/.exec(location.hash); if (!m) return;
+ $('.tab[data-tab="tpl"]')?.click();
+ const tryScroll = (n) => {
+ const card = document.getElementById('job-' + m[1]);
+ if (!card) { if (n < 20) setTimeout(() => tryScroll(n + 1), 250); return; }
+ card.scrollIntoView({ block: 'center' });
+ card.classList.add('flash'); setTimeout(() => card.classList.remove('flash'), 1600);
+ };
+ tryScroll(0);
+}
+window.addEventListener('hashchange', showReel);
+showReel();
diff --git a/server/public/studio/inspector.js b/server/public/studio/inspector.js
index bfd8fc0..7009d4b 100644
--- a/server/public/studio/inspector.js
+++ b/server/public/studio/inspector.js
@@ -36,6 +36,7 @@ export class Inspector {
else if (mode === 'gfx') this.renderGfx();
else if (mode === 'ai') this.renderAi();
else if (mode === 'review') this.renderReview();
+ else if (mode === 'video') this.renderVideo();
if (ro && mode !== 'ai') this.body.prepend(tx('p', 'st-note', 'st.readOnly'));
}
lightUpdate() {
@@ -163,6 +164,12 @@ export class Inspector {
const cb = el('input', null, null, { type: 'checkbox', role: 'switch' }); cb.checked = st.doc.hi; cb.disabled = ro;
cb.addEventListener('change', () => this.commit((d) => { d.hi = cb.checked; }));
sw.append(cb, tx('span', null, 'man.hiShort'), tx('small', null, 'man.hiTip'));
+ // reel nhập vào: phụ đề tắt sẵn (chữ đã nằm trong cảnh), bật ở đây
+ const sh = el('label', 'st-switch');
+ const cs = el('input', null, null, { type: 'checkbox', role: 'switch' }); cs.checked = st.doc.show !== false; cs.disabled = ro;
+ cs.addEventListener('change', () => this.commit((d) => { d.show = cs.checked; }));
+ sh.append(cs, tx('span', null, 'st.showCaps'), tx('small', null, 'st.showCapsTip'));
+ wrap.append(sh);
const grid = el('div', 'st-lookgrid', null, { role: 'radiogroup', 'aria-label': t('man.look') });
for (const l of v.captions.looks) {
const on = l.id === st.doc.look;
@@ -182,6 +189,39 @@ export class Inspector {
return wrap;
}
+ // ---- Track video: tách clip / cắt bỏ đoạn ----
+ renderVideo() {
+ const st = this.ctx.store; const s = this.ctx.getSel(); const ro = !!st.view.readOnly;
+ this.setHead('film', 'st.trVideo');
+ const kids = [tx('p', 'st-hint', 'st.videoHint')];
+ const card = el('div', 'st-card');
+ if (s?.kind === 'clip' || s?.kind === 'cut') {
+ const [a, b] = s.kind === 'clip' ? [s.a, s.b] : st.doc.cuts[s.i];
+ card.append(el('p', 'st-rwhat mono', `${fmtT(a)} → ${fmtT(b)} · ${(b - a).toFixed(2)} s`));
+ const act = el('button', 'btn ' + (s.kind === 'clip' ? 'warn' : 'ghost') + ' sm', null, { type: 'button' });
+ act.append(icon(s.kind === 'clip' ? 'cut' : 'rotate'), tx('span', null, s.kind === 'clip' ? 'st.cutThis' : 'st.restoreCut'));
+ act.disabled = ro; act.addEventListener('click', () => this.ctx.deleteSel());
+ card.append(act);
+ } else card.append(tx('p', 'st-hint', 'st.videoPick'));
+ const sp = el('button', 'btn ghost sm', null, { type: 'button' }); sp.append(icon('split'), tx('span', null, 'st.splitClip')); sp.disabled = ro;
+ sp.addEventListener('click', () => this.ctx.splitClip());
+ card.append(sp);
+ kids.push(card);
+ const cuts = st.doc.cuts || [];
+ if (cuts.length) {
+ kids.push(el('p', 'st-note warn', t('st.cutsPending', { n: cuts.length, s: cuts.reduce((x, [a, b]) => x + b - a, 0).toFixed(1) })));
+ const ul = el('ul', 'st-blist');
+ cuts.forEach(([a, b], i) => {
+ const btn = el('button', s?.kind === 'cut' && s.i === i ? 'on' : '', null, { type: 'button' });
+ btn.append(el('span', 'tm mono', fmtT(a)), el('span', 'lb', t('st.cutItem', { a: fmtT(a), b: fmtT(b) })));
+ btn.addEventListener('click', () => { this.ctx.select({ kind: 'cut', i }); this.ctx.seek(Math.max(0, a - 0.5)); });
+ const li = el('li'); li.append(btn); ul.append(li);
+ });
+ kids.push(ul);
+ }
+ this.body.replaceChildren(...kids);
+ }
+
// ---- Cần xem lại ----
renderReview() { this.setHead('warn', 'st.reviewH'); this.body.replaceChildren(this.reviewBody()); }
reviewBody() {
diff --git a/server/public/studio/player.js b/server/public/studio/player.js
index 972399c..09bfde1 100644
--- a/server/public/studio/player.js
+++ b/server/public/studio/player.js
@@ -1,345 +1,348 @@
-// Player giữa Studio — xem trước tức thì, không render:
-// · nền SẠCH (preview-clean.mp4: đã cắt + khung, CHƯA zoom/kính/chữ) → MỌI zoom (cũ lẫn mới) chạy bằng CSS transform
-// theo EDL đang sửa, cùng công thức lumedit Zooms (punch/push, tâm đầu lúc zoom bắt đầu, khung đặt 0,42 chiều cao);
-// · phụ đề HTML theo đúng tham số LOOKS (cỡ, stroke, bóng, cy, chữ hoa, bỏ dấu câu cuối) + hiệu ứng vào (GSAP ease
-// tương đương) + karaoke theo giờ từng chữ — tính thuần theo t nên tua tới đâu đúng tới đó;
-// · đồ hoạ: chính HTML/CSS/runtime của lớp HyperFrames trong <iframe sandbox="allow-scripts"> (postMessage), kính mờ
-// dưới thẻ bằng backdrop-filter;
-// · nhạc phát song song (<audio>, âm lượng theo dB, tự hạ khi có lời).
-// Không có nền sạch → nền cũ (base.mp4, đã có zoom gốc: chỉ zoom mới chạy CSS). "Bản xuất" → phát MP4 đã xuất, không vẽ đè.
-import { el, tx, icon, iconBtn, fmtT, tokens, clamp, t } from './util.js';
-
-const FPS = 30; const W = 1080; const H = 1920;
-const ease = (x) => { x = clamp(x, 0, 1); return x * x * (3 - 2 * x); };
-// GSAP: powerN.out = 1 − (1 − x)^(N+1); back.out(c)
-const pOut = (n) => (x) => 1 - (1 - clamp(x, 0, 1)) ** (n + 1);
-const pIn = (n) => (x) => clamp(x, 0, 1) ** (n + 1);
-const backOut = (c) => (x) => { x = clamp(x, 0, 1); return 1 + (c + 1) * (x - 1) ** 3 + c * (x - 1) ** 2; };
-
-/** Như lumedit Zooms.scale_at: punch (vào 0,08 s, giữ, ra 0,12 s) / push (đẩy chậm, lùi 0,3 s cuối). Trả {s, z}. */
-export function zoomAt(zs, tt) {
- for (const z of zs) {
- if (tt < z.at || tt >= z.at + z.dur) continue;
- const u = tt - z.at; let k;
- if (z.kind === 'punch') { k = u < 0.08 ? ease(u / 0.08) : 1; if (u > z.dur - 0.12) k = Math.min(k, ease((z.dur - u) / 0.12)); }
- else { const back = Math.min(0.3, z.dur * 0.2); k = u < z.dur - back ? ease(u / (z.dur - back)) : ease((z.dur - u) / back); }
- return { s: 1 + (z.scale - 1) * k, z };
- }
- return { s: 1, z: null };
-}
-export const zoomScale = (zs, tt) => zoomAt(zs, tt).s;
-
-export class Player {
- constructor(ctx) {
- this.ctx = ctx; // {store, onTime(t), onPlay(bool), getSel(), gfxScene()}
- this.root = el('section', 'st-stage');
- this.box = el('div', 'st-vid');
- this.video = el('video', null, null, { playsinline: true, preload: 'auto' });
- this.video.playsInline = true;
- this.zoomWrap = el('div', 'st-zw'); this.zoomWrap.append(this.video);
- this.glassLayer = el('div', 'st-glass', null, { 'aria-hidden': 'true' });
- this.frame = el('iframe', 'st-gframe', null, { sandbox: 'allow-scripts', src: '/studio/gfx-frame.html', tabindex: '-1', 'aria-hidden': 'true', title: 'gfx' });
- this.capLayer = el('div', 'st-cap', null, { 'aria-hidden': 'true' });
- this.capText = el('div', 'st-capt'); this.capLayer.append(this.capText);
- this.capSel = el('div', 'st-capsel'); this.capSel.hidden = true;
- this.badge = el('div', 'st-vbadge'); this.badge.hidden = true;
- this.box.append(this.zoomWrap, this.glassLayer, this.frame, this.capLayer, this.capSel, this.badge);
- this.audio = el('audio', null, null, { preload: 'auto' });
- const ctrl = el('div', 'st-ctrl');
- this.tm = el('span', 'st-time mono');
- this.tmNow = el('b', null, '0:00.0'); this.tmDur = el('span', null, '0:00.0');
- this.tm.append(this.tmNow, ' / ', this.tmDur);
- this.bPrev = iconBtn('prev', 'st.prevFrame', 'st-tbtn');
- this.bPlay = el('button', 'st-play', null, { type: 'button' });
- this.bNext = iconBtn('next', 'st.nextFrame', 'st-tbtn');
- this.bRatio = el('span', 'st-pill mono', '9:16');
- this.bOut = tx('button', 'st-pill st-outsw', 'st.viewOut', { type: 'button', 'aria-pressed': 'false' });
- ctrl.append(this.tm, this.bPrev, this.bPlay, this.bNext, this.bRatio, this.bOut);
- this.root.append(this.box, ctrl, this.audio);
- this.paintPlay();
- this.mode = 'edit'; // 'edit' (nền + vẽ đè) | 'out' (MP4 đã xuất)
- this.src = { clean: null, base: null, out: null };
- this.cap = null; this.raf = 0; this.musicDur = 0; this.frameReady = false; this.gfxIds = []; this.lastGlass = '';
- this.bPlay.addEventListener('click', () => this.toggle());
- this.bPrev.addEventListener('click', () => this.step(-1 / FPS));
- this.bNext.addEventListener('click', () => this.step(1 / FPS));
- this.bOut.addEventListener('click', () => this.setMode(this.mode === 'out' ? 'edit' : 'out'));
- this.box.addEventListener('click', () => this.toggle());
- const v = this.video;
- v.addEventListener('play', () => { this.paintPlay(); this.syncAudio(true); this.loop(); this.ctx.onPlay?.(true); });
- v.addEventListener('pause', () => { this.paintPlay(); this.audio.pause(); this.ctx.onPlay?.(false); this.tick(); });
- v.addEventListener('seeked', () => { this.syncAudio(true); this.tick(); });
- v.addEventListener('loadedmetadata', () => { this.tick(); this.fit(); });
- v.addEventListener('ended', () => this.paintPlay());
- this.audio.addEventListener('loadedmetadata', () => { this.musicDur = this.audio.duration || 0; this.syncAudio(true); });
- window.addEventListener('message', (e) => {
- if (e.source !== this.frame.contentWindow || e.data?.type !== 'gfx-ready') return;
- this.frameReady = true; this.postScene(); this.tick();
- });
- this.ro = new ResizeObserver(() => this.fit());
- this.ro.observe(this.root);
- }
- get time() { return this.video.currentTime || 0; }
- get duration() { return this.ctx.store.view?.duration || this.video.duration || 0; }
- /** Nguồn đang vẽ đè: 'clean' (mọi zoom CSS) | 'base' (zoom gốc đã nằm trong nền) | null (MP4 đã xuất). */
- get layerSrc() { return this.mode !== 'edit' ? null : this.src.clean ? 'clean' : this.src.base ? 'base' : null; }
- paintPlay() {
- const playing = !this.video.paused && !this.video.ended;
- this.bPlay.replaceChildren(icon(playing ? 'pause' : 'play'));
- this.bPlay.setAttribute('aria-label', t(playing ? 'st.pause' : 'st.play'));
- this.bPlay.title = `${t(playing ? 'st.pause' : 'st.play')} (Space)`;
- }
- setSources({ clean = null, base = null, out, music }) {
- this.src = { clean, base, out };
- const edit = clean || base;
- this.bOut.hidden = !edit || !out;
- this.setMode(edit && this.mode !== 'out' ? 'edit' : 'out', true);
- if (music !== undefined) this.setMusic(music);
- }
- setMode(m, force) {
- if (m === 'edit' && !this.src.clean && !this.src.base) m = 'out';
- if (m === this.mode && !force) return;
- const at = this.time; const was = !this.video.paused;
- this.mode = m;
- const url = m === 'edit' ? this.src.clean || this.src.base : this.src.out;
- this.bOut.setAttribute('aria-pressed', String(m === 'out'));
- this.box.classList.toggle('raw', m === 'out');
- if (url && this.video.getAttribute('src') !== url) {
- this.video.src = url;
- this.video.addEventListener('loadedmetadata', () => { this.video.currentTime = Math.min(at, this.video.duration || at); if (was) this.video.play().catch(() => {}); }, { once: true });
- }
- this.badge.hidden = m === 'edit' || !(this.src.clean || this.src.base);
- this.badge.textContent = t('st.viewingOut'); this.badge.dataset.i18n = 'st.viewingOut';
- this.cap = null; this.lastGlass = ''; this.tick();
- }
- setMusic(url) {
- if (!url) { this.audio.pause(); this.audio.removeAttribute('src'); this.audio.load(); this.musicUrl = null; return; }
- if (url === this.musicUrl) return;
- this.musicUrl = url; this.audio.src = url; this.audio.load();
- }
- /** Nhả file (Windows giữ khoá file đang phát): trước khi server ghi đè base.mp4 / bản sạch. */
- release() {
- this.video.pause(); this.video.removeAttribute('src'); this.video.load();
- this.audio.pause(); this.audio.removeAttribute('src'); this.audio.load(); this.musicUrl = null;
- this.src = { clean: null, base: null, out: null };
- }
- toggle() { if (!this.video.getAttribute('src')) return; if (this.video.paused || this.video.ended) this.video.play().catch(() => {}); else this.video.pause(); }
- pause() { this.video.pause(); }
- seek(tt) {
- const d = this.duration;
- const x = clamp(tt, 0, Math.max(0, d - 1 / FPS / 2));
- if (Number.isFinite(x)) this.video.currentTime = x;
- this.tick(x);
- }
- step(dt) { this.pause(); this.seek(Math.round((this.time + dt) * FPS) / FPS); }
-
- // ---- nhạc song song: âm lượng theo dB (gần đúng), tự hạ khi có lời ----
- musicVolume(tt) {
- const m = this.ctx.store.doc?.music; if (!m || m.source === 'none' || this.mode !== 'edit') return 0;
- let db = m.gainDb + 12; // nền tiếng gốc ~ −12 dBFS
- if (m.duck && this.ctx.store.lineAt(tt) >= 0) db -= this.ctx.store.view?.music?.duckDb || 10;
- const d = this.duration; if (m.fadeOut > 0 && tt > d - m.fadeOut) db += 20 * Math.log10(Math.max(0.001, (d - tt) / m.fadeOut));
- return clamp(10 ** (db / 20), 0, 1);
- }
- syncAudio(hard) {
- const a = this.audio; const m = this.ctx.store.doc?.music;
- if (!this.musicUrl || !m || m.source === 'none' || this.mode !== 'edit') { a.pause(); return; }
- const md = this.musicDur || a.duration || 0; if (!md) return;
- const want = (m.start + this.time) % md;
- if (hard || Math.abs(a.currentTime - want) > 0.25) a.currentTime = want;
- a.volume = this.musicVolume(this.time);
- const vg = this.ctx.store.doc?.voice?.gainDb || 0;
- this.video.volume = clamp(10 ** (Math.min(0, vg) / 20), 0, 1);
- if (!this.video.paused && a.paused) a.play().catch(() => {});
- }
- loop() {
- cancelAnimationFrame(this.raf);
- const f = () => { this.tick(); if (!this.video.paused && !this.video.ended) { this.syncAudio(false); this.raf = requestAnimationFrame(f); } };
- this.raf = requestAnimationFrame(f);
- }
- /** Vẽ 1 khung theo t: giờ, zoom CSS, phụ đề, đồ hoạ (iframe), kính. */
- tick(at) {
- const tt = at ?? this.time;
- this.tmNow.textContent = fmtT(tt); this.tmDur.textContent = fmtT(this.duration);
- this.ctx.onTime?.(tt);
- const src = this.layerSrc; const doc = this.ctx.store.doc;
- this.paintZoom(src, doc, tt);
- this.paintCap(src && doc ? doc.lines.findIndex((l) => tt >= l.start && tt < l.end) : -1, tt);
- this.paintGfx(src && doc ? tt : null);
- this.paintSel();
- }
- /** Tâm zoom (px khung 1080×1920): tâm khung đầu lúc zoom bắt đầu (faces-out), không có mặt thì (540, 40%). */
- zoomCenter(z) {
- const f = this.ctx.store.view?.faces; let c = [W / 2, H * 0.4];
- if (f?.boxes?.length) {
- let best = null;
- for (const [ft, b] of f.boxes) if (b && (!best || Math.abs(ft - z.at) < Math.abs(best[0] - z.at))) best = [ft, b];
- if (best && Math.abs(best[0] - z.at) < 1) c = [(best[1][0] + best[1][2]) / 2, (best[1][1] + best[1][3]) / 2];
- }
- return c;
- }
- paintZoom(src, doc, tt) {
- let tr = '';
- if (src && doc) {
- let zs = doc.zooms;
- if (src === 'base') { const orig = this.ctx.store.orig?.zooms || []; zs = zs.filter((z) => !orig.some((o) => o.n === z.n && Math.abs(o.at - z.at) < 0.005 && o.dur === z.dur && o.scale === z.scale && o.kind === z.kind)); }
- const { s, z } = zoomAt(zs, tt);
- if (s > 1.0005) {
- const k = this.k || 0.25;
- if (src === 'clean') {
- // như lumedit: cửa sổ W/s × H/s, x0 = cx − W/2s, y0 = cy − 0,42·H/s, kẹp trong khung
- const [cx, cy] = this.zoomCenter(z);
- const x0 = clamp(cx - W / (2 * s), 0, W - W / s); const y0 = clamp(cy - (H * 0.42) / s, 0, H - H / s);
- tr = `translate(${(-x0 * s * k).toFixed(2)}px, ${(-y0 * s * k).toFixed(2)}px) scale(${s.toFixed(4)})`;
- } else tr = `translate(${((1 - s) * W * 0.5 * k).toFixed(2)}px, ${((1 - s) * H * 0.4 * k).toFixed(2)}px) scale(${s.toFixed(4)})`;
- }
- }
- if (this.zoomWrap.style.transform !== tr) this.zoomWrap.style.transform = tr;
- }
- fit() {
- const w = this.box.clientWidth || 1;
- this.k = w / W;
- this.box.style.setProperty('--k', String(this.k));
- this.frame.style.transform = `scale(${this.k})`;
- this.cap = null; this.lastGlass = '';
- this.tick();
- }
- lookCss() {
- const s = this.ctx.store; const id = s.doc?.look;
- return s.view?.captions.looks.find((l) => l.id === id)?.css || null;
- }
-
- // ---- phụ đề: dựng DOM khi đổi dòng, mỗi khung chỉ đổi transform/opacity/màu ----
- /** Giờ từng chữ: giờ karaoke gốc (co giãn theo giờ dòng mới) nếu chữ không đổi, không thì chia theo số ký tự như server. */
- wordTimes(line, ws) {
- const o = line.wo; const n = ws.length;
- if (Array.isArray(o) && o.length === n && line.wt === line.text && Number.isFinite(line.w0) && line.w1 > line.w0) {
- const f = (line.end - line.start) / (line.w1 - line.w0);
- return o.map((x) => line.start + (x - line.w0) * f);
- }
- const len = ws.map((w) => [...w.w].length); const tot = len.reduce((a, b) => a + b, 0) || 1;
- let acc = 0; return len.map((l) => { const x = line.start + ((line.end - line.start) * acc) / tot; acc += l; return x; });
- }
- buildCap(line, look) {
- const s = this.ctx.store; const k = this.k || 0.25;
- const box = this.capText; const ticker = look.enter === 'ticker' && look.box;
- const ws = tokens(line.text);
- const text = ws.map((w) => { const x = w.w.replace(/[,.;:]+$/u, '') || w.w; return look.upper ? x.toUpperCase() : x; });
- let size = look.size;
- if (ticker) { const nch = text.join(' ').length; size = Math.max(34, Math.min(look.size, Math.floor((960 - 300) / (nch * 0.46 + 0.4)))); }
- else if (ws.length === 1) size = Math.min(look.size, Math.floor(840 / (Math.max(...text.map((x) => x.length)) * 0.5 + 0.5)));
- const stroke = look.box ? (look.box.stroke ?? 0) : (look.stroke ?? (look.upper ? 10 : 8));
- const shadow = look.shadow || (ticker ? 'none' : '0 6px 18px rgba(0,0,0,.55)');
- box.className = 'st-capt' + (ticker ? ' ticker' : '');
- box.style.fontFamily = `${look.font}, 'Be Vietnam Pro', sans-serif`;
- box.style.fontWeight = String(look.weight);
- box.style.fontSize = `${(size * k).toFixed(2)}px`;
- box.style.color = look.color;
- box.style.top = `${(look.cy * H * k).toFixed(1)}px`;
- box.style.webkitTextStroke = stroke ? `${(stroke * k).toFixed(2)}px #000` : '0';
- box.style.textShadow = shadow === 'none' ? 'none' : shadow.replace(/(-?\d+(?:\.\d+)?)px/g, (m0, v) => `${(Number(v) * k).toFixed(2)}px`);
- box.style.background = ticker ? look.box.bg : '';
- const hiOn = !!s.doc.hi;
- const kids = []; const words = [];
- if (ticker && look.box.tag) { const tg = el('span', 'tag', look.box.tag); tg.style.background = look.box.tagBg || '#E8202A'; kids.push(tg); }
- ws.forEach((w, i) => {
- if (i) kids.push(' ');
- const sp = el('span', 'w');
- const base = w.hi && hiOn ? look.hi : look.color;
- if (look.enter === 'typewriter') for (const ch of [...text[i]]) sp.append(el('i', 'ch', ch)); else sp.textContent = text[i];
- sp.style.color = base;
- kids.push(sp); words.push({ el: sp, base });
- });
- box.replaceChildren(...kids);
- const wo = this.wordTimes(line, ws);
- const L = s.doc.lines; const idx = L.indexOf(line); const next = L[idx + 1]; const prev = L[idx - 1];
- const chars = [...box.querySelectorAll('.ch')];
- return { line, look, words, wo, chars, ticker, fadeOut: (!next || next.start - line.end >= 0.3) && line.end - line.start > 0.55,
- runStart: ticker && (!prev || line.start - prev.end > 0.5 || /[.?!…]$/.test(prev.text.trim())) };
- }
- paintCap(idx, tt) {
- const s = this.ctx.store; const L = s.doc?.lines || []; const line = L[idx]; const look = this.lookCss();
- const box = this.capText;
- if (!line || !look) { if (this.cap) { box.replaceChildren(); box.hidden = true; this.cap = null; } return; }
- const key = `${line.u}|${line.text}|${line.start}|${line.end}|${s.doc.look}|${s.doc.hi}|${this.k}`;
- if (!this.cap || this.cap.key !== key) { this.cap = this.buildCap(line, look); this.cap.key = key; }
- box.hidden = false;
- const c = this.cap; const u = tt - line.start; const k = this.k || 0.25;
- let x = 0; let y = 0; let sc = 1; let op = 1;
- switch (look.enter) {
- case 'pop': sc = 0.55 + 0.45 * backOut(3)(u / 0.18); break;
- case 'pop-soft': { const e = backOut(2.2)(u / 0.14); sc = 0.86 + 0.14 * e; op = clamp(e, 0, 1); break; }
- case 'slide-left': { const e = pOut(3)(u / 0.16); x = 80 * (1 - e); op = e; break; }
- case 'slam': {
- const e = pIn(4)(u / 0.12); sc = 1.6 - 0.6 * e; op = 0.4 + 0.6 * e;
- const sh = [6, -6, 6, 0]; let px = 0;
- for (let q = 0; q < 4; q++) { const a0 = 0.12 + q * 0.025; if (u >= a0) px = u >= a0 + 0.025 ? sh[q] : px + (sh[q] - px) * ((u - a0) / 0.025); }
- x = px; break;
- }
- case 'fade-slow': op = pOut(1)(u / 0.3); if (c.fadeOut && tt > line.end - 0.25) op *= 1 - pIn(1)((tt - (line.end - 0.25)) / 0.25); break;
- case 'typewriter': {
- const n = c.chars.length; const st = Math.min(0.035, ((line.end - line.start) * 0.6) / Math.max(1, n));
- c.chars.forEach((ch, q) => { const v = u >= q * st ? '1' : '0'; if (ch.style.opacity !== v) ch.style.opacity = v; });
- break;
- }
- case 'ticker': if (c.runStart) x = -W * (1 - pOut(3)(u / 0.2)); else op = clamp(u / 0.08, 0, 1); break;
- default: { const e = pOut(2)(u / 0.12); y = 18 * (1 - e); op = e; }
- }
- box.style.transform = `translate(${(x * k).toFixed(2)}px, ${(y * k).toFixed(2)}px) scale(${sc.toFixed(4)})`;
- box.style.opacity = op.toFixed(3);
- // karaoke: chữ đang nói tô màu nhấn
- if (look.karaoke && c.words.length > 1) {
- c.words.forEach((w, q) => {
- const a = c.wo[q]; const b = q + 1 < c.wo.length ? c.wo[q + 1] : line.end;
- const col = tt >= a && tt < b ? look.hi : w.base;
- if (w.el.style.color !== col) w.el.style.color = col;
- });
- }
- }
- /** Khung chọn quanh dòng chữ đang chọn (như mẫu) — chỉ khi dòng đó đang hiện. */
- paintSel() {
- const sel = this.ctx.getSel?.();
- const show = !!this.layerSrc && sel?.kind === 'cap' && !this.capText.hidden && this.cap?.line?.u === sel.u;
- this.capSel.hidden = !show;
- if (!show) return;
- const b = this.box.getBoundingClientRect(); const r = this.capText.getBoundingClientRect();
- this.capSel.style.transform = `translate(${(r.left - b.left - 6).toFixed(1)}px, ${(r.top - b.top - 4).toFixed(1)}px)`;
- this.capSel.style.width = `${(r.width + 12).toFixed(1)}px`; this.capSel.style.height = `${(r.height + 8).toFixed(1)}px`;
- }
-
- // ---- đồ hoạ: cảnh thật trong iframe sandbox + kính mờ ----
- /** Cảnh mới (server dựng từ đồ hoạ đang sửa): gửi vào khung. scene = {css, html, data} | null. */
- setGfxScene(scene) { this.gfxScene = scene; this.postScene(); this.tick(); }
- postScene() {
- if (!this.frameReady || !this.frame.contentWindow) return;
- const sc = this.gfxScene || { css: '', html: '', data: [] };
- // khung sandbox có origin rỗng → targetOrigin '*'; chỉ gửi cảnh đồ hoạ (không có gì bí mật)
- this.frame.contentWindow.postMessage({ type: 'scene', css: sc.css, html: sc.html, G: sc.data }, '*');
- }
- paintGfx(tt) {
- const on = tt != null && !!this.gfxScene?.data?.length;
- this.frame.hidden = !on;
- if (on && this.frameReady && tt !== this.lastGfxT) { this.lastGfxT = tt; this.frame.contentWindow.postMessage({ type: 't', t: tt }, '*'); }
- // kính mờ dưới thẻ (như bước ghép: tem giá / sticker / thẻ ghim không có kính)
- const doc = this.ctx.store.doc; const k = this.k || 0.25;
- const list = on && this.layerSrc === 'clean' ? doc.gfx.filter((g) => g.box && !['price_tag', 'sticker'].includes(g.type) && !g.data?.pin && tt >= g.at && tt < g.until) : [];
- const key = list.map((g) => `${g.u}|${JSON.stringify(g.box)}`).join('#') + k;
- if (key !== this.lastGlass) {
- this.lastGlass = key;
- this.glassLayer.replaceChildren(...list.map((g) => {
- const d = el('div', 'gl', null, { 'data-u': g.u }); const b = g.box;
- d.style.transform = `translate(${(b.x * k).toFixed(1)}px, ${(b.y * k).toFixed(1)}px)`;
- d.style.width = `${(b.w * k).toFixed(1)}px`; d.style.height = `${(b.h * k).toFixed(1)}px`;
- d.style.borderRadius = `${(38 * (b.scale ?? 1) * k).toFixed(1)}px`;
- d.style.backdropFilter = d.style.webkitBackdropFilter = `blur(${(24 * k).toFixed(1)}px)`;
- return d;
- }));
- }
- for (const d of this.glassLayer.children) {
- const g = doc.gfx.find((x) => x.u === d.dataset.u); if (!g) continue;
- const a = Math.min(ease((tt - g.at) / 0.15), ease((g.until - tt) / 0.22));
- d.style.opacity = a.toFixed(3);
- }
- }
- destroy() { cancelAnimationFrame(this.raf); this.ro.disconnect(); this.release(); }
-}
+// Player giữa Studio — xem trước tức thì, không render:
+// · nền SẠCH (preview-clean.mp4: đã cắt + khung, CHƯA zoom/kính/chữ) → MỌI zoom (cũ lẫn mới) chạy bằng CSS transform
+// theo EDL đang sửa, cùng công thức lumedit Zooms (punch/push, tâm đầu lúc zoom bắt đầu, khung đặt 0,42 chiều cao);
+// · phụ đề HTML theo đúng tham số LOOKS (cỡ, stroke, bóng, cy, chữ hoa, bỏ dấu câu cuối) + hiệu ứng vào (GSAP ease
+// tương đương) + karaoke theo giờ từng chữ — tính thuần theo t nên tua tới đâu đúng tới đó;
+// · đồ hoạ: chính HTML/CSS/runtime của lớp HyperFrames trong <iframe sandbox="allow-scripts"> (postMessage), kính mờ
+// dưới thẻ bằng backdrop-filter;
+// · nhạc phát song song (<audio>, âm lượng theo dB, tự hạ khi có lời).
+// Không có nền sạch → nền cũ (base.mp4, đã có zoom gốc: chỉ zoom mới chạy CSS). "Bản xuất" → phát MP4 đã xuất, không vẽ đè.
+import { el, tx, icon, iconBtn, fmtT, tokens, clamp, t } from './util.js';
+
+const FPS = 30; const W = 1080; const H = 1920;
+const ease = (x) => { x = clamp(x, 0, 1); return x * x * (3 - 2 * x); };
+// GSAP: powerN.out = 1 − (1 − x)^(N+1); back.out(c)
+const pOut = (n) => (x) => 1 - (1 - clamp(x, 0, 1)) ** (n + 1);
+const pIn = (n) => (x) => clamp(x, 0, 1) ** (n + 1);
+const backOut = (c) => (x) => { x = clamp(x, 0, 1); return 1 + (c + 1) * (x - 1) ** 3 + c * (x - 1) ** 2; };
+
+/** Như lumedit Zooms.scale_at: punch (vào 0,08 s, giữ, ra 0,12 s) / push (đẩy chậm, lùi 0,3 s cuối). Trả {s, z}. */
+export function zoomAt(zs, tt) {
+ for (const z of zs) {
+ if (tt < z.at || tt >= z.at + z.dur) continue;
+ const u = tt - z.at; let k;
+ if (z.kind === 'punch') { k = u < 0.08 ? ease(u / 0.08) : 1; if (u > z.dur - 0.12) k = Math.min(k, ease((z.dur - u) / 0.12)); }
+ else { const back = Math.min(0.3, z.dur * 0.2); k = u < z.dur - back ? ease(u / (z.dur - back)) : ease((z.dur - u) / back); }
+ return { s: 1 + (z.scale - 1) * k, z };
+ }
+ return { s: 1, z: null };
+}
+export const zoomScale = (zs, tt) => zoomAt(zs, tt).s;
+
+export class Player {
+ constructor(ctx) {
+ this.ctx = ctx; // {store, onTime(t), onPlay(bool), getSel(), gfxScene()}
+ this.root = el('section', 'st-stage');
+ this.box = el('div', 'st-vid');
+ this.video = el('video', null, null, { playsinline: true, preload: 'auto' });
+ this.video.playsInline = true;
+ this.zoomWrap = el('div', 'st-zw'); this.zoomWrap.append(this.video);
+ this.glassLayer = el('div', 'st-glass', null, { 'aria-hidden': 'true' });
+ this.frame = el('iframe', 'st-gframe', null, { sandbox: 'allow-scripts', src: '/studio/gfx-frame.html', tabindex: '-1', 'aria-hidden': 'true', title: 'gfx' });
+ this.capLayer = el('div', 'st-cap', null, { 'aria-hidden': 'true' });
+ this.capText = el('div', 'st-capt'); this.capLayer.append(this.capText);
+ this.capSel = el('div', 'st-capsel'); this.capSel.hidden = true;
+ this.badge = el('div', 'st-vbadge'); this.badge.hidden = true;
+ this.box.append(this.zoomWrap, this.glassLayer, this.frame, this.capLayer, this.capSel, this.badge);
+ this.audio = el('audio', null, null, { preload: 'auto' });
+ const ctrl = el('div', 'st-ctrl');
+ this.tm = el('span', 'st-time mono');
+ this.tmNow = el('b', null, '0:00.0'); this.tmDur = el('span', null, '0:00.0');
+ this.tm.append(this.tmNow, ' / ', this.tmDur);
+ this.bPrev = iconBtn('prev', 'st.prevFrame', 'st-tbtn');
+ this.bPlay = el('button', 'st-play', null, { type: 'button' });
+ this.bNext = iconBtn('next', 'st.nextFrame', 'st-tbtn');
+ this.bRatio = el('span', 'st-pill mono', '9:16');
+ this.bOut = tx('button', 'st-pill st-outsw', 'st.viewOut', { type: 'button', 'aria-pressed': 'false' });
+ ctrl.append(this.tm, this.bPrev, this.bPlay, this.bNext, this.bRatio, this.bOut);
+ this.root.append(this.box, ctrl, this.audio);
+ this.paintPlay();
+ this.mode = 'edit'; // 'edit' (nền + vẽ đè) | 'out' (MP4 đã xuất)
+ this.src = { clean: null, base: null, out: null };
+ this.cap = null; this.raf = 0; this.musicDur = 0; this.frameReady = false; this.gfxIds = []; this.lastGlass = '';
+ this.bPlay.addEventListener('click', () => this.toggle());
+ this.bPrev.addEventListener('click', () => this.step(-1 / FPS));
+ this.bNext.addEventListener('click', () => this.step(1 / FPS));
+ this.bOut.addEventListener('click', () => this.setMode(this.mode === 'out' ? 'edit' : 'out'));
+ this.box.addEventListener('click', () => this.toggle());
+ const v = this.video;
+ v.addEventListener('play', () => { this.paintPlay(); this.syncAudio(true); this.loop(); this.ctx.onPlay?.(true); });
+ v.addEventListener('pause', () => { this.paintPlay(); this.audio.pause(); this.ctx.onPlay?.(false); this.tick(); });
+ v.addEventListener('seeked', () => { this.syncAudio(true); this.tick(); });
+ v.addEventListener('loadedmetadata', () => { this.tick(); this.fit(); });
+ v.addEventListener('ended', () => this.paintPlay());
+ this.audio.addEventListener('loadedmetadata', () => { this.musicDur = this.audio.duration || 0; this.syncAudio(true); });
+ window.addEventListener('message', (e) => {
+ if (e.source !== this.frame.contentWindow || e.data?.type !== 'gfx-ready') return;
+ this.frameReady = true; this.postScene(); this.tick();
+ });
+ this.ro = new ResizeObserver(() => this.fit());
+ this.ro.observe(this.root);
+ }
+ get time() { return this.video.currentTime || 0; }
+ get duration() { return this.ctx.store.view?.duration || this.video.duration || 0; }
+ /** Nguồn đang vẽ đè: 'clean' (mọi zoom CSS) | 'base' (zoom gốc đã nằm trong nền) | null (MP4 đã xuất). */
+ get layerSrc() { return this.mode !== 'edit' ? null : this.src.clean ? 'clean' : this.src.base ? 'base' : null; }
+ paintPlay() {
+ const playing = !this.video.paused && !this.video.ended;
+ this.bPlay.replaceChildren(icon(playing ? 'pause' : 'play'));
+ this.bPlay.setAttribute('aria-label', t(playing ? 'st.pause' : 'st.play'));
+ this.bPlay.title = `${t(playing ? 'st.pause' : 'st.play')} (Space)`;
+ }
+ setSources({ clean = null, base = null, out, music }) {
+ this.src = { clean, base, out };
+ const edit = clean || base;
+ this.bOut.hidden = !edit || !out;
+ this.setMode(edit && this.mode !== 'out' ? 'edit' : 'out', true);
+ if (music !== undefined) this.setMusic(music);
+ }
+ setMode(m, force) {
+ if (m === 'edit' && !this.src.clean && !this.src.base) m = 'out';
+ if (m === this.mode && !force) return;
+ const at = this.time; const was = !this.video.paused;
+ this.mode = m;
+ const url = m === 'edit' ? this.src.clean || this.src.base : this.src.out;
+ this.bOut.setAttribute('aria-pressed', String(m === 'out'));
+ this.box.classList.toggle('raw', m === 'out');
+ if (url && this.video.getAttribute('src') !== url) {
+ this.video.src = url;
+ this.video.addEventListener('loadedmetadata', () => { this.video.currentTime = Math.min(at, this.video.duration || at); if (was) this.video.play().catch(() => {}); }, { once: true });
+ }
+ this.badge.hidden = m === 'edit' || !(this.src.clean || this.src.base);
+ this.badge.textContent = t('st.viewingOut'); this.badge.dataset.i18n = 'st.viewingOut';
+ this.cap = null; this.lastGlass = ''; this.tick();
+ }
+ setMusic(url) {
+ if (!url) { this.audio.pause(); this.audio.removeAttribute('src'); this.audio.load(); this.musicUrl = null; return; }
+ if (url === this.musicUrl) return;
+ this.musicUrl = url; this.audio.src = url; this.audio.load();
+ }
+ /** Nhả file (Windows giữ khoá file đang phát): trước khi server ghi đè base.mp4 / bản sạch. */
+ release() {
+ this.video.pause(); this.video.removeAttribute('src'); this.video.load();
+ this.audio.pause(); this.audio.removeAttribute('src'); this.audio.load(); this.musicUrl = null;
+ this.src = { clean: null, base: null, out: null };
+ }
+ toggle() { if (!this.video.getAttribute('src')) return; if (this.video.paused || this.video.ended) this.video.play().catch(() => {}); else this.video.pause(); }
+ pause() { this.video.pause(); }
+ seek(tt) {
+ const d = this.duration;
+ const x = clamp(tt, 0, Math.max(0, d - 1 / FPS / 2));
+ if (Number.isFinite(x)) this.video.currentTime = x;
+ this.tick(x);
+ }
+ step(dt) { this.pause(); this.seek(Math.round((this.time + dt) * FPS) / FPS); }
+
+ // ---- nhạc song song: âm lượng theo dB (gần đúng), tự hạ khi có lời ----
+ musicVolume(tt) {
+ const m = this.ctx.store.doc?.music; if (!m || m.source === 'none' || this.mode !== 'edit') return 0;
+ let db = m.gainDb + 12; // nền tiếng gốc ~ −12 dBFS
+ if (m.duck && this.ctx.store.lineAt(tt) >= 0) db -= this.ctx.store.view?.music?.duckDb || 10;
+ const d = this.duration; if (m.fadeOut > 0 && tt > d - m.fadeOut) db += 20 * Math.log10(Math.max(0.001, (d - tt) / m.fadeOut));
+ return clamp(10 ** (db / 20), 0, 1);
+ }
+ syncAudio(hard) {
+ const a = this.audio; const m = this.ctx.store.doc?.music;
+ if (!this.musicUrl || !m || m.source === 'none' || this.mode !== 'edit') { a.pause(); return; }
+ const md = this.musicDur || a.duration || 0; if (!md) return;
+ const want = (m.start + this.time) % md;
+ if (hard || Math.abs(a.currentTime - want) > 0.25) a.currentTime = want;
+ a.volume = this.musicVolume(this.time);
+ const vg = this.ctx.store.doc?.voice?.gainDb || 0;
+ this.video.volume = clamp(10 ** (Math.min(0, vg) / 20), 0, 1);
+ if (!this.video.paused && a.paused) a.play().catch(() => {});
+ }
+ loop() {
+ cancelAnimationFrame(this.raf);
+ const f = () => { this.tick(); if (!this.video.paused && !this.video.ended) { this.syncAudio(false); this.raf = requestAnimationFrame(f); } };
+ this.raf = requestAnimationFrame(f);
+ }
+ /** Vẽ 1 khung theo t: giờ, zoom CSS, phụ đề, đồ hoạ (iframe), kính. */
+ tick(at) {
+ let tt = at ?? this.time;
+ // đang phát qua chỗ đã cắt (chưa xuất bản): nhảy qua như bản sau khi cắt
+ const cut = this.layerSrc && !this.video.paused ? this.ctx.store.cutAt(tt) : null;
+ if (cut) { this.video.currentTime = Math.min(cut[1] + 0.001, this.duration); tt = cut[1]; }
+ this.tmNow.textContent = fmtT(tt); this.tmDur.textContent = fmtT(this.duration);
+ this.ctx.onTime?.(tt);
+ const src = this.layerSrc; const doc = this.ctx.store.doc;
+ this.paintZoom(src, doc, tt);
+ this.paintCap(src && doc && doc.show !== false && !this.ctx.store.cutAt(tt) ? doc.lines.findIndex((l) => tt >= l.start && tt < l.end) : -1, tt);
+ this.paintGfx(src && doc ? tt : null);
+ this.paintSel();
+ }
+ /** Tâm zoom (px khung 1080×1920): tâm khung đầu lúc zoom bắt đầu (faces-out), không có mặt thì (540, 40%). */
+ zoomCenter(z) {
+ const f = this.ctx.store.view?.faces; let c = [W / 2, H * 0.4];
+ if (f?.boxes?.length) {
+ let best = null;
+ for (const [ft, b] of f.boxes) if (b && (!best || Math.abs(ft - z.at) < Math.abs(best[0] - z.at))) best = [ft, b];
+ if (best && Math.abs(best[0] - z.at) < 1) c = [(best[1][0] + best[1][2]) / 2, (best[1][1] + best[1][3]) / 2];
+ }
+ return c;
+ }
+ paintZoom(src, doc, tt) {
+ let tr = '';
+ if (src && doc) {
+ let zs = doc.zooms;
+ if (src === 'base') { const orig = this.ctx.store.orig?.zooms || []; zs = zs.filter((z) => !orig.some((o) => o.n === z.n && Math.abs(o.at - z.at) < 0.005 && o.dur === z.dur && o.scale === z.scale && o.kind === z.kind)); }
+ const { s, z } = zoomAt(zs, tt);
+ if (s > 1.0005) {
+ const k = this.k || 0.25;
+ if (src === 'clean') {
+ // như lumedit: cửa sổ W/s × H/s, x0 = cx − W/2s, y0 = cy − 0,42·H/s, kẹp trong khung
+ const [cx, cy] = this.zoomCenter(z);
+ const x0 = clamp(cx - W / (2 * s), 0, W - W / s); const y0 = clamp(cy - (H * 0.42) / s, 0, H - H / s);
+ tr = `translate(${(-x0 * s * k).toFixed(2)}px, ${(-y0 * s * k).toFixed(2)}px) scale(${s.toFixed(4)})`;
+ } else tr = `translate(${((1 - s) * W * 0.5 * k).toFixed(2)}px, ${((1 - s) * H * 0.4 * k).toFixed(2)}px) scale(${s.toFixed(4)})`;
+ }
+ }
+ if (this.zoomWrap.style.transform !== tr) this.zoomWrap.style.transform = tr;
+ }
+ fit() {
+ const w = this.box.clientWidth || 1;
+ this.k = w / W;
+ this.box.style.setProperty('--k', String(this.k));
+ this.frame.style.transform = `scale(${this.k})`;
+ this.cap = null; this.lastGlass = '';
+ this.tick();
+ }
+ lookCss() {
+ const s = this.ctx.store; const id = s.doc?.look;
+ return s.view?.captions.looks.find((l) => l.id === id)?.css || null;
+ }
+
+ // ---- phụ đề: dựng DOM khi đổi dòng, mỗi khung chỉ đổi transform/opacity/màu ----
+ /** Giờ từng chữ: giờ karaoke gốc (co giãn theo giờ dòng mới) nếu chữ không đổi, không thì chia theo số ký tự như server. */
+ wordTimes(line, ws) {
+ const o = line.wo; const n = ws.length;
+ if (Array.isArray(o) && o.length === n && line.wt === line.text && Number.isFinite(line.w0) && line.w1 > line.w0) {
+ const f = (line.end - line.start) / (line.w1 - line.w0);
+ return o.map((x) => line.start + (x - line.w0) * f);
+ }
+ const len = ws.map((w) => [...w.w].length); const tot = len.reduce((a, b) => a + b, 0) || 1;
+ let acc = 0; return len.map((l) => { const x = line.start + ((line.end - line.start) * acc) / tot; acc += l; return x; });
+ }
+ buildCap(line, look) {
+ const s = this.ctx.store; const k = this.k || 0.25;
+ const box = this.capText; const ticker = look.enter === 'ticker' && look.box;
+ const ws = tokens(line.text);
+ const text = ws.map((w) => { const x = w.w.replace(/[,.;:]+$/u, '') || w.w; return look.upper ? x.toUpperCase() : x; });
+ let size = look.size;
+ if (ticker) { const nch = text.join(' ').length; size = Math.max(34, Math.min(look.size, Math.floor((960 - 300) / (nch * 0.46 + 0.4)))); }
+ else if (ws.length === 1) size = Math.min(look.size, Math.floor(840 / (Math.max(...text.map((x) => x.length)) * 0.5 + 0.5)));
+ const stroke = look.box ? (look.box.stroke ?? 0) : (look.stroke ?? (look.upper ? 10 : 8));
+ const shadow = look.shadow || (ticker ? 'none' : '0 6px 18px rgba(0,0,0,.55)');
+ box.className = 'st-capt' + (ticker ? ' ticker' : '');
+ box.style.fontFamily = `${look.font}, 'Be Vietnam Pro', sans-serif`;
+ box.style.fontWeight = String(look.weight);
+ box.style.fontSize = `${(size * k).toFixed(2)}px`;
+ box.style.color = look.color;
+ box.style.top = `${(look.cy * H * k).toFixed(1)}px`;
+ box.style.webkitTextStroke = stroke ? `${(stroke * k).toFixed(2)}px #000` : '0';
+ box.style.textShadow = shadow === 'none' ? 'none' : shadow.replace(/(-?\d+(?:\.\d+)?)px/g, (m0, v) => `${(Number(v) * k).toFixed(2)}px`);
+ box.style.background = ticker ? look.box.bg : '';
+ const hiOn = !!s.doc.hi;
+ const kids = []; const words = [];
+ if (ticker && look.box.tag) { const tg = el('span', 'tag', look.box.tag); tg.style.background = look.box.tagBg || '#E8202A'; kids.push(tg); }
+ ws.forEach((w, i) => {
+ if (i) kids.push(' ');
+ const sp = el('span', 'w');
+ const base = w.hi && hiOn ? look.hi : look.color;
+ if (look.enter === 'typewriter') for (const ch of [...text[i]]) sp.append(el('i', 'ch', ch)); else sp.textContent = text[i];
+ sp.style.color = base;
+ kids.push(sp); words.push({ el: sp, base });
+ });
+ box.replaceChildren(...kids);
+ const wo = this.wordTimes(line, ws);
+ const L = s.doc.lines; const idx = L.indexOf(line); const next = L[idx + 1]; const prev = L[idx - 1];
+ const chars = [...box.querySelectorAll('.ch')];
+ return { line, look, words, wo, chars, ticker, fadeOut: (!next || next.start - line.end >= 0.3) && line.end - line.start > 0.55,
+ runStart: ticker && (!prev || line.start - prev.end > 0.5 || /[.?!…]$/.test(prev.text.trim())) };
+ }
+ paintCap(idx, tt) {
+ const s = this.ctx.store; const L = s.doc?.lines || []; const line = L[idx]; const look = this.lookCss();
+ const box = this.capText;
+ if (!line || !look) { if (this.cap) { box.replaceChildren(); box.hidden = true; this.cap = null; } return; }
+ const key = `${line.u}|${line.text}|${line.start}|${line.end}|${s.doc.look}|${s.doc.hi}|${this.k}|${s.doc.show}`;
+ if (!this.cap || this.cap.key !== key) { this.cap = this.buildCap(line, look); this.cap.key = key; }
+ box.hidden = false;
+ const c = this.cap; const u = tt - line.start; const k = this.k || 0.25;
+ let x = 0; let y = 0; let sc = 1; let op = 1;
+ switch (look.enter) {
+ case 'pop': sc = 0.55 + 0.45 * backOut(3)(u / 0.18); break;
+ case 'pop-soft': { const e = backOut(2.2)(u / 0.14); sc = 0.86 + 0.14 * e; op = clamp(e, 0, 1); break; }
+ case 'slide-left': { const e = pOut(3)(u / 0.16); x = 80 * (1 - e); op = e; break; }
+ case 'slam': {
+ const e = pIn(4)(u / 0.12); sc = 1.6 - 0.6 * e; op = 0.4 + 0.6 * e;
+ const sh = [6, -6, 6, 0]; let px = 0;
+ for (let q = 0; q < 4; q++) { const a0 = 0.12 + q * 0.025; if (u >= a0) px = u >= a0 + 0.025 ? sh[q] : px + (sh[q] - px) * ((u - a0) / 0.025); }
+ x = px; break;
+ }
+ case 'fade-slow': op = pOut(1)(u / 0.3); if (c.fadeOut && tt > line.end - 0.25) op *= 1 - pIn(1)((tt - (line.end - 0.25)) / 0.25); break;
+ case 'typewriter': {
+ const n = c.chars.length; const st = Math.min(0.035, ((line.end - line.start) * 0.6) / Math.max(1, n));
+ c.chars.forEach((ch, q) => { const v = u >= q * st ? '1' : '0'; if (ch.style.opacity !== v) ch.style.opacity = v; });
+ break;
+ }
+ case 'ticker': if (c.runStart) x = -W * (1 - pOut(3)(u / 0.2)); else op = clamp(u / 0.08, 0, 1); break;
+ default: { const e = pOut(2)(u / 0.12); y = 18 * (1 - e); op = e; }
+ }
+ box.style.transform = `translate(${(x * k).toFixed(2)}px, ${(y * k).toFixed(2)}px) scale(${sc.toFixed(4)})`;
+ box.style.opacity = op.toFixed(3);
+ // karaoke: chữ đang nói tô màu nhấn
+ if (look.karaoke && c.words.length > 1) {
+ c.words.forEach((w, q) => {
+ const a = c.wo[q]; const b = q + 1 < c.wo.length ? c.wo[q + 1] : line.end;
+ const col = tt >= a && tt < b ? look.hi : w.base;
+ if (w.el.style.color !== col) w.el.style.color = col;
+ });
+ }
+ }
+ /** Khung chọn quanh dòng chữ đang chọn (như mẫu) — chỉ khi dòng đó đang hiện. */
+ paintSel() {
+ const sel = this.ctx.getSel?.();
+ const show = !!this.layerSrc && sel?.kind === 'cap' && !this.capText.hidden && this.cap?.line?.u === sel.u;
+ this.capSel.hidden = !show;
+ if (!show) return;
+ const b = this.box.getBoundingClientRect(); const r = this.capText.getBoundingClientRect();
+ this.capSel.style.transform = `translate(${(r.left - b.left - 6).toFixed(1)}px, ${(r.top - b.top - 4).toFixed(1)}px)`;
+ this.capSel.style.width = `${(r.width + 12).toFixed(1)}px`; this.capSel.style.height = `${(r.height + 8).toFixed(1)}px`;
+ }
+
+ // ---- đồ hoạ: cảnh thật trong iframe sandbox + kính mờ ----
+ /** Cảnh mới (server dựng từ đồ hoạ đang sửa): gửi vào khung. scene = {css, html, data} | null. */
+ setGfxScene(scene) { this.gfxScene = scene; this.postScene(); this.tick(); }
+ postScene() {
+ if (!this.frameReady || !this.frame.contentWindow) return;
+ const sc = this.gfxScene || { css: '', html: '', data: [] };
+ // khung sandbox có origin rỗng → targetOrigin '*'; chỉ gửi cảnh đồ hoạ (không có gì bí mật)
+ this.frame.contentWindow.postMessage({ type: 'scene', css: sc.css, html: sc.html, G: sc.data }, '*');
+ }
+ paintGfx(tt) {
+ const on = tt != null && !!this.gfxScene?.data?.length;
+ this.frame.hidden = !on;
+ if (on && this.frameReady && tt !== this.lastGfxT) { this.lastGfxT = tt; this.frame.contentWindow.postMessage({ type: 't', t: tt }, '*'); }
+ // kính mờ dưới thẻ (như bước ghép: tem giá / sticker / thẻ ghim không có kính)
+ const doc = this.ctx.store.doc; const k = this.k || 0.25;
+ const list = on && this.layerSrc === 'clean' ? doc.gfx.filter((g) => g.box && !['price_tag', 'sticker'].includes(g.type) && !g.data?.pin && tt >= g.at && tt < g.until) : [];
+ const key = list.map((g) => `${g.u}|${JSON.stringify(g.box)}`).join('#') + k;
+ if (key !== this.lastGlass) {
+ this.lastGlass = key;
+ this.glassLayer.replaceChildren(...list.map((g) => {
+ const d = el('div', 'gl', null, { 'data-u': g.u }); const b = g.box;
+ d.style.transform = `translate(${(b.x * k).toFixed(1)}px, ${(b.y * k).toFixed(1)}px)`;
+ d.style.width = `${(b.w * k).toFixed(1)}px`; d.style.height = `${(b.h * k).toFixed(1)}px`;
+ d.style.borderRadius = `${(38 * (b.scale ?? 1) * k).toFixed(1)}px`;
+ d.style.backdropFilter = d.style.webkitBackdropFilter = `blur(${(24 * k).toFixed(1)}px)`;
+ return d;
+ }));
+ }
+ for (const d of this.glassLayer.children) {
+ const g = doc.gfx.find((x) => x.u === d.dataset.u); if (!g) continue;
+ const a = Math.min(ease((tt - g.at) / 0.15), ease((g.until - tt) / 0.22));
+ d.style.opacity = a.toFixed(3);
+ }
+ }
+ destroy() { cancelAnimationFrame(this.raf); this.ro.disconnect(); this.release(); }
+}
diff --git a/server/public/studio/store.js b/server/public/studio/store.js
index d2601cf..75699bc 100644
--- a/server/public/studio/store.js
+++ b/server/public/studio/store.js
@@ -12,7 +12,8 @@ const nid = (p) => `${p}${++uid}`;
function toDoc(v) {
return {
lines: v.captions.lines.map((l) => ({ u: nid('l'), start: l.start, end: l.end, text: l.text, ...(Array.isArray(l.wo) ? { wo: l.wo, wt: l.text, w0: l.start, w1: l.end } : {}) })),
- look: v.captions.look, hi: !!v.captions.highlights,
+ look: v.captions.look, hi: !!v.captions.highlights, show: v.captions.show !== false,
+ cuts: [], vsplits: [],
music: { source: v.music.on ? 'keep' : 'none', gainDb: v.music.gainDb, duck: !!v.music.duck, fadeOut: v.music.fadeOut, start: v.music.start || 0 },
voice: { gainDb: v.voice.gainDb }, sfx: { on: !!v.sfx.on },
zooms: v.zooms.map((z) => ({ u: nid('z'), n: z.n, at: z.at, dur: z.dur, scale: z.scale, kind: z.kind })),
@@ -94,6 +95,18 @@ export class Store {
get changes() { return Object.keys(this.patch()).length ? this.undo.length || 1 : 0; }
// ---- phụ đề ----
+ /** Chỗ cắt (giây bản ra hiện tại) chứa tt, hoặc null. */
+ cutAt(tt) { return (this.doc?.cuts || []).find(([a, b]) => tt >= a - 1e-3 && tt < b) || null; }
+ /** Cắt bỏ [a, b] trên track video (gộp với chỗ cắt chồng/kề). */
+ addCut(a, b) {
+ const dur = this.view?.duration || 0; a = Math.max(0, Math.min(a, b)); b = Math.min(dur, Math.max(a, b));
+ if (b - a < 1 / 30) return false;
+ return this.commit((d) => {
+ const all = [...(d.cuts || []), [r2(a), r2(b)]].sort((x, y) => x[0] - y[0]); const out = [];
+ for (const c of all) { const m = out[out.length - 1]; if (m && c[0] <= m[1] + 1e-3) m[1] = Math.max(m[1], c[1]); else out.push([...c]); }
+ d.cuts = out;
+ });
+ }
lineAt(tt) { return this.doc.lines.findIndex((l) => tt >= l.start - 1e-3 && tt < l.end); }
/** Tách dòng k tại giây tt (chữ chia theo tỉ lệ thời gian). Trả false nếu không tách được. */
splitLine(k, tt) {
@@ -120,6 +133,7 @@ export class Store {
if (ls(o.lines) !== ls(c.lines)) cap.lines = c.lines.map((l) => ({ start: r2(l.start), end: r2(l.end), text: l.text.trim() }));
if (o.hi !== c.hi) cap.highlights = c.hi;
if (o.look !== c.look) cap.look = c.look;
+ if ((o.show !== false) !== (c.show !== false)) cap.show = c.show !== false;
if (Object.keys(cap).length) p.captions = cap;
const mu = {}; const src0 = o.music.source; const src = c.music.source;
if (src !== src0) mu.source = src;
@@ -152,6 +166,7 @@ export class Store {
if (Object.keys(s).length > 1) gs.push(s);
}
if (gr.length || gs.length) p.graphics = { ...(gr.length ? { remove: gr } : {}), ...(gs.length ? { set: gs } : {}) };
+ if (c.cuts?.length) p.cuts = { remove: c.cuts.map(([a, b]) => ({ start: r2(a), end: r2(b) })) };
return p;
}
/** Lỗi chặn xuất bản (dòng rỗng/ngắn/đè). Map uid → lý do. */
diff --git a/server/public/studio/studio.css b/server/public/studio/studio.css
index 679b9cd..137c3d8 100644
--- a/server/public/studio/studio.css
+++ b/server/public/studio/studio.css
@@ -1,330 +1,339 @@
-/* Studio — trình edit toàn màn hình (mẫu _final/18-ui-edit-mau/1-studio.png). Token chung ở style.css + create.css. */
-body.studio-on { overflow: hidden; }
-body.studio-on > :not(.studio):not(script):not(dialog) { display: none !important; }
-.studio { position: fixed; inset: 0; z-index: 50; display: flex; flex-direction: column; background: var(--bg); color: var(--ink); font-size: 14px; line-height: 1.45; --tl-h: 290px; }
-.studio[hidden] { display: none; }
-.studio button { font: inherit; color: inherit; }
-.studio .ic { width: 18px; height: 18px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.9; stroke-linecap: round; stroke-linejoin: round; }
-.studio .ic .fill { fill: currentColor; stroke: none; }
-.studio :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
-.ib { width: 36px; height: 36px; border-radius: 10px; display: inline-grid; place-items: center; border: 0; background: none; color: var(--ink-2); cursor: pointer; transition: background .12s, color .12s; }
-.ib:hover:not(:disabled) { background: var(--panel-2); color: var(--ink); }
-.ib:disabled { opacity: .35; cursor: default; }
-.ib.mini { width: 30px; height: 30px; border-radius: 7px; background: var(--panel-3); }
-.ib.mini .ic { width: 15px; height: 15px; }
-.ib.mini.danger:hover:not(:disabled) { color: #FF8B8B; }
-
-/* ---- thanh trên ---- */
-.st-top { height: 56px; flex: none; display: flex; align-items: center; gap: 14px; padding: 0 16px 0 12px; border-bottom: 1px solid var(--line); background: var(--bg-2); }
-.st-title { display: flex; flex-direction: column; line-height: 1.2; min-width: 0; max-width: 300px; }
-.st-title b { font-size: 15px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
-.st-title span { font-size: 12px; color: var(--ink-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
-.st-vers { display: flex; gap: 2px; background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 3px; margin-left: 10px; overflow-x: auto; max-width: 340px; scrollbar-width: none; }
-.st-vers[hidden] { display: none; }
-.st-vers button { min-width: 34px; height: 28px; padding: 0 11px; border-radius: 7px; border: 0; background: none; font-size: 12.5px; font-weight: 600; color: var(--ink-3); cursor: pointer; white-space: nowrap; }
-.st-vers button:hover { color: var(--ink); }
-.st-vers button.on { background: var(--panel-3); color: var(--ink); }
-.st-mid { margin: 0 auto; display: flex; gap: 4px; }
-.st-top .btn { min-height: 38px; }
-.st-top .btn[hidden] { display: none; }
-.st-revb .num { font-variant-numeric: tabular-nums; }
-.st-revb[aria-pressed="true"] { background: rgba(242,201,76,.24); }
-.st-dl.pri { background: var(--accent); color: var(--accent-ink); box-shadow: 0 6px 18px -6px rgba(255,107,44,.55); }
-.st-pub { min-width: 0; }
-.st-prog { height: 2px; flex: none; background: transparent; position: relative; margin-top: -2px; z-index: 3; }
-.st-prog[hidden] { display: block; visibility: hidden; }
-.st-prog i { position: absolute; inset: 0; background: var(--accent); transform-origin: 0 50%; transform: scaleX(0); transition: transform .5s ease-out; box-shadow: 0 0 10px rgba(255,107,44,.7); }
-
-/* ---- giữa: cột icon · player · bảng ---- */
-.st-main { flex: 1; min-height: 0; display: flex; }
-.st-rail { width: 76px; flex: none; border-right: 1px solid var(--line); display: flex; flex-direction: column; align-items: center; padding-top: 12px; gap: 4px; background: var(--bg-2); }
-.st-rail button { width: 60px; height: 62px; border-radius: 12px; border: 0; background: none; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 5px; font-size: 11.5px; font-weight: 500; color: var(--ink-3); position: relative; cursor: pointer; transition: background .12s, color .12s; }
-.st-rail button .ic { width: 22px; height: 22px; }
-.st-rail button:hover { color: var(--ink); background: var(--panel); }
-.st-rail button.on { background: var(--accent-soft); color: var(--accent); }
-.st-rail .l { line-height: 1.1; text-align: center; }
-.st-rail .sep { width: 32px; height: 1px; background: var(--line); margin: 6px 0; }
-.st-rail .dot { position: absolute; top: 5px; right: 5px; min-width: 16px; height: 16px; border-radius: 9px; background: var(--warn); color: #1b1503; font-size: 10px; font-weight: 700; display: grid; place-items: center; padding: 0 4px; }
-.st-rail .dot[hidden] { display: none; }
-
-.st-stage { flex: 1; min-width: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 14px; padding: 12px; background: radial-gradient(ellipse at 50% 40%, #1a1815 0%, var(--bg) 70%); }
-.st-vid { position: relative; height: min(100%, calc(100% - 54px)); aspect-ratio: 9 / 16; max-width: 100%; border-radius: 14px; overflow: hidden; background: #000; box-shadow: 0 30px 60px -20px rgba(0,0,0,.7), 0 0 0 1px rgba(255,255,255,.06); cursor: pointer; flex: 1 1 auto; min-height: 0; }
-.st-zw { position: absolute; inset: 0; transform-origin: 50% 40%; will-change: transform; }
-.st-zw video { width: 100%; height: 100%; object-fit: cover; display: block; }
-.st-cap, .st-gfx { position: absolute; inset: 0; pointer-events: none; }
-.st-capt { position: absolute; left: calc(120 / 1080 * 100%); width: calc(840 / 1080 * 100%); margin-top: -0.6em; text-align: center; line-height: 1.18; paint-order: stroke fill; transform-origin: 50% 50%; will-change: transform, opacity; }
-.st-capt[hidden] { display: none; }
-.st-capt .w { display: inline-block; }
-.st-capt .ch { font-style: normal; }
-.st-capt.ticker { left: 0; width: 100%; height: 1.5em; margin-top: -0.75em; line-height: 1.5em; text-align: left; white-space: nowrap; overflow: hidden; padding-right: 1em; box-shadow: 0 .2em .6em rgba(0,0,0,.35); }
-.st-capt .tag { display: inline-block; padding: 0 .35em; margin: 0 .5em 0 calc(60 / 1080 * 100vw * 0); color: #fff; font-size: .62em; vertical-align: middle; height: 100%; }
-.st-glass { position: absolute; inset: 0; pointer-events: none; overflow: hidden; }
-.st-glass .gl { position: absolute; left: 0; top: 0; background: rgba(0,0,0,.001); }
-.st-gframe { position: absolute; left: 0; top: 0; width: 1080px; height: 1920px; border: 0; transform-origin: 0 0; pointer-events: none; background: transparent; color-scheme: dark; }
-.st-gframe[hidden] { display: none; }
-.st-capsel { position: absolute; left: 0; top: 0; border: 1.5px solid var(--accent); border-radius: 6px; pointer-events: none; }
-.st-capsel::before, .st-capsel::after { content: ""; position: absolute; width: 8px; height: 8px; background: #fff; border: 1.5px solid var(--accent); border-radius: 2px; top: -5px; left: -5px; }
-.st-capsel::after { left: auto; right: -5px; top: auto; bottom: -5px; }
-.st-capsel[hidden] { display: none; }
-.st-vbadge { position: absolute; top: 10px; left: 10px; padding: 3px 8px; border-radius: 6px; background: rgba(0,0,0,.7); font-size: 11.5px; font-weight: 600; color: var(--ink-2); }
-.st-vbadge[hidden] { display: none; }
-/* thẻ đồ hoạ xem trước (gần đúng thẻ HyperFrames) */
-.st-gcard { position: absolute; left: 0; top: 0; border-radius: .7em; padding: .7em .9em; background: rgba(22,24,32,.86); color: #fff; box-shadow: 0 .4em 1.2em rgba(0,0,0,.4); font-family: 'Be Vietnam Pro', sans-serif; line-height: 1.25; }
-.st-gcard .h { font-weight: 700; margin-bottom: .45em; }
-.st-gcard .h .u, .st-gcard .kick { color: var(--violet); font-weight: 600; }
-.st-gcard .row { display: flex; justify-content: space-between; gap: .6em; padding: .3em 0 .3em .5em; border-left: 2px solid rgba(255,255,255,.25); margin-top: .25em; font-size: .9em; }
-.st-gcard .row b { font-variant-numeric: tabular-nums; }
-.st-gcard .big { font: 800 2.2em/1.05 'Barlow Condensed', sans-serif; text-transform: uppercase; color: var(--accent); }
-.st-gcard .lbl { font-size: .85em; color: rgba(255,255,255,.7); }
-.st-ctrl { display: flex; align-items: center; gap: 16px; color: var(--ink-2); flex: none; }
-.st-time { font-size: 13px; color: var(--ink-2); min-width: 122px; text-align: right; }
-.st-time b { color: var(--ink); font-weight: 600; }
-.st-play { width: 40px; height: 40px; border-radius: 50%; border: 0; background: var(--ink); color: var(--bg); display: grid; place-items: center; cursor: pointer; transition: transform .1s; }
-.st-play:active { transform: scale(.94); }
-.st-play .ic { width: 18px; height: 18px; }
-.st-pill { display: inline-flex; align-items: center; min-height: 26px; padding: 0 10px; border-radius: 99px; font-size: 12.5px; font-weight: 600; background: var(--panel-2); color: var(--ink-2); border: 0; white-space: nowrap; }
-.st-pill.warn { color: var(--warn); background: var(--warn-soft); }
-button.st-pill { cursor: pointer; min-height: 30px; }
-button.st-pill:hover { color: var(--ink); }
-.st-outsw[aria-pressed="true"] { background: var(--accent-soft); color: var(--accent); }
-.st-outsw[hidden] { display: none; }
-
-/* ---- bảng thuộc tính ---- */
-.st-insp { width: 364px; flex: none; border-left: 1px solid var(--line); background: var(--bg-2); display: flex; flex-direction: column; min-height: 0; }
-.st-grab { display: none; }
-.st-ih { font-size: 15px; font-weight: 600; display: flex; align-items: center; gap: 8px; padding: 16px 18px 12px; margin: 0; flex: none; }
-.st-ih > .btn { margin-left: auto; }
-.st-ib { flex: 1; min-height: 0; overflow-y: auto; padding: 0 10px 16px; display: flex; flex-direction: column; gap: 10px; scrollbar-width: thin; }
-.st-ib > .st-seg { position: sticky; top: 0; z-index: 2; box-shadow: 0 -10px 0 var(--bg-2), 0 8px 10px -4px var(--bg-2); }
-.st-seg { display: flex; margin: 0 8px; background: var(--panel); border-radius: 10px; padding: 3px; gap: 2px; flex: none; }
-.st-seg button { flex: 1; min-height: 30px; border-radius: 7px; border: 0; background: none; font-size: 13px; font-weight: 500; color: var(--ink-3); cursor: pointer; }
-.st-seg button.on { background: var(--panel-3); color: var(--ink); }
-.st-seg.sm { margin: 0; }
-.st-lines { list-style: none; margin: 0; padding: 2px 0 0; display: flex; flex-direction: column; gap: 2px; position: relative; }
-.st-ln .row { width: 100%; display: flex; align-items: center; gap: 12px; min-height: 36px; padding: 0 10px; border-radius: 9px; border: 0; background: none; color: var(--ink-2); text-align: left; cursor: pointer; }
-.st-ln .row:hover { background: var(--panel); }
-.st-ln.now .row { color: var(--ink); background: rgba(255,255,255,.035); }
-.st-ln .tm { font-size: 11.5px; color: var(--ink-4); width: 44px; flex: none; }
-.st-ln .tx { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
-.st-ln em { font-style: normal; color: var(--accent); }
-.st-ln .flag { margin-left: auto; width: 7px; height: 7px; border-radius: 50%; background: var(--warn); flex: none; }
-.st-ln.bad .row { box-shadow: inset 2px 0 0 var(--bad); }
-.st-ln.sel { background: var(--panel-2); box-shadow: inset 0 0 0 1px var(--line-2); border-radius: 10px; padding: 12px; display: flex; flex-direction: column; gap: 10px; margin: 2px 0; }
-.st-ledit { width: 100%; min-height: 40px; background: var(--bg); border: 1px solid var(--accent); border-radius: 8px; padding: 0 12px; font-size: 15px; font-weight: 500; color: var(--ink); outline: none; }
-.st-ledit:focus { box-shadow: 0 0 0 3px rgba(255,107,44,.18); }
-.st-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
-.st-row .arrow { color: var(--ink-4); }
-.st-acts { margin-left: auto; display: flex; gap: 6px; }
-.st-tbox { display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 4px 0 9px; border-radius: 7px; background: var(--bg); border: 1px solid var(--line-2); color: var(--ink-2); }
-.st-tbox .ic { width: 13px; height: 13px; }
-.st-tbox input { width: 58px; border: 0; background: none; font-size: 12px; color: var(--ink-2); outline: none; -moz-appearance: textfield; }
-.st-tbox input::-webkit-inner-spin-button { opacity: .4; }
-.st-ainote { margin: 0; font-size: 12px; color: var(--warn); display: flex; gap: 6px; align-items: center; }
-.st-ainote .ic { width: 14px; height: 14px; }
-.st-err { margin: 0; font-size: 12px; color: var(--bad); }
-.st-note { margin: 0 8px; font-size: 12.5px; color: var(--ink-3); background: var(--panel); border-radius: 8px; padding: 8px 10px; }
-.st-note.warn { color: var(--warn); background: var(--warn-soft); }
-.st-note:empty { display: none; }
-.st-hint { margin: 0 8px; font-size: 12.5px; color: var(--ink-3); }
-.st-empty { color: var(--ink-3); text-align: center; padding: 24px 8px; margin: 0; }
-.st-lines .none, .st-blist .none { color: var(--ink-3); padding: 12px 10px; font-size: 13px; }
-/* kiểu chữ */
-.st-looks { padding: 4px 8px; display: flex; flex-direction: column; gap: 12px; }
-.st-lookgrid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
-.st-look { display: flex; flex-direction: column; align-items: stretch; gap: 6px; padding: 6px; border-radius: 10px; border: 1px solid var(--line-2); background: var(--panel); cursor: pointer; text-align: center; }
-.st-look:hover:not(:disabled) { border-color: var(--ink-4); }
-.st-look.on { border-color: var(--accent); box-shadow: 0 0 0 2px rgba(255,107,44,.25); }
-.st-look .smp { height: 46px; display: grid; place-items: center; border-radius: 7px; background: #0b0b0a; font-size: 24px; color: #fff; grid-auto-flow: column; justify-content: center; gap: 1px; }
-.st-look .nm { font-size: 11.5px; color: var(--ink-2); line-height: 1.25; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
-.st-switch { display: flex; align-items: center; gap: 10px; min-height: 36px; cursor: pointer; flex-wrap: wrap; font-size: 13.5px; color: var(--ink-2); }
-.st-switch input { width: 34px; height: 20px; appearance: none; -webkit-appearance: none; border-radius: 20px; background: var(--panel-3); position: relative; cursor: pointer; flex: none; transition: background .15s; }
-.st-switch input::after { content: ""; position: absolute; top: 3px; left: 3px; width: 14px; height: 14px; border-radius: 50%; background: var(--ink-2); transition: transform .15s; }
-.st-switch input:checked { background: var(--accent); }
-.st-switch input:checked::after { transform: translateX(14px); background: #fff; }
-.st-switch input:disabled { opacity: .4; }
-.st-switch small { flex-basis: 100%; color: var(--ink-4); font-size: 12px; margin-top: -6px; padding-left: 44px; }
-.st-switch.sm { min-height: 30px; }
-/* ô chung */
-.st-field { display: flex; flex-direction: column; gap: 6px; padding: 0 8px; font-size: 12.5px; color: var(--ink-3); }
-.st-field > span, .st-field > label { font-weight: 600; }
-.st-field input[type=text], .st-field input[type=number], .st-sel, .st-ai textarea { width: 100%; min-height: 36px; background: var(--bg); border: 1px solid var(--line-2); border-radius: 8px; padding: 0 10px; font-size: 14px; color: var(--ink); }
-.st-field input:focus, .st-sel:focus, .st-ai textarea:focus { border-color: var(--accent); outline: none; }
-.st-slide { display: grid; grid-template-columns: 1fr auto; align-items: center; gap: 4px 10px; }
-.st-slide label { grid-column: 1 / -1; }
-.st-slide input { accent-color: var(--accent); width: 100%; height: 24px; }
-.st-slide output { font-size: 12.5px; color: var(--ink); min-width: 56px; text-align: right; }
-.st-ib > .st-row, .st-ib > .st-switch { padding: 0 8px; }
-.st-ib hr { border: 0; border-top: 1px solid var(--line); margin: 4px 8px; width: auto; }
-.st-card { margin: 0 8px; padding: 12px 4px; border-radius: 12px; background: var(--panel-2); box-shadow: inset 0 0 0 1px var(--line-2); display: flex; flex-direction: column; gap: 12px; }
-.st-card > .st-row, .st-card > .st-seg, .st-card > .btn, .st-card > .st-hint { margin: 0 8px; }
-.st-card > .btn { align-self: flex-start; }
-.st-gtype { font-size: 14px; }
-.st-grow { margin: 0 8px; border: 1px solid var(--line-2); border-radius: 10px; padding: 8px 0 10px; display: flex; flex-direction: column; gap: 8px; }
-.st-grow legend { font-size: 11.5px; color: var(--ink-4); padding: 0 6px; margin-left: 6px; }
-.st-blist { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; }
-.st-blist button { width: 100%; display: flex; gap: 12px; align-items: center; min-height: 36px; padding: 0 10px; border-radius: 9px; border: 0; background: none; color: var(--ink-2); text-align: left; cursor: pointer; }
-.st-blist button:hover { background: var(--panel); }
-.st-blist button.on { background: var(--panel-2); color: var(--ink); box-shadow: inset 0 0 0 1px var(--line-2); }
-.st-blist .tm { font-size: 11.5px; color: var(--ink-4); width: 44px; flex: none; }
-.st-blist .lb { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
-/* xem lại */
-.st-review { display: flex; flex-direction: column; gap: 12px; }
-.st-rcard { margin: 0 8px; padding: 12px; border-radius: 12px; background: var(--panel-2); box-shadow: inset 0 0 0 1px rgba(242,201,76,.35); display: flex; flex-direction: column; gap: 8px; }
-.st-rtop { display: flex; align-items: center; gap: 10px; font-size: 12px; color: var(--ink-3); }
-.st-rnav { margin-left: auto; display: flex; gap: 6px; }
-.st-rwhat { margin: 0; font-size: 15px; }
-.st-rwhat .k { font-size: 11.5px; color: var(--warn); font-weight: 600; text-transform: uppercase; letter-spacing: .04em; margin-right: 4px; }
-.st-rwhat s { color: var(--ink-3); }
-.st-rwhy { margin: 0; font-size: 12px; color: var(--ink-3); }
-.st-rdone { margin: 0; font-size: 12px; color: var(--ok); }
-.st-racts { display: flex; gap: 6px; flex-wrap: wrap; }
-.st-racts .btn { flex: 1; min-height: 34px; font-size: 13px; padding: 0 10px; }
-.st-rlist { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; }
-.st-ritem { width: 100%; display: flex; gap: 10px; align-items: center; min-height: 34px; padding: 0 10px; border-radius: 9px; border: 0; background: none; color: var(--ink-2); text-align: left; cursor: pointer; font-size: 13px; }
-.st-ritem:hover { background: var(--panel); }
-.st-ritem.on { background: var(--panel-2); color: var(--ink); }
-.st-ritem.done { color: var(--ink-4); }
-.st-ritem .tm { font-size: 11.5px; color: var(--ink-4); width: 44px; flex: none; }
-.st-ritem .rx { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
-.st-ritem s { color: var(--ink-4); }
-.st-ritem .ic { color: var(--ok); width: 15px; height: 15px; }
-/* AI */
-.st-ai { margin: 0 8px; display: flex; flex-direction: column; gap: 10px; }
-.st-ai textarea { padding: 10px; min-height: 84px; resize: vertical; font-size: 14px; line-height: 1.45; }
-.st-chips { display: flex; flex-wrap: wrap; gap: 6px; }
-.st-chips .chip { min-height: 32px; padding: 0 12px; border-radius: 99px; border: 1px solid var(--line-2); background: var(--panel); font-size: 12.5px; color: var(--ink-2); }
-.st-chips .chip:hover { color: var(--ink); }
-.st-ai .btn { align-self: flex-start; }
-.st-h4 { margin: 8px 8px 0; font-size: 12px; color: var(--ink-3); text-transform: uppercase; letter-spacing: .05em; }
-.st-hist { margin: 0 8px; padding-left: 0; list-style: none; display: flex; flex-direction: column; gap: 6px; font-size: 12.5px; color: var(--ink-2); }
-.st-hist li { padding: 8px 10px; background: var(--panel); border-radius: 8px; overflow-wrap: anywhere; }
-.st-hist small { display: block; color: var(--ink-4); margin-top: 3px; }
-.st-insp.ro .st-ln .row { cursor: pointer; }
-
-/* ---- timeline ---- */
-.st-tl { height: var(--tl-h); flex: none; border-top: 1px solid var(--line); background: var(--bg-2); display: flex; flex-direction: column; user-select: none; -webkit-user-select: none; }
-.tl-bar { height: 42px; flex: none; display: flex; align-items: center; gap: 6px; padding: 0 14px; border-bottom: 1px solid var(--line); }
-.tl-bar .ib.mini { background: transparent; }
-.tl-bar .ib.mini:hover:not(:disabled) { background: var(--panel-2); }
-.tl-bar .sep { width: 1px; height: 18px; background: var(--line); margin: 0 6px; }
-.tl-hint { font-size: 12px; color: var(--ink-4); margin-left: 8px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
-.tl-zoomer { margin-left: auto; display: flex; align-items: center; gap: 6px; color: var(--ink-3); }
-.tl-zoomer > .ic { width: 15px; height: 15px; }
-.tl-zoomer input { width: 120px; accent-color: var(--ink-2); }
-.tl-main { flex: 1; min-height: 0; display: flex; }
-.tl-labs { width: 96px; flex: none; display: flex; flex-direction: column; }
-.tl-labs .lab { display: flex; align-items: center; gap: 7px; padding-left: 16px; font-size: 12px; color: var(--ink-3); border: 0; background: none; text-align: left; cursor: pointer; transition: color .12s, opacity .12s; }
-.tl-labs .lab .ic { width: 15px; height: 15px; }
-.tl-labs .lab:hover { color: var(--ink); }
-.tl-labs .lab.on { color: var(--accent); }
-.tl-labs .lab.ruler { cursor: default; }
-.tl-sc { flex: 1; min-width: 0; overflow-x: auto; overflow-y: hidden; position: relative; scrollbar-width: thin; scrollbar-color: var(--panel-3) transparent; }
-.tl-in { position: relative; height: 100%; min-width: 100%; }
-/* chiều cao hàng: thước 26 · video 66 · phụ đề 34 · zoom 30 · đồ hoạ 32 · nhạc 50 */
-.tl-labs .lab.ruler, .tl-ruler { height: 26px; flex: none; }
-.tl-labs .lab[data-k="video"], .r-video { height: 66px; }
-.tl-labs .lab[data-k="cap"], .r-cap { height: 34px; }
-.tl-labs .lab[data-k="zoom"], .r-zoom { height: 30px; }
-.tl-labs .lab[data-k="gfx"], .r-gfx { height: 32px; }
-.tl-labs .lab[data-k="music"], .r-music { height: 50px; }
-.tl-ruler { position: relative; cursor: pointer; touch-action: none; }
-.tl-ruler i { position: absolute; left: 0; bottom: 0; width: 1px; height: 5px; background: var(--line-2); }
-.tl-ruler i.mj { height: 9px; background: var(--ink-4); }
-.tl-ruler span { position: absolute; left: 0; top: 4px; font-size: 10.5px; color: var(--ink-4); pointer-events: none; }
-.tl-row { position: relative; transition: opacity .15s; }
-.st-tl[data-focus] .tl-row:not(.r-video) { opacity: .55; }
-.st-tl[data-focus="cap"] .r-cap, .st-tl[data-focus="zoom"] .r-zoom, .st-tl[data-focus="gfx"] .r-gfx, .st-tl[data-focus="music"] .r-music { opacity: 1; }
-.st-tl[data-focus="cap"] .lab[data-k="cap"], .st-tl[data-focus="zoom"] .lab[data-k="zoom"], .st-tl[data-focus="gfx"] .lab[data-k="gfx"], .st-tl[data-focus="music"] .lab[data-k="music"] { color: var(--accent); }
-.st-tl[data-focus="cap"] .r-cap, .st-tl[data-focus="zoom"] .r-zoom, .st-tl[data-focus="gfx"] .r-gfx, .st-tl[data-focus="music"] .r-music { background: linear-gradient(90deg, rgba(255,107,44,.05), rgba(255,107,44,.02)); }
-.tl-cv { position: sticky; left: 0; display: block; pointer-events: none; margin-top: 4px; z-index: 2; }
-.blk { position: absolute; left: 0; top: 4px; bottom: 4px; border-radius: 7px; overflow: hidden; display: flex; align-items: center; padding: 0 7px; font-size: 11px; font-weight: 500; white-space: nowrap; cursor: grab; will-change: transform; touch-action: none; }
-.blk .t { overflow: hidden; text-overflow: ellipsis; min-width: 0; pointer-events: none; }
-.blk::before, .blk::after { content: ""; position: absolute; top: 0; bottom: 0; width: 6px; cursor: ew-resize; }
-.blk::before { left: 0; } .blk::after { right: 0; }
-.blk.on::before, .blk.on::after { background: rgba(255,255,255,.35); }
-.blk.armed { box-shadow: 0 0 0 2px #fff; }
-.blk.drag { cursor: grabbing; z-index: 3; box-shadow: 0 6px 16px rgba(0,0,0,.45); }
-.blk.narrow { padding: 0 3px; }
-.blk.narrow .t { text-overflow: clip; }
-.blk.ro { cursor: pointer; }
-.blk.ro::before, .blk.ro::after { cursor: pointer; }
-.blk.cap { background: #3B2A1F; border: 1px solid #5a3a25; color: #F5C9A8; }
-.blk.cap.w { background: #3a3218; border-color: #6b5a1c; color: var(--warn); }
-.blk.cap.bad { border-color: var(--bad); }
-.blk.cap.on { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); font-weight: 600; }
-.blk.zoom { top: 4px; bottom: 4px; background: var(--sky-soft); border: 1px solid rgba(108,196,240,.45); color: var(--sky); font-weight: 600; }
-.blk.zoom.on { background: rgba(108,196,240,.32); border-color: var(--sky); color: #fff; }
-.blk.gfx { background: var(--violet-soft); border: 1px solid rgba(167,139,250,.45); color: #C9B8FF; font-weight: 600; }
-.blk.gfx.on { background: rgba(167,139,250,.34); border-color: var(--violet); color: #fff; }
-.blk.mu { top: 4px; bottom: 4px; background: rgba(93,211,158,.08); border: 1px solid rgba(93,211,158,.35); cursor: pointer; align-items: flex-start; padding-top: 3px; z-index: 1; }
-.blk.mu.on { border-color: var(--ok); box-shadow: inset 0 0 0 1px var(--ok); }
-.blk.mu::before, .blk.mu::after { display: none; }
-.blk[hidden] { display: none; }
-.tl-mlab { font-size: 11px; font-weight: 600; color: var(--ok); text-shadow: 0 1px 2px rgba(0,0,0,.6); }
-.r-music.empty::after { content: attr(data-empty); position: sticky; left: 14px; top: 0; display: inline-block; padding: 16px 0 0 14px; font-size: 12px; color: var(--ink-4); }
-.tl-head { position: absolute; top: 6px; bottom: 6px; left: 0; width: 2px; background: var(--accent); z-index: 6; cursor: ew-resize; touch-action: none; }
-.tl-head .knob { position: absolute; top: -4px; left: -6px; width: 14px; height: 14px; background: var(--accent); clip-path: polygon(0 0, 100% 0, 100% 55%, 50% 100%, 0 55%); }
-.tl-head::after { content: ""; position: absolute; inset: 0 -6px; }
-.tl-guide { position: absolute; top: 26px; bottom: 0; left: 0; width: 1px; background: #fff; opacity: .8; z-index: 5; pointer-events: none; }
-.tl-guide[hidden] { display: none; }
-.tl-tip { position: absolute; left: 0; top: 0; padding: 2px 6px; border-radius: 5px; background: #000; color: #fff; font: 600 11px/1.4 var(--mono); z-index: 7; pointer-events: none; white-space: nowrap; }
-.tl-tip[hidden] { display: none; }
-.tl-edit { position: absolute; left: 0; top: 0; height: 30px; z-index: 8; background: var(--bg); border: 1.5px solid var(--accent); border-radius: 7px; padding: 0 8px; font-size: 13px; color: var(--ink); outline: none; box-shadow: 0 8px 24px rgba(0,0,0,.5); }
-
-/* ---- lớp chờ, thông báo ---- */
-.st-wait { position: absolute; inset: 56px 0 0 0; z-index: 20; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 14px; background: rgba(14,13,11,.92); text-align: center; padding: 24px; }
-.st-wait[hidden] { display: none; }
-.st-wait p { margin: 0; font-size: 15px; color: var(--ink-2); max-width: 520px; }
-.st-wbar { width: 280px; height: 3px; border-radius: 2px; background: var(--panel-3); overflow: hidden; }
-.st-wbar[hidden] { display: none; }
-.st-wbar i { display: block; height: 100%; background: var(--accent); transform-origin: 0 50%; transform: scaleX(0); transition: transform .5s; }
-.st-toast { position: absolute; left: 50%; bottom: calc(var(--tl-h) + 16px); transform: translateX(-50%); z-index: 30; max-width: min(640px, calc(100% - 32px)); padding: 10px 16px; border-radius: 10px; background: #26241f; color: var(--ink); box-shadow: 0 12px 30px rgba(0,0,0,.5); font-size: 13.5px; border: 1px solid var(--line-2); }
-.st-toast[hidden] { display: none; }
-.st-toast.ok { border-color: rgba(93,211,158,.5); color: var(--ok); }
-.st-toast.bad { border-color: rgba(255,100,100,.5); color: #FFB0B0; }
-.st-scrim { display: none; }
-
-@media (max-width: 1180px) { .st-insp { width: 320px; } .st-title { max-width: 200px; } .st-reset { display: none; } }
-
-/* ---- điện thoại < 768: player trên, công cụ ngang, timeline cuộn ngang, bảng thành sheet dưới ---- */
-@media (max-width: 767px) {
- .studio { --tl-h: 262px; }
- .st-top { height: 52px; gap: 6px; padding: 0 8px 0 4px; }
- .st-title { max-width: none; flex: 1; }
- .st-title span { display: none; }
- .st-vers { display: none; }
- .st-mid { margin: 0; }
- .st-mid .ib { width: 34px; }
- .st-revb > span:not(.num), .st-dl span, .st-pub span { display: none; }
- .st-top .btn { min-height: 36px; padding: 0 10px; }
- .st-main { flex-direction: column; }
- .st-rail { width: auto; height: 52px; flex-direction: row; justify-content: space-around; padding: 4px 6px; border-right: 0; border-top: 1px solid var(--line); order: 2; }
- .st-rail button { width: auto; flex: 1; height: 46px; gap: 2px; font-size: 10.5px; border-radius: 10px; }
- .st-rail .l { white-space: nowrap; }
- .st-rail button .ic { width: 18px; height: 18px; }
- .st-rail .sep { width: 1px; height: 24px; margin: 0 2px; }
- .st-rail .dot { top: 1px; right: calc(50% - 20px); }
- .st-stage { order: 1; flex: 1; min-height: 0; padding: 8px; gap: 8px; }
- .st-ctrl { gap: 10px; }
- .st-time { min-width: 0; font-size: 12px; }
- .st-ratio, .st-ctrl .mono.st-pill { display: none; }
- .st-insp { position: fixed; left: 0; right: 0; bottom: 0; width: auto; max-height: 62vh; border-left: 0; border-top: 1px solid var(--line-2); border-radius: 16px 16px 0 0; z-index: 40; transform: translateY(105%); transition: transform .22s ease-out; box-shadow: 0 -16px 40px rgba(0,0,0,.5); padding-bottom: env(safe-area-inset-bottom); }
- .st-insp.open { transform: none; }
- .st-grab { display: block; width: 100%; height: 22px; border: 0; background: none; cursor: pointer; flex: none; position: relative; }
- .st-grab::after { content: ""; position: absolute; left: 50%; top: 9px; width: 40px; height: 4px; margin-left: -20px; border-radius: 2px; background: var(--ink-4); }
- .st-ih { padding-top: 4px; }
- .st-scrim { display: block; position: fixed; inset: 0; z-index: 39; background: rgba(0,0,0,.4); opacity: 0; pointer-events: none; transition: opacity .2s; }
- .st-scrim.on { opacity: 1; pointer-events: auto; }
- .tl-bar { padding: 0 8px; gap: 2px; overflow-x: auto; }
- .tl-hint { display: none; }
- .tl-zoomer input { width: 70px; }
- .tl-labs { width: 40px; }
- .tl-labs .lab { padding-left: 12px; }
- .tl-labs .lab span { display: none; }
- .r-video, .tl-labs .lab[data-k="video"] { height: 50px; }
- .r-music, .tl-labs .lab[data-k="music"] { height: 40px; }
- .st-toast { bottom: calc(var(--tl-h) + 60px); }
-}
-@media (prefers-reduced-motion: reduce) {
- .st-prog i, .st-wbar i, .st-insp, .tl-row, .st-rail button { transition: none; }
-}
+/* Studio — trình edit toàn màn hình (mẫu _final/18-ui-edit-mau/1-studio.png). Token chung ở style.css + create.css. */
+body.studio-on { overflow: hidden; }
+body.studio-on > :not(.studio):not(script):not(dialog) { display: none !important; }
+.studio { position: fixed; inset: 0; z-index: 50; display: flex; flex-direction: column; background: var(--bg); color: var(--ink); font-size: 14px; line-height: 1.45; --tl-h: 290px; }
+.studio[hidden] { display: none; }
+.studio button { font: inherit; color: inherit; }
+.studio .ic { width: 18px; height: 18px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.9; stroke-linecap: round; stroke-linejoin: round; }
+.studio .ic .fill { fill: currentColor; stroke: none; }
+.studio :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+.ib { width: 36px; height: 36px; border-radius: 10px; display: inline-grid; place-items: center; border: 0; background: none; color: var(--ink-2); cursor: pointer; transition: background .12s, color .12s; }
+.ib:hover:not(:disabled) { background: var(--panel-2); color: var(--ink); }
+.ib:disabled { opacity: .35; cursor: default; }
+.ib.mini { width: 30px; height: 30px; border-radius: 7px; background: var(--panel-3); }
+.ib.mini .ic { width: 15px; height: 15px; }
+.ib.mini.danger:hover:not(:disabled) { color: #FF8B8B; }
+
+/* ---- thanh trên ---- */
+.st-top { height: 56px; flex: none; display: flex; align-items: center; gap: 14px; padding: 0 16px 0 12px; border-bottom: 1px solid var(--line); background: var(--bg-2); }
+.st-title { display: flex; flex-direction: column; line-height: 1.2; min-width: 0; max-width: 300px; }
+.st-title b { font-size: 15px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.st-title span { font-size: 12px; color: var(--ink-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.st-vers { display: flex; gap: 2px; background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 3px; margin-left: 10px; overflow-x: auto; max-width: 340px; scrollbar-width: none; }
+.st-vers[hidden] { display: none; }
+.st-vers button { min-width: 34px; height: 28px; padding: 0 11px; border-radius: 7px; border: 0; background: none; font-size: 12.5px; font-weight: 600; color: var(--ink-3); cursor: pointer; white-space: nowrap; }
+.st-vers button:hover { color: var(--ink); }
+.st-vers button.on { background: var(--panel-3); color: var(--ink); }
+.st-mid { margin: 0 auto; display: flex; gap: 4px; }
+.st-top .btn { min-height: 38px; }
+.st-top .btn[hidden] { display: none; }
+.st-revb .num { font-variant-numeric: tabular-nums; }
+.st-revb[aria-pressed="true"] { background: rgba(242,201,76,.24); }
+.st-dl.pri { background: var(--accent); color: var(--accent-ink); box-shadow: 0 6px 18px -6px rgba(255,107,44,.55); }
+.st-pub { min-width: 0; }
+.st-prog { height: 2px; flex: none; background: transparent; position: relative; margin-top: -2px; z-index: 3; }
+.st-prog[hidden] { display: block; visibility: hidden; }
+.st-prog i { position: absolute; inset: 0; background: var(--accent); transform-origin: 0 50%; transform: scaleX(0); transition: transform .5s ease-out; box-shadow: 0 0 10px rgba(255,107,44,.7); }
+
+/* ---- giữa: cột icon · player · bảng ---- */
+.st-main { flex: 1; min-height: 0; display: flex; }
+.st-rail { width: 76px; flex: none; border-right: 1px solid var(--line); display: flex; flex-direction: column; align-items: center; padding-top: 12px; gap: 4px; background: var(--bg-2); }
+.st-rail button { width: 60px; height: 62px; border-radius: 12px; border: 0; background: none; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 5px; font-size: 11.5px; font-weight: 500; color: var(--ink-3); position: relative; cursor: pointer; transition: background .12s, color .12s; }
+.st-rail button .ic { width: 22px; height: 22px; }
+.st-rail button:hover { color: var(--ink); background: var(--panel); }
+.st-rail button.on { background: var(--accent-soft); color: var(--accent); }
+.st-rail .l { line-height: 1.1; text-align: center; }
+.st-rail .sep { width: 32px; height: 1px; background: var(--line); margin: 6px 0; }
+.st-rail .dot { position: absolute; top: 5px; right: 5px; min-width: 16px; height: 16px; border-radius: 9px; background: var(--warn); color: #1b1503; font-size: 10px; font-weight: 700; display: grid; place-items: center; padding: 0 4px; }
+.st-rail .dot[hidden] { display: none; }
+
+.st-stage { flex: 1; min-width: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 14px; padding: 12px; background: radial-gradient(ellipse at 50% 40%, #1a1815 0%, var(--bg) 70%); }
+.st-vid { position: relative; height: min(100%, calc(100% - 54px)); aspect-ratio: 9 / 16; max-width: 100%; border-radius: 14px; overflow: hidden; background: #000; box-shadow: 0 30px 60px -20px rgba(0,0,0,.7), 0 0 0 1px rgba(255,255,255,.06); cursor: pointer; flex: 1 1 auto; min-height: 0; }
+.st-zw { position: absolute; inset: 0; transform-origin: 50% 40%; will-change: transform; }
+.st-zw video { width: 100%; height: 100%; object-fit: cover; display: block; }
+.st-cap, .st-gfx { position: absolute; inset: 0; pointer-events: none; }
+.st-capt { position: absolute; left: calc(120 / 1080 * 100%); width: calc(840 / 1080 * 100%); margin-top: -0.6em; text-align: center; line-height: 1.18; paint-order: stroke fill; transform-origin: 50% 50%; will-change: transform, opacity; }
+.st-capt[hidden] { display: none; }
+.st-capt .w { display: inline-block; }
+.st-capt .ch { font-style: normal; }
+.st-capt.ticker { left: 0; width: 100%; height: 1.5em; margin-top: -0.75em; line-height: 1.5em; text-align: left; white-space: nowrap; overflow: hidden; padding-right: 1em; box-shadow: 0 .2em .6em rgba(0,0,0,.35); }
+.st-capt .tag { display: inline-block; padding: 0 .35em; margin: 0 .5em 0 calc(60 / 1080 * 100vw * 0); color: #fff; font-size: .62em; vertical-align: middle; height: 100%; }
+.st-glass { position: absolute; inset: 0; pointer-events: none; overflow: hidden; }
+.st-glass .gl { position: absolute; left: 0; top: 0; background: rgba(0,0,0,.001); }
+.st-gframe { position: absolute; left: 0; top: 0; width: 1080px; height: 1920px; border: 0; transform-origin: 0 0; pointer-events: none; background: transparent; color-scheme: dark; }
+.st-gframe[hidden] { display: none; }
+.st-capsel { position: absolute; left: 0; top: 0; border: 1.5px solid var(--accent); border-radius: 6px; pointer-events: none; }
+.st-capsel::before, .st-capsel::after { content: ""; position: absolute; width: 8px; height: 8px; background: #fff; border: 1.5px solid var(--accent); border-radius: 2px; top: -5px; left: -5px; }
+.st-capsel::after { left: auto; right: -5px; top: auto; bottom: -5px; }
+.st-capsel[hidden] { display: none; }
+.st-vbadge { position: absolute; top: 10px; left: 10px; padding: 3px 8px; border-radius: 6px; background: rgba(0,0,0,.7); font-size: 11.5px; font-weight: 600; color: var(--ink-2); }
+.st-vbadge[hidden] { display: none; }
+/* thẻ đồ hoạ xem trước (gần đúng thẻ HyperFrames) */
+.st-gcard { position: absolute; left: 0; top: 0; border-radius: .7em; padding: .7em .9em; background: rgba(22,24,32,.86); color: #fff; box-shadow: 0 .4em 1.2em rgba(0,0,0,.4); font-family: 'Be Vietnam Pro', sans-serif; line-height: 1.25; }
+.st-gcard .h { font-weight: 700; margin-bottom: .45em; }
+.st-gcard .h .u, .st-gcard .kick { color: var(--violet); font-weight: 600; }
+.st-gcard .row { display: flex; justify-content: space-between; gap: .6em; padding: .3em 0 .3em .5em; border-left: 2px solid rgba(255,255,255,.25); margin-top: .25em; font-size: .9em; }
+.st-gcard .row b { font-variant-numeric: tabular-nums; }
+.st-gcard .big { font: 800 2.2em/1.05 'Barlow Condensed', sans-serif; text-transform: uppercase; color: var(--accent); }
+.st-gcard .lbl { font-size: .85em; color: rgba(255,255,255,.7); }
+.st-ctrl { display: flex; align-items: center; gap: 16px; color: var(--ink-2); flex: none; }
+.st-time { font-size: 13px; color: var(--ink-2); min-width: 122px; text-align: right; }
+.st-time b { color: var(--ink); font-weight: 600; }
+.st-play { width: 40px; height: 40px; border-radius: 50%; border: 0; background: var(--ink); color: var(--bg); display: grid; place-items: center; cursor: pointer; transition: transform .1s; }
+.st-play:active { transform: scale(.94); }
+.st-play .ic { width: 18px; height: 18px; }
+.st-pill { display: inline-flex; align-items: center; min-height: 26px; padding: 0 10px; border-radius: 99px; font-size: 12.5px; font-weight: 600; background: var(--panel-2); color: var(--ink-2); border: 0; white-space: nowrap; }
+.st-pill.warn { color: var(--warn); background: var(--warn-soft); }
+button.st-pill { cursor: pointer; min-height: 30px; }
+button.st-pill:hover { color: var(--ink); }
+.st-outsw[aria-pressed="true"] { background: var(--accent-soft); color: var(--accent); }
+.st-outsw[hidden] { display: none; }
+
+/* ---- bảng thuộc tính ---- */
+.st-insp { width: 364px; flex: none; border-left: 1px solid var(--line); background: var(--bg-2); display: flex; flex-direction: column; min-height: 0; }
+.st-grab { display: none; }
+.st-ih { font-size: 15px; font-weight: 600; display: flex; align-items: center; gap: 8px; padding: 16px 18px 12px; margin: 0; flex: none; }
+.st-ih > .btn { margin-left: auto; }
+.st-ib { flex: 1; min-height: 0; overflow-y: auto; padding: 0 10px 16px; display: flex; flex-direction: column; gap: 10px; scrollbar-width: thin; }
+.st-ib > .st-seg { position: sticky; top: 0; z-index: 2; box-shadow: 0 -10px 0 var(--bg-2), 0 8px 10px -4px var(--bg-2); }
+.st-seg { display: flex; margin: 0 8px; background: var(--panel); border-radius: 10px; padding: 3px; gap: 2px; flex: none; }
+.st-seg button { flex: 1; min-height: 30px; border-radius: 7px; border: 0; background: none; font-size: 13px; font-weight: 500; color: var(--ink-3); cursor: pointer; }
+.st-seg button.on { background: var(--panel-3); color: var(--ink); }
+.st-seg.sm { margin: 0; }
+.st-lines { list-style: none; margin: 0; padding: 2px 0 0; display: flex; flex-direction: column; gap: 2px; position: relative; }
+.st-ln .row { width: 100%; display: flex; align-items: center; gap: 12px; min-height: 36px; padding: 0 10px; border-radius: 9px; border: 0; background: none; color: var(--ink-2); text-align: left; cursor: pointer; }
+.st-ln .row:hover { background: var(--panel); }
+.st-ln.now .row { color: var(--ink); background: rgba(255,255,255,.035); }
+.st-ln .tm { font-size: 11.5px; color: var(--ink-4); width: 44px; flex: none; }
+.st-ln .tx { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.st-ln em { font-style: normal; color: var(--accent); }
+.st-ln .flag { margin-left: auto; width: 7px; height: 7px; border-radius: 50%; background: var(--warn); flex: none; }
+.st-ln.bad .row { box-shadow: inset 2px 0 0 var(--bad); }
+.st-ln.sel { background: var(--panel-2); box-shadow: inset 0 0 0 1px var(--line-2); border-radius: 10px; padding: 12px; display: flex; flex-direction: column; gap: 10px; margin: 2px 0; }
+.st-ledit { width: 100%; min-height: 40px; background: var(--bg); border: 1px solid var(--accent); border-radius: 8px; padding: 0 12px; font-size: 15px; font-weight: 500; color: var(--ink); outline: none; }
+.st-ledit:focus { box-shadow: 0 0 0 3px rgba(255,107,44,.18); }
+.st-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
+.st-row .arrow { color: var(--ink-4); }
+.st-acts { margin-left: auto; display: flex; gap: 6px; }
+.st-tbox { display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 4px 0 9px; border-radius: 7px; background: var(--bg); border: 1px solid var(--line-2); color: var(--ink-2); }
+.st-tbox .ic { width: 13px; height: 13px; }
+.st-tbox input { width: 58px; border: 0; background: none; font-size: 12px; color: var(--ink-2); outline: none; -moz-appearance: textfield; }
+.st-tbox input::-webkit-inner-spin-button { opacity: .4; }
+.st-ainote { margin: 0; font-size: 12px; color: var(--warn); display: flex; gap: 6px; align-items: center; }
+.st-ainote .ic { width: 14px; height: 14px; }
+.st-err { margin: 0; font-size: 12px; color: var(--bad); }
+.st-note { margin: 0 8px; font-size: 12.5px; color: var(--ink-3); background: var(--panel); border-radius: 8px; padding: 8px 10px; }
+.st-note.warn { color: var(--warn); background: var(--warn-soft); }
+.st-note:empty { display: none; }
+.st-hint { margin: 0 8px; font-size: 12.5px; color: var(--ink-3); }
+.st-empty { color: var(--ink-3); text-align: center; padding: 24px 8px; margin: 0; }
+.st-lines .none, .st-blist .none { color: var(--ink-3); padding: 12px 10px; font-size: 13px; }
+/* kiểu chữ */
+.st-looks { padding: 4px 8px; display: flex; flex-direction: column; gap: 12px; }
+.st-lookgrid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
+.st-look { display: flex; flex-direction: column; align-items: stretch; gap: 6px; padding: 6px; border-radius: 10px; border: 1px solid var(--line-2); background: var(--panel); cursor: pointer; text-align: center; }
+.st-look:hover:not(:disabled) { border-color: var(--ink-4); }
+.st-look.on { border-color: var(--accent); box-shadow: 0 0 0 2px rgba(255,107,44,.25); }
+.st-look .smp { height: 46px; display: grid; place-items: center; border-radius: 7px; background: #0b0b0a; font-size: 24px; color: #fff; grid-auto-flow: column; justify-content: center; gap: 1px; }
+.st-look .nm { font-size: 11.5px; color: var(--ink-2); line-height: 1.25; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
+.st-switch { display: flex; align-items: center; gap: 10px; min-height: 36px; cursor: pointer; flex-wrap: wrap; font-size: 13.5px; color: var(--ink-2); }
+.st-switch input { width: 34px; height: 20px; appearance: none; -webkit-appearance: none; border-radius: 20px; background: var(--panel-3); position: relative; cursor: pointer; flex: none; transition: background .15s; }
+.st-switch input::after { content: ""; position: absolute; top: 3px; left: 3px; width: 14px; height: 14px; border-radius: 50%; background: var(--ink-2); transition: transform .15s; }
+.st-switch input:checked { background: var(--accent); }
+.st-switch input:checked::after { transform: translateX(14px); background: #fff; }
+.st-switch input:disabled { opacity: .4; }
+.st-switch small { flex-basis: 100%; color: var(--ink-4); font-size: 12px; margin-top: -6px; padding-left: 44px; }
+.st-switch.sm { min-height: 30px; }
+/* ô chung */
+.st-field { display: flex; flex-direction: column; gap: 6px; padding: 0 8px; font-size: 12.5px; color: var(--ink-3); }
+.st-field > span, .st-field > label { font-weight: 600; }
+.st-field input[type=text], .st-field input[type=number], .st-sel, .st-ai textarea { width: 100%; min-height: 36px; background: var(--bg); border: 1px solid var(--line-2); border-radius: 8px; padding: 0 10px; font-size: 14px; color: var(--ink); }
+.st-field input:focus, .st-sel:focus, .st-ai textarea:focus { border-color: var(--accent); outline: none; }
+.st-slide { display: grid; grid-template-columns: 1fr auto; align-items: center; gap: 4px 10px; }
+.st-slide label { grid-column: 1 / -1; }
+.st-slide input { accent-color: var(--accent); width: 100%; height: 24px; }
+.st-slide output { font-size: 12.5px; color: var(--ink); min-width: 56px; text-align: right; }
+.st-ib > .st-row, .st-ib > .st-switch { padding: 0 8px; }
+.st-ib hr { border: 0; border-top: 1px solid var(--line); margin: 4px 8px; width: auto; }
+.st-card { margin: 0 8px; padding: 12px 4px; border-radius: 12px; background: var(--panel-2); box-shadow: inset 0 0 0 1px var(--line-2); display: flex; flex-direction: column; gap: 12px; }
+.st-card > .st-row, .st-card > .st-seg, .st-card > .btn, .st-card > .st-hint { margin: 0 8px; }
+.st-card > .btn { align-self: flex-start; }
+.st-gtype { font-size: 14px; }
+.st-grow { margin: 0 8px; border: 1px solid var(--line-2); border-radius: 10px; padding: 8px 0 10px; display: flex; flex-direction: column; gap: 8px; }
+.st-grow legend { font-size: 11.5px; color: var(--ink-4); padding: 0 6px; margin-left: 6px; }
+.st-blist { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; }
+.st-blist button { width: 100%; display: flex; gap: 12px; align-items: center; min-height: 36px; padding: 0 10px; border-radius: 9px; border: 0; background: none; color: var(--ink-2); text-align: left; cursor: pointer; }
+.st-blist button:hover { background: var(--panel); }
+.st-blist button.on { background: var(--panel-2); color: var(--ink); box-shadow: inset 0 0 0 1px var(--line-2); }
+.st-blist .tm { font-size: 11.5px; color: var(--ink-4); width: 44px; flex: none; }
+.st-blist .lb { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+/* xem lại */
+.st-review { display: flex; flex-direction: column; gap: 12px; }
+.st-rcard { margin: 0 8px; padding: 12px; border-radius: 12px; background: var(--panel-2); box-shadow: inset 0 0 0 1px rgba(242,201,76,.35); display: flex; flex-direction: column; gap: 8px; }
+.st-rtop { display: flex; align-items: center; gap: 10px; font-size: 12px; color: var(--ink-3); }
+.st-rnav { margin-left: auto; display: flex; gap: 6px; }
+.st-rwhat { margin: 0; font-size: 15px; }
+.st-rwhat .k { font-size: 11.5px; color: var(--warn); font-weight: 600; text-transform: uppercase; letter-spacing: .04em; margin-right: 4px; }
+.st-rwhat s { color: var(--ink-3); }
+.st-rwhy { margin: 0; font-size: 12px; color: var(--ink-3); }
+.st-rdone { margin: 0; font-size: 12px; color: var(--ok); }
+.st-racts { display: flex; gap: 6px; flex-wrap: wrap; }
+.st-racts .btn { flex: 1; min-height: 34px; font-size: 13px; padding: 0 10px; }
+.st-rlist { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; }
+.st-ritem { width: 100%; display: flex; gap: 10px; align-items: center; min-height: 34px; padding: 0 10px; border-radius: 9px; border: 0; background: none; color: var(--ink-2); text-align: left; cursor: pointer; font-size: 13px; }
+.st-ritem:hover { background: var(--panel); }
+.st-ritem.on { background: var(--panel-2); color: var(--ink); }
+.st-ritem.done { color: var(--ink-4); }
+.st-ritem .tm { font-size: 11.5px; color: var(--ink-4); width: 44px; flex: none; }
+.st-ritem .rx { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.st-ritem s { color: var(--ink-4); }
+.st-ritem .ic { color: var(--ok); width: 15px; height: 15px; }
+/* AI */
+.st-ai { margin: 0 8px; display: flex; flex-direction: column; gap: 10px; }
+.st-ai textarea { padding: 10px; min-height: 84px; resize: vertical; font-size: 14px; line-height: 1.45; }
+.st-chips { display: flex; flex-wrap: wrap; gap: 6px; }
+.st-chips .chip { min-height: 32px; padding: 0 12px; border-radius: 99px; border: 1px solid var(--line-2); background: var(--panel); font-size: 12.5px; color: var(--ink-2); }
+.st-chips .chip:hover { color: var(--ink); }
+.st-ai .btn { align-self: flex-start; }
+.st-h4 { margin: 8px 8px 0; font-size: 12px; color: var(--ink-3); text-transform: uppercase; letter-spacing: .05em; }
+.st-hist { margin: 0 8px; padding-left: 0; list-style: none; display: flex; flex-direction: column; gap: 6px; font-size: 12.5px; color: var(--ink-2); }
+.st-hist li { padding: 8px 10px; background: var(--panel); border-radius: 8px; overflow-wrap: anywhere; }
+.st-hist small { display: block; color: var(--ink-4); margin-top: 3px; }
+.st-insp.ro .st-ln .row { cursor: pointer; }
+
+/* ---- timeline ---- */
+.st-tl { height: var(--tl-h); flex: none; border-top: 1px solid var(--line); background: var(--bg-2); display: flex; flex-direction: column; user-select: none; -webkit-user-select: none; }
+.tl-bar { height: 42px; flex: none; display: flex; align-items: center; gap: 6px; padding: 0 14px; border-bottom: 1px solid var(--line); }
+.tl-bar .ib.mini { background: transparent; }
+.tl-bar .ib.mini:hover:not(:disabled) { background: var(--panel-2); }
+.tl-bar .sep { width: 1px; height: 18px; background: var(--line); margin: 0 6px; }
+.tl-hint { font-size: 12px; color: var(--ink-4); margin-left: 8px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.tl-zoomer { margin-left: auto; display: flex; align-items: center; gap: 6px; color: var(--ink-3); }
+.tl-zoomer > .ic { width: 15px; height: 15px; }
+.tl-zoomer input { width: 120px; accent-color: var(--ink-2); }
+.tl-main { flex: 1; min-height: 0; display: flex; }
+.tl-labs { width: 96px; flex: none; display: flex; flex-direction: column; }
+.tl-labs .lab { display: flex; align-items: center; gap: 7px; padding-left: 16px; font-size: 12px; color: var(--ink-3); border: 0; background: none; text-align: left; cursor: pointer; transition: color .12s, opacity .12s; }
+.tl-labs .lab .ic { width: 15px; height: 15px; }
+.tl-labs .lab:hover { color: var(--ink); }
+.tl-labs .lab.on { color: var(--accent); }
+.tl-labs .lab.ruler { cursor: default; }
+.tl-sc { flex: 1; min-width: 0; overflow-x: auto; overflow-y: hidden; position: relative; scrollbar-width: thin; scrollbar-color: var(--panel-3) transparent; }
+.tl-in { position: relative; height: 100%; min-width: 100%; }
+/* chiều cao hàng: thước 26 · video 66 · phụ đề 34 · zoom 30 · đồ hoạ 32 · nhạc 50 */
+.tl-labs .lab.ruler, .tl-ruler { height: 26px; flex: none; }
+.tl-labs .lab[data-k="video"], .r-video { height: 66px; }
+.tl-labs .lab[data-k="cap"], .r-cap { height: 34px; }
+.tl-labs .lab[data-k="zoom"], .r-zoom { height: 30px; }
+.tl-labs .lab[data-k="gfx"], .r-gfx { height: 32px; }
+.tl-labs .lab[data-k="music"], .r-music { height: 50px; }
+.tl-ruler { position: relative; cursor: pointer; touch-action: none; }
+.tl-ruler i { position: absolute; left: 0; bottom: 0; width: 1px; height: 5px; background: var(--line-2); }
+.tl-ruler i.mj { height: 9px; background: var(--ink-4); }
+.tl-ruler span { position: absolute; left: 0; top: 4px; font-size: 10.5px; color: var(--ink-4); pointer-events: none; }
+.tl-row { position: relative; transition: opacity .15s; }
+.st-tl[data-focus] .tl-row:not(.r-video) { opacity: .55; }
+.st-tl[data-focus="cap"] .r-cap, .st-tl[data-focus="zoom"] .r-zoom, .st-tl[data-focus="gfx"] .r-gfx, .st-tl[data-focus="music"] .r-music { opacity: 1; }
+.st-tl[data-focus="cap"] .lab[data-k="cap"], .st-tl[data-focus="zoom"] .lab[data-k="zoom"], .st-tl[data-focus="gfx"] .lab[data-k="gfx"], .st-tl[data-focus="music"] .lab[data-k="music"] { color: var(--accent); }
+.st-tl[data-focus="cap"] .r-cap, .st-tl[data-focus="zoom"] .r-zoom, .st-tl[data-focus="gfx"] .r-gfx, .st-tl[data-focus="music"] .r-music { background: linear-gradient(90deg, rgba(255,107,44,.05), rgba(255,107,44,.02)); }
+.tl-cv { position: sticky; left: 0; display: block; pointer-events: none; margin-top: 4px; z-index: 2; }
+.blk { position: absolute; left: 0; top: 4px; bottom: 4px; border-radius: 7px; overflow: hidden; display: flex; align-items: center; padding: 0 7px; font-size: 11px; font-weight: 500; white-space: nowrap; cursor: grab; will-change: transform; touch-action: none; }
+.blk .t { overflow: hidden; text-overflow: ellipsis; min-width: 0; pointer-events: none; }
+.blk::before, .blk::after { content: ""; position: absolute; top: 0; bottom: 0; width: 6px; cursor: ew-resize; }
+.blk::before { left: 0; } .blk::after { right: 0; }
+.blk.on::before, .blk.on::after { background: rgba(255,255,255,.35); }
+.blk.armed { box-shadow: 0 0 0 2px #fff; }
+.blk.drag { cursor: grabbing; z-index: 3; box-shadow: 0 6px 16px rgba(0,0,0,.45); }
+.blk.narrow { padding: 0 3px; }
+.blk.narrow .t { text-overflow: clip; }
+.blk.ro { cursor: pointer; }
+.blk.ro::before, .blk.ro::after { cursor: pointer; }
+.blk.cap { background: #3B2A1F; border: 1px solid #5a3a25; color: #F5C9A8; }
+.blk.cap.w { background: #3a3218; border-color: #6b5a1c; color: var(--warn); }
+.blk.cap.bad { border-color: var(--bad); }
+.blk.cap.on { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); font-weight: 600; }
+.blk.zoom { top: 4px; bottom: 4px; background: var(--sky-soft); border: 1px solid rgba(108,196,240,.45); color: var(--sky); font-weight: 600; }
+.blk.zoom.on { background: rgba(108,196,240,.32); border-color: var(--sky); color: #fff; }
+.blk.gfx { background: var(--violet-soft); border: 1px solid rgba(167,139,250,.45); color: #C9B8FF; font-weight: 600; }
+.blk.gfx.on { background: rgba(167,139,250,.34); border-color: var(--violet); color: #fff; }
+.blk.mu { top: 4px; bottom: 4px; background: rgba(93,211,158,.08); border: 1px solid rgba(93,211,158,.35); cursor: pointer; align-items: flex-start; padding-top: 3px; z-index: 1; }
+.blk.mu.on { border-color: var(--ok); box-shadow: inset 0 0 0 1px var(--ok); }
+.blk.mu::before, .blk.mu::after { display: none; }
+.blk[hidden] { display: none; }
+.tl-mlab { font-size: 11px; font-weight: 600; color: var(--ok); text-shadow: 0 1px 2px rgba(0,0,0,.6); }
+.r-music.empty::after { content: attr(data-empty); position: sticky; left: 14px; top: 0; display: inline-block; padding: 16px 0 0 14px; font-size: 12px; color: var(--ink-4); }
+.tl-vl { position: absolute; inset: 4px 0; pointer-events: none; }
+.tl-vl .vcut { position: absolute; left: 0; top: 0; bottom: 0; pointer-events: auto; cursor: pointer; border-radius: 4px; z-index: 3;
+ background: repeating-linear-gradient(135deg, rgba(14,13,11,.86) 0 6px, rgba(255,100,100,.32) 6px 9px); box-shadow: inset 0 0 0 1px rgba(255,100,100,.55); }
+.tl-vl .vcut.on { box-shadow: inset 0 0 0 2px #fff; }
+.tl-vl .vsplit { position: absolute; left: 0; top: -2px; bottom: -2px; width: 2px; background: #fff; border-radius: 1px; z-index: 3; box-shadow: 0 0 0 1px rgba(0,0,0,.6); }
+.tl-vl .vsel { position: absolute; left: 0; top: 0; bottom: 0; border: 2px solid var(--accent); border-radius: 6px; background: rgba(255,107,44,.16); z-index: 2; }
+.r-video { cursor: crosshair; }
+.st-reel { display: inline-flex; align-items: center; gap: 6px; margin-left: 8px; padding: 0 9px; min-height: 24px; border-radius: 99px; background: var(--violet-soft); color: #C9B8FF; font-size: 11.5px; font-weight: 600; text-decoration: none; white-space: nowrap; max-width: 220px; overflow: hidden; text-overflow: ellipsis; }
+.st-reel:hover { color: #fff; }
+.tl-head { position: absolute; top: 6px; bottom: 6px; left: 0; width: 2px; background: var(--accent); z-index: 6; cursor: ew-resize; touch-action: none; }
+.tl-head .knob { position: absolute; top: -4px; left: -6px; width: 14px; height: 14px; background: var(--accent); clip-path: polygon(0 0, 100% 0, 100% 55%, 50% 100%, 0 55%); }
+.tl-head::after { content: ""; position: absolute; inset: 0 -6px; }
+.tl-guide { position: absolute; top: 26px; bottom: 0; left: 0; width: 1px; background: #fff; opacity: .8; z-index: 5; pointer-events: none; }
+.tl-guide[hidden] { display: none; }
+.tl-tip { position: absolute; left: 0; top: 0; padding: 2px 6px; border-radius: 5px; background: #000; color: #fff; font: 600 11px/1.4 var(--mono); z-index: 7; pointer-events: none; white-space: nowrap; }
+.tl-tip[hidden] { display: none; }
+.tl-edit { position: absolute; left: 0; top: 0; height: 30px; z-index: 8; background: var(--bg); border: 1.5px solid var(--accent); border-radius: 7px; padding: 0 8px; font-size: 13px; color: var(--ink); outline: none; box-shadow: 0 8px 24px rgba(0,0,0,.5); }
+
+/* ---- lớp chờ, thông báo ---- */
+.st-wait { position: absolute; inset: 56px 0 0 0; z-index: 20; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 14px; background: rgba(14,13,11,.92); text-align: center; padding: 24px; }
+.st-wait[hidden] { display: none; }
+.st-wait p { margin: 0; font-size: 15px; color: var(--ink-2); max-width: 520px; }
+.st-wbar { width: 280px; height: 3px; border-radius: 2px; background: var(--panel-3); overflow: hidden; }
+.st-wbar[hidden] { display: none; }
+.st-wbar i { display: block; height: 100%; background: var(--accent); transform-origin: 0 50%; transform: scaleX(0); transition: transform .5s; }
+.st-toast { position: absolute; left: 50%; bottom: calc(var(--tl-h) + 16px); transform: translateX(-50%); z-index: 30; max-width: min(640px, calc(100% - 32px)); padding: 10px 16px; border-radius: 10px; background: #26241f; color: var(--ink); box-shadow: 0 12px 30px rgba(0,0,0,.5); font-size: 13.5px; border: 1px solid var(--line-2); }
+.st-toast[hidden] { display: none; }
+.st-toast.ok { border-color: rgba(93,211,158,.5); color: var(--ok); }
+.st-toast.bad { border-color: rgba(255,100,100,.5); color: #FFB0B0; }
+.st-scrim { display: none; }
+
+@media (max-width: 1180px) { .st-insp { width: 320px; } .st-title { max-width: 200px; } .st-reset { display: none; } }
+
+/* ---- điện thoại < 768: player trên, công cụ ngang, timeline cuộn ngang, bảng thành sheet dưới ---- */
+@media (max-width: 767px) {
+ .studio { --tl-h: 262px; }
+ .st-top { height: 52px; gap: 6px; padding: 0 8px 0 4px; }
+ .st-title { max-width: none; flex: 1; }
+ .st-title span { display: none; }
+ .st-vers { display: none; }
+ .st-mid { margin: 0; }
+ .st-mid .ib { width: 34px; }
+ .st-revb > span:not(.num), .st-dl span, .st-pub span { display: none; }
+ .st-top .btn { min-height: 36px; padding: 0 10px; }
+ .st-main { flex-direction: column; }
+ .st-rail { width: auto; height: 52px; flex-direction: row; justify-content: space-around; padding: 4px 6px; border-right: 0; border-top: 1px solid var(--line); order: 2; }
+ .st-rail button { width: auto; flex: 1; height: 46px; gap: 2px; font-size: 10.5px; border-radius: 10px; }
+ .st-rail .l { white-space: nowrap; }
+ .st-rail button .ic { width: 18px; height: 18px; }
+ .st-rail .sep { width: 1px; height: 24px; margin: 0 2px; }
+ .st-rail .dot { top: 1px; right: calc(50% - 20px); }
+ .st-stage { order: 1; flex: 1; min-height: 0; padding: 8px; gap: 8px; }
+ .st-ctrl { gap: 10px; }
+ .st-time { min-width: 0; font-size: 12px; }
+ .st-ratio, .st-ctrl .mono.st-pill { display: none; }
+ .st-insp { position: fixed; left: 0; right: 0; bottom: 0; width: auto; max-height: 62vh; border-left: 0; border-top: 1px solid var(--line-2); border-radius: 16px 16px 0 0; z-index: 40; transform: translateY(105%); transition: transform .22s ease-out; box-shadow: 0 -16px 40px rgba(0,0,0,.5); padding-bottom: env(safe-area-inset-bottom); }
+ .st-insp.open { transform: none; }
+ .st-grab { display: block; width: 100%; height: 22px; border: 0; background: none; cursor: pointer; flex: none; position: relative; }
+ .st-grab::after { content: ""; position: absolute; left: 50%; top: 9px; width: 40px; height: 4px; margin-left: -20px; border-radius: 2px; background: var(--ink-4); }
+ .st-ih { padding-top: 4px; }
+ .st-scrim { display: block; position: fixed; inset: 0; z-index: 39; background: rgba(0,0,0,.4); opacity: 0; pointer-events: none; transition: opacity .2s; }
+ .st-scrim.on { opacity: 1; pointer-events: auto; }
+ .tl-bar { padding: 0 8px; gap: 2px; overflow-x: auto; }
+ .tl-hint { display: none; }
+ .tl-zoomer input { width: 70px; }
+ .tl-labs { width: 40px; }
+ .tl-labs .lab { padding-left: 12px; }
+ .tl-labs .lab span { display: none; }
+ .r-video, .tl-labs .lab[data-k="video"] { height: 50px; }
+ .r-music, .tl-labs .lab[data-k="music"] { height: 40px; }
+ .st-toast { bottom: calc(var(--tl-h) + 60px); }
+}
+@media (prefers-reduced-motion: reduce) {
+ .st-prog i, .st-wbar i, .st-insp, .tl-row, .st-rail button { transition: none; }
+}
diff --git a/server/public/studio/studio.js b/server/public/studio/studio.js
index a114452..2ea1347 100644
--- a/server/public/studio/studio.js
+++ b/server/public/studio/studio.js
@@ -34,6 +34,7 @@ class Studio {
this.bBack.addEventListener('click', () => this.leave());
const ttl = el('div', 'st-title');
this.tName = el('b'); this.tSub = el('span');
+ this.reelA = el('a', 'st-reel'); this.reelA.hidden = true;
ttl.append(this.tName, this.tSub);
this.vers = el('div', 'st-vers', null, { role: 'radiogroup' });
this.vers.setAttribute('aria-label', t('st.versions')); this.vers.dataset.i18nAria = 'st.versions';
@@ -50,7 +51,7 @@ class Studio {
this.bPub.addEventListener('click', () => this.publish());
this.aDl = el('a', 'btn st-dl', null, { download: '' });
this.aDl.append(icon('dl'), tx('span', null, 'ed.mp4'));
- top.append(this.bBack, ttl, this.vers, mid, this.bReview, this.bReset, this.bPub, this.aDl);
+ top.append(this.bBack, ttl, this.reelA, this.vers, mid, this.bReview, this.bReset, this.bPub, this.aDl);
this.prog = el('div', 'st-prog', null, { role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100' }); this.prog.append(el('i')); this.prog.hidden = true;
// giữa
const main = el('div', 'st-main');
@@ -89,7 +90,7 @@ class Studio {
select: (s, o) => this.select(s, o),
getSel: () => this.sel,
mode: () => this.mode,
- focusKind: (k, quiet) => { if (k !== 'video') this.setMode(k, !quiet); },
+ focusKind: (k, quiet) => { this.vfocus = k === 'video'; if (k === 'video') this.timeline.setFocus('video'); else this.setMode(k, !quiet); },
flagged: (u) => this.review.flagged(u),
review: this.review,
musicLabel: () => this.musicName(this.store.doc?.music.source),
@@ -97,6 +98,7 @@ class Studio {
splitAtHead: (u) => this.splitAtHead(u),
mergeSel: () => this.mergeSel(),
deleteSel: () => this.deleteSel(),
+ splitClip: () => this.splitClip(),
onZoomAdd: () => this.addZoom(),
addZoom: () => this.addZoom(),
setGfxTime: (u, f, x) => this.setGfxTime(u, f, x),
@@ -195,7 +197,11 @@ class Studio {
const name = j?.sourceName || this.id || '';
this.tName.textContent = name; this.tName.title = name;
const style = j?.styleName || j?.style || '';
- this.tSub.textContent = [style, v ? fmtDur(v.duration) : ''].filter(Boolean).join(' · ');
+ this.tSub.textContent = [v?.keepAll ? t('st.fromReel') : style, v ? fmtDur(v.duration) : ''].filter(Boolean).join(' · ');
+ // nguồn là reel (Sửa tiếp trong Studio): link quay về video đó ở tab Dựng từ mẫu
+ const reel = v?.reel || j?.reel;
+ this.reelA.hidden = !reel;
+ if (reel) { this.reelA.textContent = t('st.reelLink', { title: reel.title || reel.id }); this.reelA.href = `#reel/${encodeURIComponent(reel.id)}`; this.reelA.title = t('st.reelBack'); }
// phiên bản
const vs = v?.versions || [];
this.vers.replaceChildren(...vs.filter((x) => x.out).map((x) => {
@@ -280,14 +286,18 @@ class Studio {
if (s.kind === 'zoom') return d.zooms.find((x) => x.u === s.u);
if (s.kind === 'gfx') return d.gfx.find((x) => x.u === s.u);
if (s.kind === 'music') return d.music.source !== 'none' ? d.music : null;
+ if (s.kind === 'clip') return s.b - s.a >= 1 / 30 ? s : null;
+ if (s.kind === 'cut') return (d.cuts || [])[s.i] || null;
return null;
}
select(s, { quiet } = {}) {
this.sel = s && this.findSel(s) ? s : null;
if (this.sel) {
- this.mode = this.sel.kind;
+ const vid = this.sel.kind === 'clip' || this.sel.kind === 'cut';
+ this.vfocus = vid;
+ this.mode = vid ? 'video' : this.sel.kind;
if (this.sel.kind === 'cap') this.insp.capTab = 'lines';
- this.timeline.setFocus(this.sel.kind);
+ this.timeline.setFocus(vid ? 'video' : this.sel.kind);
}
this.timeline.renderBlocks();
this.paintRail();
@@ -299,6 +309,7 @@ class Studio {
// ---- thao tác ----
splitAtHead(u) {
const st = this.store; const tt = this.player.time;
+ if (!u && this.vfocus) { this.splitClip(); return; }
let k = u ? st.doc.lines.findIndex((l) => l.u === u) : st.lineAt(tt);
if (k < 0 && this.sel?.kind === 'cap') k = st.doc.lines.findIndex((l) => l.u === this.sel.u);
if (k < 0) { this.toast(t('st.noLineHere')); return; }
@@ -319,8 +330,17 @@ class Studio {
else if (s.kind === 'zoom') this.store.commit((d) => { d.zooms = d.zooms.filter((x) => x.u !== s.u); });
else if (s.kind === 'gfx') this.store.commit((d) => { d.gfx = d.gfx.filter((x) => x.u !== s.u); });
else if (s.kind === 'music') this.store.commit((d) => { d.music.source = 'none'; });
+ else if (s.kind === 'clip') { if (this.store.addCut(s.a, s.b)) this.toast(t('st.cutDone', { a: fmtT(s.a), b: fmtT(s.b) })); }
+ else if (s.kind === 'cut') this.store.commit((d) => { d.cuts = (d.cuts || []).filter((_, i) => i !== s.i); });
this.sel = null; this.repaintAll();
}
+ /** S khi đang ở track video: tách clip tại đầu phát (chọn clip rồi Xoá = cắt bỏ). */
+ splitClip() {
+ const st = this.store; const tt = r2(this.player.time);
+ if (tt <= 0.05 || tt >= st.view.duration - 0.05 || st.cutAt(tt)) { this.toast(t('st.noSplitHere')); return; }
+ st.commit((d) => { d.vsplits = [...new Set([...(d.vsplits || []), tt])].sort((a, b) => a - b); });
+ const c = this.timeline.clipAt(tt + 0.01); if (c) this.select({ kind: 'clip', a: c[0], b: c[1] });
+ }
/** Zoom mới tại đầu phát: đẩy chậm 1,1× dài 1,5 s (ngắn lại nếu sát zoom sau / cuối video). */
addZoom() {
const st = this.store; if (st.view?.readOnly) return;
@@ -360,6 +380,7 @@ class Studio {
musicName(src) {
const v = this.store.view; if (!src || src === 'none') return t('ed.noMusic');
if (src === 'keep') src = v?.music.name || '';
+ if (src === 'reel') return t('st.reelMusic');
if (src.startsWith('synth:')) { const s = src.slice(6); return s.charAt(0).toUpperCase() + s.slice(1); }
if (src.startsWith('upload:')) return v?.music.uploads.find((u) => u.file === src.slice(7))?.name || src.slice(7);
return src;
diff --git a/server/public/studio/timeline.js b/server/public/studio/timeline.js
index 0cc43a5..38661a7 100644
--- a/server/public/studio/timeline.js
+++ b/server/public/studio/timeline.js
@@ -50,7 +50,7 @@ export class Timeline {
this.ruler = el('div', 'tl-ruler');
this.rows = {};
for (const k of ROWS) { const r = el('div', `tl-row r-${k}`, null, { 'data-k': k }); this.rows[k] = r; }
- this.vCanvas = el('canvas', 'tl-cv'); this.rows.video.append(this.vCanvas);
+ this.vCanvas = el('canvas', 'tl-cv'); this.vLayer = el('div', 'tl-vl'); this.rows.video.append(this.vCanvas, this.vLayer);
this.mCanvas = el('canvas', 'tl-cv'); this.mLabel = el('span', 'tl-mlab');
this.mBlock = el('div', 'blk mu', null, { 'data-u': 'music' }); this.mBlock.append(this.mLabel);
this.rows.music.append(this.mCanvas, this.mBlock);
@@ -152,6 +152,7 @@ export class Timeline {
}
for (const [u, b] of map) if (!seen.has(u)) { b.remove(); map.delete(u); }
}
+ this.paintVideoMarks();
// nhạc: 1 khối suốt video
const m = this.ctx.store.doc?.music;
const on = m && m.source !== 'none';
@@ -283,6 +284,9 @@ export class Timeline {
if (e.button !== 0) return;
const b = e.target.closest('.blk');
if (b && b.dataset.k) return this.down(e, b);
+ const vc = e.target.closest('.vcut');
+ if (vc) { this.ctx.select({ kind: 'cut', i: Number(vc.dataset.i) }); return; }
+ if (e.target.closest('.r-video')) return this.videoDown(e);
if (b === this.mBlock) { this.ctx.select({ kind: 'music', u: 'music' }); return; }
const row = e.target.closest('.tl-row');
if (row) { this.ctx.player.pause(); this.ctx.seek(clamp(this.tAt(e.clientX), 0, this.dur)); this.ctx.select(null); this.ctx.focusKind?.(row.dataset.k, true); }
@@ -339,6 +343,56 @@ export class Timeline {
};
b.addEventListener('pointermove', mv); b.addEventListener('pointerup', up); b.addEventListener('pointercancel', up);
}
+ // ---- track video: tách clip (S), chọn vùng (kéo), xoá = cắt bỏ đoạn; chỗ đã cắt hiện gạch chéo, bấm để chọn (Xoá = trả lại) ----
+ /** Mốc chia clip: đầu/cuối, điểm tách, mép chỗ cắt. */
+ clipBounds() {
+ const d = this.ctx.store.doc;
+ return [...new Set([0, this.dur, ...(d?.vsplits || []), ...(d?.cuts || []).flat()].map((x) => Math.round(x * 1000) / 1000))].sort((a, b) => a - b);
+ }
+ /** Clip (giữa 2 mốc, không nằm trong chỗ cắt) chứa tt. */
+ clipAt(tt) {
+ const bs = this.clipBounds();
+ for (let k = 0; k + 1 < bs.length; k++) if (tt >= bs[k] && tt < bs[k + 1] && !this.ctx.store.cutAt((bs[k] + bs[k + 1]) / 2)) return [bs[k], bs[k + 1]];
+ return null;
+ }
+ paintVideoMarks() {
+ const d = this.ctx.store.doc; const sel = this.ctx.getSel?.();
+ const kids = [];
+ (d?.cuts || []).forEach(([a, b], i) => {
+ const c = el('div', 'vcut' + (sel?.kind === 'cut' && sel.i === i ? ' on' : ''), null, { 'data-i': String(i), title: `${fmtT(a)}–${fmtT(b)}` });
+ c.style.transform = `translateX(${this.x(a).toFixed(1)}px)`; c.style.width = `${Math.max(2, (b - a) * this.pps).toFixed(1)}px`;
+ kids.push(c);
+ });
+ for (const s of d?.vsplits || []) { const i = el('i', 'vsplit'); i.style.transform = `translateX(${(this.x(s) - 1).toFixed(1)}px)`; kids.push(i); }
+ if (sel?.kind === 'clip') {
+ const v = el('div', 'vsel'); v.style.transform = `translateX(${this.x(sel.a).toFixed(1)}px)`; v.style.width = `${Math.max(2, (sel.b - sel.a) * this.pps).toFixed(1)}px`;
+ kids.push(v);
+ }
+ this.vLayer.replaceChildren(...kids);
+ }
+ /** Bấm track video: tua + chọn clip chứa chỗ bấm; kéo: chọn vùng [a, b]. */
+ videoDown(e) {
+ this.ctx.player.pause();
+ const t0 = clamp(this.tAt(e.clientX), 0, this.dur);
+ const row = this.rows.video; row.setPointerCapture(e.pointerId);
+ let moved = false; let t1 = t0;
+ const mv = (ev) => {
+ t1 = clamp(this.tAt(ev.clientX), 0, this.dur);
+ if (!moved && Math.abs(ev.clientX - e.clientX) < 4) return;
+ moved = true;
+ this.ctx.select({ kind: 'clip', a: Math.min(t0, t1), b: Math.max(t0, t1) }, { quiet: true });
+ this.paintVideoMarks();
+ };
+ const up = () => {
+ row.removeEventListener('pointermove', mv); row.removeEventListener('pointerup', up); row.removeEventListener('pointercancel', up);
+ this.ctx.focusKind?.('video', true);
+ if (moved) { const a = Math.min(t0, t1); const b = Math.max(t0, t1); this.ctx.select(b - a >= 1 / 30 ? { kind: 'clip', a, b } : null); return; }
+ this.ctx.seek(t0);
+ const c = this.clipAt(t0);
+ this.ctx.select(c ? { kind: 'clip', a: c[0], b: c[1] } : null);
+ };
+ row.addEventListener('pointermove', mv); row.addEventListener('pointerup', up); row.addEventListener('pointercancel', up);
+ }
/** 1 khung kéo: tính giờ mới (kẹp + hít), ghi tạm vào doc, chỉ đổi transform/width của khối đó. */
dragTo(st, dx) {
const dt = dx / this.pps; const thr = SNAP_PX / this.pps;