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
// Phương tiện cho Studio (timeline trình edit): dải ảnh khung (sprite) của từng bản ra và đỉnh sóng của bài nhạc.
// Sinh bằng ffmpeg, cache theo bản: strip-<out>.jpg + strip-<out>.json trong edits/<id>/, đỉnh sóng giữ trong RAM
// theo (file, mtime). Chỉ đọc file trong thư mục edit (tên file kiểm bằng regex, không nhận đường dẫn).
import fs from 'node:fs';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';

export const OUT_RE = /^out(-r\d{1,4})?\.mp4$/;
const TILE_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 });

function ff(args, { binary = false, timeoutMs = 120000 } = {}) {
  return new Promise((resolve, reject) => {
    const p = spawn('ffmpeg', ['-hide_banner', '-loglevel', 'error', ...args], { windowsHide: true });
    const out = []; let err = '';
    const timer = setTimeout(() => { p.kill('SIGKILL'); reject(new Error('ffmpeg quá thời gian')); }, timeoutMs);
    p.stdout.on('data', (d) => out.push(d));
    p.stderr.on('data', (d) => { err += d; if (err.length > 4000) err = err.slice(-4000); });
    p.on('error', (e) => { clearTimeout(timer); reject(e); });
    p.on('close', (code) => {
      clearTimeout(timer);
      if (code !== 0) reject(new Error('ffmpeg lỗi: ' + err.trim().split(/\r?\n/).pop()));
      else resolve(binary ? Buffer.concat(out) : Buffer.concat(out).toString('utf8'));
    });
  });
}

async function durationOf(file) {
  const r = await new Promise((resolve) => {
    const p = spawn('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', file], { windowsHide: true });
    let o = ''; p.stdout.on('data', (d) => { o += d; }); p.on('close', () => resolve(o)); p.on('error', () => resolve(''));
  });
  const d = parseFloat(r);
  if (!Number.isFinite(d) || d <= 0) throw httpErr(422, 'không đọc được độ dài ' + path.basename(file));
  return d;
}

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) {
  if (!OUT_RE.test(String(out))) throw httpErr(400, 'tên bản ra không hợp lệ');
  const video = path.join(dir, out);
  if (!fs.existsSync(video)) throw httpErr(404, 'không thấy ' + out);
  const base = 'strip-' + out.replace(/\.mp4$/, '');
  const jpg = path.join(dir, base + '.jpg'); const meta = path.join(dir, base + '.json');
  const url = (m) => ({ ...m, url: `/edits/${id}/${base}.jpg?v=${Math.round(fs.statSync(jpg).mtimeMs)}` });
  try {
    const m = JSON.parse(fs.readFileSync(meta, 'utf8'));
    if (fs.existsSync(jpg) && fs.statSync(jpg).mtimeMs >= fs.statSync(video).mtimeMs - 1) return Promise.resolve(url(m));
  } catch { /* chưa có */ }
  const key = jpg;
  if (pending.has(key)) return pending.get(key);
  const job = (async () => {
    const seconds = await durationOf(video);
    const [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';
    // mỗi ô lấy khung ở giữa khoảng của nó; tile 1 hàng n cột
    await ff(['-y', '-i', video, '-vf', `tpad=stop_mode=clone:stop_duration=${(every + 0.5).toFixed(2)},fps=1/${every.toFixed(4)}:start_time=${(every / 2).toFixed(4)},scale=${TILE_W}:${TILE_H}:force_original_aspect_ratio=increase,crop=${TILE_W}:${TILE_H},tile=${n}x1`, '-frames:v', '1', '-q:v', '5', tmp]);
    fs.renameSync(tmp, jpg);
    const m = { n, every: +every.toFixed(4), tileW: TILE_W, tileH: TILE_H, seconds: +seconds.toFixed(3) };
    fs.writeFileSync(meta, JSON.stringify(m));
    return url(m);
  })().finally(() => pending.delete(key));
  pending.set(key, job);
  return job;
}

const NAME_RE = /^music(-[a-z0-9-]{1,30})?\.(wav|mp3|m4a|aac|ogg|flac|opus)$|^music-up-\d{1,4}\.(mp3|wav|m4a|aac|ogg|flac|opus)$/;
/** Tên file nhạc trong thư mục edit cho 1 nguồn chỉnh tay ('keep' = nhạc của bản hiện tại). Nhạc tổng hợp chưa có thì sinh. */
export function musicFileFor(dir, source, currentFile) {
  const s = String(source || '');
  if (s === 'keep') {
    if (!currentFile) throw httpErr(404, 'bản này không có nhạc');
    const name = path.basename(currentFile);
    if (path.resolve(path.dirname(currentFile)) !== path.resolve(dir) || !NAME_RE.test(name)) throw httpErr(404, 'nhạc của bản này nằm ngoài thư mục edit');
    return name;
  }
  let m = /^synth:([a-z0-9-]{1,30})$/.exec(s);
  if (m) {
    if (!MUSIC_STYLES.includes(m[1])) throw httpErr(400, `không có nhạc tổng hợp "${m[1]}"`);
    const name = `music-${m[1]}.wav`;
    if (!fs.existsSync(path.join(dir, name))) writeMusic(m[1], path.join(dir, name), 60, 1);
    return name;
  }
  m = /^upload:(music-up-\d{1,4}\.(mp3|wav|m4a|aac|ogg|flac|opus))$/.exec(s);
  if (m) { if (!fs.existsSync(path.join(dir, m[1]))) throw httpErr(404, 'chưa tải lên ' + m[1]); return m[1]; }
  throw httpErr(400, 'nguồn nhạc không hợp lệ');
}
export const isMusicName = (n) => NAME_RE.test(String(n));

const waves = new Map(); // file|mtime → {rate, peaks, seconds}
export const WAVE_RATE = 25; // đỉnh mỗi giây
/** Đỉnh sóng (0..1, trị tuyệt đối lớn nhất mỗi 1/25 s) của 1 file nhạc trong thư mục edit. */
export async function waveOf(dir, name) {
  if (!NAME_RE.test(name)) throw httpErr(400, 'tên nhạc không hợp lệ');
  const f = path.join(dir, name);
  const st = fs.statSync(f);
  const key = `${f}|${st.mtimeMs}`;
  if (waves.has(key)) return waves.get(key);
  const sr = 4000;
  const pcm = await ff(['-i', f, '-ac', '1', '-ar', String(sr), '-t', '600', '-f', 's16le', '-acodec', 'pcm_s16le', 'pipe:1'], { binary: true });
  const n = Math.floor(pcm.length / 2); const per = sr / WAVE_RATE;
  const peaks = [];
  let top = 1;
  for (let i = 0; i < n; i += per) {
    let mx = 0;
    for (let j = i; j < Math.min(n, i + per); j++) { const v = Math.abs(pcm.readInt16LE(j * 2)); if (v > mx) mx = v; }
    peaks.push(mx); if (mx > top) top = mx;
  }
  const r = { rate: WAVE_RATE, seconds: +(n / sr).toFixed(3), peaks: peaks.map((x) => Math.round((x / top) * 100) / 100) };
  if (waves.size > 30) waves.delete(waves.keys().next().value);
  waves.set(key, r);
  return r;
}