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.

5.5 KB
Raw Blame
#!/usr/bin/env node
// node engine/render.mjs <sceneDir> -o out.mp4 [--audio nhac.mp3] [--quality draft|looks|delivery]
// MP4 H.264 30fps qua HyperFrames, cỡ theo #root của cảnh (1080x1920 hoặc khung khác: engine/ratio.mjs). --audio: ghép 1 file âm thanh (giọng đọc/nhạc) sau khi render hình.
// Có <sceneDir>/audio.json thì tự trộn nhạc + sfx + lời (engine/audio/) và ghép; bản không tiếng giữ ở out.silent.mp4.
// Khoá như preview.mjs: LUMREELS_JAIL (thoát mã 2 nếu cảnh / file ra / --audio ngoài jail), CSP, Chromium không mạng.
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { syncLib, lintScene, runHF, run, parseArgs, probe } from './lib.mjs';
import { fontCheck } from './fontcheck.mjs';
import { loadAudioSpec, addAudio } from './audio/mix.mjs';
import { applyAudioPrefs } from './audio/prefs.mjs';
import { assertJail, withCsp, offlineEnv, lockEngine, JailError } from './sandbox.mjs';

export async function render(sceneDir, outFile, { audio, audioPrefs, quality = 'looks', log = console.log, restricted = !!process.env.LUMREELS_JAIL, expect = null } = {}) {
  sceneDir = path.resolve(sceneDir);
  outFile = path.resolve(outFile || path.join(sceneDir, 'out.mp4'));
  assertJail([sceneDir, outFile, audio && path.resolve(audio)]);
  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 { width, height } = lint.meta;
  if (!expect && (width !== 1080 || height !== 1920)) log(`kích thước ${width}x${height} (không phải 9:16 mặc định)`);
  // scene/audio.json (nhạc + sfx + lời tự tổng hợp) → render hình ra out.silent.mp4 rồi trộn + ghép vào out.mp4.
  // --audio file (ghép thẳng 1 file) được ưu tiên hơn audio.json.
  let audioSpec = null;
  if (!audio) {
    // audioPrefs (tuỳ chọn của job: {music, voice, sfx, fallbackStyle}) ghi đè audio.json; không có audio.json mà có nhạc fallback thì vẫn có tiếng
    try { audioSpec = applyAudioPrefs(loadAudioSpec(sceneDir), audioPrefs); } catch (e) { log('LỖI: ' + e.message); return { ok: false, errors: [e.message] }; }
  }
  const silent = audio ? outFile.replace(/\.mp4$/i, '.video.mp4') : audioSpec ? outFile.replace(/\.mp4$/i, '.silent.mp4') : outFile;
  fs.mkdirSync(path.dirname(outFile), { recursive: true });
  let lastPct = -1;
  const fcP = process.env.VIDEOAI_FONTCHECK !== '0' ? fontCheck(sceneDir, { log }) : Promise.resolve(null);
  const r = await withCsp(sceneDir, () => runHF(['render', sceneDir, '-o', silent, '-f', '30', '-q', quality], {
    cwd: sceneDir,
    env: offlineEnv(lock),
    onLine: (l) => {
      const m = l.match(/^@hf-progress (.*)$/);
      if (m) {
        try {
          const p = JSON.parse(m[1]);
          const bucket = Math.floor(p.pct / 10);
          if (bucket !== lastPct) { lastPct = bucket; log(`render ${p.pct}% ${p.code}${p.total ? ` ${p.done}/${p.total}` : ''}`); }
        } catch {}
      } else if (/error|lỗi|fail/i.test(l) && !l.includes('[INFO]')) log(l);
    },
  }), lock);
  const fc = await fcP;
  if (r.code !== 0 || !fs.existsSync(silent)) {
    log(r.out.slice(-3000));
    return { ok: false, errors: ['HyperFrames render lỗi (mã ' + r.code + ')'] };
  }
  if (audio) {
    // Chỗ gắn audio: giữ nguyên hình, AAC 192k, cắt theo độ dài hình.
    const a = await run('ffmpeg', ['-y', '-v', 'error', '-i', silent, '-i', path.resolve(audio), '-map', '0:v:0', '-map', '1:a:0',
      '-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-shortest', '-movflags', '+faststart', outFile]);
    if (a.code !== 0) return { ok: false, errors: ['ghép audio lỗi: ' + a.out.slice(-500)] };
    fs.rmSync(silent, { force: true });
  }
  let audioRes = null;
  if (audioSpec) {
    try { audioRes = await addAudio(sceneDir, silent, outFile, { log, spec: audioSpec }); }
    catch (e) { log('CẢNH BÁO: trộn âm thanh lỗi, giữ video không tiếng: ' + e.message); fs.copyFileSync(silent, outFile); audioRes = { ok: false, error: e.message }; }
  }
  const info = await probe(outFile);
  const v = info?.streams?.find((s) => s.codec_name === 'h264') || info?.streams?.[0];
  log(`out: ${outFile}  ${v?.codec_name} ${v?.width}x${v?.height} ${v?.r_frame_rate} ${(+info?.format?.duration).toFixed(2)}s`);
  return { ok: true, file: outFile, probe: info, fonts: fc ? fc.issues : null, audio: audioRes };
}

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/render.mjs <sceneDir> -o out.mp4 [--audio file] [--quality draft|looks|delivery]'); process.exit(2); }
  const t0 = Date.now();
  let res;
  try { res = await render(pos[0], opt.o || opt.out, { audio: opt.audio, quality: opt.quality || 'looks' }); } 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`);
  process.exit(res.ok ? 0 : 1);
}