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.

10.4 KB
Raw Blame
// Trộn âm thanh theo scene/audio.json rồi ghép vào MP4 (ffmpeg).
//   nhạc (style) + sfx (adelay) + giọng đọc → nhạc tự hạ khi có giọng (sidechain) → loudnorm −14 LUFS 2 lượt
//   → AAC 192k stereo 48 kHz, cắt đúng độ dài hình. Hình giữ nguyên (-c:v copy).
//
// Mức gain (dB) so với "mức chuẩn" của từng lớp: nhạc và giọng đã chuẩn hoá RMS −16 dBFS, sfx đỉnh −1 dBFS.
//   0 dB nhạc = ngang giọng đọc. Mặc định: nhạc −6 (không lời) / −12 (có lời), sfx −6, giọng 0.
import fs from 'node:fs';
import path from 'node:path';
import { run, probe } from '../lib.mjs';
import { SFX_NAMES, writeSfx } from './sfx.mjs';
import { MUSIC_STYLES, writeMusic } from './music.mjs';
import { synthVoice, detectLang } from './voice.mjs';
import { voiceEngine, defaultVoiceFor } from './prefs.mjs';
import { hashStr } from './dsp.mjs';

export const TARGET_LUFS = -14;

/** Đọc + kiểm scene/audio.json. Trả null nếu không có file. Ném lỗi nếu sai luật. */
export function loadAudioSpec(sceneDir) {
  const f = path.join(sceneDir, 'audio.json');
  if (!fs.existsSync(f)) return null;
  let spec;
  try { spec = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { throw new Error(`audio.json không phải JSON hợp lệ: ${e.message}`); }
  return validateAudioSpec(spec);
}

/** Kiểm 1 spec audio (cùng dạng audio.json). Ném lỗi nếu sai luật, trả lại spec. */
export function validateAudioSpec(spec) {
  if (!spec || typeof spec !== 'object') throw new Error('audio.json phải là object');
  const errs = [];
  if (spec.music) {
    if (!MUSIC_STYLES.includes(spec.music.style)) errs.push(`music.style "${spec.music.style}" không có (có: ${MUSIC_STYLES.join(', ')})`);
  }
  (spec.sfx || []).forEach((s, i) => {
    if (!SFX_NAMES.includes(s.name)) errs.push(`sfx[${i}].name "${s.name}" không có (có: ${SFX_NAMES.join(', ')})`);
    if (!(typeof s.t === 'number' && s.t >= 0)) errs.push(`sfx[${i}].t phải là số giây ≥ 0`);
  });
  const lines = spec.voice?.lines || [];
  lines.forEach((l, i) => {
    if (!(typeof l.t === 'number' && l.t >= 0)) errs.push(`voice.lines[${i}].t phải là số giây ≥ 0`);
    if (!String(l.text || '').trim()) errs.push(`voice.lines[${i}].text trống`);
  });
  if (errs.length) throw new Error('audio.json sai: ' + errs.join('; '));
  return spec;
}

async function ff(args, what, durS = 60) {
  // ffmpeg đôi khi treo ở graph sidechain → giới hạn 3 phút, thử lại 1 lần
  let r;
  // treo hiếm gặp (~1/12 lần, ffmpeg 9 trên Windows): chờ ngắn theo độ dài video rồi thử lại, tối đa 3 lượt
  const timeoutMs = Math.round(30000 + durS * 1500);
  for (let i = 0; i < 3; i++) {
    r = await run('ffmpeg', ['-y', '-hide_banner', '-nostats', '-nostdin', '-filter_complex_threads', '1', ...args], { stdio: ['ignore', 'pipe', 'pipe'], timeoutMs });
    if (r.code === 0) break;
  }
  if (r.code !== 0) throw new Error(`${what} lỗi: ${r.out.slice(-800)}`);
  return r.out;
}
function parseLoudnorm(out) {
  const m = out.match(/\{[^{}]*"input_i"[^{}]*\}/);
  if (!m) throw new Error('không đọc được kết quả loudnorm');
  return JSON.parse(m[0]);
}
/** Đo loudness tích hợp (LUFS) + true peak (dBTP) của 1 file. */
export async function measureLoudness(file) {
  const r = await run('ffmpeg', ['-hide_banner', '-nostats', '-i', file, '-map', '0:a:0', '-af', `loudnorm=I=${TARGET_LUFS}:TP=-1.5:LRA=11:print_format=json`, '-f', 'null', '-']);
  const j = parseLoudnorm(r.out);
  return { lufs: Number(j.input_i), truePeak: Number(j.input_tp), lra: Number(j.input_lra) };
}

/**
 * Dựng file trộn WAV dài đúng `duration` giây. workDir: nơi chứa sfx/nhạc/giọng sinh ra (cache).
 * Trả { wav, warnings, voice: [{t,text,dur}] }.
 */
export async function buildMix(sceneDir, { duration, workDir, log = console.log, seedKey, spec: given } = {}) {
  const spec = given ? validateAudioSpec(given) : loadAudioSpec(sceneDir);
  if (!spec) throw new Error('Không có scene/audio.json');
  fs.mkdirSync(workDir, { recursive: true });
  const warnings = [];
  const warn = (w) => { warnings.push(w); log('CẢNH BÁO âm thanh: ' + w); };
  const inputs = [], chains = [], mixLabels = [];
  const addInput = (file) => { inputs.push('-i', file); return inputs.length / 2 - 1; };
  const fmt = 'aformat=sample_fmts=fltp:sample_rates=48000:channel_layouts=stereo';

  // giọng đọc
  const lines = (spec.voice?.lines || []).slice().sort((a, b) => a.t - b.t);
  let voice = [];
  if (lines.length) {
    // thiếu speaker → giọng mặc định theo ngôn ngữ của lời (có dấu tiếng Việt → Hải Đăng, không thì af_heart);
    // thiếu engine → suy từ tên giọng (af_heart → kokoro, edge:… → edge, còn lại vieneu; máy thiếu thì edge-tts)
    const speaker = spec.voice.speaker || defaultVoiceFor(detectLang(lines.map((l) => l.text).join(' ')));
    const ve = spec.voice.engine ? { engine: spec.voice.engine, speaker } : voiceEngine(speaker);
    voice = await synthVoice(lines, workDir, { engine: ve.engine, voice: ve.speaker, log });
    voice.forEach((v, i) => {
      const end = v.t + v.dur, next = i + 1 < voice.length ? voice[i + 1].t : duration;
      if (end > next + 0.05) warn(`lời "${v.text}" dài ${v.dur.toFixed(2)}s, từ ${v.t}s tới ${end.toFixed(2)}s, lấn sang ${i + 1 < voice.length ? `câu sau (${next}s)` : `hết video (${duration.toFixed(2)}s)`}. Rút gọn câu hoặc dời mốc.`);
    });
  }
  const vGain = spec.voice?.gain ?? 0;
  const vLabels = voice.map((v, i) => {
    const k = addInput(v.file);
    chains.push(`[${k}:a]${fmt},adelay=${Math.round(v.t * 1000)}:all=1,volume=${vGain}dB[v${i}]`);
    return `[v${i}]`;
  });

  // nhạc
  if (spec.music) {
    const seed = spec.music.seed ?? (hashStr(seedKey || sceneDir) % 997) + 1;
    const mf = path.join(workDir, `music-${spec.music.style}-${seed}-${duration.toFixed(3)}.wav`);
    if (!fs.existsSync(mf)) writeMusic(spec.music.style, mf, duration, seed);
    const k = addInput(mf);
    const g = spec.music.gain ?? (vLabels.length ? -12 : -6);
    chains.push(`[${k}:a]${fmt},volume=${g}dB,apad,atrim=0:${duration.toFixed(4)}[mus]`);
    if (vLabels.length) {
      chains.push(`${vLabels.join('')}amix=inputs=${vLabels.length}:normalize=0:duration=longest,apad,atrim=0:${duration.toFixed(4)},asplit=2[vbus][vkey]`); // cùng độ dài với nhạc: tránh sidechain chờ nhau mà treo
      chains.push(`[mus][vkey]sidechaincompress=threshold=0.05:ratio=3:attack=25:release=450:makeup=1[musd]`);
      mixLabels.push('[musd]', '[vbus]');
    } else mixLabels.push('[mus]');
  } else mixLabels.push(...vLabels);

  // tiếng động
  (spec.sfx || []).forEach((s, i) => {
    if (s.t >= duration) { warn(`sfx "${s.name}" ở ${s.t}s nằm ngoài video (${duration.toFixed(2)}s), bỏ qua`); return; }
    const seed = s.seed ?? i + 1;
    const f = path.join(workDir, `sfx-${s.name}-${seed}.wav`);
    if (!fs.existsSync(f)) writeSfx(s.name, f, seed);
    const k = addInput(f);
    chains.push(`[${k}:a]${fmt},adelay=${Math.round(s.t * 1000)}:all=1,volume=${s.gain ?? -6}dB[s${i}]`);
    mixLabels.push(`[s${i}]`);
  });
  if (!mixLabels.length) throw new Error('audio.json không có nhạc, sfx hay lời nào');

  // tiền trộn (float, chưa chuẩn hoá) dài đúng duration
  const pre = path.join(workDir, 'premix.wav');
  const graph = [...chains, `${mixLabels.join('')}amix=inputs=${mixLabels.length}:normalize=0:duration=longest,apad,atrim=0:${duration.toFixed(4)}[out]`].join(';');
  await ff([...inputs, '-filter_complex', graph, '-map', '[out]', '-t', duration.toFixed(4), '-ar', '48000', '-c:a', 'pcm_f32le', pre], 'trộn âm thanh', duration);

  // loudnorm 2 lượt → −14 LUFS
  const m = parseLoudnorm(await ff(['-i', pre, '-af', `loudnorm=I=${TARGET_LUFS}:TP=-1.5:LRA=11:print_format=json`, '-f', 'null', '-'], 'đo loudness', duration));
  const wav = path.join(workDir, 'mix.wav');
  await ff(['-i', pre, '-af', `loudnorm=I=${TARGET_LUFS}:TP=-1.5:LRA=11:measured_I=${m.input_i}:measured_TP=${m.input_tp}:measured_LRA=${m.input_lra}:measured_thresh=${m.input_thresh}:offset=${m.target_offset}:linear=true,atrim=0:${duration.toFixed(4)}`,
    '-ar', '48000', '-ac', '2', '-c:a', 'pcm_s16le', wav], 'chuẩn hoá loudness', duration);
  return { wav, warnings, voice: voice.map(({ t, text, spoken, dur }) => ({ t, text, spoken, dur })) };
}

/** Ghép WAV vào MP4: giữ hình (-c:v copy), AAC 192k stereo 48 kHz, cắt đúng độ dài hình. */
export async function muxAudio(videoIn, wav, outFile, duration) {
  const tmp = outFile.replace(/\.mp4$/i, '.mux.tmp.mp4');
  await ff(['-i', videoIn, '-i', wav, '-map', '0:v:0', '-map', '1:a:0', '-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-ar', '48000', '-ac', '2',
    '-t', duration.toFixed(4), '-movflags', '+faststart', tmp], 'ghép âm thanh vào MP4', duration);
  fs.renameSync(tmp, outFile);
  return outFile;
}

export async function videoDuration(file) {
  const info = await probe(file);
  const v = info?.streams?.find((s) => s.codec_name === 'h264') || info?.streams?.[0];
  const [fa, fb] = String(v?.r_frame_rate || '0/1').split('/').map(Number);
  const fps = fa / (fb || 1);
  const d = Number(v?.nb_frames) > 0 && fps > 0 ? Number(v.nb_frames) / fps : Number(info?.format?.duration);
  if (!(d > 0)) throw new Error('không đọc được độ dài video: ' + file);
  return d;
}

/**
 * Trộn theo sceneDir/audio.json (hoặc `spec` truyền vào) và ghép vào `silentMp4` → `outMp4`. workDir mặc định = <thư mục out>/audio.
 * Trả { ok, file, lufs, truePeak, warnings, voice }.
 */
export async function addAudio(sceneDir, silentMp4, outMp4, { workDir, log = console.log, seedKey, spec } = {}) {
  const duration = await videoDuration(silentMp4);
  workDir = workDir || path.join(path.dirname(outMp4), 'audio');
  const mix = await buildMix(sceneDir, { duration, workDir, log, spec, seedKey: seedKey || path.basename(path.dirname(path.resolve(sceneDir))) });
  await muxAudio(silentMp4, mix.wav, outMp4, duration);
  const L = await measureLoudness(outMp4);
  log(`âm thanh: ${L.lufs.toFixed(1)} LUFS, đỉnh ${L.truePeak.toFixed(1)} dBTP, ${duration.toFixed(2)}s${mix.voice.length ? `, ${mix.voice.length} lời` : ''}`);
  return { ok: true, file: outMp4, ...L, warnings: mix.warnings, voice: mix.voice };
}