feat(ai-avatar): 标题改为Canvas渲染PNG图层叠加,所见即所得

This commit is contained in:
xiaoxia
2026-09-13 00:41:38 +08:00
parent 6503a74a7c
commit 577ec83636
10 changed files with 574 additions and 63 deletions
+7 -1
View File
@@ -210,11 +210,17 @@ def generate_avatar_smart_cover(
if not video_url.startswith(("http://", "https://")):
raise HTTPException(status_code=400, detail="video_url 必须是合法的 HTTP/HTTPS URL")
# 兼容:顶层 title_image_dataurl 透传进 title_config(前端可以放在任一位置)
title_config = getattr(body, "title_config", None)
top_dataurl = getattr(body, "title_image_dataurl", None)
if top_dataurl and isinstance(title_config, dict) and not title_config.get("title_image_dataurl"):
title_config = {**title_config, "title_image_dataurl": top_dataurl}
try:
cover_url = generate_smart_cover(
video_url,
max_frames=body.max_frames,
title_config=getattr(body, "title_config", None),
title_config=title_config,
)
except Exception as exc:
logger.error(
+11 -2
View File
@@ -110,12 +110,21 @@ class AiAvatarRenderProgressResponse(BaseModel):
class SmartCoverRequest(BaseModel):
"""智能封面请求 — MediaKit 抽帧 + 质量评分选最佳帧 + 可选标题 drawtext 叠加."""
"""智能封面请求 — MediaKit 抽帧 + 质量评分选最佳帧 + 可选标题叠加."""
video_url: str = Field(..., description="数字人视频 URL(对口型/渲染成片)")
max_frames: int = Field(5, ge=1, le=10, description="抽帧数量(默认 5)")
title_config: Optional[dict[str, Any]] = Field(
None, description="标题配置;传入时在封面上用 drawtext 叠加标题(竖屏 720x1280)"
None,
description="标题配置;传入时在封面上叠加标题。"
"若 title_config 含 title_image_dataurl(前端 Canvas 渲染的 PNG dataURL),"
"后端用 overlay 叠加图片图层实现所见即所得;否则降级用 drawtext 重画文字。",
)
title_image_dataurl: Optional[str] = Field(
None,
description="前端 Canvas 渲染的标题 PNG dataURL(data:image/png;base64,...);"
"传入时后端用 overlay 叠加图片图层,不再用 drawtext 重画文字。"
"推荐方式:直接放在 title_config.title_image_dataurl 里透传,本字段为兼容保留。",
)
@@ -10,6 +10,8 @@
from __future__ import annotations
import base64
import binascii
import logging
import os
import subprocess
@@ -159,19 +161,35 @@ def select_best_cover_frame(video_url: str, *, max_frames: int = 5) -> str:
def apply_title_to_cover(local_frame: str, *, title_config: dict | None) -> str:
"""用 ffmpeg drawtext 在封面图上叠加标题,返回叠加后图片的本地路径.
"""在封面图上叠加标题,返回叠加后图片的本地路径.
ffmpeg 失败时回退返回原始 local_frame。竖屏封面按 720x1280 计算位置。
优先使用前端 Canvas 渲染的 PNG 图层(overlay=0:0,所见即所得);
无 title_image_dataurl 时降级到 drawtext 重画文字。
ffmpeg 失败时回退返回原始 local_frame。竖屏封面按 720x1280 计算位置(drawtext 降级路径)。
"""
if not title_config or not isinstance(title_config, dict):
return local_frame
text = (title_config.get("text") or title_config.get("content") or "").strip()
text = (
title_config.get("text")
or title_config.get("content")
or title_config.get("title")
or ""
).strip()
if not text:
return local_frame
enabled = title_config.get("enabled", True)
if not enabled:
return local_frame
# 优先:前端 Canvas 渲染的 PNG 图层
title_dataurl = title_config.get("title_image_dataurl")
if isinstance(title_dataurl, str) and title_dataurl.startswith("data:image/"):
out_path = _overlay_title_png_on_image(local_frame, title_dataurl)
if out_path:
return out_path
logger.warning("[数字人封面] PNG 叠加失败,回退 drawtext")
# 降级:drawtext 重画文字
try:
from packages.domain.video_filter_builder import build_title_drawtext_filter
@@ -194,7 +212,7 @@ def apply_title_to_cover(local_frame: str, *, title_config: dict | None) -> str:
"-y",
titled_path,
]
logger.info("[数字人封面] 叠加标题: text=%s", text[:30])
logger.info("[数字人封面] drawtext 叠加标题: text=%s", text[:30])
result = subprocess.run(
cmd,
capture_output=True,
@@ -217,6 +235,64 @@ def apply_title_to_cover(local_frame: str, *, title_config: dict | None) -> str:
return local_frame
def _overlay_title_png_on_image(local_frame: str, dataurl: str) -> str | None:
"""解码 title PNG dataURL 并用 ffmpeg overlay 叠加到封面图上。
成功返回新文件路径;失败返回 None。
"""
try:
header, b64 = dataurl.split(",", 1)
if "base64" not in header:
return None
png_bytes = base64.b64decode(b64, validate=True)
if not png_bytes:
return None
base_dir = os.path.dirname(local_frame)
title_png = os.path.join(base_dir, f"title_{uuid.uuid4().hex[:8]}.png")
with open(title_png, "wb") as f:
f.write(png_bytes)
base, ext = os.path.splitext(local_frame)
titled_path = f"{base}_titled{ext or '.jpg'}"
cmd = [
"ffmpeg",
"-i",
local_frame,
"-i",
title_png,
"-filter_complex",
"[0:v][1:v]overlay=0:0",
"-y",
titled_path,
]
logger.info("[数字人封面] PNG overlay 叠加标题")
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=30,
)
# 清理临时 PNG
try:
os.unlink(title_png)
except OSError:
pass
if result.returncode != 0:
logger.warning(
"[数字人封面] PNG overlay 失败: exit=%s stderr=%s",
result.returncode,
(result.stderr or "")[-300:],
)
return None
if not os.path.exists(titled_path) or os.path.getsize(titled_path) == 0:
return None
return titled_path
except (binascii.Error, ValueError, OSError) as exc:
logger.warning("[数字人封面] PNG 解码/overlay 异常: %s", exc, exc_info=True)
return None
def persist_cover_to_oss(
frame_url: str,
*,
+123 -23
View File
@@ -9,6 +9,8 @@
from __future__ import annotations
import base64
import binascii
import logging
import os
import subprocess
@@ -27,6 +29,7 @@ from packages.adapters.sqlalchemy_impl.models import (
from packages.domain.video_filter_builder import (
build_broll_overlay_filter,
build_title_drawtext_filter,
build_title_overlay_filter,
)
from packages.shared.storage import get_shared_storage_service
@@ -248,29 +251,12 @@ class AiAvatarRenderService:
output_height=output_height,
)
# 标题叠加(传入实际输出尺寸,保证位置计算正确)
title_filter = build_title_drawtext_filter(
job.title_config,
output_width=output_width,
output_height=output_height,
)
filter_complex = ""
final_label = None
if broll_filter and title_filter:
# B-roll → 标题叠在 B-roll 输出上
filter_complex = broll_filter + f";[{broll_label}]{title_filter}[vout_titled]"
final_label = "vout_titled"
elif broll_filter:
filter_complex = broll_filter
final_label = broll_label
elif title_filter:
filter_complex = f"[0:v]{title_filter}[vout_titled]"
final_label = "vout_titled"
else:
# 无滤镜:直接拷贝视频流
filter_complex = ""
final_label = None
# 标题叠加路径:优先前端 Canvas 渲染的 PNG 图层(所见即所得),
# 无 title_image_dataurl 时降级到 drawtext 重画文字。
title_cfg = job.title_config if isinstance(job.title_config, dict) else {}
title_dataurl = (title_cfg or {}).get("title_image_dataurl") if title_cfg else None
use_title_png = isinstance(title_dataurl, str) and title_dataurl.startswith("data:image/")
title_input_index = 1 + len(job.b_roll_segments or []) if use_title_png else None
job.progress = 40
self.db.commit()
@@ -279,9 +265,81 @@ class AiAvatarRenderService:
with tempfile.TemporaryDirectory() as tmpdir:
output_video_path = os.path.join(tmpdir, "output.mp4")
# 在临时目录里解码保存标题 PNG(with 退出自动清理)
title_png_path: Optional[str] = None
extra_inputs: list[str] = []
title_filter = None
if use_title_png:
try:
title_png_path = os.path.join(tmpdir, f"title_{job.id}.png")
self._save_title_dataurl_to_file(title_dataurl, dst_path=title_png_path)
extra_inputs.append(title_png_path)
logger.info(
"[数字人渲染] 标题 PNG 已保存: %s (input index %d)", title_png_path, title_input_index
)
except Exception as exc:
logger.warning("[数字人渲染] 标题 PNG 解码/保存失败,降级 drawtext: %s", exc)
title_png_path = None
extra_inputs = []
# 构建标题滤镜
final_label = None
if title_png_path and title_input_index is not None:
title_input_label = f"[{title_input_index}:v]"
base_label = f"[{broll_label}]" if broll_label else "[0:v]"
title_filter = build_title_overlay_filter(
title_cfg,
output_width=output_width,
output_height=output_height,
title_png_path=title_png_path,
title_input_label=title_input_label,
base_label=base_label,
output_label="vout_titled",
)
if not title_filter:
# build 返回 None → 文件不存在(极端并发情况),降级 drawtext
title_png_path = None
extra_inputs = []
if title_png_path:
# overlay 路径
if broll_filter and title_filter:
filter_complex = broll_filter + f";{title_filter}"
elif broll_filter:
filter_complex = broll_filter
final_label = broll_label
elif title_filter:
filter_complex = title_filter
else:
filter_complex = ""
if title_filter:
final_label = "vout_titled"
elif not final_label:
final_label = None
else:
# 降级:drawtext 重画文字
title_filter = build_title_drawtext_filter(
title_cfg,
output_width=output_width,
output_height=output_height,
)
if broll_filter and title_filter:
filter_complex = broll_filter + f";[{broll_label}]{title_filter}[vout_titled]"
final_label = "vout_titled"
elif broll_filter:
filter_complex = broll_filter
final_label = broll_label
elif title_filter:
filter_complex = f"[0:v]{title_filter}[vout_titled]"
final_label = "vout_titled"
else:
filter_complex = ""
final_label = None
cmd_list = self._build_ffmpeg_command(
input_video=input_video_path,
b_roll_segments=job.b_roll_segments,
extra_inputs=extra_inputs,
filter_complex=filter_complex,
final_label=final_label,
output_path=output_video_path,
@@ -408,6 +466,44 @@ class AiAvatarRenderService:
os.unlink(tmp.name)
raise
@staticmethod
def _save_title_dataurl_to_file(dataurl: str, *, dst_path: str | None = None, job_id: str = "") -> str:
"""解码前端传来的 data:image/png;base64,... 并保存为本地 PNG 文件。
Args:
dataurl: 完整 dataURL 字符串
dst_path: 指定输出路径;为 None 时创建临时文件并返回路径
job_id: 仅在 dst_path 为空时用于临时文件命名
Returns:
保存后的本地文件路径
"""
if not isinstance(dataurl, str) or not dataurl.startswith("data:image/"):
raise ValueError("title_image_dataurl 不是合法的 data:image URL")
# 拆分 data:image/png;base64,<payload>
try:
header, b64 = dataurl.split(",", 1)
except ValueError as exc:
raise ValueError("title_image_dataurl 缺少 base64 payload") from exc
if "base64" not in header:
raise ValueError("title_image_dataurl 不是 base64 编码")
try:
png_bytes = base64.b64decode(b64, validate=True)
except (binascii.Error, ValueError) as exc:
raise ValueError(f"title_image_dataurl base64 解码失败: {exc}") from exc
if not png_bytes:
raise ValueError("title_image_dataurl 解码后为空")
if dst_path:
out_path = dst_path
with open(out_path, "wb") as f:
f.write(png_bytes)
return out_path
suffix = f"_title_{job_id}.png" if job_id else "_title.png"
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
tmp.write(png_bytes)
return tmp.name
@staticmethod
def _probe_video_resolution(video_path: str) -> tuple[int, int]:
"""用 ffprobe 探测视频分辨率,返回 (width, height);失败返回 (0, 0)。"""
@@ -444,6 +540,7 @@ class AiAvatarRenderService:
*,
input_video: str,
b_roll_segments: list[dict[str, Any]],
extra_inputs: list[str] | None = None,
filter_complex: str,
final_label: Optional[str],
output_path: str,
@@ -460,6 +557,9 @@ class AiAvatarRenderService:
asset_url = seg.get("asset_url", "")
if asset_url:
cmd.extend(["-i", asset_url])
# 额外输入(例如前端 Canvas 渲染的标题 PNG)
for extra in extra_inputs or []:
cmd.extend(["-i", extra])
if filter_complex and final_label:
cmd.extend(
+19 -1
View File
@@ -32,6 +32,7 @@ import {
buildTitleConfigPayload,
buildCoverConfigPayload,
} from "./utils/contract"
import { renderTitleToPngDataUrl, getVideoResolution } from "./utils/titleCanvas"
/** 面板折叠状态 */
type PanelKey = "video" | "voice" | "script" | "lipsync" | "title" | "cover"
@@ -210,6 +211,23 @@ const AiAvatarPage: React.FC = () => {
try {
// 确保有 project_id(AI数字人入口独立,不在项目内,自动取默认项目;#1860 P0 bugfix)
const defaultProject = await getOrCreateDefaultProject()
// 用 Canvas 预渲染标题为 PNG dataURL(所见即所得,后端用 overlay 直接叠加)
let titleImageDataUrl: string | null = null
if (state.titleConfig.title?.trim()) {
try {
const res = await getVideoResolution(state.lipsyncJob.output_video_url || "")
titleImageDataUrl = renderTitleToPngDataUrl({
titleConfig: state.titleConfig,
videoWidth: res.width,
videoHeight: res.height,
})
} catch (canvasErr) {
console.warn("[渲染] 标题 Canvas 渲染失败,降级 drawtext:", canvasErr)
titleImageDataUrl = null
}
}
const job = await submitRender({
lipsync_job_id: state.lipsyncJob.id,
script_id: state.script?.id,
@@ -223,7 +241,7 @@ const AiAvatarPage: React.FC = () => {
pip_position: seg.pip_position,
pip_scale: seg.pip_scale,
})) as never,
title_config: buildTitleConfigPayload(state.titleConfig),
title_config: buildTitleConfigPayload(state.titleConfig, titleImageDataUrl),
// 封面不阻塞渲染:用户未选定封面时传空 dict,后端不生成封面;渲染完成后再单独抽帧
cover_config:
state.coverConfig.smart_cover_url ||
+3 -2
View File
@@ -58,7 +58,7 @@ export const getLipsyncJob = async (id: string): Promise<LipsyncJob> => {
return response.data
}
/* ── 智能封面(MediaKit 抽帧 + 质量评分选最佳帧 + 可选 drawtext 标题叠加) ── */
/* ── 智能封面(MediaKit 抽帧 + 质量评分选最佳帧 + 可选标题 overlay/drawtext 叠加) ── */
export const generateSmartCover = async (
video_url: string,
title_config?: Record<string, unknown> | null,
@@ -67,7 +67,7 @@ export const generateSmartCover = async (
const response = await apiClient.post<{ cover_url: string; status: string; message: string }>(
"/ai-avatar/render/smart-cover",
{ video_url, max_frames, title_config: title_config ?? null },
// smart-cover 链路:下载视频+抽帧+drawtext 加标题+上传 OSS,需要较长时间,120s 超时
// smart-cover 链路:下载视频+抽帧+overlay/drawtext 加标题+上传 OSS,需要较长时间,120s 超时
{ timeout: 120000 },
)
return response.data
@@ -82,6 +82,7 @@ export const submitRender = async (data: {
cover_config?: Record<string, unknown>
project_id?: string
}): Promise<RenderJob> => {
// title_config 内可含 title_image_dataurl(前端 Canvas 渲染的 PNG dataURL)
const response = await apiClient.post<RenderJob>("/ai-avatar/render", data)
return response.data
}
@@ -28,10 +28,13 @@ export function normalizeEmotion(raw: string | undefined | null): VoiceEmotion {
* 后端真实字段:text(或content)、font(或font_preset)、font_size(或size)、
* font_color(或color,可传 #RRGGBB)、position(top/center/bottom/custom)、
* enabled、bold、stroke{enabled,width,color}、shadow{enabled,color,offset_x,offset_y}、
* pos_x/pos_y(custom 时)。
* pos_x/pos_y(custom 时)、title_image_dataurl(前端 Canvas 渲染的 PNG dataURL,WYSIWYG 路径优先)。
* 口播标题默认 position=bottom(不传后端会默认 top 跑到画面顶部)。
*/
export function buildTitleConfigPayload(cfg: AiAvatarTitleConfig): Record<string, unknown> {
export function buildTitleConfigPayload(
cfg: AiAvatarTitleConfig,
titleImageDataUrl?: string | null,
): Record<string, unknown> {
const text = (cfg.title || "").trim()
if (!text) return {}
const position = cfg.position || "bottom"
@@ -53,6 +56,10 @@ export function buildTitleConfigPayload(cfg: AiAvatarTitleConfig): Record<string
payload.pos_x = cfg.pos_x
payload.pos_y = cfg.pos_y
}
// 前端 Canvas 渲染好的 PNG dataURL(所见即所得,后端优先 overlay 此图片图层)
if (titleImageDataUrl) {
payload.title_image_dataurl = titleImageDataUrl
}
return payload
}
@@ -0,0 +1,175 @@
/**
* AI数字人 — 标题 Canvas 渲染工具
*
* 把标题按前端预览的 HTML/CSS 效果画到透明背景 PNG 上(与视频同分辨率),
* 以 dataURL 形式传给后端,后端用 FFmpeg overlay 直接叠加图层,
* 彻底解决前端 HTML/CSS 预览 ≠ FFmpeg drawtext 成片的 WYSIWYG 问题。
*/
import type { AiAvatarTitleConfig } from "../types"
export interface RenderTitlePngOptions {
/** 标题配置 */
titleConfig: AiAvatarTitleConfig
/** 视频宽度(像素),默认 720 */
videoWidth?: number
/** 视频高度(像素),默认 1280 */
videoHeight?: number
}
/**
* 将标题渲染为透明背景 PNG 的 dataURL(data:image/png;base64,...)
* Canvas 尺寸与视频一致,保证叠加时 1:1 像素对齐。
*
* 标题为空时返回 null。
*/
export function renderTitleToPngDataUrl(opts: RenderTitlePngOptions): string | null {
const { titleConfig, videoWidth = 720, videoHeight = 1280 } = opts
if (!titleConfig) return null
const rawTitle = (titleConfig.title || "").trim()
if (!rawTitle) return null
// 按 / 或 / 分割为多行
const lines = rawTitle
.split(/[//]/)
.map((l) => l.trim())
.filter((l) => l.length > 0)
if (lines.length === 0) return null
const canvas = document.createElement("canvas")
canvas.width = videoWidth
canvas.height = videoHeight
const ctx = canvas.getContext("2d")
if (!ctx) return null
const size = Math.max(12, Math.round(titleConfig.size || 48))
const bold = !!titleConfig.bold
const italic = !!titleConfig.italic
const color = titleConfig.color || "#ffffff"
const stroke = !!titleConfig.stroke
const shadow = !!titleConfig.shadow
// 字体族 fallback 链:优先中文字体
const fontFamily =
'"Noto Sans CJK SC","Source Han Sans CN","PingFang SC","Microsoft YaHei",sans-serif'
const fontParts: string[] = []
if (italic) fontParts.push("italic")
if (bold) fontParts.push("bold")
fontParts.push(`${size}px`, fontFamily)
ctx.font = fontParts.join(" ")
ctx.fillStyle = color
ctx.textAlign = "center"
ctx.textBaseline = "middle"
// 阴影(shadow=true 时开启)
if (shadow) {
ctx.shadowColor = "rgba(0,0,0,0.8)"
ctx.shadowBlur = 4
ctx.shadowOffsetX = 0
ctx.shadowOffsetY = 2
}
// 位置计算:与 PanelLipsyncPreview 的 CSS 对齐
// 预览用 top/bottom 8px padding + transform translateX(-50%) 居中;
// 这里画到整尺寸 canvas,padding 按比例放大到全分辨率(预览缩放 0.35x 时 8px ≈ 23px 全尺寸,
// 为更贴近原 CSS 16px 安全边距,用 16px 作为内边距)。
const PAD = 16
let centerX = videoWidth / 2
let startY: number
const position = titleConfig.position || "bottom"
const lineGap = size * 1.2
const totalTextH = lines.length * lineGap - (lineGap - size) // 所有行的总高度
// 文本块顶部 y(textBaseline=middle 时首行基线)
let firstLineY: number
if (
position === "custom" &&
typeof titleConfig.pos_x === "number" &&
typeof titleConfig.pos_y === "number"
) {
centerX = (Math.max(0, Math.min(100, titleConfig.pos_x)) / 100) * videoWidth
const centerY = (Math.max(0, Math.min(100, titleConfig.pos_y)) / 100) * videoHeight
firstLineY = centerY - totalTextH / 2 + size / 2
} else if (position === "top") {
// 顶部:y = size/2 + PAD
firstLineY = size / 2 + PAD
} else if (position === "center") {
firstLineY = videoHeight / 2 - totalTextH / 2 + size / 2
} else {
// bottom(默认)
firstLineY = videoHeight - totalTextH - PAD + size / 2
}
// 描边参数(stroke=true 或 bold 默认细描边模拟粗体时都画;
// 注意:浏览器原生 bold 已经是粗体 glyph,Canvas 这里对 stroke=true 才加黑描边,
// 与预览 CSS 的 WebkitTextStroke 保持一致,不对 bold 自动加描边避免双粗)。
const doStroke = stroke
// 逐行绘制
lines.forEach((line, idx) => {
const y = firstLineY + idx * lineGap
if (doStroke) {
const prevShadowColor = ctx.shadowColor
const prevShadowBlur = ctx.shadowBlur
// 描边不要带阴影(避免黑色描边发虚)
ctx.shadowColor = "rgba(0,0,0,0)"
ctx.shadowBlur = 0
ctx.lineWidth = Math.max(2, size * 0.06)
ctx.strokeStyle = "#000000"
ctx.lineJoin = "round"
ctx.strokeText(line, centerX, y)
// 恢复阴影
if (shadow) {
ctx.shadowColor = "rgba(0,0,0,0.8)"
ctx.shadowBlur = 4
} else {
ctx.shadowColor = prevShadowColor
ctx.shadowBlur = prevShadowBlur
}
}
ctx.fillText(line, centerX, y)
})
try {
return canvas.toDataURL("image/png")
} catch {
return null
}
}
/**
* 获取视频真实分辨率(HTMLVideoElement + loadedmetadata,超时 3 秒兜底 720×1280)。
*/
export function getVideoResolution(
videoUrl: string,
timeoutMs = 3000,
): Promise<{ width: number; height: number }> {
return new Promise((resolve) => {
if (!videoUrl) {
resolve({ width: 720, height: 1280 })
return
}
const video = document.createElement("video")
video.preload = "metadata"
video.muted = true
video.playsInline = true
video.crossOrigin = "anonymous"
let settled = false
const done = (w: number, h: number) => {
if (settled) return
settled = true
video.removeAttribute("src")
video.load()
resolve({ width: w, height: h })
}
const timer = window.setTimeout(() => done(720, 1280), timeoutMs)
video.onloadedmetadata = () => {
window.clearTimeout(timer)
const w = video.videoWidth || 720
const h = video.videoHeight || 1280
done(w, h)
}
video.onerror = () => {
window.clearTimeout(timer)
done(720, 1280)
}
video.src = videoUrl
})
}
+52 -28
View File
@@ -420,44 +420,29 @@ def _escape_drawtext_text(text: str) -> str:
return result
# 粗体字体文件映射:服务器镜像只保留了 NotoSansSC-VF.ttf(可变字体,已删除
# NotoSansCJK-Bold.ttc 以避免 Mono 变体问题,见 worker-base.Dockerfile),
# 因此无法通过 fontfile 切换到 Bold 字重。这里保留路径列表作为未来扩展,
# 实际加粗通过 borderw 黑色描边实现(见下)。
DRAWTEXT_BOLD_FONT_SEARCH_PATHS: list[str] = [
"/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc",
"/usr/share/fonts/noto-cjk/NotoSansCJK-Bold.ttc",
"/usr/share/fonts/google-noto-cjk/NotoSansCJK-Bold.ttc",
"/usr/share/fonts/truetype/noto/NotoSansSC-Bold.ttf",
"/usr/share/fonts/noto/NotoSansSC-Bold.ttf",
]
# 粗体字体已由前端 Canvas 直接渲染(Canvas 使用浏览器原生粗体 glyph),
# FFmpeg 侧不再需要查找 Bold 字体文件;drawtext 仅作为旧版前端的降级路径,
# 通过 borderw 黑色细描边模拟粗体(见 build_title_drawtext_filter)。
def _resolve_font_path(font_name: str, bold: bool = False) -> str:
def _resolve_font_path(font_name: str) -> str:
"""解析字体名到服务器实际字体文件路径。
查找策略:
1. 通过 DRAWTEXT_FONT_MAP 映射前端字体名到服务器关键字
2. bold=True 时优先查找粗体变体;找不到回退常规字重
3. 在 DRAWTEXT_FONT_SEARCH_PATHS 中查找匹配路径
4. 未找到则返回空字符串(drawtext 使用内置默认字体)
2. 在 DRAWTEXT_FONT_SEARCH_PATHS 中查找匹配路径
3. 未找到则返回空字符串(drawtext 使用内置默认字体)
注:粗体已由前端 Canvas 渲染时直接用浏览器 bold glyph 绘制,
此处仅作为旧版前端降级路径,无需切换 Bold 字体文件。
"""
keyword = DRAWTEXT_FONT_MAP.get(font_name, font_name)
import os
if bold:
for path in DRAWTEXT_BOLD_FONT_SEARCH_PATHS:
if keyword.lower() in path.lower() and os.path.isfile(path):
return path
# 粗体文件找不到时,再查常规字重(后面会用描边兜底加粗)
for path in DRAWTEXT_FONT_SEARCH_PATHS:
if keyword.lower() in path.lower() and os.path.isfile(path):
return path
# fallback:遍历搜索任意可用字体
if bold:
for path in DRAWTEXT_BOLD_FONT_SEARCH_PATHS:
if os.path.isfile(path):
return path
for path in DRAWTEXT_FONT_SEARCH_PATHS:
if os.path.isfile(path):
return path
@@ -493,8 +478,10 @@ def build_title_drawtext_filter(
if not title_config or not isinstance(title_config, dict):
return None
# 字段名归一化:兼容 content/text、font_preset/font 两套命名
text = (title_config.get("text") or title_config.get("content") or "").strip()
# 字段名归一化:兼容 content/text/title 三套命名
text = (
title_config.get("text") or title_config.get("content") or title_config.get("title") or ""
).strip()
if not text:
return None
@@ -518,8 +505,8 @@ def build_title_drawtext_filter(
# ── 构建 drawtext 参数 ──
params: list[str] = []
# 字体文件:粗体优先使用 Bold 字体文件,避免同色描边造成字形偏移/重影
font_path = _resolve_font_path(font_name, bold=bold)
# 字体文件(drawtext 降级路径:粗体通过 borderw 黑色描边模拟)
font_path = _resolve_font_path(font_name)
if font_path:
escaped_path = font_path.replace("\\", "\\\\").replace(":", "\\\\:").replace("'", "\\\\'")
params.append(f"fontfile='{escaped_path}'")
@@ -599,6 +586,43 @@ def build_title_drawtext_filter(
return "drawtext=" + ":".join(params)
def build_title_overlay_filter(
title_config: dict[str, Any],
output_width: int, # noqa: ARG001 - 保留参数签名,PNG 已按视频分辨率绘制
output_height: int, # noqa: ARG001
title_png_path: str,
*,
title_input_label: str = "[1:v]",
base_label: str = "[0:v]",
output_label: str = "vout_titled",
) -> str | None:
"""构建标题 PNG 图层 overlay 滤镜(WYSIWYG 路径)。
前端用 Canvas 把标题画成与视频同分辨率的透明 PNG(所见即所得),
后端直接 overlay=0:0 叠加即可,PNG 透明区域不遮挡视频。
Args:
title_config: 标题配置 dict(仅用来判断降级)
output_width: 输出宽度(未使用,PNG 已按该分辨率绘制)
output_height: 输出高度(未使用)
title_png_path: 已保存到本地的标题 PNG 文件路径
title_input_label: 标题 PNG 在 filter_complex 中的输入标签(默认 "[1:v]")
base_label: 前序滤镜输出标签(如 B-roll 输出 "[vout]")
output_label: overlay 输出标签名
Returns:
overlay 滤镜字符串;title_png_path 为空/文件不存在时返回 None(降级到 drawtext)
"""
import os
if not title_png_path or not os.path.isfile(title_png_path):
return None
if not title_config or not isinstance(title_config, dict):
return None
return f"{base_label}{title_input_label}overlay=0:0[{output_label}]"
# ── B-roll 叠加滤镜 ─────────────────────────────────────────────────────────
+95
View File
@@ -13,6 +13,7 @@
from __future__ import annotations
import os
import unittest
from dataclasses import FrozenInstanceError
from unittest.mock import patch
@@ -29,10 +30,12 @@ from packages.domain.video_filter_builder import (
ClipFilterChain,
_escape_drawtext_text,
_resolve_font_path,
build_broll_overlay_filter,
build_clip_filter,
build_concat_filter,
build_filter_complex,
build_title_drawtext_filter,
build_title_overlay_filter,
build_xfade_filter,
chain_filters,
has_audio,
@@ -1161,5 +1164,97 @@ class TestDrawtextNotDictConfig(unittest.TestCase):
self.assertIsNone(build_title_drawtext_filter([1, 2, 3]))
class TestTitleOverlay(unittest.TestCase):
"""build_title_overlay_filter 单元测试(WYSIWYG PNG 叠加路径)。"""
def test_overlay_filter_format(self):
"""PNG 文件存在时返回正确的 overlay 滤镜字符串。"""
import tempfile
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
tmp.write(b"\x89PNG\r\n\x1a\n")
tmp_path = tmp.name
try:
result = build_title_overlay_filter(
{"text": "标题"},
output_width=720,
output_height=1280,
title_png_path=tmp_path,
title_input_label="[2:v]",
base_label="[vout]",
output_label="vout_titled",
)
self.assertIsNotNone(result)
self.assertIn("[vout][2:v]overlay=0:0[vout_titled]", result)
finally:
os.unlink(tmp_path)
def test_overlay_default_labels(self):
"""不传 label 参数时使用默认 [0:v] / [1:v] / vout_titled。"""
import tempfile
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
tmp.write(b"\x89PNG\r\n\x1a\n")
tmp_path = tmp.name
try:
result = build_title_overlay_filter(
{"text": "标题"},
output_width=720,
output_height=1280,
title_png_path=tmp_path,
)
self.assertEqual(result, "[0:v][1:v]overlay=0:0[vout_titled]")
finally:
os.unlink(tmp_path)
def test_overlay_returns_none_when_png_missing(self):
"""PNG 文件不存在时返回 None,供调用方降级到 drawtext。"""
result = build_title_overlay_filter(
{"text": "标题"},
output_width=720,
output_height=1280,
title_png_path="/nonexistent/path/title.png",
)
self.assertIsNone(result)
def test_overlay_returns_none_for_empty_config(self):
"""title_config 为空/非 dict 时返回 None。"""
import tempfile
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
tmp.write(b"\x89PNG\r\n\x1a\n")
tmp_path = tmp.name
try:
self.assertIsNone(
build_title_overlay_filter(
None,
output_width=720,
output_height=1280,
title_png_path=tmp_path,
)
)
self.assertIsNone(
build_title_overlay_filter(
"not a dict",
output_width=720,
output_height=1280,
title_png_path=tmp_path,
)
)
finally:
os.unlink(tmp_path)
def test_overlay_returns_none_for_empty_path(self):
"""title_png_path 为空字符串时返回 None。"""
self.assertIsNone(
build_title_overlay_filter(
{"text": "标题"},
output_width=720,
output_height=1280,
title_png_path="",
)
)
if __name__ == "__main__":
unittest.main()