718 lines
29 KiB
Python
718 lines
29 KiB
Python
"""FFmpeg / FFprobe 封装:探测、标准化、转场拼接、字幕(烧录/内嵌)、混音、导出。
|
||
|
||
【二进制是「能力感知」挑选的】
|
||
Homebrew 官方 ffmpeg bottle 编译时不带 libass/freetype/fontconfig,
|
||
subtitles / ass / drawtext 滤镜全部缺失,字幕只能外挂;brew reinstall 也救不了
|
||
(公式本身不依赖 libass)。所以这里按
|
||
配置指定(FFMPEG_BIN)→ PATH → 常见完整版/静态 GPL 构建目录
|
||
逐个探测,优先选中真正带 libass 的那个;只有全都缺滤镜时才退回 PATH 上的默认构建。
|
||
内嵌软字幕(mov_text 等)是另一套能力,用 -encoders 单独探测。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import re
|
||
import shutil
|
||
import subprocess
|
||
from dataclasses import dataclass
|
||
from functools import lru_cache
|
||
from pathlib import Path
|
||
|
||
from app.config import settings
|
||
|
||
# 除 PATH 之外还要尝试的目录:ffmpeg-full / 静态 GPL 构建通常装在这些地方
|
||
_EXTRA_DIRS = (
|
||
"~/.local/ffmpeg/bin",
|
||
"~/.local/bin",
|
||
"/opt/homebrew/opt/ffmpeg-full/bin",
|
||
"/usr/local/opt/ffmpeg-full/bin",
|
||
"/opt/homebrew/bin",
|
||
"/usr/local/bin",
|
||
)
|
||
|
||
# 烧录字幕(libass)可用的滤镜名,按优先级
|
||
SUBTITLE_FILTERS = ("subtitles", "ass")
|
||
# 各容器用于「内嵌软字幕」的编码器(探测不到时视为不支持)
|
||
EMBED_CODECS = {".mp4": "mov_text", ".m4v": "mov_text", ".mov": "mov_text",
|
||
".mkv": "mov_text", ".webm": "webvtt"}
|
||
|
||
# 字幕字体必须**真的含中文字形**,否则 libass 不报错、直接画一排豆腐块(本轮踩过)。
|
||
# 所以首选字体族名(ASS 的 Fontname 只认族名,写文件路径等于没写),
|
||
# 并且一律用 fontconfig 的 charset 查询(":charset=4e2d")来验证覆盖。
|
||
# 注意:Linux 上最常见的 DejaVuSans 不含中文,绝不能当首选。
|
||
_FONT_FAMILY_CANDIDATES = [
|
||
"PingFang SC", "Hiragino Sans GB", "Heiti SC", "Songti SC",
|
||
"Noto Sans CJK SC", "Noto Sans SC", "Source Han Sans SC",
|
||
"WenQuanYi Micro Hei", "Microsoft YaHei", "SimHei", "Arial Unicode MS",
|
||
]
|
||
# fontconfig 查不到时的文件兜底(会用 fc-scan 反查真实族名)
|
||
_FONT_FILE_CANDIDATES = [
|
||
"/System/Library/Fonts/PingFang.ttc",
|
||
"/System/Library/Fonts/Hiragino Sans GB.ttc",
|
||
"/System/Library/Fonts/STHeiti Medium.ttc",
|
||
"/System/Library/Fonts/Supplemental/Songti.ttc",
|
||
"/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
|
||
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
|
||
"/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
|
||
"/usr/share/fonts/opentype/noto/NotoSansSC-Regular.otf",
|
||
"/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
|
||
"/usr/share/fonts/wenquanyi/wqy-microhei/wqy-microhei.ttc",
|
||
"C:/Windows/Fonts/msyh.ttc",
|
||
"C:/Windows/Fonts/simhei.ttf",
|
||
]
|
||
_FONT_SUFFIXES = (".ttf", ".ttc", ".otf", ".woff", ".woff2")
|
||
|
||
|
||
def _exe_name(kind: str) -> str:
|
||
return "ffprobe" if kind == "ffprobe" else "ffmpeg"
|
||
|
||
|
||
def _configured_bin(kind: str) -> str:
|
||
return str(getattr(settings, "ffmpeg_bin" if kind == "ffmpeg" else "ffprobe_bin", "") or "").strip()
|
||
|
||
|
||
def _usable(path: str) -> bool:
|
||
return bool(path) and (Path(path).is_file() or shutil.which(path) is not None)
|
||
|
||
|
||
def _candidates(kind: str) -> list[str]:
|
||
"""按优先级列出候选可执行文件(解析为绝对路径、去重、只保留真实存在的)。"""
|
||
exe = _exe_name(kind)
|
||
configured = _configured_bin(kind)
|
||
raw: list[str] = []
|
||
if configured:
|
||
raw.append(configured) # 显式配置永远排第一
|
||
raw.append(shutil.which(exe) or exe) # 其次是 PATH
|
||
raw += [str(Path(os.path.expanduser(d)) / exe) for d in _EXTRA_DIRS]
|
||
out: list[str] = []
|
||
seen: set[str] = set()
|
||
for item in raw:
|
||
resolved = shutil.which(item) or item
|
||
if resolved in seen:
|
||
continue
|
||
seen.add(resolved)
|
||
if Path(resolved).is_file():
|
||
out.append(resolved)
|
||
return out
|
||
|
||
|
||
@lru_cache(maxsize=64)
|
||
def _probe_names(binary: str, flag: str) -> frozenset[str]:
|
||
"""解析 ffmpeg -filters / -encoders 输出的名字集合(按二进制缓存)。
|
||
|
||
注意 -encoders 每行前缀是 **六位** 标记(V/A/S + F/S/X/B/D),
|
||
曾经把它写成只允许 `[VAS.]`,于是所有「支持直接渲染」的编码器
|
||
(libwebp、mjpeg、libx264……真实输出都是 `V....D`/`VFS..D`)全部被漏掉,
|
||
can_encode() 于是恒为 False、内嵌字幕与缩略图能力探测双双失真。
|
||
"""
|
||
names: set[str] = set()
|
||
try:
|
||
proc = subprocess.run([binary, "-hide_banner", flag], capture_output=True, text=True, timeout=90)
|
||
except Exception:
|
||
return frozenset()
|
||
for line in proc.stdout.splitlines():
|
||
cols = line.split()
|
||
if len(cols) < 2:
|
||
continue
|
||
if flag == "-filters":
|
||
if len(cols) >= 4 and "->" in "".join(cols):
|
||
names.add(cols[1])
|
||
else:
|
||
if re.fullmatch(r"[A-Z.]{6}", cols[0]) and cols[1] != "=":
|
||
names.add(cols[1])
|
||
return frozenset(names)
|
||
|
||
|
||
def resolve_binary(kind: str) -> str:
|
||
"""挑一个真正能干活的 ffmpeg/ffprobe:ffmpeg 优先带 libass(能烧字幕)的构建。"""
|
||
exe = _exe_name(kind)
|
||
cands = _candidates(kind)
|
||
if not cands:
|
||
return exe
|
||
configured = _configured_bin(kind)
|
||
if configured and _usable(configured):
|
||
return shutil.which(configured) or configured # 用户点名 → 不再自动改选
|
||
if kind == "ffmpeg":
|
||
for path in cands:
|
||
filters = _probe_names(path, "-filters")
|
||
if any(f in filters for f in SUBTITLE_FILTERS):
|
||
return path
|
||
return cands[0]
|
||
|
||
|
||
FFMPEG = resolve_binary("ffmpeg")
|
||
FFPROBE = resolve_binary("ffprobe")
|
||
|
||
|
||
def available() -> bool:
|
||
return _usable(FFMPEG) and _usable(FFPROBE)
|
||
|
||
|
||
_FILTERS: set[str] | None = None
|
||
_ENCODERS: set[str] | None = None
|
||
|
||
|
||
def list_filters() -> set[str]:
|
||
"""缓存当前 ffmpeg 实际支持的滤镜名(精简版 ffmpeg 常缺 drawtext / subtitles / ass)。"""
|
||
global _FILTERS
|
||
if _FILTERS is None:
|
||
_FILTERS = set(_probe_names(FFMPEG, "-filters"))
|
||
return _FILTERS
|
||
|
||
|
||
def list_encoders() -> set[str]:
|
||
"""缓存当前 ffmpeg 实际支持的编码器名(内嵌字幕轨需要 mov_text / webvtt)。"""
|
||
global _ENCODERS
|
||
if _ENCODERS is None:
|
||
_ENCODERS = set(_probe_names(FFMPEG, "-encoders"))
|
||
return _ENCODERS
|
||
|
||
|
||
def has_filter(name: str) -> bool:
|
||
return name in list_filters()
|
||
|
||
|
||
def can_encode(name: str) -> bool:
|
||
return name in list_encoders()
|
||
|
||
|
||
def can_draw_text() -> bool:
|
||
return has_filter("drawtext")
|
||
|
||
|
||
def subtitle_filter() -> str:
|
||
"""返回可用的字幕烧录滤镜名,都不可用时返回空串。"""
|
||
filters = list_filters()
|
||
for name in SUBTITLE_FILTERS:
|
||
if name in filters:
|
||
return name
|
||
return ""
|
||
|
||
|
||
def can_burn_subtitles() -> bool:
|
||
return bool(subtitle_filter())
|
||
|
||
|
||
def subtitle_codec(container: str = ".mp4") -> str:
|
||
"""该容器可用于内嵌软字幕的编码器;不支持时返回空串。"""
|
||
suffix = (Path(container).suffix or str(container) or ".mp4").lower()
|
||
codec = EMBED_CODECS.get(suffix, "mov_text")
|
||
return codec if can_encode(codec) else ""
|
||
|
||
|
||
def can_embed_subtitles(container: str = ".mp4") -> bool:
|
||
return bool(subtitle_codec(container))
|
||
|
||
|
||
def ffmpeg_version() -> str:
|
||
"""当前 ffmpeg 版本号(用于健康检查排查「到底用的哪个构建」)。"""
|
||
try:
|
||
proc = subprocess.run([FFMPEG, "-hide_banner", "-version"], capture_output=True,
|
||
text=True, timeout=60)
|
||
lines = (proc.stdout or "").splitlines()
|
||
if lines:
|
||
parts = lines[0].split()
|
||
if len(parts) >= 3:
|
||
return parts[2]
|
||
except Exception:
|
||
pass
|
||
return ""
|
||
|
||
|
||
def capabilities() -> dict:
|
||
"""给健康检查/前端展示:这台机器的 ffmpeg 到底能做什么、用的是哪个二进制。"""
|
||
burn = subtitle_filter()
|
||
return {"available": available(), "drawtext": can_draw_text(),
|
||
"subtitle_burn": bool(burn), "subtitle_filter": burn,
|
||
"subtitle_embed": can_embed_subtitles(".mp4"), "subtitle_codec": subtitle_codec(".mp4"),
|
||
"libass": bool(burn),
|
||
"ffmpeg_path": FFMPEG, "ffprobe_path": FFPROBE, "ffmpeg_version": ffmpeg_version(),
|
||
"xfade": has_filter("xfade"), "concat": has_filter("concat"),
|
||
# settb/asettb(4.4+):转场与直切混排时把每路链路钉成同一个时间基,
|
||
# 缺了它 xfade 会直接拒绝配置滤镜图(compose.py 里有实测说明)
|
||
"timebase": has_filter("settb") and has_filter("asettb"),
|
||
"loudnorm": has_filter("loudnorm"), "blackdetect": has_filter("blackdetect"),
|
||
"freezedetect": has_filter("freezedetect"),
|
||
# 字体:family 给 libass/ASS,path 给 drawtext;两者都必须含中文字形
|
||
"font": bool(subtitle_font()["path"]) or bool(subtitle_font()["family"]),
|
||
"subtitle_font": subtitle_font()["family"], "subtitle_font_path": subtitle_font()["path"]}
|
||
|
||
|
||
def _fc_list(fmt: str, pattern: str = ":") -> list[tuple[str, str]]:
|
||
"""跑 fc-list 拿 (族名, 文件)。fontconfig 不存在时返回空表。"""
|
||
try:
|
||
probe = subprocess.run(["fc-list", pattern, "--format", fmt],
|
||
capture_output=True, text=True, timeout=30)
|
||
except (OSError, subprocess.SubprocessError):
|
||
return []
|
||
if probe.returncode != 0:
|
||
return []
|
||
rows: list[tuple[str, str]] = []
|
||
for line in probe.stdout.splitlines():
|
||
fam, _, path = line.partition("\t")
|
||
fam, path = fam.strip(), path.strip()
|
||
if fam and path:
|
||
rows.append((fam, path))
|
||
return rows
|
||
|
||
|
||
@lru_cache(maxsize=1)
|
||
def cjk_font_catalog() -> tuple[tuple[str, str], ...]:
|
||
"""所有「含中文字形」的 (族名, 文件)。用 U+4E2D 作为覆盖判据。"""
|
||
rows = [r for r in _fc_list("%{family[0]}\t%{file}\n", ":charset=4e2d")
|
||
if not r[0].startswith(".")] # ".Hiragino … Interface" 这类内部名画不出字
|
||
if rows:
|
||
return tuple(rows)
|
||
fallback = []
|
||
for cand in _FONT_FILE_CANDIDATES:
|
||
if Path(cand).exists():
|
||
fallback.append((_family_of_file(cand) or Path(cand).stem, cand))
|
||
return tuple(fallback)
|
||
|
||
|
||
def _families_of_file(path: str | Path) -> tuple[str, ...]:
|
||
"""字体文件 → 真实族名列表(ASS 只认族名;.ttc 一个文件里有多个面)。"""
|
||
try:
|
||
probe = subprocess.run(["fc-scan", "--format", "%{family[0]}\n", str(path)],
|
||
capture_output=True, text=True, timeout=30)
|
||
except (OSError, subprocess.SubprocessError):
|
||
return ()
|
||
if probe.returncode != 0:
|
||
return ()
|
||
out: list[str] = []
|
||
for line in probe.stdout.splitlines():
|
||
fam = line.strip()
|
||
if fam and not fam.startswith(".") and fam not in out:
|
||
out.append(fam)
|
||
return tuple(out)
|
||
|
||
|
||
def _family_of_file(path: str | Path) -> str:
|
||
"""优先返回候选表里认识的族名(.ttc 里第 0 个面常常是繁体)。"""
|
||
fams = _families_of_file(path)
|
||
lower = {f.casefold(): f for f in fams}
|
||
for want in _FONT_FAMILY_CANDIDATES:
|
||
if want.casefold() in lower:
|
||
return lower[want.casefold()]
|
||
return fams[0] if fams else ""
|
||
|
||
|
||
@lru_cache(maxsize=1)
|
||
def _default_subtitle_font() -> tuple[str, str]:
|
||
catalog = cjk_font_catalog()
|
||
by_name = {}
|
||
for fam, path in catalog:
|
||
by_name.setdefault(fam.strip().casefold(), path)
|
||
for want in _FONT_FAMILY_CANDIDATES:
|
||
if want.casefold() in by_name:
|
||
return want, by_name[want.casefold()]
|
||
for cand in _FONT_FILE_CANDIDATES: # fontconfig 不认识 → 直接问文件
|
||
if Path(cand).exists():
|
||
fam = _family_of_file(cand)
|
||
if fam:
|
||
return fam, cand
|
||
for token in ("cjk sc", "cjk", "hei", "song", "yahei"): # 近似名(如只装了 Noto CJK JP 之外的 SC 变体)
|
||
for fam, path in catalog:
|
||
if token in fam.casefold():
|
||
return fam, path
|
||
return "", ""
|
||
|
||
|
||
def subtitle_font(preferred: str | None = None) -> dict:
|
||
"""烧录字幕用的字体。
|
||
|
||
返回 {"family": ASS/libass 用的族名, "path": drawtext 用的文件路径}。
|
||
preferred 允许是族名或字体文件路径(时间线里可能存了老配置的路径)。
|
||
"""
|
||
pref = str(preferred or "").strip()
|
||
if pref and not cjk_font_catalog() and not Path(pref).expanduser().exists():
|
||
return {"family": pref, "path": ""} # 完全没有 fontconfig,只能照抄用户填的族名
|
||
if pref:
|
||
p = Path(pref).expanduser()
|
||
if p.suffix.lower() in _FONT_SUFFIXES and p.exists():
|
||
return {"family": _family_of_file(p) or pref, "path": str(p)}
|
||
catalog = cjk_font_catalog()
|
||
exact = [f for f, _ in catalog if f.casefold() == pref.casefold()]
|
||
if exact:
|
||
return {"family": exact[0], "path": dict(catalog).get(exact[0], "")}
|
||
loose = [f for f, _ in catalog if pref.casefold() in f.casefold()]
|
||
if loose:
|
||
return {"family": loose[0], "path": dict(catalog).get(loose[0], "")}
|
||
# 用户点名的字体在本机没有中文字形 → 回退到可用的中文字体,别画豆腐块
|
||
fam, path = _default_subtitle_font()
|
||
return {"family": fam or pref, "path": path, "requested": pref,
|
||
"downgraded": not (fam and fam.casefold() == pref.casefold())}
|
||
fam, path = _default_subtitle_font()
|
||
return {"family": fam, "path": path, "requested": pref, "downgraded": False}
|
||
|
||
|
||
def find_font() -> str:
|
||
"""drawtext 需要的字体**文件路径**(必须含中文字形)。"""
|
||
return subtitle_font()["path"]
|
||
|
||
|
||
class FFmpegError(RuntimeError):
|
||
def __init__(self, message: str, cmd: list[str] | None = None, stderr: str = ""):
|
||
super().__init__(message if not stderr else f"{message}: {stderr[-1500:]}")
|
||
self.cmd = cmd or []
|
||
self.stderr = stderr
|
||
|
||
|
||
def run(cmd: list[str], *, timeout: int = 3600, check: bool = True) -> subprocess.CompletedProcess:
|
||
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
|
||
if check and proc.returncode != 0:
|
||
raise FFmpegError(f"命令执行失败(返回码 {proc.returncode})", cmd, proc.stderr)
|
||
return proc
|
||
|
||
|
||
@dataclass
|
||
class MediaProbe:
|
||
path: str
|
||
duration: float = 0.0
|
||
width: int = 0
|
||
height: int = 0
|
||
fps: float = 0.0
|
||
bitrate_kbps: float = 0.0
|
||
has_audio: bool = False
|
||
codec: str = ""
|
||
audio_codec: str = ""
|
||
streams: list = None # type: ignore[assignment]
|
||
subtitle_tracks: list = None # type: ignore[assignment]
|
||
|
||
def __post_init__(self):
|
||
if self.streams is None:
|
||
self.streams = []
|
||
if self.subtitle_tracks is None:
|
||
self.subtitle_tracks = []
|
||
|
||
def as_dict(self) -> dict:
|
||
return {"path": self.path, "duration": round(self.duration, 3), "width": self.width,
|
||
"height": self.height, "fps": round(self.fps, 3), "bitrate_kbps": round(self.bitrate_kbps, 1),
|
||
"has_audio": self.has_audio, "codec": self.codec, "audio_codec": self.audio_codec,
|
||
"subtitle_tracks": self.subtitle_tracks}
|
||
|
||
|
||
def _parse_rate(value: str | None) -> float:
|
||
if not value:
|
||
return 0.0
|
||
if "/" in value:
|
||
num, _, den = value.partition("/")
|
||
try:
|
||
den_v = float(den) or 1
|
||
return float(num) / den_v
|
||
except ValueError:
|
||
return 0.0
|
||
try:
|
||
return float(value)
|
||
except ValueError:
|
||
return 0.0
|
||
|
||
|
||
def probe(path: str | Path) -> MediaProbe:
|
||
p = Path(path)
|
||
proc = run([FFPROBE, "-v", "error", "-print_format", "json", "-show_format", "-show_streams", str(p)],
|
||
timeout=120, check=False)
|
||
if proc.returncode != 0:
|
||
raise FFmpegError("ffprobe 无法解析媒体文件", [FFPROBE, str(p)], proc.stderr)
|
||
data = json.loads(proc.stdout or "{}")
|
||
fmt = data.get("format", {})
|
||
streams = data.get("streams", [])
|
||
video = next((s for s in streams if s.get("codec_type") == "video"), None)
|
||
audio = next((s for s in streams if s.get("codec_type") == "audio"), None)
|
||
duration = _parse_rate(fmt.get("duration")) or (_parse_rate((video or {}).get("duration")))
|
||
fps = _parse_rate((video or {}).get("avg_frame_rate")) or _parse_rate((video or {}).get("r_frame_rate"))
|
||
bitrate = _parse_rate(fmt.get("bit_rate")) / 1000
|
||
return MediaProbe(
|
||
path=str(p),
|
||
duration=duration,
|
||
width=int((video or {}).get("width") or 0),
|
||
height=int((video or {}).get("height") or 0),
|
||
fps=fps,
|
||
bitrate_kbps=bitrate,
|
||
has_audio=audio is not None,
|
||
codec=str((video or {}).get("codec_name") or ""),
|
||
audio_codec=str((audio or {}).get("codec_name") or ""),
|
||
streams=[{"codec_type": s.get("codec_type"), "codec_name": s.get("codec_name")} for s in streams],
|
||
subtitle_tracks=[{"codec_name": s.get("codec_name"),
|
||
"language": str(((s.get("tags") or {}).get("language")) or ""),
|
||
"title": str(((s.get("tags") or {}).get("title")) or "")}
|
||
for s in streams if s.get("codec_type") == "subtitle"],
|
||
)
|
||
|
||
|
||
def image_size(path: str | Path) -> tuple[int, int]:
|
||
try:
|
||
info = probe(path)
|
||
return info.width, info.height
|
||
except Exception:
|
||
return 0, 0
|
||
|
||
|
||
def duration_ms(path: str | Path) -> int:
|
||
try:
|
||
return int(round(probe(path).duration * 1000))
|
||
except Exception:
|
||
return 0
|
||
|
||
|
||
def decode_errors(path: str | Path, *, timeout: int = 300) -> str:
|
||
"""完整解码一次,返回解码阶段的错误输出(空字符串代表无损坏帧)。"""
|
||
proc = run([FFMPEG, "-v", "error", "-i", str(path), "-f", "null", "-"], timeout=timeout, check=False)
|
||
return (proc.stderr or "").strip()
|
||
|
||
|
||
def detect_black_ratio(path: str | Path, threshold: float = 0.98, timeout: int = 300) -> float:
|
||
"""黑屏时长占比(0~1)。
|
||
|
||
注意 blackdetect 的两个阈值完全不同:
|
||
pic_th(picture_black_threshold)= 一帧里要有多少比例的画面是黑的才算「黑帧」;
|
||
pix_th(pixel_black_threshold) = 单个像素亮度低于多少才算「黑像素」。
|
||
把配置里的 0.98 传给 pix_th 会把所有像素都判成黑色(整片被判黑屏),
|
||
因此这里 threshold 走 pic_th,像素阈值固定用常规值 0.10。
|
||
"""
|
||
proc = run([FFMPEG, "-i", str(path), "-vf",
|
||
f"blackdetect=d=0.2:pic_th={float(threshold):.3f}:pix_th=0.10",
|
||
"-an", "-f", "null", "-"], timeout=timeout, check=False)
|
||
total = 0.0
|
||
for line in (proc.stderr or "").splitlines():
|
||
m = re.search(r"black_start:(\d+\.?\d*)\s+black_end:(\d+\.?\d*)", line)
|
||
if m:
|
||
total += max(0.0, float(m.group(2)) - float(m.group(1)))
|
||
try:
|
||
dur = probe(path).duration or 1
|
||
except Exception:
|
||
dur = 1
|
||
return min(1.0, total / dur)
|
||
|
||
|
||
def detect_silence_ratio(path: str | Path, timeout: int = 300) -> float:
|
||
proc = run([FFMPEG, "-i", str(path), "-af", "silencedetect=noise=-45dB:d=0.6", "-f", "null", "-"],
|
||
timeout=timeout, check=False)
|
||
total = 0.0
|
||
for line in (proc.stderr or "").splitlines():
|
||
m = re.search(r"silence_duration:\s*(\d+\.?\d*)", line)
|
||
if m:
|
||
total += float(m.group(1))
|
||
try:
|
||
dur = probe(path).duration or 1
|
||
except Exception:
|
||
dur = 1
|
||
return min(1.0, total / dur)
|
||
|
||
|
||
def detect_freeze_ratio(path: str | Path, timeout: int = 300, *, min_duration: float | None = None) -> float:
|
||
"""画面冻结时长占比(0~1)。冻结判定时长随片段长度自适应,短镜头也能查出「静止不动」。"""
|
||
try:
|
||
dur = probe(path).duration or 0.0
|
||
except Exception:
|
||
dur = 0.0
|
||
freeze_d = min_duration if min_duration else max(0.3, min(2.5, (dur or 2.0) * 0.45))
|
||
proc = run([FFMPEG, "-i", str(path), "-vf", f"freezedetect=n=-0.01d:d={freeze_d:.3f}",
|
||
"-map", "0:v:0", "-f", "null", "-"],
|
||
timeout=timeout, check=False)
|
||
total = 0.0
|
||
for line in (proc.stderr or "").splitlines():
|
||
m = re.search(r"freeze_start:(\d+\.?\d*).*?freeze_end:(\d+\.?\d*)", line)
|
||
if m:
|
||
total += max(0.0, float(m.group(2)) - float(m.group(1)))
|
||
try:
|
||
dur = probe(path).duration or 1
|
||
except Exception:
|
||
dur = 1
|
||
return min(1.0, total / dur)
|
||
|
||
|
||
def sample_points(count: int) -> list[float]:
|
||
"""抽帧时间点(占全片时长的比例):首帧贴近片头,其余均匀铺到 85%。
|
||
|
||
穿帮常常只在某一瞬间出现(镜 4 首帧空无一人、镜 7 说话人不在场),
|
||
所以第一帧必须贴着 0.1s 取,而不是均分后的 25%。
|
||
"""
|
||
count = max(1, int(count))
|
||
if count == 1:
|
||
return [0.5]
|
||
points = [0.0]
|
||
rest = count - 1
|
||
if rest == 1:
|
||
points.append(0.85)
|
||
else:
|
||
points += [round(0.25 + 0.60 * i / (rest - 1), 4) for i in range(rest)]
|
||
return points
|
||
|
||
|
||
def extract_frames(path: str | Path, dest_dir: str | Path, *, count: int = 4, width: int = 640,
|
||
timestamps: list[float] | None = None, stem: str = "frame",
|
||
timeout: int = 90) -> list[Path]:
|
||
"""按时间点抽取 jpg 帧(画面质检用)。抽不到的时间点静默跳过,返回真实存在的文件。"""
|
||
src = Path(path)
|
||
binary = resolve_binary("ffmpeg")
|
||
folder = Path(dest_dir)
|
||
folder.mkdir(parents=True, exist_ok=True)
|
||
if timestamps is None:
|
||
try:
|
||
duration = float(probe(src).duration or 0)
|
||
except Exception:
|
||
duration = 0.0
|
||
if duration <= 0:
|
||
return []
|
||
timestamps = [min(p * duration, max(0.0, duration - 0.2)) for p in sample_points(count)]
|
||
timestamps[0] = min(0.05, timestamps[0]) # 第一帧必须贴着片头:空镜、说话人缺席都在这
|
||
out: list[Path] = []
|
||
for index, moment in enumerate(timestamps, 1):
|
||
dest = folder / f"{stem}-{index:02d}.jpg"
|
||
cmd = [binary, "-y", "-hide_banner", "-loglevel", "error",
|
||
"-ss", f"{max(0.0, float(moment)):.3f}", "-i", str(src), "-frames:v", "1",
|
||
"-vf", f"scale={max(16, int(width))}:-2", "-q:v", "3", str(dest)]
|
||
try:
|
||
run(cmd, timeout=timeout)
|
||
except FFmpegError:
|
||
continue
|
||
if dest.is_file() and dest.stat().st_size > 0:
|
||
out.append(dest)
|
||
return out
|
||
|
||
|
||
def checksum(path: str | Path, limit_bytes: int = 1 << 24) -> str:
|
||
import hashlib
|
||
|
||
h = hashlib.sha256()
|
||
with Path(path).open("rb") as fh:
|
||
read = 0
|
||
while True:
|
||
chunk = fh.read(1 << 20)
|
||
if not chunk:
|
||
break
|
||
h.update(chunk)
|
||
read += len(chunk)
|
||
if read >= limit_bytes: # 大文件只哈希前 16MB,够用于完整性对账
|
||
break
|
||
return h.hexdigest()[:32]
|
||
|
||
|
||
def scale_flags(src_w: int = 0, src_h: int = 0, dst_w: int = 0, dst_h: int = 0) -> tuple[str, str]:
|
||
"""按缩放方向选重采样算法,返回 (flags, 追加滤镜)。
|
||
|
||
ffmpeg 裸 `scale=` 默认 bilinear:放大时又软又糊(768p 素材交付 1080p 全靠这一步,
|
||
软一档观众是直接看得出来的),缩小时又会出锯齿。所以放大走 lanczos 并叠一度
|
||
轻锐化补回边缘细节,缩小走 area(等价超采样,不产生摩尔纹)。
|
||
源尺寸拿不到时按放大处理——lanczos 至少不比原来的 bilinear 差。
|
||
"""
|
||
if src_w > 0 and src_h > 0 and dst_w > 0 and dst_h > 0:
|
||
if src_w * src_h >= dst_w * dst_h:
|
||
return "area", ""
|
||
return "lanczos", "unsharp=5:5:0.4:5:5:0.0"
|
||
|
||
|
||
def normalize_filter(width: int, height: int, fps: int,
|
||
src_size: tuple[int, int] | None = None) -> str:
|
||
"""把片段归一到目标画布(等比缩放 + 黑边补齐)。"""
|
||
src_w, src_h = (src_size or (0, 0))
|
||
flags, extra = scale_flags(int(src_w), int(src_h), width, height)
|
||
sharpen = f",{extra}" if extra else ""
|
||
return (f"scale={width}:{height}:force_original_aspect_ratio=decrease:flags={flags}{sharpen},"
|
||
f"pad={width}:{height}:(ow-iw)/2:(oh-ih)/2:color=black,"
|
||
f"setsar=1,fps={fps},format=yuv420p")
|
||
|
||
|
||
def escape_filter_path(path: str | Path) -> str:
|
||
return str(path).replace("\\", "/").replace(":", r"\:").replace("'", r"\'")
|
||
|
||
|
||
def srt_time(ms: int) -> str:
|
||
ms = max(0, int(ms))
|
||
h, rem = divmod(ms, 3600_000)
|
||
m, rem = divmod(rem, 60_000)
|
||
s, msec = divmod(rem, 1000)
|
||
return f"{h:02d}:{m:02d}:{s:02d},{msec:03d}"
|
||
|
||
|
||
def ass_time(ms: int) -> str:
|
||
ms = max(0, int(ms))
|
||
h, rem = divmod(ms, 3600_000)
|
||
m, rem = divmod(rem, 60_000)
|
||
s, msec = divmod(rem, 1000)
|
||
return f"{h}:{m:02d}:{s:02d}.{msec // 10:02d}"
|
||
|
||
|
||
_DEFAULT_ASS_HEADER = """[Script Info]
|
||
ScriptType: v4.00+
|
||
PlayResX: {w}
|
||
PlayResY: {h}
|
||
WrapStyle: 0
|
||
ScaledBorderAndShadow: yes
|
||
|
||
[V4+ Styles]
|
||
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
|
||
Style: Default,{font},{size},&H00FFFFFF,&H00FFFFFF,&H00101010,&H96000000,-1,0,0,0,100,100,0,0,1,{outline},1,2,60,60,{margin},1
|
||
|
||
[Events]
|
||
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
|
||
"""
|
||
|
||
|
||
def write_ass(cues: list[dict], target: str | Path, *, width: int = 1920, height: int = 1080,
|
||
style: dict | None = None) -> Path | None:
|
||
"""把字幕句写入 ASS(保留中文、可控样式),返回文件路径。"""
|
||
style = style or {}
|
||
cues = [c for c in cues if (c.get("text") or "").strip()]
|
||
if not cues:
|
||
return None
|
||
font = subtitle_font(style.get("font"))["family"] or "sans-serif"
|
||
size = int(style.get("size") or max(28, int(height * 0.042)))
|
||
outline = int(style.get("outline") or max(2, size // 16))
|
||
margin = int(style.get("margin") or max(40, int(height * 0.06)))
|
||
target = Path(target)
|
||
target.parent.mkdir(parents=True, exist_ok=True)
|
||
lines = [_DEFAULT_ASS_HEADER.format(w=width, h=height, font=font, size=size, outline=outline, margin=margin)]
|
||
for cue in sorted(cues, key=lambda c: c.get("start_ms", 0)):
|
||
text = (cue["text"] or "").strip().replace("\n", "\\N")
|
||
if cue.get("speaker"):
|
||
text = f"{{\\i1}}{cue['speaker']}:{{\\i0}}{text}"
|
||
lines.append(f"Dialogue: 0,{ass_time(cue['start_ms'])},{ass_time(cue['end_ms'])},Default,,0,0,0,,{text}")
|
||
target.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||
return target
|
||
|
||
|
||
def write_srt(cues: list[dict], target: str | Path) -> Path | None:
|
||
cues = [c for c in cues if (c.get("text") or "").strip()]
|
||
if not cues:
|
||
return None
|
||
target = Path(target)
|
||
target.parent.mkdir(parents=True, exist_ok=True)
|
||
blocks = []
|
||
for idx, cue in enumerate(sorted(cues, key=lambda c: c.get("start_ms", 0)), start=1):
|
||
text = cue["text"].strip()
|
||
if cue.get("speaker"):
|
||
text = f"{cue['speaker']}:{text}"
|
||
blocks.append(f"{idx}\n{srt_time(cue['start_ms'])} --> {srt_time(cue['end_ms'])}\n{text}\n")
|
||
target.write_text("\n".join(blocks), encoding="utf-8")
|
||
return target
|
||
|
||
|
||
EXPORT_PRESETS: dict[str, dict] = {
|
||
"draft_720p": {"width": 1280, "height": 720, "crf": 28, "preset": "veryfast", "audio_bitrate": "128k"},
|
||
"vertical_720p": {"width": 720, "height": 1280, "crf": 24, "preset": "medium", "audio_bitrate": "128k"},
|
||
"web_1080p": {"width": 1920, "height": 1080, "crf": 21, "preset": "medium", "audio_bitrate": "192k"},
|
||
"hq_1080p": {"width": 1920, "height": 1080, "crf": 18, "preset": "slow", "audio_bitrate": "256k"},
|
||
"vertical_1080p": {"width": 1080, "height": 1920, "crf": 21, "preset": "medium", "audio_bitrate": "192k"},
|
||
"uhd_4k": {"width": 3840, "height": 2160, "crf": 18, "preset": "slow", "audio_bitrate": "320k"},
|
||
}
|
||
|
||
|
||
def export_args(output: str | Path, *, crf: int, preset: str, audio_bitrate: str, threads: int = 0,
|
||
shortest: bool = True) -> list[str]:
|
||
"""成片编码参数(结尾固定是 -y <output>,字幕等参数必须插在它之前)。
|
||
|
||
shortest=False 的用法:内嵌字幕轨时**必须**关掉 -shortest —— SRT 字幕流通常比画面短,
|
||
-shortest 会在最后一条字幕结束时提前收尾,实测 20.1s 的片子被切到 17.7s。
|
||
调用方已经用 -t 精确限定时长,关掉它不会让成片变长。
|
||
"""
|
||
return ["-c:v", "libx264", "-preset", preset, "-crf", str(crf),
|
||
"-pix_fmt", "yuv420p", "-profile:v", "high", "-level", "4.2",
|
||
"-c:a", "aac", "-b:a", audio_bitrate, "-ar", "48000", "-ac", "2",
|
||
"-movflags", "+faststart",
|
||
*(["-shortest"] if shortest else []),
|
||
*(["-threads", str(threads)] if threads else []),
|
||
"-y", str(output)]
|