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.
// Đổi tiếng cho video ĐÃ DỰNG: trộn tiếng mới theo tuỳ chọn {music, voice, sfx} và ghép vào hình cũ (không dựng lại hình).
// Dùng chung cho CLI (`node cli.mjs audio`), REST (POST /api/jobs/:id/audio) và MCP (set_audio).
// out.mp4 luôn là bản mới nhất; bản trước chuyển sang versions/out-<n>.mp4 + versions/audio-<n>.json.
// out.silent.mp4 = hình gốc không tiếng (giữ nguyên).
// Chưa có lời đọc mà chọn giọng → AI viết 1–3 câu ngắn từ brief.json/nội dung (api → claude headless, như "Viết lại kịch bản").
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import Anthropic from '@anthropic-ai/sdk';
import { readJob, jobDir, guidancePath, logTo, exportOutput } from './jobs.mjs';
import { resolveRewriteEngine } from './rewrite.mjs';
import { probe } from '../engine/lib.mjs';
import { addAudio, loadAudioSpec, videoDuration } from '../engine/audio/mix.mjs';
import { normalizeAudioPrefs, applyAudioPrefs, styleFromGuidance, voiceEngine, detectLang } from '../engine/audio/prefs.mjs';
const AI_TIMEOUT_MS = 90_000;
const busy = new Set();
function saveJob(id, patch) {
const f = path.join(jobDir(id), 'job.json');
const cur = JSON.parse(fs.readFileSync(f, 'utf8'));
Object.assign(cur, patch, { updatedAt: new Date().toISOString() });
fs.writeFileSync(f, JSON.stringify(cur, null, 2));
return cur;
}
const hasAudioStream = async (f) => !!(await probe(f))?.streams?.some((s) => !s.width);
/** Danh sách bản: [{n, file, audio, createdAt, current?}] — bản hiện tại (out.mp4) đứng đầu. */
export function listVersions(id) {
const dir = jobDir(id), vd = path.join(dir, 'versions'), job = readJob(id) || {};
const meta = job.audioVersions || [];
const out = [];
if (fs.existsSync(path.join(dir, 'out.mp4'))) out.push({ n: meta.length ? Math.max(...meta.map((m) => m.n)) + 1 : 1, file: 'out.mp4', current: true, audio: job.audio || null, createdAt: job.audioAt || job.updatedAt });
for (const m of [...meta].sort((a, b) => b.n - a.n)) if (fs.existsSync(path.join(vd, `out-${m.n}.mp4`))) out.push({ ...m, file: `versions/out-${m.n}.mp4` });
return out;
}
/** Hỏi AI viết lời đọc ngắn khớp mốc. lang 'vi' | 'en' (mặc định: đoán từ nội dung). Trả [{t, text}]. */
export async function writeNarration(job, spec, duration, { log = () => {}, lang = detectLang(job.content) } = {}) {
const en = lang === 'en';
const dir = jobDir(job.id);
const brief = fs.existsSync(path.join(dir, 'brief.json')) ? fs.readFileSync(path.join(dir, 'brief.json'), 'utf8').slice(0, 6000) : '';
const g = fs.existsSync(guidancePath(job.templateId)) ? fs.readFileSync(guidancePath(job.templateId), 'utf8') : '';
const s9 = (g.match(/##\s*9\.[^\n]*\n([\s\S]*?)(\n##\s|$)/) || [])[1] || '';
const marks = (spec?.sfx || []).map((s) => `${s.t}s ${s.name}`).join(', ');
const prompt = `Viết LỜI ĐỌC ${en ? 'TIẾNG ANH (English)' : 'tiếng Việt'} cho 1 video dọc ${duration.toFixed(1)} giây đã dựng xong (không đổi hình).
Trả ĐÚNG 1 khối JSON, không thêm gì: {"lines":[{"t":<giây bắt đầu>,"text":"<câu>"}]}
Luật:
- 1 đến ${duration > 12 ? 5 : 3} câu, mỗi câu ngắn. Tốc độ đọc ${en ? '~2,7 từ tiếng Anh/giây' : '~4,5 âm tiết/giây'}: câu phải đọc xong trước "t" câu sau và trước giây ${(duration - 0.3).toFixed(1)}.
- Câu đầu bắt đầu trong 0,1–0,6s. Đặt "t" trùng mốc chuyển động chính (mốc tiếng động: ${marks || 'không có'}).
- Chỉ dùng ý, số, tên thương hiệu có trong nội dung/brief; không bịa số. ${en ? 'Viết bằng tiếng Anh tự nhiên kiểu người bản xứ (nội dung gốc tiếng Việt thì dịch ý), viết số bằng chữ số bình thường ($5, 12%, 2024).' : 'Tiếng Việt đủ dấu, viết số bằng chữ số bình thường.'}
- Có tên thương hiệu/CTA thì câu cuối nói tên đó.
${s9 ? `- Gợi ý giọng/lời của mẫu: ${s9.trim().slice(0, 600)}` : ''}
Nội dung người dùng:
"""
${String(job.content || '').slice(0, 3000)}
"""
${brief ? `\nbrief.json (ô nội dung trên màn hình):\n${brief}` : ''}`;
const engine = resolveRewriteEngine();
if (!engine) throw new Error('Chưa có lời đọc và chưa cấu hình AI để viết lời (ANTHROPIC_API_KEY hoặc Claude Code). Thêm "voice.lines" vào scene/audio.json bằng tay.');
log(`lời đọc: nhờ AI (${engine}) viết…`);
let text;
try { text = engine === 'api' ? await viaApi(prompt) : await viaClaude(prompt); }
catch (e) {
// khoá API sai (401/403) mà máy có Claude Code → thử claude, như "Viết lại kịch bản"
const { findClaude } = await import('./claude.mjs');
if (engine === 'api' && (e.status === 401 || e.status === 403) && findClaude()) { log(`lời đọc: API lỗi ${e.status}, chuyển Claude Code`); text = await viaClaude(prompt); }
else throw new Error('AI viết lời đọc lỗi: ' + String(e.message).slice(0, 200));
}
const m = text.match(/\{[\s\S]*\}/);
let lines;
try { lines = JSON.parse(m?.[0] || '').lines; } catch { throw new Error('AI trả lời đọc sai dạng JSON, bấm lại thử'); }
lines = (Array.isArray(lines) ? lines : []).filter((l) => typeof l?.t === 'number' && String(l.text || '').trim())
.map((l) => ({ t: Math.max(0, Math.min(duration - 0.5, +l.t.toFixed(2))), text: String(l.text).trim().slice(0, 200) }));
if (!lines.length) throw new Error('AI không trả câu lời đọc nào');
return lines;
}
async function viaApi(prompt) {
const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY, maxRetries: 1, timeout: AI_TIMEOUT_MS });
const msg = await client.messages.create({ model: process.env.REWRITE_MODEL || 'claude-haiku-5-5', max_tokens: 1000, messages: [{ role: 'user', content: prompt }] });
return (msg.content || []).filter((b) => b.type === 'text').map((b) => b.text).join('\n');
}
async function viaClaude(prompt) {
const { spawnClaude } = await import('./claude.mjs');
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'lumreels-voice-'));
const args = ['-p', '--output-format', 'json', '--permission-mode', 'default', '--tools', '', '--setting-sources', 'project', '--strict-mcp-config', '--no-session-persistence', '--max-turns', '2'];
return new Promise((resolve, reject) => {
const p = spawnClaude(args, { cwd, windowsHide: true, env: (({ ANTHROPIC_API_KEY, ...e }) => e)(process.env) });
let out = '';
const timer = setTimeout(() => { p.kill(); reject(new Error('Claude Code quá giờ khi viết lời đọc')); }, AI_TIMEOUT_MS);
p.stdout.on('data', (d) => { out += d; });
p.on('error', (e) => { clearTimeout(timer); reject(e); });
p.on('close', (code) => {
clearTimeout(timer); fs.rm(cwd, { recursive: true, force: true }, () => {});
try { const r = JSON.parse(out.trim().split(/\r?\n/).pop()); if (code === 0 && !r.is_error) return resolve(String(r.result || '')); } catch { /* rơi xuống lỗi */ }
reject(new Error(`claude thoát mã ${code} khi viết lời đọc`));
});
p.stdin.end(prompt);
});
}
/**
* Trộn tiếng mới cho job đã dựng. prefs = {music, voice, sfx} (thiếu → giữ như job/audio.json hiện có).
* Trả { ok, file, version, lufs, truePeak, warnings, voice, spec }.
*/
export async function reAudio(id, prefs, { log, exportOut = false } = {}) {
const job = readJob(id);
if (!job) throw new Error('Không thấy job ' + id);
if (busy.has(id)) throw new Error('Job này đang trộn tiếng, chờ xong đã');
busy.add(id);
const L = log || logTo(job);
saveJob(id, { audioStatus: 'mixing', audioError: null });
try {
const dir = jobDir(id), scene = path.join(dir, 'scene'), mp4 = path.join(dir, 'out.mp4'), silent = path.join(dir, 'out.silent.mp4');
if (!fs.existsSync(mp4) && !fs.existsSync(silent)) throw new Error('Job chưa dựng hình (chưa có out.mp4)');
// out.mp4 chưa có tiếng = bản hình mới nhất → làm out.silent.mp4
const mp4HasAudio = fs.existsSync(mp4) && await hasAudioStream(mp4);
if (fs.existsSync(mp4) && (!mp4HasAudio || !fs.existsSync(silent))) fs.copyFileSync(mp4, silent);
const base = typeof job.audio === 'object' && job.audio ? job.audio : {};
const p = normalizeAudioPrefs({ ...base, ...Object.fromEntries(Object.entries(prefs || {}).filter(([, v]) => v !== undefined)) });
const fallbackStyle = styleFromGuidance(fs.existsSync(guidancePath(job.templateId)) ? fs.readFileSync(guidancePath(job.templateId), 'utf8') : '');
const cur = loadAudioSpec(scene);
let spec = applyAudioPrefs(cur, { ...p, fallbackStyle });
const duration = await videoDuration(silent);
const ve = p.voice !== 'none' && p.voice !== 'auto' ? voiceEngine(p.voice) : null;
// giọng khác ngôn ngữ với lời đang có (vd lời Việt mà chọn giọng Anh) → bỏ lời cũ, AI viết lại đúng ngôn ngữ giọng
if (ve && spec?.voice?.lines?.length && detectLang(spec.voice.lines.map((l) => l.text).join(' ')) !== ve.lang) {
L(`lời đọc đang có khác ngôn ngữ giọng "${p.voice}" (${ve.lang}), nhờ AI viết lại`);
spec = { ...spec, voice: null };
}
if (ve && !spec?.voice?.lines?.length) {
const lines = await writeNarration(job, spec || cur, duration, { log: L, lang: ve.lang });
spec = { ...(spec || { music: null, sfx: [] }), voice: { speaker: ve.speaker, engine: ve.engine, lines } };
L(`lời đọc AI viết: ${lines.map((l) => `${l.t}s "${l.text}"`).join(' | ')}`);
}
if (!spec) throw new Error('Không có gì để trộn (nhạc "none", tắt tiếng động, không lời đọc)');
// lưu bản cũ (nếu out.mp4 đang có tiếng)
const versions = [...(job.audioVersions || [])];
if (mp4HasAudio) {
const vd = path.join(dir, 'versions'); fs.mkdirSync(vd, { recursive: true });
const n = versions.length ? Math.max(...versions.map((v) => v.n)) + 1 : 1;
fs.copyFileSync(mp4, path.join(vd, `out-${n}.mp4`));
if (cur) fs.writeFileSync(path.join(vd, `audio-${n}.json`), JSON.stringify(cur, null, 2));
versions.push({ n, audio: job.audio || null, createdAt: job.audioAt || job.updatedAt });
L(`giữ bản cũ: versions/out-${n}.mp4`);
}
fs.writeFileSync(path.join(scene, 'audio.json'), JSON.stringify(spec, null, 2));
const res = await addAudio(scene, silent, mp4, { log: L, seedKey: id });
saveJob(id, { audio: p, audioVersions: versions, audioAt: new Date().toISOString(), audioStatus: 'done' });
if (exportOut) exportOutput(readJob(id), L);
return { ...res, version: versions.length + 1, spec };
} catch (e) {
saveJob(id, { audioStatus: 'error', audioError: e.message });
L('trộn tiếng lỗi: ' + e.message);
throw e;
} finally {
busy.delete(id);
}
}
export const audioBusy = (id) => busy.has(id);
/** Agent nộp scene/audio.json (MCP submit_scene / REST). Kiểm luật trước khi ghi; sai → ném lỗi, giữ bản cũ. */
export async function saveAudioSpec(id, spec) {
const { validateAudioSpec } = await import('../engine/audio/mix.mjs');
const obj = typeof spec === 'string' ? JSON.parse(spec) : spec;
validateAudioSpec(obj);
const f = path.join(jobDir(id), 'scene', 'audio.json');
fs.mkdirSync(path.dirname(f), { recursive: true });
fs.writeFileSync(f, JSON.stringify(obj, null, 2));
return f;
}