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.

7.1 KB
Raw Blame
// Nạp video nguồn: đọc đủ metadata (xoay, VFR, HDR, start_time, âm), băm SHA-256, rồi dựng proxy
//   CFR 30 fps · H.264 yuv420p SDR BT.709 · đã xoay đúng chiều · GOP 1 s · âm 48 kHz stereo
// cùng trục thời gian với nguồn (proxy t = PTS nguồn − start_time). Nguồn giữ nguyên, không sửa.
import fs from 'node:fs';
import crypto from 'node:crypto';
import { run } from '../engine/lib.mjs';
import { videoArgs, withEncoder } from './encoder.mjs';

const num = (v) => (v === undefined || v === null || v === 'N/A' ? NaN : Number(v));
const ratio = (s) => { const [a, b] = String(s || '0/1').split('/').map(Number); return b ? a / b : NaN; };

export function sha256File(file) {
  return new Promise((resolve, reject) => {
    const h = crypto.createHash('sha256');
    fs.createReadStream(file).on('data', (d) => h.update(d)).on('end', () => resolve(h.digest('hex'))).on('error', reject);
  });
}

/** ffprobe đầy đủ: luồng hình/tiếng, xoay (side data hoặc tag), màu, fps thật và trung bình. */
export async function probeSource(file) {
  const r = await run('ffprobe', ['-v', 'error', '-show_format', '-show_streams', '-of', 'json', file]);
  let j;
  try { j = JSON.parse(r.out); } catch { throw new Error(`ffprobe không đọc được ${file}`); }
  const v = (j.streams || []).find((s) => s.codec_type === 'video' && !s.disposition?.attached_pic);
  const a = (j.streams || []).find((s) => s.codec_type === 'audio');
  if (!v) throw new Error('file không có luồng hình');
  let rotation = 0;
  for (const sd of v.side_data_list || []) if (typeof sd.rotation === 'number') rotation = sd.rotation;
  if (!rotation && v.tags?.rotate) rotation = Number(v.tags.rotate) || 0;
  rotation = ((Math.round(rotation) % 360) + 360) % 360;
  const sar = ratio(v.sample_aspect_ratio && v.sample_aspect_ratio !== '0:1' ? v.sample_aspect_ratio.replace(':', '/') : '1/1') || 1;
  let w = Math.round(v.width * (sar > 0 ? sar : 1)); let h = v.height;
  if (rotation === 90 || rotation === 270) [w, h] = [h, w];
  const rFps = ratio(v.r_frame_rate); const aFps = ratio(v.avg_frame_rate);
  const transfer = v.color_transfer || '';
  const hdr = ['smpte2084', 'arib-std-b67'].includes(transfer) || /bt2020/.test(v.color_primaries || '');
  const duration = num(j.format?.duration) || num(v.duration);
  return {
    duration, startTime: num(j.format?.start_time) || num(v.start_time) || 0,
    fps: Number.isFinite(aFps) && aFps > 0 ? aFps : rFps,
    vfr: Number.isFinite(rFps) && Number.isFinite(aFps) && aFps > 0 && Math.abs(rFps - aFps) / aFps > 0.01,
    rotation, width: w, height: h, codec: v.codec_name, pixFmt: v.pix_fmt,
    color: { primaries: v.color_primaries || '', transfer, matrix: v.color_space || '', range: v.color_range || '' },
    hdr, hasAudio: !!a, audio: a ? { codec: a.codec_name, rate: num(a.sample_rate), channels: a.channels, layout: a.channel_layout || '' } : null,
  };
}

let zscaleOk = null;
async function hasZscale() {
  if (zscaleOk === null) { const r = await run('ffmpeg', ['-hide_banner', '-filters']); zscaleOk = / zscale /.test(r.out); }
  return zscaleOk;
}

/**
 * Proxy CFR 30 fps. Cạnh ngắn tối đa 1080 (dọc: rộng ≤ 1080; ngang: cao ≤ 1080). HDR → tonemap về SDR BT.709
 * (cần ffmpeg có zscale). Nguồn không có tiếng → chèn tiếng lặng để mọi bước sau có luồng âm.
 */
export async function makeProxy(file, info, out, { log = console.log, encoder = null } = {}) {
  // encoder: 'gpu' | 'cpu' (dựng lại proxy cho lần sửa: dùng đúng loại lần đầu để file ra giống hệt → cache chữ dùng lại)
  if (encoder) return { file: await proxyWith(encoder, file, info, out, log), encoder };
  const { result, kind } = await withEncoder((k) => proxyWith(k, file, info, out, log), { log, what: 'proxy' });
  return { file: result, encoder: kind };
}

async function proxyWith(kind, file, info, out, log) {
  const portrait = info.height >= info.width;
  const scale = portrait ? "scale='min(1080,iw)':-2:flags=lanczos" : "scale=-2:'min(1080,ih)':flags=lanczos";
  const vf = [];
  if (info.hdr) {
    if (await hasZscale()) vf.push('zscale=t=linear:npl=100', 'format=gbrpf32le', 'zscale=p=bt709', 'tonemap=hable:desat=0', 'zscale=t=bt709:m=bt709:r=tv');
    else log('cảnh báo: video HDR nhưng ffmpeg không có zscale, màu có thể nhạt');
  }
  vf.push(scale, 'setsar=1', 'fps=30', 'format=yuv420p');
  // -ss/-itsoffset không dùng: ffmpeg tự trừ start_time khi ghi (avoid_negative_ts), xoay được áp tự động (autorotate).
  // GPU: chỉ mã hoá bằng NVENC. Giải mã vẫn CPU: đo 60 s nguồn 4K H.264, NVDEC + chép khung về RAM 9,3 s, CPU 3,9 s;
  // scale_cuda còn chậm hơn (13,1 s cả proxy). CPU giải mã + NVENC 5,9 s, CPU + libx264 veryfast 8,5 s.
  const args = ['-hide_banner', '-y', '-i', file];
  if (!info.hasAudio) args.push('-f', 'lavfi', '-i', 'anullsrc=r=48000:cl=stereo');
  args.push('-map', '0:v:0', '-map', info.hasAudio ? '0:a:0' : '1:a:0',
    '-vf', vf.join(','), '-fps_mode', 'cfr',
    ...videoArgs(kind, { quality: 16, speed: 'fast', gop: 30 }), '-pix_fmt', 'yuv420p',
    '-color_primaries', 'bt709', '-color_trc', 'bt709', '-colorspace', 'bt709',
    '-c:a', 'pcm_s16le', '-ar', '48000', '-ac', '2',
    '-t', String(info.duration), '-avoid_negative_ts', 'make_zero', '-movflags', '+faststart', out);
  const movOut = out;
  const r = await run('ffmpeg', args, { timeoutMs: Math.max(10 * 60e3, info.duration * 20e3) });
  if (r.code !== 0 || !fs.existsSync(movOut)) throw new Error('dựng proxy lỗi: ' + r.out.trim().split(/\r?\n/).slice(-4).join(' | '));
  return movOut;
}

/** Nạp: probe + băm + proxy (.mov, tiếng PCM để không lệch mốc như AAC). Trả {source, proxy} đúng dạng EDL. */
export async function ingest(file, proxyOut, { log = console.log } = {}) {
  const info = await probeSource(file);
  if (!Number.isFinite(info.duration) || info.duration <= 0) throw new Error('không đọc được độ dài video');
  log(`nguồn: ${info.width}×${info.height} ${info.codec} ${info.fps.toFixed(2)} fps${info.vfr ? ' (VFR)' : ''}${info.rotation ? ` xoay ${info.rotation}°` : ''}${info.hdr ? ' HDR' : ''} · ${info.duration.toFixed(2)} s${info.hasAudio ? '' : ' · KHÔNG có tiếng'}`);
  const t = Date.now();
  const [sha, px] = await Promise.all([sha256File(file), makeProxy(file, info, proxyOut, { log })]);
  const proxyFile = px.file;
  log(`proxy: ${px.encoder === 'gpu' ? 'h264_nvenc' : 'libx264'} ${((Date.now() - t) / 1000).toFixed(1)} s`);
  const pr = await run('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=width,height', '-of', 'json', proxyFile]);
  const ps = JSON.parse(pr.out).streams[0];
  return {
    info, encoder: px.encoder,
    source: {
      file, sha256: sha, size: fs.statSync(file).size, duration: +info.duration.toFixed(3), startTime: info.startTime,
      fps: +info.fps.toFixed(3), vfr: info.vfr, rotation: info.rotation, width: info.width, height: info.height,
      codec: info.codec, hdr: info.hdr, hasAudio: info.hasAudio,
    },
    proxy: { file: proxyFile, width: ps.width, height: ps.height, fps: 30, audioRate: 48000 },
  };
}