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.
#!/usr/bin/env node
// node engine/preview.mjs <sceneDir> [-o preview.jpg] → lưới 4x4 = 16 khung cách đều duration/16
// (8s → 0,0s 0,5s … 7,5s); mỗi ô = 1/3 khung (9:16 → lưới 1440x2560,
// cùng dạng templates/ref/<id>/sheet.jpg; 16:9 → 2560x1440 …)
// node engine/preview.mjs <sceneDir> --frame 3.5 [-o khung.jpg] → 1 khung cỡ đầy đủ (theo #root) để soát chữ
// Cảnh nằm trong thư mục job (jobs/<id>/scene) → đọc ../job.json: #root phải đúng khung job đã chọn (tỉ lệ).
// Luôn chạy kèm kiểm font (fontcheck.mjs): dòng FONT_FALLBACK / FONT_OUTSIDE / FONT_WEIGHT / FONT_DIGITS là cảnh báo.
// Tắt kiểm font: VIDEOAI_FONTCHECK=0
// Khoá (engine/sandbox.mjs): có LUMREELS_JAIL thì thư mục cảnh + file ra phải nằm trong jail (sai → thoát mã 2);
// HyperFrames chạy với CSP chèn vào cảnh + Chromium không mạng (tắt bằng LUMREELS_RESTRICT=off).
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { syncLib, lintScene, runHF, run, parseArgs } from './lib.mjs';
import { fontCheck } from './fontcheck.mjs';
import { assertJail, withCsp, offlineEnv, lockEngine, JailError } from './sandbox.mjs';
import { dimsOf } from './ratio.mjs';
const fontCheckOn = () => process.env.VIDEOAI_FONTCHECK !== '0';
export async function preview(sceneDir, outFile, log = console.log, { frame, restricted = !!process.env.LUMREELS_JAIL, expect = null } = {}) {
sceneDir = path.resolve(sceneDir);
const single = frame !== undefined && frame !== null && frame !== true;
outFile = path.resolve(outFile || path.join(sceneDir, single ? `frame-${frame}s.jpg` : 'preview.jpg'));
assertJail([sceneDir, outFile]);
if (!fs.existsSync(path.join(sceneDir, 'index.html'))) return { ok: false, errors: [`Không thấy ${path.join(sceneDir, 'index.html')}`] };
syncLib(sceneDir);
const lint = lintScene(sceneDir, { restricted, expect });
const lock = lockEngine(restricted);
for (const w of lint.warnings) log('CẢNH BÁO: ' + w);
if (lint.errors.length) {
for (const e of lint.errors) log('LỖI: ' + e);
return { ok: false, errors: lint.errors };
}
const D = lint.meta.duration;
const times = single
? [Math.max(0, Math.min(D, Number(frame)))]
: Array.from({ length: 16 }, (_, i) => +((D / 16) * i).toFixed(3));
const shotDir = path.join(sceneDir, '.hyperframes', single ? 'frame' : 'preview-frames');
fs.rmSync(shotDir, { recursive: true, force: true });
const [r, fc] = await withCsp(sceneDir, () => Promise.all([
runHF(['snapshot', sceneDir, '--at', times.join(','), '--no-end', '-o', shotDir, '--json'], { cwd: sceneDir, env: offlineEnv(lock) }),
fontCheckOn() && !single ? fontCheck(sceneDir, { log }) : Promise.resolve(null),
]), lock);
const pngs = fs.existsSync(shotDir) ? fs.readdirSync(shotDir).filter((f) => /^frame-\d+.*\.png$/.test(f)).sort() : [];
if (pngs.length < times.length) {
log(r.out.slice(-3000));
return { ok: false, errors: [`snapshot chỉ ra ${pngs.length}/${times.length} khung`] };
}
if (single) {
const f = await run('ffmpeg', ['-y', '-v', 'error', '-i', path.join(shotDir, pngs[0]), '-frames:v', '1', '-q:v', '2', outFile]);
if (f.code !== 0 || !fs.existsSync(outFile)) return { ok: false, errors: ['ffmpeg lỗi: ' + f.out.slice(-500)] };
log(`khung ${times[0]}s: ${outFile} (${lint.meta.width}x${lint.meta.height})`);
return { ok: true, file: outFile };
}
const inputs = pngs.slice(0, 16).flatMap((f) => ['-i', path.join(shotDir, f)]);
let fcg = '';
const tw = Math.round(lint.meta.width / 3 / 2) * 2; const th = Math.round(lint.meta.height / 3 / 2) * 2; // ô = 1/3 khung (9:16 → 360×640)
for (let i = 0; i < 16; i++) fcg += `[${i}:v]scale=${tw}:${th}[s${i}];`;
for (let row = 0; row < 4; row++) fcg += `${[0, 1, 2, 3].map((c) => `[s${row * 4 + c}]`).join('')}hstack=inputs=4[r${row}];`;
fcg += '[r0][r1][r2][r3]vstack=inputs=4[out]';
const f = await run('ffmpeg', ['-y', '-v', 'error', ...inputs, '-filter_complex', fcg, '-map', '[out]', '-frames:v', '1', '-q:v', '3', outFile]);
if (f.code !== 0 || !fs.existsSync(outFile)) return { ok: false, errors: ['ffmpeg ghép lưới lỗi: ' + f.out.slice(-500)] };
log(`preview: ${outFile} (16 khung: ${times[0]}s … ${times[15]}s)`);
return { ok: true, file: outFile, frames: pngs.map((p) => path.join(shotDir, p)), fonts: fc ? fc.issues : null };
}
if (path.resolve(process.argv[1] || '') === fileURLToPath(import.meta.url)) {
const { pos, opt } = parseArgs(process.argv.slice(2));
if (!pos[0]) { console.error('Dùng: node engine/preview.mjs <sceneDir> [-o preview.jpg] [--frame <giây>]'); process.exit(2); }
const t0 = Date.now();
let res;
// cảnh của 1 job: khung phải đúng tỉ lệ job đã chọn (jobs/<id>/job.json, trường aspect)
let expect = null;
try { const j = JSON.parse(fs.readFileSync(path.join(path.resolve(pos[0]), '..', 'job.json'), 'utf8')); if (j && j.aspect) expect = dimsOf(j.aspect); } catch { /* không phải thư mục job */ }
try { res = await preview(pos[0], opt.o || opt.out, console.log, { frame: opt.frame, expect }); } catch (e) {
if (e instanceof JailError) { console.error('LỖI: ' + e.message); process.exit(2); }
throw e;
}
console.log(`${res.ok ? 'OK' : 'FAIL'} sau ${((Date.now() - t0) / 1000).toFixed(1)}s${res.fonts?.length ? ` — ${res.fonts.length} cảnh báo font` : ''}`);
process.exit(res.ok ? 0 : 1);
}