Files
flypic/backend/src/routes/video.js
T

684 lines
30 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 视频处理路由
* - POST /api/video/edit 单视频编辑:watermark-add / watermark-remove / subtitle-audio / strip
* - POST /api/video/aigenerate 多图 + 标题 + 模型KEY → AI 生成带字幕朗读的视频(异步任务)
* - GET /api/video/task/:id 查询 AI 生成进度
* - GET /api/video/probe ffprobe 宽高/时长(前端预览用)
*
* 输出约定与批量水印一致:output='new' 后缀另存(_wm/_nowm/_sub/_out),'overwrite' 原地覆盖(原子写)。
*/
const express = require('express');
const router = express.Router();
const path = require('path');
const fs = require('fs');
const os = require('os');
const { asyncHandler, ValidationError, NotFoundError } = require('../middleware/errorHandler');
const { processImage } = require('../../utils/scanner');
const { getSettings, resolveVideoGen } = require('../../utils/settings');
const logger = require('../utils/logger');
const videotool = require('../../utils/videotool');
const multer = require('multer');
const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 20 * 1024 * 1024 } });
const VIDEO_EXTS = new Set(['.mp4', '.mov', '.m4v', '.webm', '.mkv', '.avi', '.flv', '.wmv', '.mpg', '.mpeg', '.3gp', '.ts']);
// ---------- 通用:定位文件 ----------
function resolveFile(req, libraryId, relPath) {
const configManager = req.app.get('configManager');
const dbPool = req.app.get('dbPool');
if (!configManager || !dbPool) throw new ValidationError('服务未初始化');
const config = configManager.load();
const library = config.libraries.find((l) => String(l.id) === String(libraryId));
if (!library) throw new NotFoundError('Library', libraryId);
const abs = path.join(library.path, relPath);
if (!abs.startsWith(path.resolve(library.path))) throw new ValidationError('非法路径');
if (!fs.existsSync(abs)) throw new NotFoundError('File', relPath);
const ext = path.extname(abs).toLowerCase();
if (!VIDEO_EXTS.has(ext)) throw new ValidationError(`不是视频文件: ${relPath}`);
return { library, abs };
}
async function reindex(req, libraryPath, absPath) {
const dbPool = req.app.get('dbPool');
const db = dbPool.acquire(libraryPath);
try {
await processImage(absPath, libraryPath, db);
} finally {
dbPool.release(libraryPath);
}
}
/** 输出路径:new=后缀另存,overwrite=同名临时文件原子替换 */
function outputPath(abs, mode, suffix) {
if (mode !== 'new') return { target: abs, atomic: true };
const ext = path.extname(abs);
const base = abs.slice(0, abs.length - ext.length);
let target = `${base}${suffix}${ext}`;
let n = 1;
while (fs.existsSync(target)) {
target = `${base}${suffix}${n}${ext}`;
n++;
}
return { target, atomic: false };
}
// ---------- 单视频编辑 ----------
router.post(
'/edit',
asyncHandler(async (req, res) => {
const { libraryId, path: relPath, action, options = {}, output = 'new' } = req.body || {};
if (!libraryId || !relPath) throw new ValidationError('缺少 libraryId / path');
const { library, abs } = resolveFile(req, libraryId, relPath);
const SUFFIX = {
'watermark-add': '_wm',
'watermark-remove': '_nowm',
'subtitle-audio': '_sub',
'strip': '_out'
};
const { target, atomic } = outputPath(abs, output, SUFFIX[action] || '_edit');
let meta;
switch (action) {
case 'watermark-add':
meta = await videotool.addWatermark(abs, target, options);
break;
case 'watermark-remove':
if (!options.region) throw new ValidationError('缺少去水印区域');
meta = await videotool.removeWatermark(abs, target, options.region);
break;
case 'subtitle-audio':
meta = await videotool.addSubtitleAudio(abs, target, options);
break;
case 'strip':
meta = await videotool.stripSubtitleAudio(abs, target, options);
break;
default:
throw new ValidationError(`未知视频操作: ${action}`);
}
await reindex(req, library.path, target);
logger.info(`🎬 视频${{ 'watermark-add': '加水印', 'watermark-remove': '去水印', 'subtitle-audio': '加字幕声音', strip: '去字幕声音' }[action]} 完成: ${path.basename(target)}`);
res.json({ success: true, path: path.relative(library.path, target), duration: meta && meta.duration });
})
);
// ---------- ffprobe 预览信息 ----------
router.get(
'/probe',
asyncHandler(async (req, res) => {
const { libraryId, path: relPath } = req.query;
if (!libraryId || !relPath) throw new ValidationError('缺少 libraryId / path');
const { abs } = resolveFile(req, libraryId, relPath);
const info = await videotool.probeVideo(abs);
res.json(info);
})
);
// ---------- AI 生成视频(异步任务) ----------
const aiTasks = new Map();
let aiTaskSeq = 0;
router.post(
'/aigenerate',
asyncHandler(async (req, res) => {
const {
libraryId,
images, // [{ path }] 库内相对路径(同一文件夹顺序展示)
title, // 标题
apiKey, // 模型 KEY(留空用服务器设置)
baseUrl, // OpenAI 兼容接口(留空用服务器设置)
model, // 模型名
voice = 'zh-CN-XiaoxiaoNeural',
resolution = '1920x1080',
extraPrompt = '',
saveDir = '',
duration = 0,
subtitleStyle = {}
} = req.body || {};
if (!libraryId || !Array.isArray(images) || images.length < 2) {
throw new ValidationError('请至少选择 2 张图片');
}
if (!title || !String(title).trim()) throw new ValidationError('请填写视频标题');
// 图片扩展名校验(buildSegment 用 image2 demuxer,视频文件会报 Option loop not found)
const IMG_EXTS = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif', '.bmp', '.avif']);
for (const it of images) {
const p = it && it.path ? String(it.path) : '';
if (!p || !IMG_EXTS.has(path.extname(p).toLowerCase())) {
throw new ValidationError(`仅支持图片文件,收到: ${p || '(空)'}`);
}
}
const configManager = req.app.get('configManager');
const config = configManager.load();
const library = config.libraries.find((l) => String(l.id) === String(libraryId));
if (!library) throw new NotFoundError('Library', libraryId);
const settings = getSettings();
// 设置 - AI 视频(或复用 AI 生图)中的文本模型配置;请求参数可临时覆盖
const gen = resolveVideoGen(settings);
const url = (baseUrl || gen.url || '').replace(/\/+$/, '');
const key = apiKey || gen.apiKey || process.env.NEWAPI_KEY || '';
const mdl = model || gen.model || 'mimo-v2.6-flash';
if (!url) throw new ValidationError('未配置模型接口地址(请到右上角设置 → AI 视频里填写)');
if (!key) throw new ValidationError('请先在右上角设置 → AI 视频里填写模型 KEY');
const id = `vt${++aiTaskSeq}_${Date.now()}`;
const [w, h] = String(resolution).split('x').map((n) => parseInt(n, 10));
const task = {
id,
status: 'running',
step: 'script',
stepLabel: '正在生成脚本',
progress: 0,
error: '',
resultPath: '',
createdAt: Date.now()
};
aiTasks.set(id, task);
// 任务完成后 30 分钟清理
setTimeout(() => aiTasks.delete(id), 30 * 60 * 1000);
// 后台执行,不阻塞响应
runAiVideo({
task, library, images, title: String(title).trim(), url, key, model: mdl,
voice, width: Number.isFinite(w) ? w : 1920, height: Number.isFinite(h) ? h : 1080,
extraPrompt: String(extraPrompt || ''), duration: Math.min(600, Math.max(0, Number(duration) || 0)), subtitleStyle: subtitleStyle || {},
req
}).catch((err) => {
task.status = 'error';
task.error = err.message || String(err);
logger.warn(`⚠️ AI 生成视频失败: ${task.error}`);
});
res.json({ success: true, taskId: id });
})
);
router.get(
'/task/:id',
asyncHandler(async (req, res) => {
const task = aiTasks.get(req.params.id) || textTasks.get(req.params.id);
if (!task) throw new NotFoundError('Task', req.params.id);
res.json(task);
})
);
/** LLM 生成分镜脚本:返回 [{ subtitle, tts }] 数组,长度=图片数 */
async function llmScript({ url, key, model, title, count, extraPrompt }) {
const sys = '你是短视频编导。根据给定标题与图片数量,输出每个画面的旁白与字幕。要求口语化、有画面感、避免空话。';
const user = [
`标题:${title}`,
`共 ${count} 张图片(将按顺序做成视频分镜)。`,
extraPrompt ? `补充要求:${extraPrompt}` : '',
`严格只输出 JSON 数组(不要代码块标记),长度恰好 ${count},每项格式:{"subtitle":"画面字幕(15字内)","tts":"朗读文案(30字内,可与字幕不同)"}`
].filter(Boolean).join('\n');
const resp = await fetch(`${url}/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },
body: JSON.stringify({
model,
messages: [
{ role: 'system', content: sys },
{ role: 'user', content: user }
],
temperature: 0.7,
max_tokens: 4000
}),
signal: AbortSignal.timeout(90 * 1000)
});
if (!resp.ok) {
let msg = `模型接口错误 (${resp.status})`;
try { const j = await resp.json(); msg = (j.error && j.error.message) || j.message || msg; } catch (_) { /* 非 JSON */ }
throw new Error(msg);
}
const data = await resp.json();
let content = data.choices && data.choices[0] && data.choices[0].message && data.choices[0].message.content;
if (!content) throw new Error('模型未返回内容');
content = String(content).replace(/^```(?:json)?\s*/i, '').replace(/```\s*$/, '').trim();
let arr;
try {
arr = JSON.parse(content);
} catch (_) {
const m = content.match(/\[[\s\S]*\]/);
if (!m) throw new Error('脚本 JSON 解析失败');
arr = JSON.parse(m[0]);
}
if (!Array.isArray(arr) || !arr.length) throw new Error('脚本为空');
return arr.map((it) => ({
subtitle: String((it && it.subtitle) || (it && it.text) || '').slice(0, 40),
tts: String((it && it.tts) || (it && it.subtitle) || '').slice(0, 120)
}));
}
async function runAiVideo(ctx) {
const { task, library, images, title, url, key, model, voice, width, height, extraPrompt, subtitleStyle, req } = ctx;
// 1) 校验图片文件
const files = [];
for (const item of images) {
const rel = typeof item === 'string' ? item : item.path;
const abs = path.join(library.path, rel);
if (!fs.existsSync(abs)) throw new ValidationError(`图片不存在: ${rel}`);
files.push(abs);
}
// 2) LLM 脚本
task.step = 'script';
task.stepLabel = '正在生成分镜脚本';
task.progress = 5;
const script = await llmScript({ url, key, model, title, count: files.length, extraPrompt });
logger.info(`🎬 AI 视频脚本生成完成(${script.length} 段)`);
// 3) 逐段 TTS
const work = fs.mkdtempSync(path.join(os.tmpdir(), 'flypic-aiv-'));
try {
const segments = [];
for (let i = 0; i < files.length; i++) {
if (task.cancelled) throw new Error('已取消');
task.step = 'tts';
task.stepLabel = `正在朗读配音 ${i + 1}/${files.length}`;
task.progress = 10 + Math.round((i / files.length) * 40);
const seg = script[i];
let ttsFile = '';
let dur = 0;
if (seg.tts) {
try {
const t = await videotool.generateTts(seg.tts, {
voice,
outPath: path.join(work, `tts${i}.mp3`)
});
ttsFile = t.file;
dur = t.seconds;
} catch (err) {
logger.warn(`⚠️ TTS 第${i + 1}段失败(降级为静音): ${err.message}`);
}
}
segments.push({
imagePath: files[i],
subtitle: seg.subtitle || seg.tts || title,
ttsFile,
ttsSeconds: dur,
duration: Math.max(2.5, Math.min(12, dur || 4))
});
}
// 目标时长:按各段自然时长比例分配(该路径无转场重叠)
const targetDur = Number(ctx.duration) > 0 ? Number(ctx.duration) : 0;
if (targetDur > 0 && segments.length) {
const avail = Math.max(segments.length * 1.0, targetDur);
const natural = segments.reduce((s, x) => s + x.duration, 0) || 1;
for (const s of segments) {
const d = Math.max(1.0, (s.duration / natural) * avail);
s.duration = d;
s.audioDuration = d;
}
logger.info(`⏱ AI 视频目标时长 ${targetDur}s → 分配 ${segments.length} 段`);
}
// 4) 逐段合成
const segFiles = [];
for (let i = 0; i < segments.length; i++) {
if (task.cancelled) throw new Error('已取消');
task.step = 'compose';
task.stepLabel = `正在合成画面 ${i + 1}/${segments.length}`;
task.progress = 50 + Math.round((i / segments.length) * 45);
const out = path.join(work, `seg${i}.mp4`);
await videotool.buildSegment(segments[i], out, { width, height, subtitleStyle: ctx.subtitleStyle });
segFiles.push(out);
}
// 5) 拼接
task.step = 'merge';
task.stepLabel = '正在合并视频';
task.progress = 96;
const finalTmp = path.join(work, 'final.mp4');
await videotool.concatSegments(segFiles, finalTmp);
// 6) 落库:与第一张图同文件夹,文件名=标题
const firstRel = typeof images[0] === 'string' ? images[0] : images[0].path;
const dirRel = path.dirname(firstRel) === '.' ? '' : path.dirname(firstRel);
const safeTitle = String(title).replace(/[\\/:*?"<>|]/g, '_').slice(0, 60) || 'AI视频';
let target = path.join(library.path, dirRel, `${safeTitle}.mp4`);
let n = 1;
while (fs.existsSync(target)) {
target = path.join(library.path, dirRel, `${safeTitle}_${n}.mp4`);
n++;
}
fs.copyFileSync(finalTmp, target);
await reindex(req, library.path, target);
task.status = 'done';
task.progress = 100;
task.step = 'done';
task.stepLabel = '完成';
task.resultPath = path.relative(library.path, target);
logger.info(`🎬 AI 视频生成完成: ${task.resultPath}`);
} finally {
fs.rmSync(work, { recursive: true, force: true });
}
}
// ---------- URL 抓取:内容 + 图片 ----------
router.post(
'/extract-url',
asyncHandler(async (req, res) => {
const { url } = req.body || {};
if (!url) throw new ValidationError('缺少 url');
let html = '';
try {
const r = await fetch(url, { headers: { 'User-Agent': 'Mozilla/5.0' }, signal: AbortSignal.timeout(20000) });
html = await r.text();
} catch (e) { throw new ValidationError('抓取失败: ' + (e.message || e)); }
const titleMatch = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
const title = titleMatch ? titleMatch[1].replace(/\s+/g, ' ').trim().slice(0, 80) : '';
// images
const imgs = [];
const imgRe = /<img[^>]+src=["']([^"']+)["']/gi;
let m;
while ((m = imgRe.exec(html)) && imgs.length < 8) {
let src = m[1];
if (src.startsWith('//')) src = 'https:' + src;
else if (src.startsWith('/')) { try { src = new URL(src, url).href; } catch (_) {} }
else if (!/^https?:/i.test(src)) { try { src = new URL(src, url).href; } catch (_) {} }
if (/^https?:/i.test(src) && !imgs.includes(src)) imgs.push(src);
}
// text: strip tags
const text = html
.replace(/<script[\s\S]*?<\/script>/gi, '')
.replace(/<style[\s\S]*?<\/style>/gi, '')
.replace(/<[^>]+>/g, ' ')
.replace(/\s+/g, ' ')
.trim()
.slice(0, 4000);
res.json({ success: true, title, text, images: imgs });
})
);
// ---------- 文档/PDF 提取 ----------
router.post(
'/extract-doc',
upload.single('file'),
asyncHandler(async (req, res) => {
if (!req.file) throw new ValidationError('缺少文件');
const name = req.file.originalname || 'doc';
let text = '';
const ext = path.extname(name).toLowerCase();
if (ext === '.pdf') {
const tmp = path.join(os.tmpdir(), `doc_${Date.now()}.pdf`);
fs.writeFileSync(tmp, req.file.buffer);
try {
const { stdout } = await videotool.run('pdftotext', ['-layout', tmp, '-'], { timeoutMs: 60000 });
text = stdout;
} catch (e) {
text = req.file.buffer.toString('utf8').replace(/[^\x20-\x7E\u4e00-\u9fa5]/g, ' ');
} finally {
try { fs.unlinkSync(tmp); } catch (_) {}
}
} else {
text = req.file.buffer.toString('utf8');
}
text = String(text).replace(/\s+/g, ' ').trim().slice(0, 6000);
res.json({ success: true, title: name.replace(/\.[^.]+$/, ''), text, images: [] });
})
);
// ---------- 按标题快速生成文案(可编辑,生成视频时严格按此文案分镜) ----------
/** 把整段文案切成逐句分镜:按行优先,长行再按句读符号切 */
function splitCopyToScenes(text) {
const raw = String(text || '').replace(/\r/g, '').split('\n').map((s) => s.trim()).filter(Boolean);
const out = [];
for (let line of raw) {
line = line.replace(/^\d+\s*[.、))]\s*/, ''); // 去掉序号
if (!line) continue;
if (line.length <= 45) { out.push(line); continue; }
const parts = line.split(/(?<=[。!?!?;;])/).map((s) => s.trim()).filter(Boolean);
if (parts.length > 1) out.push(...parts);
else out.push(line);
}
return out.slice(0, 40).map((s) => ({
subtitle: s.slice(0, 40),
tts: s.slice(0, 120)
}));
}
router.post(
'/gen-script',
asyncHandler(async (req, res) => {
const { title, duration = 0, count = 0 } = req.body || {};
const t = String(title || '').trim();
if (!t) throw new ValidationError('请填写视频标题');
const settings = getSettings();
const gen = resolveVideoGen(settings);
const url = String(gen.url || '').replace(/\/+$/, '');
const key = gen.apiKey || process.env.NEWAPI_KEY || '';
const model = gen.model || 'mimo-v2.6-flash';
if (!url) throw new ValidationError('AI 视频未配置:请在右上角「设置 → AI 视频」里填写 Base URL');
if (!key) throw new ValidationError('AI 视频未配置 API Key:请在右上角「设置 → AI 视频」里填写');
const targetSec = Math.min(600, Math.max(0, Number(duration) || 0));
const lineCount = Number(count) > 0
? Math.min(30, Number(count))
: (targetSec ? Math.min(30, Math.max(2, Math.ceil(targetSec / 5))) : 6);
const sys = '你是短视频编导。根据标题写出可直接朗读的短视频旁白文案。要求口语化、有画面感、避免空话。';
const user = [
`标题:${t}`,
`共 ${lineCount} 个画面,每行对应一个画面的旁白。`,
targetSec ? `视频总时长约 ${targetSec} 秒,文案总字数控制在 ${Math.round(targetSec * 3.5)} 字左右。` : '',
'严格只输出文案本身:每行一句,不要编号、不要引号、不要小标题、不要代码块标记;每行不超过 40 个字。'
].filter(Boolean).join('\n');
const resp = await fetch(`${url}/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer' + ' ' + key },
body: JSON.stringify({
model,
messages: [
{ role: 'system', content: sys },
{ role: 'user', content: user }
],
temperature: 0.7,
max_tokens: 2000
}),
signal: AbortSignal.timeout(60 * 1000)
});
if (!resp.ok) {
let msg = `模型接口错误 (${resp.status})`;
try { const j = await resp.json(); msg = (j.error && j.error.message) || j.message || msg; } catch (_) { /* 非 JSON */ }
throw new Error(msg);
}
const data = await resp.json();
const raw = data.choices && data.choices[0] && data.choices[0].message && data.choices[0].message.content;
if (!raw) throw new Error('模型未返回内容');
const script = String(raw)
.replace(/^```[a-z]*\s*/i, '').replace(/```\s*$/, '')
.split('\n').map((s) => s.trim().replace(/^\d+\s*[.、))]\s*/, '')).filter(Boolean)
.slice(0, 40).join('\n');
if (!script) throw new Error('模型未返回文案');
res.json({ success: true, script });
})
);
// ---------- 文本源 AI 生成视频(提示词/URL/文档) ----------
const textTasks = new Map();
let textTaskSeq = 0;
router.post(
'/aigenerate-text',
asyncHandler(async (req, res) => {
const {
libraryId, title, content, images = [],
apiKey, baseUrl, model,
voice = 'zh-CN-XiaoxiaoNeural',
resolution = '1920x1080',
extraPrompt = '',
saveDir = '',
transition = 'fade',
duration = 0,
subtitleStyle = {}
} = req.body || {};
if (!libraryId) throw new ValidationError('缺少 libraryId');
if (!title || !String(title).trim()) throw new ValidationError('请填写视频标题');
const text = String(content || '').trim();
if (!text && (!Array.isArray(images) || images.length === 0)) throw new ValidationError('缺少内容或图片');
const configManager = req.app.get('configManager');
const config = configManager.load();
const library = config.libraries.find((l) => String(l.id) === String(libraryId));
if (!library) throw new NotFoundError('Library', libraryId);
const settings = getSettings();
// 设置 - AI 视频(或复用 AI 生图)中的文本模型配置;请求参数可临时覆盖
const gen = resolveVideoGen(settings);
const url = (baseUrl || gen.url || '').replace(/\/+$/, '');
const key = apiKey || gen.apiKey || process.env.NEWAPI_KEY || '';
const mdl = model || gen.model || 'mimo-v2.6-flash';
if (!url) throw new ValidationError('未配置模型接口地址(请到右上角设置 → AI 视频里填写)');
if (!key) throw new ValidationError('请先在右上角设置 → AI 视频里填写模型 KEY');
// 转场效果白名单(防注入 ffmpeg filter)
const TRANSITIONS = new Set(['cut','fade','fadeblack','fadewhite','slideleft','slideright','slideup','slidedown','circlecrop','circleopen','circleclose','dissolve','smoothleft','smoothright','wipeleft','wiperight','pixelize','radial','hblur']);
const trans = TRANSITIONS.has(String(transition)) ? String(transition) : 'fade';
const id = `vt${++textTaskSeq}_${Date.now()}`;
const [w, h] = String(resolution).split('x').map((n) => parseInt(n, 10));
const task = { id, status: 'running', step: 'script', stepLabel: '正在生成', progress: 0, error: '', resultPath: '', createdAt: Date.now() };
textTasks.set(id, task);
setTimeout(() => textTasks.delete(id), 30 * 60 * 1000);
const durSec = Math.min(600, Math.max(0, Number(duration) || 0)); // 目标时长(秒),0=自动
const userScript = String(req.body.script || '').trim().slice(0, 8000); // 用户已编辑的文案:原样分镜,不改写
runTextVideo({ task, library, title: String(title).trim(), content: text, script: userScript, images, url, key, model: mdl, voice, width: Number.isFinite(w)?w:1920, height: Number.isFinite(h)?h:1080, extraPrompt: String(extraPrompt||''), saveDir: String(saveDir||''), transition: trans, duration: durSec, subtitleStyle: subtitleStyle||{}, req }).catch((err) => {
task.status = 'error'; task.error = err.message || String(err);
});
res.json({ success: true, taskId: id });
})
);
async function runTextVideo(ctx) {
const { task, library, title, content, images, url, key, model, voice, width, height, extraPrompt, saveDir, transition, subtitleStyle, req } = ctx;
const work = fs.mkdtempSync(path.join(os.tmpdir(), 'flypic-tv-'));
try {
// 生成背景图(若无图片)
// 解析全部选中图片(本地库路径 / 远程 URL 下载)—— 让每张选中图片都进视频
const imagePaths = [];
if (Array.isArray(images) && images.length) {
for (const it of images) {
const rel = typeof it === 'string' ? it : (it && (it.path || it.url)) || '';
if (!rel) continue;
if (/^https?:/i.test(rel)) {
try {
const r = await fetch(rel);
const buf = Buffer.from(await r.arrayBuffer());
const ext = (path.extname(new URL(rel).pathname) || '.jpg').toLowerCase();
const fp = path.join(work, `img${imagePaths.length}${ext}`);
fs.writeFileSync(fp, buf);
imagePaths.push(fp);
} catch (e) { logger.warn('图片下载失败: ' + e.message); }
} else {
const abs = path.join(library.path, rel);
if (fs.existsSync(abs)) imagePaths.push(abs);
}
}
}
// 兜底:无图时生成纯色背景
if (!imagePaths.length) {
const bgPath = path.join(work, 'bg.png');
await videotool.run('ffmpeg', ['-y', '-f', 'lavfi', '-i', `color=c=0x1a1a2e:s=${width}x${height}`, '-frames:v', '1', bgPath], { timeoutMs: 60000 });
imagePaths.push(bgPath);
}
// LLM 生成分镜:基于内容切分
task.step = 'script'; task.stepLabel = '正在生成脚本'; task.progress = 5;
let script = [];
const targetDur0 = Number(ctx.duration) > 0 ? Number(ctx.duration) : 0;
const userScript = String(ctx.script || '').trim();
if (userScript) {
// 用户已编辑的文案:原样按行切分成镜,绝不改写
script = splitCopyToScenes(userScript);
logger.info(`📝 使用用户文案直通分镜 ${script.length} 段(不改写)`);
} else if (content) {
// 让模型按内容生成 N 段(N = min(8, 句子数))
const sentences = content.split(/[。!?.!?]/).map(s=>s.trim()).filter(Boolean);
const baseN = Math.min(8, Math.max(2, sentences.length));
let n = Math.max(baseN, imagePaths.length); // 分镜数 ≥ 选中图片数,保证每张图都出现
if (targetDur0 > 0) n = Math.max(n, Math.min(30, Math.ceil(targetDur0 / 5))); // 时长越长分镜越多(约5s/段)
script = await llmScript({ url, key, model, title, count: n, extraPrompt: (extraPrompt + ' 内容:' + content.slice(0, 1500)).trim() });
} else {
script = [{ subtitle: title, tts: title }];
}
if (!Array.isArray(script) || !script.length) script = [{ subtitle: title, tts: title }];
// TTS + segments:每段轮换使用选中图片,保证所有图片都出现
const segments = [];
let segCount = Math.max(script.length, imagePaths.length);
if (targetDur0 > 0 && !userScript) segCount = Math.max(segCount, Math.min(30, Math.ceil(targetDur0 / 5))); // 时长越长分镜越多(仅自动文案时)
for (let i = 0; i < segCount; i++) {
task.step = 'tts'; task.stepLabel = `正在朗读 ${i+1}/${segCount}`; task.progress = 10 + Math.round((i/segCount)*40);
const seg = userScript ? (script[i] || {}) : (script[i % script.length] || {}); // 用户文案不循环重复朗读
let ttsFile = ''; let dur = 0;
if (seg.tts) {
try {
const t = await videotool.generateTts(seg.tts, { voice, outPath: path.join(work, `tts${i}.mp3`) });
ttsFile = t.file; dur = t.seconds;
} catch (e) { logger.warn('TTS fail: ' + e.message); }
}
segments.push({ imagePath: imagePaths[i % imagePaths.length], subtitle: seg.subtitle || seg.tts || (userScript ? '' : title), ttsFile, ttsSeconds: dur, duration: Math.max(2.5, Math.min(12, dur || 4)) });
}
// 目标时长:画面段总长 = 目标 + 转场重叠(xfade 每次吃掉 0.6s),
// 配音段总长 = 目标(音频走 concat 无重叠),使音画总长都精确等于目标时长
const targetDur = Number(ctx.duration) > 0 ? Number(ctx.duration) : 0;
if (targetDur > 0 && segments.length) {
const n = segments.length;
const overlap = (transition && transition !== 'cut' && n > 1) ? 0.6 * (n - 1) : 0;
const natural = segments.reduce((s, x) => s + x.duration, 0) || 1;
const videoTotal = targetDur + overlap; // 画面段之和
const audioShare = overlap / n; // 每段配音比画面短的秒数(落在转场区)
for (const s of segments) {
const d = Math.max(1.0, (s.duration / natural) * videoTotal);
s.duration = d;
s.audioDuration = Math.max(0.5, d - audioShare); // 精确模式:配音对齐
}
logger.info(`⏱ AI 视频目标时长 ${targetDur}s → 画面 ${videoTotal.toFixed(1)}s + 转场重叠 ${overlap.toFixed(1)}s,分 ${n} 段`);
}
// compose
const segFiles = [];
for (let i = 0; i < segments.length; i++) {
task.step = 'compose'; task.stepLabel = `合成 ${i+1}/${segments.length}`; task.progress = 50 + Math.round((i/segments.length)*45);
const out = path.join(work, `seg${i}.mp4`);
await videotool.buildSegment(segments[i], out, { width, height, subtitleStyle });
segFiles.push(out);
}
task.step = 'merge'; task.stepLabel = '合并'; task.progress = 96;
const finalTmp = path.join(work, 'final.mp4');
await videotool.concatWithTransition(segFiles, finalTmp, { transition: transition || 'fade', width, height });
// 6) 落库:保存到用户选择的目录(默认素材库根目录)
const safeDir = String(saveDir || '').replace(/^\/+/, '').replace(/\.\./g, '');
const baseDir = safeDir ? path.join(library.path, safeDir) : library.path;
try { fs.mkdirSync(baseDir, { recursive: true }); } catch (_) {}
const safeTitle = String(title).replace(/[\\/:*?"<>|]/g, '_').slice(0, 60) || 'AI视频';
let target = path.join(baseDir, `${safeTitle}.mp4`);
let n = 1;
while (fs.existsSync(target)) { target = path.join(baseDir, `${safeTitle}_${n}.mp4`); n++; }
fs.copyFileSync(finalTmp, target);
await reindex(req, library.path, target);
task.status = 'done'; task.progress = 100; task.step = 'done'; task.stepLabel = '完成'; task.resultPath = path.relative(library.path, target);
} finally {
fs.rmSync(work, { recursive: true, force: true });
}
}
// llmScript is defined later? it's a function declaration in same module scope (hoisted). ok.
module.exports = router;