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.

Tỉ lệ khung cho Edit video + Studio: 9:16 / 16:9 / 4:3 / 3:4

Lumtek10198fbd139d
diff --git a/edit/askeditor/fx/core/framing.py b/edit/askeditor/fx/core/framing.py
index 051775f..bb15ebb 100644
--- a/edit/askeditor/fx/core/framing.py
+++ b/edit/askeditor/fx/core/framing.py
@@ -29,7 +29,7 @@ from .face import FaceTrack
from .layout import Rect
PORTRAIT = (1080, 1920)
-SHAPES = {"9:16": 9 / 16, "4:5": 4 / 5, "1:1": 1.0, "16:9": 16 / 9}
+SHAPES = {"9:16": 9 / 16, "4:5": 4 / 5, "1:1": 1.0, "16:9": 16 / 9, "4:3": 4 / 3, "3:4": 3 / 4} # LumReels: + 4:3, 3:4
CROWN_ROOM = 0.10 # the room kept above the top of the head, as a share of the frame's height
MIN_FOUND = 0.5 # the face must be found in at least this share of frames to be followed
diff --git a/edit/captions-hf.mjs b/edit/captions-hf.mjs
index 65a554b..ee22fe0 100644
--- a/edit/captions-hf.mjs
+++ b/edit/captions-hf.mjs
@@ -6,7 +6,7 @@
import fs from 'node:fs';
import path from 'node:path';
import { syncLib, runHF } from '../engine/lib.mjs';
-import { toOutputNearest, outputDuration, timelineOf, SAFE, OUT } from './edl.mjs';
+import { toOutputNearest, outputDuration, timelineOf, SAFE, OUT, frameCy, captionFloor } from './edl.mjs';
import { graphicsScene, GFX_RUNTIME } from './graphics.mjs';
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
@@ -116,14 +116,14 @@ export const LOOKS = {
export const lookOf = (captionStyle) => LOOKS[captionStyle] || LOOKS['sach-gon'];
// thanh tin (ticker): ô tag bên trái, chữ căn trái sau tag, cả thanh cao 1,5 em ở cy
-const TICKER = { tagX: 60, tagPad: 22, tagEm: 0.62, gap: 24, right: Math.round(SAFE.x1 * OUT.width) };
+const TICKER = { tagX: 60, tagPad: 22, tagEm: 0.62, gap: 24, get right() { return Math.round(SAFE.x1 * OUT.width); } }; // mép phải theo khung đang dùng
const tickerTagW = (look) => Math.round([...look.box.tag].length * 0.56 * look.size * TICKER.tagEm + 2 * TICKER.tagPad);
/** Mép trên (px) của dòng phụ đề kiểu này — đồ hoạ đặt phía trên mép này. */
export function captionTop(captionStyle) {
const look = lookOf(captionStyle);
- if (look.enter === 'ticker') return Math.round(look.cy * OUT.height - 0.75 * look.size) - 8;
- return Math.round(look.cy * OUT.height - 0.6 * look.size * 1.18) - 8;
+ if (look.enter === 'ticker') return Math.round(frameCy(look.cy) * OUT.height - 0.75 * look.size) - 8;
+ return Math.round(frameCy(look.cy) * OUT.height - 0.6 * look.size * 1.18) - 8;
}
/** Cỡ chữ cho khối chữ tự xuống dòng: thu nhỏ tới khi ước số dòng ≤ maxLines (ước theo bề rộng trung bình 1 ký tự). */
@@ -172,7 +172,7 @@ export function writeCaptionScene(edl, sceneDir, { captions = true, accent, styl
// chữ nhấn: dòng chỉnh tay mang cờ hl riêng; tắt chữ nhấn (hiOff) thì không chữ nào nhấn
const hi = { has: (i, wd) => !edl.captions.hiOff && (wd?.hl ?? hiSet.has(i)) };
const x0 = Math.round(SAFE.x0 * OUT.width); const w = Math.round((SAFE.x1 - SAFE.x0) * OUT.width);
- const cy = Math.round(look.cy * OUT.height); const yMax = Math.round(SAFE.y1 * OUT.height);
+ const cy = Math.round(frameCy(look.cy) * OUT.height); const yMax = Math.round(captionFloor() * OUT.height); // cy theo khung (edl.mjs frameCy)
// câu trích dẫn: phụ đề thường tắt trong lúc đó
const qs = captions ? quoteSpan(edl, dur) : null;
diff --git a/edit/edl.mjs b/edit/edl.mjs
index 0ac744b..3c39b0c 100644
--- a/edit/edl.mjs
+++ b/edit/edl.mjs
@@ -7,13 +7,52 @@
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
+import { AsyncLocalStorage } from 'node:async_hooks';
import { z } from 'zod';
import { graphicsErrors } from './graphics.mjs';
+import { RATIO_IDS, DEFAULT_RATIO, normRatio, dimsOf, safeArea, isLandscape } from '../engine/ratio.mjs';
export const EDL_VERSION = 1;
-export const 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
+
+// ---- khung bản ra (tỉ lệ) -----------------------------------------------------------------------------------------
+// Mỗi bản edit có 1 tỉ lệ (edl.output.ratio: 9:16 · 16:9 · 4:3 · 3:4). Mọi chỗ đọc OUT.width/height/SAFE (phụ đề,
+// đồ hoạ, kiểm) đọc khung của lượt chạy hiện tại: withFrame(edl | tỉ lệ, fn) đặt khung cho fn và mọi await bên trong
+// (AsyncLocalStorage — 2 edit khác tỉ lệ chạy xen nhau không lẫn). Ngoài withFrame: 9:16 như trước.
+const FRAME = new AsyncLocalStorage();
+const frames = Object.fromEntries(RATIO_IDS.map((r) => [r, Object.freeze({ ratio: r, ...dimsOf(r), safe: Object.freeze(safeArea(r)), landscape: isLandscape(r) })]));
+/** Khung đang dùng: {ratio, width, height, safe, landscape}. */
+export const frameNow = () => FRAME.getStore() || frames[DEFAULT_RATIO];
+/** edl | {output} | '16:9' | null → khung. */
+export function frameOf(x) {
+ const r = typeof x === 'string' ? x : x?.output?.ratio || x?.ratio || (x?.output ? ratioFromDims(x.output) : null);
+ return frames[normRatio(r || DEFAULT_RATIO)];
+}
+const ratioFromDims = (o) => RATIO_IDS.find((r) => frames[r].width === o.width && frames[r].height === o.height) || DEFAULT_RATIO;
+/** Chạy fn trong khung của edl/tỉ lệ (fn đồng bộ hay async đều được; trả đúng giá trị của fn). */
+export const withFrame = (x, fn) => FRAME.run(frameOf(x), fn);
+export const OUT = {
+ get ratio() { return frameNow().ratio; },
+ get width() { return frameNow().width; },
+ get height() { return frameNow().height; },
+ fps: 30, audioRate: 48000, lufs: -14,
+};
+/** Vùng an toàn (phần của khung): 9:16 né nút Reels/Shorts/TikTok (120..960 px, 10..80%); khung khác lề đều (engine/ratio.mjs). */
+export const SAFE = {
+ get x0() { return frameNow().safe.x0; }, get x1() { return frameNow().safe.x1; },
+ get y0() { return frameNow().safe.y0; }, get y1() { return frameNow().safe.y1; },
+};
+/**
+ * Tâm dòng phụ đề (phần chiều cao) của 1 kiểu (LOOKS.cy, viết cho 9:16) trên khung đang dùng: phụ đề dưới (cy ≥ 0,62)
+ * xuống sát đáy vùng an toàn (khung ngang/3:4 không có nút đè ở đáy), phụ đề giữa khung giữ gần giữa.
+ */
+export function frameCy(cy, f = frameNow()) {
+ if (f.ratio === '9:16' || !Number.isFinite(cy)) return cy;
+ if (cy >= 0.62) return +Math.min(f.safe.y1 - 0.06, (f.landscape ? 0.80 : 0.78) + (cy - 0.70) * 0.5).toFixed(3);
+ return +(0.5 + (cy - 0.5) * (f.landscape ? 0.8 : 0.9)).toFixed(3);
+}
+/** Đáy tối đa của khối phụ đề (phần chiều cao): 9:16 = đáy vùng an toàn (nút của app đè bên dưới); khung khác 97%. */
+export const captionFloor = (f = frameNow()) => (f.ratio === '9:16' ? f.safe.y1 : 0.97);
const sec = z.number().finite().min(0);
const span = z.object({ start: sec, end: sec }).strict();
@@ -29,7 +68,7 @@ export const GraphicSchema = z.object({
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)
+ squeeze: z.object({ scale: z.number().min(0.5).max(1), anchorY: z.number().min(0).max(1920) }).strict().nullable().default(null)
.describe('thu cả khung hình quanh (giữa, anchorY) trong lúc đồ hoạ hiện — cận mặt, không đủ chỗ phía trên'),
}).strict();
@@ -51,7 +90,8 @@ export const EdlSchema = z.object({
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),
+ ratio: z.enum(RATIO_IDS).default(DEFAULT_RATIO).describe('tỉ lệ khung bản ra: 9:16 = 1080×1920, 16:9 = 1920×1080, 4:3 = 1440×1080, 3:4 = 1080×1440'),
+ width: z.number().int().positive(), height: z.number().int().positive(), fps: z.literal(OUT.fps),
audioRate: z.literal(OUT.audioRate), lufs: z.number().min(-30).max(-8),
}).strict(),
keep: z.array(span).min(1).describe('đoạn nguồn được giữ, theo thứ tự, không chồng nhau'),
@@ -144,7 +184,12 @@ export const inKeep = (keep, t) => keep.some((k) => t >= k.start - 1e-6 && 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 } = {}) {
+export function validateEdl(input, opts = {}) {
+ let f;
+ try { f = frameOf(input); } catch { f = null; } // tỉ lệ lạ: schema báo lỗi
+ return f ? FRAME.run(f, () => validateIn(input, opts)) : validateIn(input, opts);
+}
+function validateIn(input, { sfxNames, checkFiles = true } = {}) {
const errors = [];
const add = (code, p, msg) => errors.push({ code, path: p, msg });
const parsed = EdlSchema.safeParse(input);
@@ -153,6 +198,8 @@ export function validateEdl(input, { sfxNames, checkFiles = true } = {}) {
return { ok: false, errors };
}
const e = parsed.data;
+ const want = dimsOf(e.output.ratio);
+ if (e.output.width !== want.width || e.output.height !== want.height) add('output', 'output', `khung ${e.output.width}×${e.output.height} không khớp tỉ lệ ${e.output.ratio} (${want.width}×${want.height})`);
const dur = e.source.duration;
const tl = timelineOf(e);
const frame = 1 / e.output.fps;
diff --git a/edit/edl.schema.json b/edit/edl.schema.json
index 972a6c6..8d0f543 100644
--- a/edit/edl.schema.json
+++ b/edit/edl.schema.json
@@ -128,13 +128,26 @@
"output": {
"type": "object",
"properties": {
+ "ratio": {
+ "default": "9:16",
+ "description": "tỉ lệ khung bản ra: 9:16 = 1080×1920, 16:9 = 1920×1080, 4:3 = 1440×1080, 3:4 = 1080×1440",
+ "type": "string",
+ "enum": [
+ "9:16",
+ "16:9",
+ "4:3",
+ "3:4"
+ ]
+ },
"width": {
- "type": "number",
- "const": 1080
+ "type": "integer",
+ "exclusiveMinimum": 0,
+ "maximum": 9007199254740991
},
"height": {
- "type": "number",
- "const": 1920
+ "type": "integer",
+ "exclusiveMinimum": 0,
+ "maximum": 9007199254740991
},
"fps": {
"type": "number",
diff --git a/edit/graphics.mjs b/edit/graphics.mjs
index 6ae4702..8b7d475 100644
--- a/edit/graphics.mjs
+++ b/edit/graphics.mjs
@@ -638,6 +638,7 @@ const boxHit = (a, b) => a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h &
export const GOOD_SCALE = 0.8; // dưới mức này chữ trên đồ hoạ khó đọc trên điện thoại → thu hình
export const MIN_SCALE = 0.5;
export const MIN_SQUEEZE = 0.62; // thu hình nhỏ nhất (tỉ lệ)
+const WIDE_SQUEEZE = 0.62; // khung ngang: cột cạnh mặt chỉ cho đồ hoạ < mức này → thử thu hình
/** Khung mặt sau khi thu hình k quanh điểm (540, ay). */
export const squeezeBox = (b, q) => (b && q ? [Math.round(OUT.width / 2 + (b[0] - OUT.width / 2) * q.scale), Math.round(q.anchorY + (b[1] - q.anchorY) * q.scale),
Math.round(OUT.width / 2 + (b[2] - OUT.width / 2) * q.scale), Math.round(q.anchorY + (b[3] - q.anchorY) * q.scale)] : b);
@@ -651,12 +652,13 @@ export const squeezeBox = (b, q) => (b && q ? [Math.round(OUT.width / 2 + (b[0]
* Đồ hoạ nhỏ hiện cùng lúc dùng chung khung mặt đã thu của đồ hoạ đang hiện.
* faces: {step, boxes:[[t,[x0,y0,x1,y1]|null]]}. captionTop: px mép trên phụ đề. Ghi g.box, g.face, g.squeeze. Trả warnings.
*/
-export const STEP_BAR = { y: 196, h: 44 }; // thanh tiến độ bước (stepTracker): dải chấm ở mép trên vùng an toàn
+export const STEP_BAR = { get y() { return Math.round(SAFE.y0 * OUT.height) + 4; }, h: 44 }; // thanh tiến độ bước (stepTracker): dải chấm ở mép trên vùng an toàn (9:16: y 196)
export function layoutGraphics(graphics, keep, faces, captionTop, { stepTracker = false } = {}) {
const warnings = [];
const Y0 = stepTracker ? STEP_BAR.y + STEP_BAR.h + 16 : Math.round(SAFE.y0 * OUT.height) + 8;
const Y1 = Math.min(captionTop - 24, Math.round(SAFE.y1 * OUT.height));
const X0 = Math.round(SAFE.x0 * OUT.width); const X1 = Math.round(SAFE.x1 * OUT.width);
+ const wide = OUT.width > OUT.height; // 16:9, 4:3: đặt được cột cạnh mặt
const placed = [];
const out = [];
for (const g of graphics) {
@@ -689,14 +691,27 @@ export function layoutGraphics(graphics, keep, faces, captionTop, { stepTracker
const s = Math.min(1, (b - a) / h, (X1 - X0) / w);
if (!best || s > best.s + 1e-6) best = { a, b, s };
}
+ if (wide) {
+ // khung ngang: thêm cột trái/phải của mặt (cả chiều cao vùng an toàn) — mặt thường ở giữa, trên/dưới mặt không đủ cao
+ let cols = [[X0, X1]];
+ const bx = [];
+ if (face && face[3] > Y0 && face[1] < Y1) bx.push([face[0], face[2]]);
+ for (const p of over) bx.push([p.box.x - 16, p.box.x + p.box.w + 16]);
+ for (const [b0, b1] of bx) cols = cols.flatMap(([a, b]) => (b1 <= a || b0 >= b ? [[a, b]] : [[a, Math.min(b, b0)], [Math.max(a, b1), b]].filter(([x, y]) => y - x > 60)));
+ for (const [a, b] of cols) {
+ const s = Math.min(1, (b - a) / w, (Y1 - Y0) / h);
+ if (!best || s > best.s + 0.02) best = { col: true, a, b, s };
+ }
+ }
return best;
};
let squeeze = null; let face = squeezeBox(face0, inherited);
let best = fit(face);
- if (face0 && !inherited && !over.length && (!best || best.s < GOOD_SCALE)) {
+ // khung ngang: cột cạnh mặt trước; cột hẹp quá (4:3, mặt to) mới thu hình lấy chỗ phía trên đầu
+ if (face0 && (!wide || !best || best.s < WIDE_SQUEEZE) && !inherited && !over.length && (!best || best.s < GOOD_SCALE)) {
// thu hình quanh (giữa, cằm): đỉnh đầu hạ xuống ay − (ay − top)·k; cần đỉnh đầu ≥ Y0 + cỡ đồ hoạ
const ay = Math.min(face0[3], Y1);
- for (const s of [1, 0.92, 0.85, GOOD_SCALE]) {
+ for (const s of wide ? [1, 0.92, 0.85, GOOD_SCALE, 0.72, 0.64] : [1, 0.92, 0.85, GOOD_SCALE]) { // khung ngang thấp 1080: cho thu đồ hoạ thêm
const k = (ay - Y0 - s * h - 12) / Math.max(1, ay - face0[1]);
if (k >= MIN_SQUEEZE && k < 1 && s * w <= X1 - X0) { squeeze = { scale: +Math.min(0.97, k).toFixed(3), anchorY: ay }; break; }
}
@@ -706,11 +721,15 @@ export function layoutGraphics(graphics, keep, faces, captionTop, { stepTracker
const s = +best.s.toFixed(3);
const bw = Math.round(w * s); const bh = Math.round(h * s);
// dải phía trên mặt: dính sát dưới (gần mặt); dải dưới mặt: dính sát trên; không có mặt: giữa dải
- let y;
- if (face && best.b <= face[1] + 1) y = Math.round(best.b - bh);
+ let y; let x = Math.round(OUT.width / 2 - bw / 2);
+ if (best.col) {
+ // cột cạnh mặt: dính sát phía mặt (cột trái → mép phải cột, cột phải → mép trái), giữa theo chiều dọc vùng an toàn
+ x = face && best.b <= face[0] + 1 ? Math.round(best.b - bw) : face && best.a >= face[2] - 1 ? Math.round(best.a) : Math.round((best.a + best.b - bw) / 2);
+ y = Math.round(Math.max(Y0, Math.min(Y1 - bh, (Y0 + Y1 - bh) / 2)));
+ } else if (face && best.b <= face[1] + 1) y = Math.round(best.b - bh);
else if (face && best.a >= face[3] - 1) y = Math.round(best.a);
else y = Math.round((best.a + best.b - bh) / 2);
- const box = { x: Math.round(OUT.width / 2 - bw / 2), y, w: bw, h: bh, scale: s };
+ const box = { x, y, w: bw, h: bh, scale: s };
g.box = box; g.face = face; g.squeeze = squeeze;
placed.push({ o0, o1, box, squeeze: squeeze || inherited });
out.push(g);
diff --git a/edit/http.mjs b/edit/http.mjs
index f3f76d4..f48d672 100644
--- a/edit/http.mjs
+++ b/edit/http.mjs
@@ -4,8 +4,9 @@
// GET /api/edit-setup → tiến độ cài (nút "Cài ngay"): {running, step, ok, word, hint, elapsedS, log[]}
// POST /api/edit-setup → chạy node edit/setup.mjs nền (409 nếu đang cài)
// GET /api/edits → danh sách
-// POST /api/edits → multipart (video ≤ 2 GB, music?, style, musicStyle?, content?, names?, draft?, target?)
-// hoặc JSON {path, style, music?(đường dẫn|tên nhạc tổng hợp), content?, names?, draft?, target?}
+// POST /api/edits → multipart (video ≤ 2 GB, music?, style, ratio?, musicStyle?, content?, names?, draft?, target?)
+// hoặc JSON {path, style, ratio?, music?(đường dẫn|tên nhạc tổng hợp), content?, names?, draft?, target?}
+// ratio: 9:16 (mặc định) · 16:9 · 4:3 · 3:4
// GET /api/edits/:id → trạng thái, tiến độ, log, chữ LLM đã sửa, các lần sửa
// POST /api/edits/from-reel → {job}: Sửa tiếp trong Studio 1 reel đã dựng (giữ nguyên, tách track giọng/nhạc nếu còn)
// POST /api/edits/:id/revise → {instruction}: LLM sửa EDL theo lời, render lại, không phân tích lại
@@ -32,6 +33,7 @@ import { prepareReel, ReelImportSchema } from './reel.mjs';
import { graphicsScene, GFX_RUNTIME } from './graphics.mjs';
import { loadStyle } from './planner.mjs';
import { lookOf } from './captions-hf.mjs';
+import { withFrame } from './edl.mjs';
export const MAX_UPLOAD = 2 * 1024 ** 3; // 2 GB
const MAX_BODY = MAX_UPLOAD + 200 * 1024 ** 2; // + nhạc + trường chữ
@@ -217,7 +219,7 @@ window.gfxRender = gfxRender;
let music = files.music?.size ? files.music.path : null;
if (!music && fields.musicStyle && fields.musicStyle !== 'none') music = synthMusicFile(id, fields.musicStyle);
const job = await createEdit({
- id, video: files.video.path, sourceName: files.video.filename, style: fields.style, music,
+ id, video: files.video.path, sourceName: files.video.filename, style: fields.style, ratio: fields.ratio, music,
musicName: files.music?.filename || (fields.musicStyle && fields.musicStyle !== 'none' ? `nhạc tổng hợp ${fields.musicStyle}` : null),
content: fields.content, names: fields.names, draft: fields.draft === '1' || fields.draft === 'true', target: fields.target,
noMusic: fields.musicStyle === 'none' && !files.music?.size,
@@ -241,7 +243,7 @@ window.gfxRender = gfxRender;
let music = null; let musicName = null;
if (body.music && MUSIC_STYLES.includes(body.music)) { fs.mkdirSync(editDir(id), { recursive: true }); music = synthMusicFile(id, body.music); musicName = `nhạc tổng hợp ${body.music}`; }
else if (body.music && body.music !== 'none') music = body.music;
- const job = await createEdit({ id, video: body.path, style: body.style, music, musicName, content: body.content ?? body.notes, names: body.names, draft: !!body.draft, llm: body.llm, target: body.target });
+ const job = await createEdit({ id, video: body.path, style: body.style, ratio: body.ratio, music, musicName, content: body.content ?? body.notes, names: body.names, draft: !!body.draft, llm: body.llm, target: body.target });
runEditJob(job.id).catch((e) => console.error('[edit]', job.id, e.message));
send(res, 202, editView(job.id));
} catch (e) {
@@ -262,7 +264,8 @@ window.gfxRender = gfxRender;
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,
+ // giữ tỉ lệ của reel (job dựng từ mẫu 16:9 → bản edit 16:9, khung không cắt)
+ const job = await createEdit({ id, video: pr.video, sourceName: pr.sourceName, style: 'sach-gon', ratio: pr.reel.aspect || '9:16', music: pr.music, musicName: pr.musicName, noMusic: !pr.music,
content: pr.reel.content, llm: 'off', keepAll: true, reel: { ...pr.reel, split: pr.split }, script: pr.script, musicGainDb: pr.musicGainDb });
runEditJob(job.id).catch((e) => console.error('[edit reel]', job.id, e.message));
send(res, 202, editView(job.id));
@@ -367,7 +370,7 @@ window.gfxRender = gfxRender;
if (!ID_RE.test(m[1]) || !readEditJob(m[1])) throw httpErr(404, 'không thấy edit');
const edl = JSON.parse(fs.readFileSync(path.join(editDir(m[1]), 'edl.json'), 'utf8'));
let accent; try { accent = loadStyle(edl.style).graphics?.accent; } catch { /* kiểu đã xoá */ }
- send(res, 200, previewGraphics(edl, body, { accent: accent || lookOf(edl.captions.style).hi, graphicsScene }));
+ send(res, 200, withFrame(edl, () => previewGraphics(edl, body, { accent: accent || lookOf(edl.captions.style).hi, graphicsScene })));
} catch (e) { send(res, Number.isInteger(e.code) ? e.code : 422, { error: e.message }); }
return true;
}
diff --git a/edit/jobs.mjs b/edit/jobs.mjs
index 469c3d1..4a0f240 100644
--- a/edit/jobs.mjs
+++ b/edit/jobs.mjs
@@ -12,6 +12,8 @@ import { setupStatus } from './env.mjs';
import { resolveEditStyle } from '../packs/registry.mjs';
import { probeSource } from './ingest.mjs';
import { redact } from '../server/logs.mjs';
+import { withFrame, frameOf } from './edl.mjs';
+import { normRatio } from '../engine/ratio.mjs';
export { STEPS, EDITS, newEditId, editDir };
export const ID_RE = /^[\w-]{1,80}$/;
@@ -103,7 +105,7 @@ export async function checkMusic(music) {
}
/**
- * Tạo hồ sơ edit (chưa chạy). input: {id?, video, style, music?, musicName?, content?, names?, draft?, llm?, sourceName?}
+ * Tạo hồ sơ edit (chưa chạy). input: {id?, video, style, ratio? (9:16 · 16:9 · 4:3 · 3:4), music?, musicName?, content?, names?, draft?, llm?, sourceName?}
* Kiểm kiểu edit, file và ffprobe trước khi ghi job.json.
*/
export async function createEdit(input) {
@@ -115,6 +117,8 @@ export async function createEdit(input) {
if (!listStyles().includes(style)) throw new Error(`không có kiểu edit "${style}" (có: ${listStyles().join(', ')})`);
const music = input.music ? path.resolve(String(input.music)) : null;
if (music && (!fs.existsSync(music) || !fs.statSync(music).isFile())) throw new Error(`không thấy file nhạc ${input.music}`);
+ let ratio;
+ try { ratio = normRatio(input.ratio); } catch (e) { throw Object.assign(e, { code: 400 }); }
const info = await checkMedia(video, music);
const content = String(input.content || '').slice(0, 2000);
const target = parseTarget(input.target);
@@ -122,7 +126,7 @@ export async function createEdit(input) {
return writeJob(id, {
status: 'queued', action: 'edit', step: null, stepIndex: -1, stepTotal: STEPS.length, pct: 0, note: '',
source: video, sourceName: input.sourceName || path.basename(video), sourceSeconds: +info.duration.toFixed(2),
- style, music, musicName: input.musicName || (music ? path.basename(music) : null),
+ style, ratio, 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,
@@ -226,7 +230,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, 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),
+ id, style: job.style, ratio: job.ratio || '9:16', 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);
@@ -291,7 +295,7 @@ export function manualState(id, rev = null) {
}
}
const lookNames = Object.fromEntries(editStyles().map((s) => [s.id, { name: s.name, nameEn: s.nameEn }]));
- const v = manualView(edl, state, { lookNames, uploads: musicUploads(id) });
+ const v = withFrame(edl, () => manualView(edl, state, { lookNames, uploads: musicUploads(id) })); // khung của bản đang xem
const has = (f) => fs.existsSync(path.join(dir, f));
const stamp = (f) => { try { return Math.round(fs.statSync(path.join(dir, f)).mtimeMs); } catch { return 0; } };
const url = (f) => `/edits/${id}/${f}?v=${stamp(f)}`;
@@ -328,7 +332,8 @@ export function manualEditJob(id, body, { log = () => {} } = {}) {
const dir = editDir(id);
const st = readJson(path.join(dir, 'state.json'), {});
let style = null; try { style = loadStyle(st.style); } catch { /* kiểu đã xoá */ }
- const ap = applyPatch(readJson(path.join(dir, 'edl.json')), st, patch, { dir, style, uploads: musicUploads(id) });
+ const cur = readJson(path.join(dir, 'edl.json'));
+ const ap = withFrame(patch.ratio || cur, () => applyPatch(cur, st, patch, { dir, style, uploads: musicUploads(id) }));
const from = manualStartStep(dir, ap.edl, st.draft);
writeJob(id, { status: 'queued', action: 'manual', instruction: null, reviseError: null, pid: process.pid, stepFrom: from, stepIndex: from, step: STEPS[from], pct: 0 });
return withLock(id, async () => {
@@ -355,6 +360,7 @@ export function editView(id, { withLog = true, urlBase = `/edits/${id}` } = {})
const outName = currentOut(id);
const v = {
...job,
+ ratio: (() => { try { return frameOf(readJson(path.join(dir, 'edl.json')) || job.ratio || '9:16').ratio; } catch { return job.ratio || '9:16'; } })(),
styleName: (() => { try { return loadStyle(job.style).name; } catch { return job.style; } })(),
steps: STEPS,
fixes: result.checks?.fixes || [],
diff --git a/edit/manual.mjs b/edit/manual.mjs
index 5a5a1f9..09b119d 100644
--- a/edit/manual.mjs
+++ b/edit/manual.mjs
@@ -8,7 +8,8 @@ import path from 'node:path';
import { z } from 'zod';
import { MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';
import { captionCards, cardOverlaps, LOOKS, captionTop } from './captions-hf.mjs';
-import { outputDuration, timelineOf, toOutputNearest, inKeep, hookDur, validateEdl, OUT } from './edl.mjs';
+import { outputDuration, timelineOf, toOutputNearest, inKeep, hookDur, validateEdl, OUT, frameCy, frameOf } from './edl.mjs';
+import { RATIO_IDS, dimsOf } from '../engine/ratio.mjs';
import { outputToSource, layoutGraphics, MIN_GRAPHIC } from './graphics.mjs';
import { applyExtraCuts, outputCutToSource } from './planner.mjs';
@@ -37,6 +38,8 @@ export const GFX_FIELDS = ['title', 'unit', 'label', 'prefix', 'suffix', 'text',
const ROW_FIELDS = { items: ['label', 'text', 'value', 'ok'], rows: ['label', 'value', 'a', 'b'], points: ['label', 'value'] };
export const ManualSchema = z.object({
+ // đổi tỉ lệ khung (Studio): reframe lại theo mặt, phụ đề/đồ hoạ đặt lại theo khung mới, xuất bản mới
+ ratio: z.enum(RATIO_IDS).optional(),
captions: z.object({
lines: z.array(z.object({ start: sec, end: sec, text: z.string().trim().min(1).max(200) }).strict()).max(MAX_LINES).optional(),
highlights: z.boolean().optional(),
@@ -188,7 +191,7 @@ export function cutsOf(edl) {
return out;
}
/** Thông số kiểu chữ cho lớp xem trước HTML của Studio (gần đúng với lớp chữ HyperFrames). */
-const lookCss = (l) => ({ font: l.font, weight: l.weight, size: l.size, upper: !!l.upper, color: l.color, hi: l.hi, cy: l.cy, karaoke: !!l.karaoke, enter: l.enter, stroke: l.stroke ?? null, shadow: l.shadow || null, box: l.box ? { bg: l.box.bg, tag: l.box.tag || null, tagBg: l.box.tagBg || null, stroke: l.box.stroke ?? null } : null });
+const lookCss = (l) => ({ font: l.font, weight: l.weight, size: l.size, upper: !!l.upper, color: l.color, hi: l.hi, cy: frameCy(l.cy), cy0: l.cy, karaoke: !!l.karaoke, enter: l.enter, stroke: l.stroke ?? null, shadow: l.shadow || null, box: l.box ? { bg: l.box.bg, tag: l.box.tag || null, tagBg: l.box.tagBg || null, stroke: l.box.stroke ?? null } : null });
/** Mọi thứ chỉnh tay được của bản hiện tại (UI vẽ bảng từ đây). */
export function manualView(edl, state, { lookNames = {}, uploads = {} } = {}) {
@@ -198,8 +201,10 @@ export function manualView(edl, state, { lookNames = {}, uploads = {} } = {}) {
const m = edl.music;
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));
+ const f = frameOf(edl);
return {
duration: dur, draft: !!state.draft, cuts: cutsOf(edl),
+ output: { ratio: f.ratio, width: f.width, height: f.height, safe: f.safe },
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) })),
@@ -308,7 +313,7 @@ export function patchGfxData(g, d) {
return changed;
}
/** Dời/giãn đồ hoạ (giây bản ra) + sửa ô chữ/số. Mốc nội bộ (data.at, dòng/cột) dời theo đầu đồ hoạ, kẹp trong khoảng mới. */
-function applyGraphicsSet(edl, list, { dur, dir, style, man, redo, summary, warnings }) {
+function applyGraphicsSet(edl, list, { dur, dir, style, man, redo, summary, warnings, noLayout = false }) {
const tl = timelineOf(edl);
let retimed = false;
man.graphicsSet = man.graphicsSet || {};
@@ -337,7 +342,7 @@ function applyGraphicsSet(edl, list, { dur, dir, style, man, redo, summary, warn
}
if (Object.keys(rec).length) man.graphicsSet[g.id] = rec;
}
- if (!retimed) return;
+ if (!retimed || noLayout) return; // đổi tỉ lệ cùng lúc: đặt lại vị trí ở manualEdit (đo mặt trên khung mới)
// đặt lại vị trí né mặt theo khoảng mới (khung mặt bản ra đã đo ở lần dựng trước: faces-out.json)
edl.graphics.sort((x, y) => x.start - y.start);
let faces = null;
@@ -442,6 +447,16 @@ export function applyPatch(edlIn, state, patch, { dir, style = null, uploads = {
const dur = outputDuration(timelineOf(edl));
let music = state.music || null;
const draft = !!state.draft;
+ // tỉ lệ khung: đổi → mọi thứ vẽ theo khung dựng lại; vị trí đồ hoạ đặt lại sau (manualEdit đo mặt trên khung mới)
+ const ratio0 = frameOf(edl).ratio;
+ const relayout = !!patch.ratio && patch.ratio !== ratio0;
+ if (relayout) {
+ const d = dimsOf(patch.ratio);
+ edl.output = { ...edl.output, ratio: patch.ratio, width: d.width, height: d.height };
+ man.ratio = patch.ratio;
+ redo.base = true; redo.layer = true;
+ summary.push(`khung ${ratio0} → ${patch.ratio} (${d.width}×${d.height})`);
+ }
if (patch.captions) {
const c = patch.captions;
@@ -475,7 +490,7 @@ export function applyPatch(edlIn, state, patch, { dir, style = null, uploads = {
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?.set?.length) applyGraphicsSet(edl, patch.graphics.set, { dur, dir, style, man, redo, summary, warnings, noLayout: relayout });
if (patch.graphics?.remove?.length) {
const ids = new Set(patch.graphics.remove);
const known = new Set((edl.graphics || []).map((g) => g.id));
@@ -493,7 +508,9 @@ export function applyPatch(edlIn, state, patch, { dir, style = null, uploads = {
if (patch.graphics?.set?.length || patch.zooms?.add?.length || patch.zooms?.set?.length) {
// kiểm ngay (4xx đồng bộ) những luật thời gian/vị trí mà render sẽ kiểm lại: zoom trong đoạn giữ, đồ hoạ ≥ 1,5 s, không đè mặt/đè nhau
const v = validateEdl(edl, { checkFiles: false });
- const errs = v.ok ? [] : v.errors.filter((e) => /^(zoom|graphic)/.test(e.code) || /^(zooms|graphics)/.test(e.path));
+ // đổi tỉ lệ: vị trí đồ hoạ cũ (khung cũ) sẽ đặt lại → chỉ kiểm luật thời gian, bỏ lỗi vị trí
+ const posErr = (e) => relayout && e.code === 'graphic' && /tràn vùng an toàn|đè mặt|đè |chưa có vị trí/.test(e.msg);
+ const errs = v.ok ? [] : v.errors.filter((e) => (/^(zoom|graphic)/.test(e.code) || /^(zooms|graphics)/.test(e.path)) && !posErr(e));
if (errs.length) throw httpErr(400, 'zoom/đồ hoạ sau chỉnh không hợp lệ: ' + errs.slice(0, 3).map((e) => e.msg).join('; '));
}
@@ -548,7 +565,7 @@ export function applyPatch(edlIn, state, patch, { dir, style = null, uploads = {
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, extraCuts };
+ return { edl, manual: man, music, redo, summary, warnings, extraCuts, relayout };
}
/**
diff --git a/edit/pipeline.mjs b/edit/pipeline.mjs
index f073591..cfa8546 100644
--- a/edit/pipeline.mjs
+++ b/edit/pipeline.mjs
@@ -22,7 +22,7 @@ import {
} from './planner.mjs';
import { selectSegments, planGraphics, layoutGraphics, fillUnits, figureList, checkFigures, dropLowFigures } from './graphics.mjs';
import { fmtVi } from './numbers.mjs';
-import { validateEdl, toOutputNearest, outputDuration, timelineOf, inKeep, OUT } from './edl.mjs';
+import { validateEdl, toOutputNearest, outputDuration, timelineOf, inKeep, OUT, SAFE, captionFloor, withFrame, frameOf } from './edl.mjs';
import { writeCaptionScene, writeGraphicScene, renderCaptionLayer, captionTop, LAYER, LAYERS, layerInput } from './captions-hf.mjs';
import { buildEditMix } from './audio.mjs';
import { pickEncoder, videoArgs } from './encoder.mjs';
@@ -63,7 +63,11 @@ function runner(dir, opts) {
* target: clip nguồn dài → LLM chọn các đoạn hay nhất (hook … kết) ghép thành short ≈ target giây, rồi mới cắt ngập ngừng.
* Trả {ok, id, dir, out, edl, timings, checks, warnings, error?}
*/
-export async function editVideo(video, opts = {}) {
+export function editVideo(video, opts = {}) {
+ // tỉ lệ khung của bản ra (9:16 mặc định): mọi bước bên trong đọc OUT/SAFE theo khung này (edl.mjs withFrame)
+ return withFrame(opts.ratio || '9:16', () => editVideoIn(video, opts));
+}
+async function editVideoIn(video, opts) {
const id = opts.id || newEditId();
const dir = editDir(id);
const R = runner(dir, opts);
@@ -74,7 +78,7 @@ export async function editVideo(video, opts = {}) {
if (opts.music && !fs.existsSync(opts.music)) throw new Error(`không thấy file nhạc ${opts.music}`);
const style = { ...loadStyle(opts.style || 'sach-gon'), sfxNames: SFX_NAMES };
const names = parseNames(opts.names);
- log(`edit ${id}: ${path.basename(video)} · kiểu ${style.id}${opts.draft ? ' · bản nháp (phụ đề PIL)' : ''}${opts.music ? ' · nhạc ' + path.basename(opts.music) : ''}${names.length ? ' · tên riêng: ' + names.join(', ') : ''}`);
+ log(`edit ${id}: ${path.basename(video)} · khung ${OUT.ratio} (${OUT.width}×${OUT.height}) · kiểu ${style.id}${opts.draft ? ' · bản nháp (phụ đề PIL)' : ''}${opts.music ? ' · nhạc ' + path.basename(opts.music) : ''}${names.length ? ' · tên riêng: ' + names.join(', ') : ''}`);
const ing = await step('nạp', () => ingest(path.resolve(video), path.join(dir, 'proxy.mov'), { log }));
fs.writeFileSync(path.join(dir, 'ingest.json'), JSON.stringify(ing, null, 1));
@@ -136,7 +140,7 @@ export async function editVideo(video, opts = {}) {
if (MUSIC_STYLES.includes(style.music.default)) { music = writeMusic(style.music.default, path.join(dir, `music-${style.music.default}.wav`), 60, 1); log(` nhạc nền mặc định của kiểu: ${style.music.default}`); }
}
const state = {
- version: 1, style: style.id, music, content: opts.content || '', names,
+ version: 1, style: style.id, ratio: OUT.ratio, music, content: opts.content || '', names,
draft: !!opts.draft, llm: opts.llm || 'on', proposal: plan.proposal, overrides: {}, extraCuts: [], revisions: [],
target, segments: selection?.segments || null, exclude: selection ? [...selection.exclude] : [], graphics: plan.graphics || [],
figures: plan.figures || [], units: plan.units || [], cutRepairs: [],
@@ -173,7 +177,7 @@ export async function editVideo(video, opts = {}) {
/**
* 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ũ.
+ * người dùng bật trong Studio), khung không cắt (bản edit lấy đúng tỉ lệ của reel), nhạc của reel ở đúng âm lượng cũ.
*/
function keepWhole(edl, ing, state) {
const d = ing.source.duration;
@@ -235,6 +239,28 @@ function cutRepairer(ctx, rounds = 2) {
};
}
+/**
+ * Đặt đồ hoạ né mặt trên khung của EDL: bỏ đồ hoạ rơi vào đoạn bỏ, đo khung mặt bản ra (lumedit faces, sau reframe +
+ * zoom → faces-out.json, Studio cũng đọc), rồi layoutGraphics. Cảnh báo đẩy vào gw. Trả faces.
+ */
+async function placeGraphics(edl, dir, st, gw) {
+ const tlk = timelineOf(edl);
+ const lost = edl.graphics.filter((g) => !inKeep(tlk, g.data.at));
+ for (const g of lost) gw.push(`đồ hoạ ${g.type} ở ${g.data.at} s rơi vào đoạn bị bỏ, không hiện`);
+ edl.graphics = edl.graphics.filter((g) => inKeep(tlk, g.data.at));
+ const tmp = path.join(dir, 'edl.faces.json');
+ // vị trí cũ (khung khác) không còn đúng: bỏ thu hình cũ trước khi đo (lumedit faces đo trên khung chưa thu)
+ fs.writeFileSync(tmp, JSON.stringify({ ...edl, graphics: edl.graphics.map((g) => ({ ...g, squeeze: null })) }));
+ const facesFile = path.join(dir, 'faces-out.json');
+ const fr = await runLumedit(['faces', tmp, '--out', facesFile, '--step', '0.25']);
+ fs.rmSync(tmp, { force: true });
+ if (!fr.ok) throw new Error('đo khung mặt cho đồ hoạ lỗi: ' + fr.error);
+ const faces = JSON.parse(fs.readFileSync(facesFile, 'utf8'));
+ for (const g of edl.graphics) { g.box = null; g.face = null; g.squeeze = null; }
+ gw.push(...layoutGraphics(edl.graphics, tlk, faces, captionTop(edl.captions.style), { stepTracker: !!st?.graphics?.stepTracker }));
+ return faces;
+}
+
/** state (đề xuất + núm kiểu + cắt thêm + đồ hoạ) → EDL đã kiểm (đồ hoạ đã đặt né mặt). */
async function buildEdl({ id, dir, ing, analysis, words, style, state, checks, warnings, log }) {
const st = applyOverrides(style, state.overrides);
@@ -255,17 +281,7 @@ async function buildEdl({ id, dir, ing, analysis, words, style, state, checks, w
if (edl.graphics.length) {
// đồ hoạ: đo khung mặt bản ra (sau reframe + zoom) rồi đặt né mặt, phía trên phụ đề
const tlk = timelineOf(edl);
- const lost = edl.graphics.filter((g) => !inKeep(tlk, g.data.at));
- for (const g of lost) gw.push(`đồ hoạ ${g.type} ở ${g.data.at} s rơi vào đoạn bị bỏ, không hiện`);
- edl.graphics = edl.graphics.filter((g) => inKeep(tlk, g.data.at));
- const tmp = path.join(dir, 'edl.faces.json');
- fs.writeFileSync(tmp, JSON.stringify(edl));
- const facesFile = path.join(dir, 'faces-out.json');
- const fr = await runLumedit(['faces', tmp, '--out', facesFile, '--step', '0.25']);
- fs.rmSync(tmp, { force: true });
- if (!fr.ok) throw new Error('đo khung mặt cho đồ hoạ lỗi: ' + fr.error);
- const faces = JSON.parse(fs.readFileSync(facesFile, 'utf8'));
- gw.push(...layoutGraphics(edl.graphics, tlk, faces, captionTop(edl.captions.style), { stepTracker: !!st.graphics?.stepTracker }));
+ const faces = await placeGraphics(edl, dir, st, gw);
checks.graphics = {
count: edl.graphics.length, faceFound: faces.found_share,
items: edl.graphics.map((g) => ({ type: g.type, at: +toOutputNearest(tlk, g.start).toFixed(2), until: +toOutputNearest(tlk, g.end).toFixed(2), estimate: g.estimate, box: g.box, faceAvoided: !!g.face, pinned: !!g.data.pin })),
@@ -493,7 +509,7 @@ async function finishRender({ dir, edl, edlFile, base, rb, draft, R, outName, re
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: 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 };
+ checks.captions = { cards: sc.cards, graphics: (edl.graphics || []).length, overlaps: 0, box: sc.box, safeZone: `${OUT.ratio}: ${Math.round(SAFE.x0 * OUT.width)}–${Math.round(SAFE.x1 * OUT.width)} px ngang, đáy ≤ ${Math.round(captionFloor() * 100)}% 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);
const ranges = LAYER.name === 'png' && fs.existsSync(layerFile) && sigOk(dir, 'layerMeta', prev ? sha(prev) : '-') ? dirtyRanges(prev, sc) : null;
@@ -602,7 +618,7 @@ async function finishRender({ dir, edl, edlFile, base, rb, draft, R, outName, re
checks.loudness = { lufs: +loud.lufs.toFixed(1), truePeak: +loud.truePeak.toFixed(1), ok: Math.abs(loud.lufs - OUT.lufs) <= 1 && loud.truePeak <= -1 };
const n = 16; const d = checks.file.duration;
const sel = Array.from({ length: n }, (_, k) => `eq(n\\,${Math.floor(((k + 0.5) / n) * d * OUT.fps)})`).join('+');
- await run('ffmpeg', ['-hide_banner', '-y', '-i', out, '-vf', `select='${sel}',scale=270:480,tile=4x4:padding=6:color=0x181818`, '-frames:v', '1', '-q:v', '3', path.join(dir, 'preview-final.jpg')]);
+ await run('ffmpeg', ['-hide_banner', '-y', '-i', out, '-vf', `select='${sel}',scale=${Math.round(OUT.width / 4)}:${Math.round(OUT.height / 4)},tile=4x4:padding=6:color=0x181818`, '-frames:v', '1', '-q:v', '3', path.join(dir, 'preview-final.jpg')]);
if (qc) {
const q = await runLumedit(['qc', out, '--out', path.join(dir, 'qc.json')]);
if (q.ok) {
@@ -621,7 +637,18 @@ async function finishRender({ dir, edl, edlFile, base, rb, draft, R, outName, re
* Sửa bằng lời: không phân tích lại. Ra out-r<n>.mp4 mới; EDL cũ → versions/edl-<n>.json.
* opts: {log?, progress?}. Trả như editVideo (+ revision).
*/
-export async function reviseEdit(id, instruction, opts = {}) {
+export function reviseEdit(id, instruction, opts = {}) {
+ return withFrame(ratioOfEdit(id), () => reviseEditIn(id, instruction, opts));
+}
+/** Tỉ lệ khung hiện tại của 1 edit: state.ratio (đổi trong Studio thì ghi lại), không có thì theo edl.json, rồi 9:16. */
+export function ratioOfEdit(id, patch = null) {
+ if (patch?.ratio) return patch.ratio;
+ const dir = editDir(id);
+ const st = readJson(path.join(dir, 'state.json'), {});
+ if (st.ratio) return st.ratio;
+ return frameOf(readJson(path.join(dir, 'edl.json'), null) || '9:16').ratio;
+}
+async function reviseEditIn(id, instruction, opts) {
const dir = editDir(id);
const R = runner(dir, opts);
const { log, timings, checks, warnings, step } = R;
@@ -687,13 +714,15 @@ const sha = (x) => crypto.createHash('sha1').update(JSON.stringify(x)).digest('h
* Chữ/số/giờ đồ hoạ và kính mờ không ở đây (lớp đồ hoạ riêng + kính vẽ lúc ghép) → sửa đồ hoạ không render lại nền.
*/
const squeezes = (edl) => (edl.graphics || []).filter((g) => g.squeeze).map((g) => [g.start, g.end, g.squeeze]);
-export const baseSig = (edl, draft) => sha(['nền-v2', edl.proxy.file, edl.keep, edl.hook, edl.zooms, edl.reframe, squeezes(edl), edl.quote, draft ? edl.captions : null, !!draft]);
+// tỉ lệ khung: chỉ thêm vào chữ ký khi khác 9:16 (bản cũ 9:16 giữ nguyên chữ ký, không phải render lại)
+const fr = (x) => { const r = typeof x === 'string' ? x : x?.output?.ratio || '9:16'; return r === '9:16' ? [] : [r]; };
+export const baseSig = (edl, draft) => sha(['nền-v2', edl.proxy.file, edl.keep, edl.hook, edl.zooms, edl.reframe, squeezes(edl), edl.quote, draft ? edl.captions : null, !!draft, ...fr(edl)]);
/** Bản sạch xem trước: phần cắt + khung. */
-export const cleanSig = (edl) => sha(['sạch-v1', edl.proxy.file, edl.keep, edl.hook, edl.reframe]);
+export const cleanSig = (edl) => sha(['sạch-v1', edl.proxy.file, edl.keep, edl.hook, edl.reframe, ...fr(edl)]);
/** Lớp phụ đề: phụ đề + chữ móc + trích dẫn (+ đồ hoạ khi kiểu có thanh bước). */
-export const layerSig = (edl, draft, comb = false) => sha([LAYER.name, 'chữ-v2', edl.style, edl.keep, edl.hook, edl.captions, comb ? edl.graphics || [] : null, edl.hookText, edl.quote, !!draft]);
-/** Lớp 1 đồ hoạ: chính đồ hoạ (chữ, số, mốc, vị trí) + màu nhấn + khoảng render. */
-export const gfxSig = (g, accent, w) => sha([LAYERS.png.name, 'đh-v1', g, accent || null, w.from, w.dur]);
+export const layerSig = (edl, draft, comb = false) => sha([LAYER.name, 'chữ-v2', edl.style, edl.keep, edl.hook, edl.captions, comb ? edl.graphics || [] : null, edl.hookText, edl.quote, !!draft, ...fr(edl)]);
+/** Lớp 1 đồ hoạ: chính đồ hoạ (chữ, số, mốc, vị trí) + màu nhấn + khoảng render (+ tỉ lệ khung đang dùng). */
+export const gfxSig = (g, accent, w) => sha([LAYERS.png.name, 'đh-v1', g, accent || null, w.from, w.dur, ...fr(OUT.ratio)]);
/** Tiếng: giọng gốc (theo phần cắt) + nhạc + sfx + giọng/sfx chỉnh tay + LUFS. */
export const mixSig = (edl) => sha([edl.keep, edl.hook, edl.audio, edl.music, edl.audio?.sfxOff ? [] : outputSfx(edl), edl.output.lufs]);
const sigFile = (dir) => path.join(dir, 'render.sig.json');
@@ -713,7 +742,10 @@ async function baseSeconds(base) {
* xoá zoom → render nền (không nghe lại); phụ đề/look/chữ nhấn/đồ hoạ → lớp chữ; nhạc/giọng/sfx → trộn tiếng; luôn ghép.
* Ra out-r<n>.mp4 mới, EDL cũ → versions/edl-<n>.json. patch đã qua parseManual. opts: {log?, progress?, uploads?}.
*/
-export async function manualEdit(id, patch, opts = {}) {
+export function manualEdit(id, patch, opts = {}) {
+ return withFrame(ratioOfEdit(id, patch), () => manualEditIn(id, patch, opts));
+}
+async function manualEditIn(id, patch, opts) {
const dir = editDir(id);
const R = runner(dir, opts);
const { log, checks, warnings } = R;
@@ -732,6 +764,24 @@ export async function manualEdit(id, patch, opts = {}) {
for (const w of ap.warnings) { log(' ' + w); warnings.push(w); }
const edl = ap.edl;
const base = path.join(dir, 'base.mp4');
+ const ensureProxy = async () => {
+ if (fs.existsSync(ing.proxy.file)) return;
+ if (!fs.existsSync(ing.source.file)) throw new Error('không còn file nguồn ' + ing.source.file);
+ const t = Date.now();
+ await makeProxy(ing.source.file, ing.info, ing.proxy.file, { log, encoder: ing.encoder || 'cpu' });
+ R.timings['dựng lại proxy'] = +((Date.now() - t) / 1000).toFixed(1); // proxy bị dọn sau lượt trước (jobs.cleanupEdit)
+ log(` dựng lại proxy từ nguồn: ${R.timings['dựng lại proxy']} s`);
+ };
+ if (ap.relayout) {
+ // đổi tỉ lệ khung: khung mặt bản ra đổi → đo lại, đặt lại đồ hoạ né mặt trên khung mới
+ log(` khung mới ${OUT.ratio} (${OUT.width}×${OUT.height}): reframe lại theo mặt, đặt lại phụ đề/đồ hoạ`);
+ if ((edl.graphics || []).length || fs.existsSync(path.join(dir, 'faces-out.json'))) {
+ await ensureProxy();
+ const gw = [];
+ await placeGraphics(edl, dir, style, gw);
+ for (const w of gw) { log(' ' + w); warnings.push(w); }
+ }
+ }
// nền chỉ dựng lại khi phần vẽ trong nền đổi (zoom, đồ hoạ có kính mờ) hoặc thiếu/không khớp chữ ký
const redoBase = !fs.existsSync(base) || !sigOk(dir, 'base', baseSig(edl, state.draft));
if (ap.redo.base && !redoBase) log(' nền: không đổi, dùng lại');
@@ -746,13 +796,7 @@ export async function manualEdit(id, patch, opts = {}) {
fs.writeFileSync(edlFile, JSON.stringify(edl, null, 1));
let rb;
if (redoBase) {
- if (!fs.existsSync(ing.proxy.file)) {
- if (!fs.existsSync(ing.source.file)) throw new Error('không còn file nguồn ' + ing.source.file);
- const t = Date.now();
- await makeProxy(ing.source.file, ing.info, ing.proxy.file, { log, encoder: ing.encoder || 'cpu' });
- R.timings['dựng lại proxy'] = +((Date.now() - t) / 1000).toFixed(1); // proxy bị dọn sau lượt trước (jobs.cleanupEdit)
- log(` dựng lại proxy từ nguồn: ${R.timings['dựng lại proxy']} s`);
- }
+ await ensureProxy();
rb = await renderBase({ edlFile, base, draft: state.draft, R, check: false });
} else rb = { seconds_out: readJson(sigFile(dir), {}).baseSeconds || await baseSeconds(base) };
// lớp chữ / bản trộn dùng lại khi chữ ký khớp EDL mới (nền đổi vì zoom thì tiếng gốc vẫn y hệt → trộn cũ dùng được)
@@ -760,7 +804,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, ...(ap.extraCuts?.length ? { extraCuts: [...(state.extraCuts || []), ...ap.extraCuts] } : {}),
+ ...state, ratio: OUT.ratio, 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));
@@ -779,6 +823,9 @@ export async function manualEdit(id, patch, opts = {}) {
/** Bước đầu tiên chỉnh tay phải chạy (để thanh tiến độ bắt đầu đúng chỗ): nền → phụ đề → tiếng → ghép. */
export function manualStartStep(dir, edl, draft) {
+ return withFrame(edl, () => startStepIn(dir, edl, draft));
+}
+function startStepIn(dir, edl, draft) {
if (!fs.existsSync(path.join(dir, 'base.mp4')) || !sigOk(dir, 'base', baseSig(edl, draft))) return STEPS.indexOf('render nền');
let style = null; try { style = loadStyle(edl.style); } catch { /* bỏ qua */ }
const comb = gfxInCaptions(style);
diff --git a/edit/py/lumedit.py b/edit/py/lumedit.py
index 279fabd..9365b3c 100644
--- a/edit/py/lumedit.py
+++ b/edit/py/lumedit.py
@@ -12,7 +12,7 @@ is missing, 1 on any other failure.
Everything in an EDL is in source seconds; the proxy shares the source's time axis. The render is
one pass: AskEditor's Timeline (the kept stretches, with the source sound joined by 20 ms
-crossfades) and Framing (9:16 window following the face), then our zooms and draft captions drawn
+crossfades) and Framing (a window of the EDL's frame — 9:16, 16:9, 4:3 or 3:4 — following the face), then our zooms and draft captions drawn
on each output frame.
"""
@@ -35,6 +35,33 @@ os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "3")
OUT_W, OUT_H, OUT_FPS = 1080, 1920, 30
SAFE = (120 / 1080, 0.10, 960 / 1080, 0.80) # x0, y0, x1, y1 as shares of the frame
+OUT_RATIO = "9:16"
+# The output frame of each ratio (engine/ratio.mjs): the short side is always 1080. Set from edl.output by load_edl.
+RATIOS = {"9:16": (1080, 1920), "16:9": (1920, 1080), "4:3": (1440, 1080), "3:4": (1080, 1440)}
+SAFES = {"9:16": (120 / 1080, 0.10, 960 / 1080, 0.80), "16:9": (0.06, 0.07, 0.94, 0.90),
+ "4:3": (0.06, 0.07, 0.94, 0.90), "3:4": (0.07, 0.07, 0.93, 0.86)}
+
+
+def set_frame(edl: dict) -> None:
+ """The output frame of this EDL (edl.output.ratio; an old EDL without one is 9:16)."""
+ global OUT_W, OUT_H, SAFE, OUT_RATIO
+ out = edl.get("output") or {}
+ ratio = out.get("ratio") or next((r for r, wh in RATIOS.items() if wh == (out.get("width"), out.get("height"))), "9:16")
+ if ratio not in RATIOS:
+ raise ValueError(f"output ratio {ratio!r} is not supported")
+ OUT_RATIO = ratio
+ OUT_W, OUT_H = RATIOS[ratio]
+ SAFE = SAFES[ratio]
+
+
+def caption_cy(cy: float) -> float:
+ """A caption line's centre (share of the height) written for 9:16, on this frame (edit/edl.mjs frameCy)."""
+ if OUT_RATIO == "9:16":
+ return cy
+ land = OUT_W > OUT_H
+ if cy >= 0.62:
+ return min(SAFE[3] - 0.06, (0.80 if land else 0.78) + (cy - 0.70) * 0.5)
+ return 0.5 + (cy - 0.5) * (0.8 if land else 0.9)
def emit(kind: str, obj: dict) -> None:
@@ -103,6 +130,7 @@ def load_edl(path: Path) -> dict:
edl = json.loads(path.read_text(encoding="utf-8"))
if edl.get("version") != 1:
raise ValueError(f"EDL version {edl.get('version')!r} is not supported (want 1)")
+ set_frame(edl)
return edl
@@ -120,7 +148,8 @@ def build(edl: dict, draft_captions: bool, glass_on: bool = True):
tl = hook_timeline(Timeline, segs, edl.get("hook"), info.duration)
mode = edl["reframe"]["mode"]
face = clip.face if mode == "face" else None
- fr = framing_mod.plan(info.width, info.height, info.rate, info.frames, face, shape="9:16",
+ # the window follows the face into the EDL's frame; a clip already in that shape (landscape → 16:9) is not cut
+ fr = framing_mod.plan(info.width, info.height, info.rate, info.frames, face, shape=OUT_RATIO,
size=(OUT_W, OUT_H), mode={"face": "track", "center": "center", "fill": "fill",
"none": "center"}[mode])
if (fr.out_w, fr.out_h) != (OUT_W, OUT_H):
@@ -443,7 +472,7 @@ class DraftCaptions:
self.cards = caption_cards(edl, tl)
self.hi = set(cap["highlights"])
self.base, self.hcol, self.active, self.size, self.upper = STYLE_DRAFT.get(cap["style"], STYLE_DRAFT["sach-gon"])
- self.cy = OUT_H * (0.70 if cap["position"] == "lower" else 0.58)
+ self.cy = OUT_H * caption_cy(0.70 if cap["position"] == "lower" else 0.58)
self.cache: dict = {}
def sprite(self, ci: int, active: int):
@@ -579,7 +608,7 @@ def cmd_stills(edl_path: Path, out: Path, count: int, draft_captions: bool) -> d
frames = rmod.still_frames(clip, tl, fr, draw, times)
cols = int(math.ceil(math.sqrt(count)))
rows = int(math.ceil(count / cols))
- tw, th = 270, 480
+ tw, th = OUT_W // 4, OUT_H // 4 # 9:16 → 270×480
sheet = Image.new("RGB", (cols * tw + (cols + 1) * 6, rows * (th + 32) + (rows + 1) * 6), (24, 24, 24))
d = ImageDraw.Draw(sheet)
for n, (t, f) in enumerate(frames):
diff --git a/edit/reel.mjs b/edit/reel.mjs
index 5d7efd7..3d863cb 100644
--- a/edit/reel.mjs
+++ b/edit/reel.mjs
@@ -63,7 +63,7 @@ export async function prepareReel(jobId, dir, { log = () => {} } = {}) {
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 reel = { id: jobId, title, templateId: job.templateId || null, aspect: job.aspect || '9:16', 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) {
diff --git a/edit/studio-media.mjs b/edit/studio-media.mjs
index 7402e51..c448c2f 100644
--- a/edit/studio-media.mjs
+++ b/edit/studio-media.mjs
@@ -7,7 +7,7 @@ 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 TILE_H = 96; // ô cao 96 px, ngang theo tỉ lệ bản ra (9:16 → 54, 16:9 → 170, 4:3 → 128, 3:4 → 72)
const MAX_TILES = 240;
const httpErr = (code, msg) => Object.assign(new Error(msg), { code });
@@ -37,6 +37,15 @@ async function durationOf(file) {
return d;
}
+async function sizeOf(file) {
+ const r = await new Promise((resolve) => {
+ const p = spawn('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=width,height', '-of', 'csv=p=0:s=x', file], { windowsHide: true });
+ let o = ''; p.stdout.on('data', (d) => { o += d; }); p.on('close', () => resolve(o)); p.on('error', () => resolve(''));
+ });
+ const m = /(\d+)x(\d+)/.exec(r);
+ return m ? [Number(m[1]), Number(m[2])] : [1080, 1920];
+}
+
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) {
@@ -54,6 +63,8 @@ export function stripOf(dir, id, out) {
if (pending.has(key)) return pending.get(key);
const job = (async () => {
const seconds = await durationOf(video);
+ const [vw, vh] = await sizeOf(video);
+ const TILE_W = Math.max(16, Math.round((TILE_H * vw) / vh / 2) * 2);
const n = Math.max(1, Math.min(MAX_TILES, Math.ceil(seconds / 0.5)));
const every = seconds / n;
const tmp = jpg + '.part.jpg';
diff --git a/edit/test/ratio-check.mjs b/edit/test/ratio-check.mjs
new file mode 100644
index 0000000..f3fbd91
--- /dev/null
+++ b/edit/test/ratio-check.mjs
@@ -0,0 +1,149 @@
+#!/usr/bin/env node
+// Kiểm tỉ lệ khung (9:16 · 16:9 · 4:3 · 3:4) cho cả 2 luồng, không gọi AI, không render:
+// node edit/test/ratio-check.mjs → phần chạy tại chỗ (job tạm tự xoá, EDL dựng trong RAM)
+// node edit/test/ratio-check.mjs 4400 → thêm vài lệnh HTTP bị từ chối (tỉ lệ sai → 400, không tạo job)
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import http from 'node:http';
+import { fileURLToPath } from 'node:url';
+import { RATIOS, normRatio, dimsOf, safeArea, ratioOfDims, nearestRatio } from '../../engine/ratio.mjs';
+import { createJob, validateBatch, jobDir, readJob } from '../../generator/jobs.mjs';
+import { ratioRule } from '../../generator/prompt.mjs';
+import { lintScene } from '../../engine/lib.mjs';
+import { validateEdl, withFrame, OUT, SAFE, frameCy, frameOf } from '../edl.mjs';
+import { layoutGraphics, baseSize } from '../graphics.mjs';
+import { writeCaptionScene, captionTop } from '../captions-hf.mjs';
+import { ManualSchema, applyPatch, manualView } from '../manual.mjs';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
+let pass = 0; let fail = 0;
+const ok = (c, name, extra = '') => { if (c) { pass++; console.log('PASS', name); } else { fail++; console.log('FAIL', name, extra); } };
+const throws = (fn) => { try { fn(); return false; } catch { return true; } };
+
+// ---- 1. bảng tỉ lệ ----
+ok(JSON.stringify(Object.keys(RATIOS)) === '["9:16","16:9","4:3","3:4"]', 'đủ 4 tỉ lệ');
+ok(dimsOf('9:16').width === 1080 && dimsOf('9:16').height === 1920 && dimsOf('16:9').width === 1920 && dimsOf('4:3').width === 1440 && dimsOf('3:4').height === 1440, 'kích thước đúng spec');
+ok(Object.values(RATIOS).every((d) => Math.min(d.width, d.height) === 1080), 'cạnh ngắn luôn 1080 (luật cỡ chữ giữ nguyên)');
+ok(normRatio(undefined) === '9:16' && normRatio('16x9') === '16:9' && normRatio('1440x1080') === '4:3' && normRatio(' 3/4 ') === '3:4', 'normRatio nhận nhiều cách viết');
+ok(throws(() => normRatio('1:1')) && throws(() => normRatio('21:9')) && throws(() => normRatio('../x')), 'normRatio từ chối tỉ lệ lạ');
+ok(ratioOfDims(1920, 1080) === '16:9' && ratioOfDims(1000, 1000) === null && nearestRatio(3840, 2160) === '16:9' && nearestRatio(720, 1280) === '9:16', 'ratioOfDims / nearestRatio');
+for (const r of Object.keys(RATIOS)) { const s = safeArea(r); ok(s.x0 > 0 && s.x1 < 1 && s.y0 > 0 && s.y1 < 1 && s.x0 < s.x1 && s.y0 < s.y1, `vùng an toàn ${r} hợp lệ`); }
+
+// ---- 2. dựng từ mẫu: job.json, prompt, lint ----
+const made = [];
+try {
+ for (const r of Object.keys(RATIOS)) {
+ const j = createJob({ templateId: '009', content: 'Kiểm tỉ lệ khung tự động, không chạy AI', durationS: 8, aspect: r, mode: 'manual', source: 'test' });
+ made.push(j.id);
+ const d = dimsOf(r);
+ ok(j.aspect === r && j.width === d.width && j.height === d.height, `job ${r}: job.json có aspect + ${d.width}×${d.height}`);
+ const p = fs.readFileSync(path.join(jobDir(j.id), 'PROMPT.md'), 'utf8');
+ ok(p.includes(`(${d.width}×${d.height}`), `job ${r}: PROMPT ghi khung ${d.width}×${d.height}`);
+ ok(r === '9:16' ? !p.includes('## Khung ') : p.includes(`## Khung ${r}`) && p.includes('Vùng an toàn') && p.includes('Cỡ chữ theo cạnh ngắn'), `job ${r}: ${r === '9:16' ? 'không thêm' : 'có'} khối luật khung chung`);
+ }
+ const j2 = createJob({ templateId: '009', content: 'Kiểm job cũ', durationS: 8, ratio: '16:9', mode: 'manual', source: 'test' });
+ made.push(j2.id);
+ ok(readJob(j2.id).aspect === '16:9', 'createJob nhận cả trường ratio (MCP/CLI)');
+ ok(throws(() => createJob({ templateId: '009', content: 'x'.repeat(20), aspect: '1:1', mode: 'manual' })), 'createJob từ chối 1:1');
+ ok(throws(() => validateBatch({ templateIds: ['009', '045'], content: 'x'.repeat(20), aspect: '5:4' })), 'lô nhiều mẫu: tỉ lệ sai → từ chối cả lô');
+ ok(ratioRule('16:9').includes('xếp thành cột') && ratioRule('3:4').includes('×0.75') && ratioRule('9:16') === '', 'luật bố cục: ngang xếp cột, 3:4 nén dọc, 9:16 không thêm');
+} finally { for (const id of made) fs.rmSync(path.join(ROOT, 'jobs', id), { recursive: true, force: true }); }
+
+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ratio-check-'));
+try {
+ const scene = (w, h, dw = w, dh = h) => `<!doctype html><html><head><meta charset="utf-8"><script src="./lib/vendor/gsap.min.js"></script><script src="./lib/runtime/scene.js"></script></head>
+<body><div id="root" data-composition-id="main" data-start="0" data-duration="8" data-fps="30" data-width="${w}" data-height="${h}"></div>
+<script>VideoScene.define({ duration: 8, fps: 30, width: ${dw}, height: ${dh}, render(t) {} });</script></body></html>`;
+ fs.writeFileSync(path.join(tmp, 'index.html'), scene(1080, 1920));
+ ok(lintScene(tmp, { expect: dimsOf('16:9') }).errors.some((e) => /Khung 1080×1920 sai/.test(e)), 'lint: job 16:9 mà cảnh 1080×1920 → lỗi');
+ fs.writeFileSync(path.join(tmp, 'index.html'), scene(1920, 1080));
+ ok(!lintScene(tmp, { expect: dimsOf('16:9') }).errors.some((e) => /Khung|không khớp/.test(e)), 'lint: cảnh 1920×1080 đúng job 16:9');
+ fs.writeFileSync(path.join(tmp, 'index.html'), scene(1920, 1080, 1080, 1920));
+ ok(lintScene(tmp, { expect: dimsOf('16:9') }).errors.some((e) => /VideoScene\.define width\/height/.test(e)), 'lint: define lệch #root → lỗi');
+} finally { fs.rmSync(tmp, { recursive: true, force: true }); }
+
+// ---- 3. edit: EDL, khung theo lượt chạy, phụ đề, đồ hoạ ----
+const editDir = fs.readdirSync(path.join(ROOT, 'edits')).filter((d) => fs.existsSync(path.join(ROOT, 'edits', d, 'edl.json'))).sort().reverse()
+ .find((d) => { try { const e = JSON.parse(fs.readFileSync(path.join(ROOT, 'edits', d, 'edl.json'), 'utf8')); return (e.output.ratio || '9:16') === '9:16' && (e.graphics || []).length; } catch { return false; } });
+if (!editDir) console.log('(không có edit 9:16 có đồ hoạ để thử EDL: bỏ phần 3)');
+else {
+ const edl0 = JSON.parse(fs.readFileSync(path.join(ROOT, 'edits', editDir, 'edl.json'), 'utf8'));
+ const old = JSON.parse(JSON.stringify(edl0)); delete old.output.ratio;
+ ok(validateEdl(old, { checkFiles: false }).errors.every((e) => e.code !== 'schema'), 'EDL cũ (không có ratio) vẫn hợp lệ, hiểu là 9:16');
+ ok(frameOf(old).ratio === '9:16', 'frameOf(EDL cũ) = 9:16');
+ const bad = JSON.parse(JSON.stringify(edl0)); bad.output.ratio = '16:9';
+ ok(validateEdl(bad, { checkFiles: false }).errors.some((e) => e.code === 'output'), 'EDL ratio 16:9 mà khung 1080×1920 → lỗi output');
+ const wide = JSON.parse(JSON.stringify(edl0)); wide.output = { ...wide.output, ratio: '16:9', width: 1920, height: 1080 };
+ wide.graphics[0].box = { ...wide.graphics[0].box, y: 1300 }; // chỗ hợp lệ trên khung dọc 1920, ngoài khung ngang 1080
+ ok(validateEdl(wide, { checkFiles: false }).errors.some((e) => e.code === 'graphic' && /tràn vùng an toàn/.test(e.msg)), 'kiểm vùng an toàn theo khung của EDL (y 1300 tràn khung 16:9)');
+ // khung theo lượt chạy, 2 lượt xen nhau không lẫn
+ const seen = await Promise.all(['16:9', '3:4', '9:16', '4:3'].map((r) => withFrame(r, async () => { await new Promise((z) => setTimeout(z, 20 * Math.random())); return `${OUT.ratio}=${OUT.width}x${OUT.height}`; })));
+ ok(seen.join(',') === '16:9=1920x1080,3:4=1080x1440,9:16=1080x1920,4:3=1440x1080', 'withFrame: 4 lượt async xen nhau giữ đúng khung riêng', seen.join(','));
+ ok(OUT.width === 1080 && OUT.height === 1920 && Math.abs(SAFE.x0 - 120 / 1080) < 1e-9, 'ngoài withFrame: 9:16 như cũ');
+ ok(withFrame('9:16', () => frameCy(0.70)) === 0.70 && withFrame('16:9', () => frameCy(0.70)) === 0.80 && withFrame('16:9', () => frameCy(0.5)) === 0.5, 'frameCy: 9:16 giữ, 16:9 phụ đề dưới xuống 0,80');
+ // phụ đề: cảnh HyperFrames đúng cỡ khung
+ const sd = fs.mkdtempSync(path.join(os.tmpdir(), 'ratio-cap-'));
+ try {
+ for (const r of ['16:9', '3:4']) {
+ const d = dimsOf(r); const e = { ...JSON.parse(JSON.stringify(edl0)), output: { ...edl0.output, ratio: r, ...d }, graphics: [] };
+ const sc = withFrame(e, () => writeCaptionScene(e, sd, { captions: true }));
+ const html = fs.readFileSync(path.join(sd, 'index.html'), 'utf8');
+ ok(html.includes(`data-width="${d.width}" data-height="${d.height}"`) && sc.box.x1 <= d.width && sc.box.cy < d.height && sc.box.yMax <= d.height, `phụ đề ${r}: cảnh ${d.width}×${d.height}, khối chữ trong khung (cy ${sc.box.cy}, đáy ${sc.box.yMax})`);
+ }
+ } finally { fs.rmSync(sd, { recursive: true, force: true }); }
+ // đồ hoạ: khung ngang, mặt giữa khung → đặt cột cạnh mặt, không đè mặt, trong vùng an toàn
+ await withFrame('16:9', async () => {
+ const g = JSON.parse(JSON.stringify(edl0.graphics.find((x) => !x.data?.pin) || edl0.graphics[0]));
+ g.box = null; g.face = null; g.squeeze = null;
+ const keep = Object.assign(edl0.keep.map((k) => ({ ...k })), {});
+ const face = [760, 160, 1160, 760];
+ const faces = { step: 0.25, boxes: Array.from({ length: 4000 }, (_, i) => [i * 0.25, face]) };
+ const list = [g];
+ const w = layoutGraphics(list, keep, faces, captionTop(edl0.captions.style));
+ const b = list[0]?.box;
+ const hit = b && b.x < face[2] && b.x + b.w > face[0] && b.y < face[3] && b.y + b.h > face[1];
+ const sa = safeArea('16:9');
+ ok(b && !hit && b.x >= sa.x0 * 1920 - 1 && b.x + b.w <= sa.x1 * 1920 + 1 && b.y >= sa.y0 * 1080 - 1, `đồ hoạ ${g.type} 16:9: cột cạnh mặt, không đè, trong vùng an toàn`, JSON.stringify({ b, w, size: baseSize(g) }));
+ ok(!list[0]?.squeeze, 'khung ngang không thu hình (squeeze)');
+ });
+ // Studio: bản vá ratio
+ ok(ManualSchema.safeParse({ ratio: '4:3' }).success && !ManualSchema.safeParse({ ratio: '2:1' }).success, 'bản vá Studio nhận ratio 4:3, từ chối 2:1');
+ const st = JSON.parse(fs.readFileSync(path.join(ROOT, 'edits', editDir, 'state.json'), 'utf8'));
+ const ap = withFrame('3:4', () => applyPatch(edl0, st, { ratio: '3:4' }, { dir: path.join(ROOT, 'edits', editDir) }));
+ ok(ap.relayout && ap.edl.output.ratio === '3:4' && ap.edl.output.width === 1080 && ap.edl.output.height === 1440 && ap.manual.ratio === '3:4' && ap.redo.base, 'applyPatch ratio: khung mới, cần đặt lại + render nền');
+ ok(edl0.output.width === 1080 && edl0.output.height === 1920, 'applyPatch không sửa EDL gốc');
+ ok(throws(() => withFrame('9:16', () => applyPatch(edl0, st, { ratio: '9:16' }, { dir: path.join(ROOT, 'edits', editDir) }))), 'đổi sang đúng tỉ lệ đang có → "không có gì khác"');
+ const v = withFrame(edl0, () => manualView(edl0, st));
+ ok(v.output?.ratio === '9:16' && v.output.width === 1080 && v.captions.looks.every((l) => Number.isFinite(l.css.cy0)), 'manualView có output.ratio + cy0 cho Studio');
+}
+
+// ---- 4. HTTP: tỉ lệ sai bị từ chối, không tạo gì ----
+const port = Number(process.argv[2]);
+function req(method, p, body) {
+ return new Promise((resolve) => {
+ const data = body ? JSON.stringify(body) : null;
+ const r = http.request({ host: '127.0.0.1', port, path: p, method, headers: { Host: `127.0.0.1:${port}`, ...(data ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) } : {}) } }, (res) => {
+ let b = ''; res.setEncoding('utf8'); res.on('data', (c) => { b += c; }); res.on('end', () => resolve({ code: res.statusCode, body: b }));
+ });
+ r.on('error', (e) => resolve({ code: 0, body: e.message }));
+ if (data) r.write(data); r.end();
+ });
+}
+if (port) {
+ const before = fs.readdirSync(path.join(ROOT, 'jobs')).length;
+ const a = await req('POST', '/api/jobs', { templateId: '009', content: 'Kiểm tỉ lệ sai qua HTTP', aspect: '1:1', mode: 'manual' });
+ ok(a.code === 400 && /Tỉ lệ khung không hỗ trợ/.test(a.body), 'POST /api/jobs tỉ lệ 1:1 → 400', a.body.slice(0, 120));
+ const b = await req('POST', '/api/jobs/batch', { templateIds: ['009', '045'], content: 'Kiểm tỉ lệ sai qua HTTP', aspect: '21:9', mode: 'manual' });
+ ok(b.code === 400, 'POST /api/jobs/batch tỉ lệ 21:9 → 400');
+ ok(fs.readdirSync(path.join(ROOT, 'jobs')).length === before, 'không tạo job nào');
+ const eds = fs.readdirSync(path.join(ROOT, 'edits')).length;
+ const c = await req('POST', '/api/edits', { path: path.join(ROOT, 'test', 'VGA ngáo giá.mp4'), style: 'sach-gon', ratio: '2:3' });
+ ok([400, 503].includes(c.code), 'POST /api/edits tỉ lệ 2:3 → 400', `${c.code} ${c.body.slice(0, 100)}`);
+ ok(fs.readdirSync(path.join(ROOT, 'edits')).length === eds, 'không tạo edit nào');
+ const d = await req('POST', '/api/edits/khong-co/manual', { ratio: '16:9' });
+ ok(d.code === 404 || d.code === 415, 'bản vá ratio cho edit không có → 404');
+}
+
+console.log(`\n${pass} PASS, ${fail} FAIL`);
+process.exit(fail ? 1 : 0);
diff --git a/server/public/studio/create.css b/server/public/studio/create.css
index ce3a049..7d136ff 100644
--- a/server/public/studio/create.css
+++ b/server/public/studio/create.css
@@ -212,3 +212,6 @@
.job.flash { box-shadow: 0 0 0 3px var(--accent); transition: box-shadow .3s; }
.cr-log { margin-top: 6px; min-height: 36px; padding: 0 10px; font-size: 12.5px; }
.cr-log:not(.bad) { border-color: transparent; background: none; color: var(--ink-3); }
+.cr-rhint { margin: 8px 0 0; font-size: 12.5px; line-height: 1.45; color: var(--ink-3); }
+.cr-ratios .ratio { min-height: 56px; }
+.cr-open .th .rt { position: absolute; left: 8px; top: 8px; background: rgba(0,0,0,.72); border-radius: 6px; padding: 2px 6px; font-size: 11.5px; color: var(--ink); }
diff --git a/server/public/studio/create.js b/server/public/studio/create.js
index 058dc2d..742deb7 100644
--- a/server/public/studio/create.js
+++ b/server/public/studio/create.js
@@ -44,7 +44,7 @@ async function init() {
} else $('#edSetup').hidden = true;
S.style = ls.get('lumreels.cr.style') || o.styles[0]?.id || null;
if (!styleById(S.style)) S.style = o.styles[0]?.id || null;
- renderStyles(); renderMusic(); renderNames(); renderLen(); renderClip(); setStep(1); loadList();
+ renderStyles(); renderMusic(); renderNames(); renderLen(); renderRatio(); renderClip(); setStep(1); loadList();
}
// ---- bước ----
@@ -135,6 +135,26 @@ $('#crMusic').addEventListener('click', (e) => {
});
$('#edMusicFile').addEventListener('change', (e) => { const f = e.target.files[0]; e.target.value = ''; if (!f) return; S.music = f; S.musicSel = 'file'; renderMusic(); refreshFoot(); });
+// ---- khung hình (tỉ lệ bản ra): 9:16 · 16:9 · 4:3 · 3:4 — clip ngang + 16:9 thì giữ nguyên khung, không cắt ----
+const RATIO_DIMS = { '9:16': [1080, 1920], '16:9': [1920, 1080], '4:3': [1440, 1080], '3:4': [1080, 1440] };
+S.ratio = RATIO_DIMS[ls.get('lumreels.cr.ratio')] ? ls.get('lumreels.cr.ratio') : '9:16';
+function renderRatio(focus) {
+ $$('#crRatio .ratio').forEach((b) => { const on = b.dataset.ratio === S.ratio; b.classList.toggle('on', on); b.setAttribute('aria-checked', String(on)); b.tabIndex = on ? 0 : -1; if (on && focus) b.focus(); });
+ const [w, h] = RATIO_DIMS[S.ratio];
+ $('#crRatioSize').textContent = `${w}×${h}`;
+ // clip đã chọn: báo trước có cắt khung hay giữ nguyên
+ const v = $('#crClipVid'); const vw = v?.videoWidth; const vh = v?.videoHeight;
+ const same = S.video && vw && vh && Math.abs(vw / vh - w / h) < 0.02 * (w / h);
+ $('#crRatioHint').textContent = same ? t('cr.ratioSame') : t('cr.ratioHint.' + S.ratio.replace(':', 'x'));
+ refreshFoot();
+}
+function setRatio(r, focus) { if (!RATIO_DIMS[r]) return; S.ratio = r; ls.set('lumreels.cr.ratio', r); renderRatio(focus); }
+$('#crRatio').addEventListener('click', (e) => { const b = e.target.closest('.ratio'); if (b) setRatio(b.dataset.ratio); });
+$('#crRatio').addEventListener('keydown', (e) => {
+ const d = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }[e.key]; if (!d) return;
+ e.preventDefault(); const ids = Object.keys(RATIO_DIMS); setRatio(ids[(ids.indexOf(S.ratio) + d + ids.length) % ids.length], true);
+});
+
// ---- độ dài bản ra ----
function renderLen() {
const r = $('#crLen'); const auto = S.target == null;
@@ -201,7 +221,7 @@ function renderClip() {
if (v.dataset.name !== f.name + f.size) {
if (v.src) URL.revokeObjectURL(v.src);
v.dataset.name = f.name + f.size; v.src = URL.createObjectURL(f);
- v.onloadedmetadata = () => { S.videoDur = v.duration; v.currentTime = Math.min(v.duration / 3, 20); $('#crClipDur').textContent = fmtDur(v.duration); renderClip(); refreshFoot(); };
+ v.onloadedmetadata = () => { S.videoDur = v.duration; v.currentTime = Math.min(v.duration / 3, 20); $('#crClipDur').textContent = fmtDur(v.duration); renderClip(); refreshFoot(); if (S.opts) renderRatio(); };
}
}
drop.addEventListener('click', () => $('#edVideo').click());
@@ -222,6 +242,7 @@ function refreshFoot() {
if (S.step >= 2) {
sum.push(el('span', 'pill', S.musicSel === 'style' ? t('cr.musicStyle') : S.musicSel === 'none' ? t('ed.noMusic') : S.musicSel === 'file' ? (S.music?.name || '') : S.musicSel));
sum.push(el('span', 'pill', S.target == null ? t('cr.lenAutoV') : t('cr.lenV', { s: S.target })));
+ sum.push(el('span', 'pill mono', S.ratio));
}
$('#crSum').replaceChildren(...sum);
const go = $('#edGo'); const lab = $('#edGo span');
@@ -238,6 +259,7 @@ $('#edGo').addEventListener('click', () => {
if (S.musicSel === 'file' && !S.music) { setErr(t('ed.needMusic')); return; }
const fd = new FormData();
fd.append('style', S.style);
+ fd.append('ratio', S.ratio);
fd.append('content', $('#edNotes').value.trim());
fd.append('names', S.names.join(', '));
fd.append('draft', $('#edDraft').checked ? '1' : '0');
@@ -288,6 +310,7 @@ function paintBuild(v) {
const lg = $('#crLog'); lg.dataset.logId = v.id; lg.classList.toggle('bad', v.status === 'error'); lg.textContent = t(v.status === 'error' ? 'log.btnErr' : 'log.btn');
const th = $('#crBuildThumb'); const pv = safeUrl(v.links?.previewFinal || v.links?.preview);
th.style.backgroundImage = pv ? `url("${pv}")` : '';
+ th.style.aspectRatio = (RATIO_DIMS[v.ratio] ? v.ratio : '9:16').replace(':', ' / ');
}
$('#crAnother').addEventListener('click', () => { clearTimeout(S.timer); S.job = null; S.video = null; renderClip(); setStep(1); });
@@ -308,6 +331,7 @@ function renderList() {
const th = el('span', 'th', null, { 'aria-hidden': 'true' });
const pv = safeUrl(v.links?.previewFinal || v.links?.preview);
if (pv) th.style.backgroundImage = `url("${pv}")`;
+ if (RATIO_DIMS[v.ratio] && v.ratio !== '9:16') { th.style.aspectRatio = v.ratio.replace(':', ' / '); th.append(el('span', 'rt mono', v.ratio)); }
const dur = v.checks?.edl?.outSeconds;
if (Number.isFinite(dur)) th.append(el('span', 'd mono', fmtDur(dur)));
const meta = el('span', 'meta');
@@ -388,7 +412,7 @@ window.addEventListener('lumreels:lang', () => {
if (S.noServer) $('#edSetupText').textContent = t('ed.noServer');
else if (S.opts && !S.opts.ready) $('#edSetupText').textContent = t('ed.setupText');
if (lastInstall) paintInstall(lastInstall);
- if (S.opts) { const had = document.activeElement?.closest?.('#edStyles'); renderStyles(); renderMusic(); renderNames(); renderLen(); if (had) $('#edStyles .sty[aria-checked="true"]')?.focus(); }
+ if (S.opts) { const had = document.activeElement?.closest?.('#edStyles'); renderStyles(); renderMusic(); renderNames(); renderLen(); renderRatio(); if (had) $('#edStyles .sty[aria-checked="true"]')?.focus(); }
renderClip(); refreshFoot();
if (S.list) renderList();
if (S.job && S.step === 3) paintBuild(S.job);
diff --git a/server/public/studio/gfx-frame.html b/server/public/studio/gfx-frame.html
index 0cc64ad..188517c 100644
--- a/server/public/studio/gfx-frame.html
+++ b/server/public/studio/gfx-frame.html
@@ -6,8 +6,9 @@
<title>gfx</title>
<link rel="stylesheet" href="/fonts/fonts.css" />
<style>
- html, body { margin: 0; width: 1080px; height: 1920px; overflow: hidden; background: transparent; }
- #root { position: relative; width: 1080px; height: 1920px; overflow: hidden; background: transparent; }
+ /* khung = cỡ bản ra (Studio đặt cỡ iframe theo tỉ lệ: 1080×1920, 1920×1080, 1440×1080, 1080×1440) */
+ html, body { margin: 0; width: 100vw; height: 100vh; overflow: hidden; background: transparent; }
+ #root { position: relative; width: 100vw; height: 100vh; overflow: hidden; background: transparent; }
</style>
<style id="gcss"></style>
</head>
diff --git a/server/public/studio/player.js b/server/public/studio/player.js
index 09bfde1..d807454 100644
--- a/server/public/studio/player.js
+++ b/server/public/studio/player.js
@@ -9,7 +9,18 @@
// 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 FPS = 30;
+// khung bản ra (edl.output.ratio; đổi trong Studio = doc.ratio): cùng bảng với engine/ratio.mjs + edit/edl.mjs frameCy
+export const RATIO_DIMS = { '9:16': [1080, 1920], '16:9': [1920, 1080], '4:3': [1440, 1080], '3:4': [1080, 1440] };
+const SAFE_OF = { '9:16': { x0: 120 / 1080, x1: 960 / 1080, y1: 0.80 }, '16:9': { x0: 0.06, x1: 0.94, y1: 0.90 }, '4:3': { x0: 0.06, x1: 0.94, y1: 0.90 }, '3:4': { x0: 0.07, x1: 0.93, y1: 0.86 } };
+/** Tâm dòng phụ đề (viết cho 9:16) trên khung r — như edit/edl.mjs frameCy. */
+export function frameCy(cy, r) {
+ if (r === '9:16' || !Number.isFinite(cy)) return cy;
+ const land = RATIO_DIMS[r][0] > RATIO_DIMS[r][1];
+ if (cy >= 0.62) return Math.min(SAFE_OF[r].y1 - 0.06, (land ? 0.80 : 0.78) + (cy - 0.70) * 0.5);
+ return 0.5 + (cy - 0.5) * (land ? 0.8 : 0.9);
+}
+let W = 1080; let H = 1920; let RATIO = '9:16';
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);
@@ -52,7 +63,10 @@ export class Player {
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');
+ // tỉ lệ khung: đổi ở đây = 1 thay đổi (Undo được), xuất bản mới mới reframe theo mặt + đặt lại phụ đề/đồ hoạ
+ this.bRatio = el('select', 'st-pill st-ratiosel', null, { 'aria-label': t('st.ratioAria'), title: t('st.ratioAria'), 'data-i18n-aria': 'st.ratioAria', 'data-i18n-title': 'st.ratioAria' });
+ for (const r of Object.keys(RATIO_DIMS)) this.bRatio.append(el('option', null, r, { value: r }));
+ this.bRatio.addEventListener('change', () => this.ctx.onRatio?.(this.bRatio.value));
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);
@@ -108,8 +122,7 @@ export class Player {
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.paintBadge();
this.cap = null; this.lastGlass = ''; this.tick();
}
setMusic(url) {
@@ -157,8 +170,30 @@ export class Player {
const f = () => { this.tick(); if (!this.video.paused && !this.video.ended) { this.syncAudio(false); this.raf = requestAnimationFrame(f); } };
this.raf = requestAnimationFrame(f);
}
+ /**
+ * Khung đang xem = tỉ lệ đang sửa (doc.ratio) — khác bản đã xuất thì là xem trước gần đúng: hình cắt giữa (object-fit),
+ * phụ đề đúng chỗ khung mới, không zoom CSS / đồ hoạ (vị trí mặt và đồ hoạ chỉ có sau khi xuất).
+ */
+ applyFrame() {
+ const v = this.ctx.store.view; const doc = this.ctx.store.doc;
+ const cur = RATIO_DIMS[v?.output?.ratio] ? v.output.ratio : '9:16';
+ const want = this.mode === 'out' ? cur : RATIO_DIMS[doc?.ratio] ? doc.ratio : cur;
+ this.pendingRatio = want !== cur;
+ if (this.bRatio.value !== (doc?.ratio || cur)) this.bRatio.value = doc?.ratio || cur;
+ this.bRatio.disabled = !!v?.readOnly || !!this.ctx.busy?.();
+ if (want === RATIO && this.box.dataset.ratio === want) return;
+ RATIO = want; [W, H] = RATIO_DIMS[want];
+ this.box.dataset.ratio = want;
+ this.box.style.aspectRatio = `${W} / ${H}`;
+ this.frame.style.width = `${W}px`; this.frame.style.height = `${H}px`;
+ const sa = SAFE_OF[want];
+ this.capText.style.left = `${(sa.x0 * 100).toFixed(3)}%`; this.capText.style.width = `${((sa.x1 - sa.x0) * 100).toFixed(3)}%`;
+ this.cap = null; this.lastGlass = '';
+ this.fit();
+ }
/** Vẽ 1 khung theo t: giờ, zoom CSS, phụ đề, đồ hoạ (iframe), kính. */
tick(at) {
+ this.applyFrame();
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;
@@ -171,7 +206,7 @@ export class Player {
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%). */
+ /** Tâm zoom (px khung bản ra, vd 1080×1920): tâm khung đầu lúc zoom bắt đầu (faces-out), không có mặt thì (giữa, 40%). */
zoomCenter(z) {
const f = this.ctx.store.view?.faces; let c = [W / 2, H * 0.4];
if (f?.boxes?.length) {
@@ -181,9 +216,15 @@ export class Player {
}
return c;
}
+ paintBadge() {
+ const out = this.mode !== 'edit' && !!(this.src.clean || this.src.base);
+ const key = out ? 'st.viewingOut' : this.pendingRatio ? 'st.ratioPending' : null;
+ this.badge.hidden = !key;
+ if (key) { this.badge.textContent = t(key, { r: RATIO }); if (key === 'st.viewingOut') this.badge.dataset.i18n = key; else delete this.badge.dataset.i18n; } // chuỗi có {r}: vẽ lại ở tick khi đổi ngôn ngữ
+ }
paintZoom(src, doc, tt) {
let tr = '';
- if (src && doc) {
+ if (src && doc && !this.pendingRatio) {
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);
@@ -229,8 +270,9 @@ export class Player {
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 sa = SAFE_OF[RATIO];
+ if (ticker) { const nch = text.join(' ').length; size = Math.max(34, Math.min(look.size, Math.floor((sa.x1 * W - 300) / (nch * 0.46 + 0.4)))); }
+ else if (ws.length === 1) size = Math.min(look.size, Math.floor(((sa.x1 - sa.x0) * W) / (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' : '');
@@ -238,7 +280,7 @@ export class Player {
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.top = `${(frameCy(look.cy0 ?? look.cy, RATIO) * 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 : '';
@@ -264,7 +306,7 @@ export class Player {
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}`;
+ const key = `${line.u}|${line.text}|${line.start}|${line.end}|${s.doc.look}|${s.doc.hi}|${this.k}|${s.doc.show}|${RATIO}`;
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;
@@ -320,7 +362,8 @@ export class Player {
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.paintBadge();
+ const on = tt != null && !!this.gfxScene?.data?.length && !this.pendingRatio;
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)
diff --git a/server/public/studio/store.js b/server/public/studio/store.js
index 75699bc..45b2fdc 100644
--- a/server/public/studio/store.js
+++ b/server/public/studio/store.js
@@ -13,6 +13,7 @@ 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, show: v.captions.show !== false,
+ ratio: v.output?.ratio || '9:16',
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 },
@@ -167,6 +168,7 @@ export class Store {
}
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) })) };
+ if ((c.ratio || '9:16') !== (o.ratio || '9:16')) p.ratio = c.ratio;
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 137c3d8..082e7a5 100644
--- a/server/public/studio/studio.css
+++ b/server/public/studio/studio.css
@@ -337,3 +337,5 @@ button.st-pill:hover { color: var(--ink); }
@media (prefers-reduced-motion: reduce) {
.st-prog i, .st-wbar i, .st-insp, .tl-row, .st-rail button { transition: none; }
}
+.st-ratiosel { cursor: pointer; color: var(--ink); padding: 0 8px; min-height: 30px; font: 600 12.5px var(--mono); }
+.st-ratiosel:disabled { opacity: .55; cursor: default; }
diff --git a/server/public/studio/studio.js b/server/public/studio/studio.js
index 9c7ed87..db3d04e 100644
--- a/server/public/studio/studio.js
+++ b/server/public/studio/studio.js
@@ -68,7 +68,8 @@ class Studio {
b.addEventListener('click', () => this.setMode(k, true));
this.railBtns[k] = b; this.rail.append(b);
}
- this.player = new Player({ store: this.store, onTime: (tt) => this.onTime(tt), onPlay: (p) => { this.timeline.follow = p; }, getSel: () => this.sel });
+ this.player = new Player({ store: this.store, onTime: (tt) => this.onTime(tt), onPlay: (p) => { this.timeline.follow = p; }, getSel: () => this.sel,
+ onRatio: (r) => this.setRatio(r), busy: () => busyOf(this.job) || !!this.publishing });
this.insp = new Inspector(this.ctx());
main.append(this.rail, this.player.root, this.insp.root);
this.timeline = new Timeline(this.ctx());
@@ -263,6 +264,11 @@ class Studio {
if (this.store.doc?.music.source !== this.waveSrc) this.loadWave();
else this.player.syncAudio(false);
}
+ /** Đổi tỉ lệ khung (1 bước Undo). Xuất bản mới: reframe theo mặt, phụ đề/đồ hoạ đặt lại trên khung mới. */
+ setRatio(r) {
+ if (!this.store.doc || this.store.view?.readOnly) return;
+ if (this.store.commit((d) => { d.ratio = r; })) this.toast(t('st.ratioChanged', { r }));
+ }
/** Cảnh đồ hoạ xem trước: server dựng HTML/CSS từ đồ hoạ đang sửa (giờ + ô chữ/số), khung sandbox vẽ theo t. */
refreshGfx(now) {
const v = this.store.view; const id = this.id;