refactor(preflight): 移除音轨判定与补轨/改默认音轨相关代码
- 不再检测默认音轨、不再提供 add_ac3 / fix_default_audio / 改默认标志 - 音频信息仅保留在报告 audio_codecs 列,不参与 verdict - 同步移除 [Compatibility] auto_add_ac3 / direct_audio / auto_fix_default_audio / backup_dir / refresh_jellyfin_after_prep 及 TaskManager 的 prepare 阶段 - DV Profile 7 不再算 TRANSCODE(视频可去 DV 元数据直传),仅 DV5 需 tonemap
This commit is contained in:
@@ -74,7 +74,7 @@ class ParserService:
|
||||
return m_type, title, year, season_num, target_season_folder, root_dir_path, f"{title.replace('.', ' ')} ({year})"
|
||||
|
||||
@staticmethod
|
||||
def get_target_info(f_path: Path, m_type: str, title: str, year: str, season_num: str, is_multi_version: bool = False, audio_tag: str = None):
|
||||
def get_target_info(f_path: Path, m_type: str, title: str, year: str, season_num: str, is_multi_version: bool = False):
|
||||
tags = MediaInfoService.get_scene_tags(f_path)
|
||||
tmdb = TMDBService.search_media(title, year, m_type, season_num)
|
||||
|
||||
@@ -87,9 +87,7 @@ class ParserService:
|
||||
tid = f"[tmdbid-{tmdb['tmdb_id']}]" if (tmdb and config.INCLUDE_TMDB_ID) else ""
|
||||
|
||||
source = "BluRay.REMUX" if tags['is_remux'] else "WEB-DL"
|
||||
# 预补 AC3 时,命名按处理后的音轨来(避免写入真实文件不存在的音轨)
|
||||
audio_info = audio_tag or tags['a_info']
|
||||
tech = f"{tags['res']}.{source}.{tags['v_codec']}.{tags['bits']}.{audio_info}"
|
||||
tech = f"{tags['res']}.{source}.{tags['v_codec']}.{tags['bits']}.{tags['a_info']}"
|
||||
|
||||
target_folder = f"{title.replace('.', ' ')} ({year}) {tid}".strip()
|
||||
|
||||
|
||||
+384
-482
@@ -1,482 +1,384 @@
|
||||
# src/services/preflight.py
|
||||
"""入库前兼容性体检(Preflight)。
|
||||
|
||||
目标:入库后电视点开即播,服务器尽量直传不转码。
|
||||
结论四档:
|
||||
READY 直接入库,客户端直传
|
||||
PREP 轻量预处理后即可直传(补 AC3 / 抽外挂 ASS / 改默认音轨)
|
||||
TRANSCODE 不能直传,但服务端转码可正常播放(DV5、老编码、码率超限)
|
||||
BLOCKED 连转码都救不了(文件损坏、无视频轨),不入库,写报告
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from core import config
|
||||
from core.logger import log
|
||||
from core.utils import FFprobeUtil
|
||||
|
||||
READY, PREP, TRANSCODE, BLOCKED = "READY", "PREP", "TRANSCODE", "BLOCKED"
|
||||
_ORDER = {READY: 0, PREP: 1, TRANSCODE: 2, BLOCKED: 3}
|
||||
|
||||
|
||||
@dataclass
|
||||
class PreflightResult:
|
||||
verdict: str = READY
|
||||
reasons: list = field(default_factory=list)
|
||||
actions: list = field(default_factory=list)
|
||||
info: dict = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def summary(self) -> str:
|
||||
return f"{self.verdict}" + (f" | {', '.join(self.reasons)}" if self.reasons else "")
|
||||
|
||||
|
||||
class PreflightService:
|
||||
"""ffprobe 体检 + 补 AC3 音轨 + 报告输出。"""
|
||||
|
||||
# 电视(Amlogic S905X3 + Jellyfin Android TV 0.20)实测可直传的编码
|
||||
VIDEO_OK = {"hevc", "h264"}
|
||||
# 可在 config.ini [Compatibility] direct_audio 里按实测调整
|
||||
AUDIO_OK = set(config.DIRECT_AUDIO_CODECS)
|
||||
SUB_OK = {
|
||||
"ass", "ssa", "subrip", "srt", "webvtt", "mov_text",
|
||||
"hdmv_pgs_subtitle", "dvd_subtitle", "dvb_subtitle", "idx",
|
||||
}
|
||||
HDR_TRANSFERS = {"smpte2084", "arib-std-b67"}
|
||||
ASS_OK = {"ass", "ssa"}
|
||||
|
||||
# ------------------------------------------------------------------ 评估
|
||||
|
||||
@classmethod
|
||||
def _raise(cls, r: PreflightResult, level: str, reason: str) -> None:
|
||||
r.reasons.append(reason)
|
||||
if _ORDER[level] > _ORDER[r.verdict]:
|
||||
r.verdict = level
|
||||
|
||||
@staticmethod
|
||||
def _primary_video(streams: list) -> dict | None:
|
||||
for s in streams:
|
||||
if s.get("codec_type") != "video":
|
||||
continue
|
||||
if (s.get("disposition") or {}).get("attached_pic"):
|
||||
continue # 封面图(mjpeg/png)
|
||||
return s
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _dv_profile(video: dict) -> int | None:
|
||||
for sd in video.get("side_data_list") or []:
|
||||
name = str(sd.get("side_data_type", "")).lower()
|
||||
if "dovi" in name or "dolby vision" in name:
|
||||
profile = sd.get("dv_profile")
|
||||
return int(profile) if profile is not None else None
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def evaluate(cls, path: Path, use_cache: bool = True) -> PreflightResult:
|
||||
cached = cls._cache_get(path) if use_cache else None
|
||||
if cached:
|
||||
return cached
|
||||
|
||||
r = PreflightResult()
|
||||
data = FFprobeUtil.get_json(path, "-show_format", "-show_streams")
|
||||
if not data:
|
||||
r.verdict, r.reasons = BLOCKED, ["ffprobe 读取失败"]
|
||||
return r
|
||||
|
||||
streams = data.get("streams", [])
|
||||
fmt = data.get("format", {})
|
||||
size_gb = int(fmt.get("size") or 0) / 1e9
|
||||
v = cls._primary_video(streams)
|
||||
if not v:
|
||||
r.verdict, r.reasons = BLOCKED, ["无主视频轨"]
|
||||
return r
|
||||
|
||||
codec = (v.get("codec_name") or "").lower()
|
||||
height = int(v.get("height") or 0)
|
||||
width = int(v.get("width") or 0)
|
||||
level = v.get("level")
|
||||
v_bitrate = int(v.get("bit_rate") or 0) or int(fmt.get("bit_rate") or 0)
|
||||
mbps = v_bitrate / 1e6
|
||||
dv_profile = cls._dv_profile(v)
|
||||
transfer = (v.get("color_transfer") or "").lower()
|
||||
|
||||
audios = []
|
||||
for s in streams:
|
||||
if s.get("codec_type") != "audio":
|
||||
continue
|
||||
audios.append({
|
||||
"codec": (s.get("codec_name") or "").lower(),
|
||||
"channels": int(s.get("channels") or 0),
|
||||
"language": (s.get("tags") or {}).get("language", ""),
|
||||
"title": (s.get("tags") or {}).get("title", ""),
|
||||
"default": bool((s.get("disposition") or {}).get("default")),
|
||||
})
|
||||
subs = [
|
||||
{"codec": (s.get("codec_name") or "").lower(),
|
||||
"language": (s.get("tags") or {}).get("language", "")}
|
||||
for s in streams if s.get("codec_type") == "subtitle"
|
||||
]
|
||||
|
||||
r.info.update(
|
||||
codec=codec, width=width, height=height, level=level,
|
||||
mbps=round(mbps, 1), dv_profile=dv_profile,
|
||||
hdr=transfer in cls.HDR_TRANSFERS, color_transfer=transfer,
|
||||
size_gb=round(size_gb, 1), audio=audios, subs=subs,
|
||||
duration=int(float(fmt.get("duration") or 0)),
|
||||
)
|
||||
|
||||
# 1. 容器
|
||||
if path.suffix.lower() not in {".mkv", ".mp4"}:
|
||||
cls._raise(r, TRANSCODE, f"容器 {path.suffix} 需重新封装或转码")
|
||||
r.actions.append("server_transcode")
|
||||
# 2. 视频编码
|
||||
if codec not in cls.VIDEO_OK:
|
||||
cls._raise(r, TRANSCODE, f"视频编码 {codec} 电视无法解码,需服务端转码")
|
||||
r.actions.append("server_transcode")
|
||||
# 3. 分辨率
|
||||
if height > 2160:
|
||||
cls._raise(r, TRANSCODE, f"{height}p 超过 4K,需服务端缩放转码")
|
||||
r.actions.append("server_transcode")
|
||||
# 4. HEVC level(153 = 5.1):仅提示,很多片源 tag 偏高但实际能解
|
||||
if codec == "hevc" and isinstance(level, int) and level > 153:
|
||||
r.reasons.append(f"HEVC level {level}(>5.1,实际解码可能仍正常)")
|
||||
# 5. Dolby Vision
|
||||
if dv_profile == 5:
|
||||
cls._raise(r, TRANSCODE, "纯 DV Profile 5 无 HDR10 兼容层,需服务端 tonemap 转码")
|
||||
r.actions.append("server_tonemap")
|
||||
elif dv_profile == 7:
|
||||
cls._raise(r, TRANSCODE, "DV Profile 7(HDR10 基座),客户端不支持 DV,需服务端 tonemap 转码")
|
||||
r.actions.append("server_tonemap")
|
||||
# 6. 码率
|
||||
if mbps > config.MAX_DIRECT_MBPS:
|
||||
cls._raise(r, TRANSCODE, f"码率 {mbps:.1f} Mbps 超过直传上限 {config.MAX_DIRECT_MBPS:g},需转码")
|
||||
r.actions.append("transcode_bitrate")
|
||||
# 7. 音频
|
||||
playable = [a for a in audios if a["codec"] in cls.AUDIO_OK and 0 < a["channels"] <= 8]
|
||||
if not playable:
|
||||
cls._raise(r, PREP, "没有可直传的音轨(需补 AC3)")
|
||||
r.actions.append("add_ac3")
|
||||
else:
|
||||
# 默认轨若不可直传,客户端可能仍按默认轨触发转码;没有显式默认时以第一条为准
|
||||
defaults = [a for a in audios if a["default"]] or audios[:1]
|
||||
if defaults and not any(a["codec"] in cls.AUDIO_OK for a in defaults):
|
||||
cls._raise(r, PREP, "默认音轨不可直传,建议把兼容轨设为默认")
|
||||
r.actions.append("fix_default_audio")
|
||||
# 8. 字幕编码
|
||||
bad = [s["codec"] for s in subs if s["codec"] not in cls.SUB_OK]
|
||||
if bad:
|
||||
r.reasons.append(f"未知字幕编码: {sorted(set(bad))}")
|
||||
# 9. 大文件内嵌 ASS:客户端首次播放要现场抽取,会超时
|
||||
has_ass = any(s["codec"] in cls.ASS_OK for s in subs)
|
||||
if has_ass and size_gb > config.PRE_EXTRACT_ASS_GB and 'ass' not in config.SUBTITLE_EXPORT:
|
||||
cls._raise(r, PREP, f"内嵌 ASS + {size_gb:.0f}GB 大文件,需提前抽外挂")
|
||||
r.actions.append("extract_ass")
|
||||
|
||||
cls._cache_set(path, r)
|
||||
return r
|
||||
|
||||
# ------------------------------------------------------------------ 缓存
|
||||
|
||||
@staticmethod
|
||||
def _cache_path() -> Path:
|
||||
return config.PREFLIGHT_CACHE_PATH
|
||||
|
||||
@classmethod
|
||||
def _load_cache(cls) -> dict:
|
||||
try:
|
||||
if cls._cache_data is None:
|
||||
p = cls._cache_path()
|
||||
raw = json.loads(p.read_text("utf-8")) if p.exists() else {}
|
||||
if isinstance(raw, dict) and raw.get("version") == config.PREFLIGHT_CACHE_VERSION:
|
||||
cls._cache_data = raw.get("entries", {})
|
||||
else:
|
||||
cls._cache_data = {} # 旧版本/格式不匹配,丢弃重建
|
||||
except Exception:
|
||||
cls._cache_data = {}
|
||||
return cls._cache_data
|
||||
|
||||
_cache_data = None
|
||||
|
||||
@classmethod
|
||||
def _cache_key(cls, path: Path) -> str:
|
||||
st = path.stat()
|
||||
return f"{path}|{st.st_size}|{int(st.st_mtime)}"
|
||||
|
||||
@classmethod
|
||||
def _cache_get(cls, path: Path) -> PreflightResult | None:
|
||||
try:
|
||||
entry = cls._load_cache().get(cls._cache_key(path))
|
||||
except OSError:
|
||||
return None
|
||||
if not entry:
|
||||
return None
|
||||
r = PreflightResult(verdict=entry.get("verdict", READY),
|
||||
reasons=entry.get("reasons", []),
|
||||
actions=entry.get("actions", []),
|
||||
info=entry.get("info", {}))
|
||||
return r
|
||||
|
||||
@classmethod
|
||||
def _cache_set(cls, path: Path, result: PreflightResult) -> None:
|
||||
cache = cls._load_cache()
|
||||
try:
|
||||
cache[cls._cache_key(path)] = {
|
||||
"verdict": result.verdict, "reasons": result.reasons,
|
||||
"actions": result.actions, "info": result.info,
|
||||
"ts": int(time.time()),
|
||||
}
|
||||
except OSError:
|
||||
return
|
||||
try:
|
||||
cls._cache_path().write_text(
|
||||
json.dumps({"version": config.PREFLIGHT_CACHE_VERSION, "entries": cache},
|
||||
ensure_ascii=False, indent=1),
|
||||
"utf-8")
|
||||
except Exception as e:
|
||||
log.debug(f"preflight 缓存写入失败: {e}")
|
||||
|
||||
# ------------------------------------------------------------------ 动作
|
||||
|
||||
@staticmethod
|
||||
def add_ac3_track(src: Path, dst: Path) -> Path:
|
||||
"""视频/字幕 copy,首条音轨转 AC3 5.1 并设为默认,其余音轨保留。"""
|
||||
data = FFprobeUtil.get_json(src, "-show_streams")
|
||||
audio_count = 0
|
||||
if data:
|
||||
audio_count = sum(1 for s in data.get("streams", []) if s.get("codec_type") == "audio")
|
||||
|
||||
maps = ["-map", "0:v:0", "-map", "0:a:0", "-map", "0:a:0"]
|
||||
for i in range(1, max(audio_count, 1)):
|
||||
maps += ["-map", f"0:a:{i}"]
|
||||
maps += ["-map", "0:s?"]
|
||||
|
||||
cmd = [
|
||||
"ffmpeg", "-y", "-v", "error", "-i", str(src), *maps,
|
||||
"-c:v", "copy", "-c:s", "copy",
|
||||
"-c:a", "copy",
|
||||
"-c:a:0", "ac3", "-b:a:0", "640k", "-ac:a:0", "6",
|
||||
"-metadata:s:a:0", "title=AC3 5.1",
|
||||
"-disposition:a:0", "default", "-disposition:a:1", "0",
|
||||
"-map_metadata", "0", "-map_chapters", "0",
|
||||
str(dst),
|
||||
]
|
||||
log.info(f"🎚️ 补 AC3 音轨: {src.name} → {dst.name}")
|
||||
res = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
|
||||
text=True, errors="ignore")
|
||||
if res.returncode != 0:
|
||||
tail = [line for line in (res.stderr or "").strip().splitlines() if line.strip()]
|
||||
raise RuntimeError(f"ffmpeg 失败: {tail[-1][:300] if tail else res.returncode}")
|
||||
return dst
|
||||
|
||||
@staticmethod
|
||||
def verify_ac3(path: Path) -> bool:
|
||||
data = FFprobeUtil.get_json(path, "-show_streams", "-select_streams", "a")
|
||||
if not data:
|
||||
return False
|
||||
audio = data.get("streams", [])
|
||||
if not audio:
|
||||
return False
|
||||
first = audio[0]
|
||||
is_default = bool((first.get("disposition") or {}).get("default"))
|
||||
return (first.get("codec_name") == "ac3" and is_default)
|
||||
|
||||
@classmethod
|
||||
def prepare_ac3(cls, src: Path, tmp: Path) -> Path:
|
||||
"""生成 AC3 版本 → 备份原文件 → 原子替换。返回最终路径。"""
|
||||
tmp.unlink(missing_ok=True)
|
||||
cls.add_ac3_track(src, tmp)
|
||||
if not tmp.exists() or tmp.stat().st_size == 0:
|
||||
raise RuntimeError("输出文件为空")
|
||||
if not cls.verify_ac3(tmp):
|
||||
raise RuntimeError("校验失败:首条音轨不是 AC3 或未设为默认")
|
||||
|
||||
backup_dir = src.parent / config.PREFLIGHT_BACKUP_DIRNAME
|
||||
backup_dir.mkdir(parents=True, exist_ok=True)
|
||||
backup = backup_dir / src.name
|
||||
if backup.exists():
|
||||
backup = backup_dir / f"{src.stem}.{int(time.time())}{src.suffix}"
|
||||
shutil.move(str(src), str(backup))
|
||||
os.replace(tmp, src)
|
||||
log.info(f"✅ 已替换为 AC3 版本(原文件备份: {backup})")
|
||||
return src
|
||||
|
||||
# ------------------------------------------------------------------ 报告
|
||||
|
||||
HEADERS = ["path", "verdict", "codec", "height", "mbps", "dv_profile",
|
||||
"audio_codecs", "sub_codecs", "actions", "reasons"]
|
||||
|
||||
@classmethod
|
||||
def _report_rows(cls, results: list) -> list:
|
||||
order = {BLOCKED: 0, TRANSCODE: 1, PREP: 2, READY: 3}
|
||||
rows = []
|
||||
for path, r in sorted(results, key=lambda x: (order.get(x[1].verdict, 9), str(x[0]))):
|
||||
i = r.info
|
||||
audio = "/".join(f"{a['codec']}{a['channels']}" for a in i.get("audio", []))
|
||||
subs = "/".join(sorted({s["codec"] for s in i.get("subs", [])}))
|
||||
rows.append((path, r, [
|
||||
str(path), r.verdict, i.get("codec", ""), i.get("height", ""),
|
||||
i.get("mbps", ""), i.get("dv_profile") or "",
|
||||
audio, subs, "/".join(r.actions), " | ".join(r.reasons),
|
||||
]))
|
||||
return rows
|
||||
|
||||
@staticmethod
|
||||
def _prune_reports() -> None:
|
||||
"""只保留最近 N 份报告([Compatibility] report_keep,<=0 表示不清理)。"""
|
||||
keep = config.PREFLIGHT_REPORT_KEEP
|
||||
if keep <= 0:
|
||||
return
|
||||
try:
|
||||
files = [p for p in config.PREFLIGHT_REPORT_DIR.glob("preflight-*.*")
|
||||
if p.is_file() and p.suffix.lower() in {".xlsx", ".csv"}]
|
||||
files.sort(key=lambda p: p.stat().st_mtime, reverse=True)
|
||||
except OSError:
|
||||
return
|
||||
for old in files[keep:]:
|
||||
try:
|
||||
old.unlink()
|
||||
log.debug(f"🧹 清理旧报告: {old.name}")
|
||||
except OSError as e:
|
||||
log.warning(f"⚠️ 清理旧报告失败: {old.name} -> {e}")
|
||||
|
||||
@staticmethod
|
||||
def _report_path(ext: str) -> Path:
|
||||
"""集中目录 + 时间戳:<report_dir>/preflight-YYYYmmdd-HHMMSS.<ext>"""
|
||||
report_dir = config.PREFLIGHT_REPORT_DIR
|
||||
report_dir.mkdir(parents=True, exist_ok=True)
|
||||
stamp = time.strftime("%Y%m%d-%H%M%S")
|
||||
path = report_dir / f"preflight-{stamp}.{ext}"
|
||||
n = 2
|
||||
while path.exists():
|
||||
path = report_dir / f"preflight-{stamp}-{n}.{ext}"
|
||||
n += 1
|
||||
return path
|
||||
|
||||
@classmethod
|
||||
def write_report(cls, root: Path, results: list, only_issues: bool = False) -> Path | None:
|
||||
"""results: [(path, PreflightResult)],输出 root/preflight_report.xlsx(无 openpyxl 时退回 csv)。"""
|
||||
if not config.PREFLIGHT_REPORT or not results:
|
||||
return None
|
||||
if only_issues:
|
||||
results = [(p, r) for p, r in results if r.verdict != READY]
|
||||
if not results:
|
||||
return None
|
||||
|
||||
rows = cls._report_rows(results)
|
||||
|
||||
try:
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment, Font, PatternFill
|
||||
from openpyxl.utils import get_column_letter
|
||||
except ImportError:
|
||||
log.warning("⚠️ 未安装 openpyxl,报告退回 CSV(pip install openpyxl 可启用 xlsx)")
|
||||
return cls._write_csv(root, rows)
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "preflight"
|
||||
ws.append(cls.HEADERS)
|
||||
|
||||
header_fill = PatternFill("solid", fgColor="305496")
|
||||
for cell in ws[1]:
|
||||
cell.font = Font(bold=True, color="FFFFFF")
|
||||
cell.fill = header_fill
|
||||
cell.alignment = Alignment(vertical="center")
|
||||
|
||||
fills = {
|
||||
BLOCKED: PatternFill("solid", fgColor="F8CBAD"),
|
||||
TRANSCODE: PatternFill("solid", fgColor="BDD7EE"),
|
||||
PREP: PatternFill("solid", fgColor="FFE699"),
|
||||
}
|
||||
for path, r, values in rows:
|
||||
ws.append(values)
|
||||
row_idx = ws.max_row
|
||||
if r.verdict in fills:
|
||||
for cell in ws[row_idx]:
|
||||
cell.fill = fills[r.verdict]
|
||||
|
||||
last_col = get_column_letter(len(cls.HEADERS))
|
||||
ws.auto_filter.ref = f"A1:{last_col}{ws.max_row}"
|
||||
# verdict 列(0-based colId=1)默认只勾选 PREP/BLOCKED,并把 READY 行隐藏;
|
||||
# 若整份报告全是 READY,就保持全部可见,避免打开是空表
|
||||
has_issues = any(r.verdict != READY for _, r, _ in rows)
|
||||
if has_issues:
|
||||
ws.auto_filter.add_filter_column(1, [PREP, TRANSCODE, BLOCKED])
|
||||
for offset, (_, r, _) in enumerate(rows):
|
||||
if r.verdict == READY:
|
||||
ws.row_dimensions[offset + 2].hidden = True
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
widths = {"A": 80, "B": 10, "C": 11, "D": 8, "E": 9, "F": 10,
|
||||
"G": 26, "H": 32, "I": 22, "J": 60}
|
||||
for col, width in widths.items():
|
||||
ws.column_dimensions[col].width = width
|
||||
|
||||
report = cls._report_path("xlsx")
|
||||
wb.save(report)
|
||||
cls._prune_reports()
|
||||
log.info(f"📄 兼容性报告: {report}")
|
||||
return report
|
||||
|
||||
@classmethod
|
||||
def _write_csv(cls, root: Path, rows: list) -> Path:
|
||||
report = cls._report_path("csv")
|
||||
lines = [",".join(cls.HEADERS) + "\n"]
|
||||
for _, _, values in rows:
|
||||
lines.append(",".join('"' + str(v).replace('"', '""') + '"' for v in values) + "\n")
|
||||
report.write_text("".join(lines), "utf-8")
|
||||
cls._prune_reports()
|
||||
log.info(f"📄 兼容性报告(CSV): {report}")
|
||||
return report
|
||||
|
||||
@classmethod
|
||||
def scan(cls, root: Path) -> list:
|
||||
"""check 模式:只体检不动文件。"""
|
||||
results = []
|
||||
files = [
|
||||
p for p in root.rglob("*")
|
||||
if p.is_file() and p.suffix.lower() in config.SUPPORTED_EXTS
|
||||
and not any(excl in str(p) for excl in config.EXCLUDE_DIRS)
|
||||
]
|
||||
for p in sorted(files):
|
||||
r = cls.evaluate(p)
|
||||
results.append((p, r))
|
||||
mark = {"READY": "✅", "PREP": "🟡", "TRANSCODE": "🎞️", "BLOCKED": "⛔"}.get(r.verdict, "?")
|
||||
detail = f"{r.info.get('codec')} {r.info.get('height')}p {r.info.get('mbps')}Mbps"
|
||||
log.info(f"{mark} {r.verdict:<7} {p.name} [{detail}]"
|
||||
+ (f" | {', '.join(r.reasons)}" if r.reasons else ""))
|
||||
|
||||
counts = {}
|
||||
for _, r in results:
|
||||
counts[r.verdict] = counts.get(r.verdict, 0) + 1
|
||||
log.info(f"📊 共 {len(results)} 个文件: " +
|
||||
", ".join(f"{k}={v}" for k, v in sorted(counts.items())))
|
||||
cls.write_report(root, results)
|
||||
return results
|
||||
|
||||
# ------------------------------------------------------------------ Jellyfin
|
||||
|
||||
@staticmethod
|
||||
def refresh_jellyfin() -> None:
|
||||
if not config.PREFLIGHT_REFRESH_JELLYFIN:
|
||||
return
|
||||
if not config.JELLYFIN_API_KEY:
|
||||
return
|
||||
try:
|
||||
import urllib.request
|
||||
req = urllib.request.Request(
|
||||
f"{config.JELLYFIN_URL.rstrip('/')}/Library/Refresh",
|
||||
headers={"X-Emby-Token": config.JELLYFIN_API_KEY},
|
||||
method="POST",
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
log.info(f"🎞️ 已触发 Jellyfin 库刷新(HTTP {resp.status})")
|
||||
except Exception as e:
|
||||
log.warning(f"⚠️ Jellyfin 刷新失败: {e}")
|
||||
# src/services/preflight.py
|
||||
"""入库前兼容性体检(Preflight)。
|
||||
|
||||
目标:入库后电视点开即播,服务器尽量直传不转码。
|
||||
结论四档:
|
||||
READY 直接入库,客户端直传
|
||||
PREP 轻量预处理后即可直传(补 AC3 / 抽外挂 ASS / 改默认音轨)
|
||||
TRANSCODE 不能直传,但服务端转码可正常播放(DV5、老编码、码率超限)
|
||||
BLOCKED 连转码都救不了(文件损坏、无视频轨),不入库,写报告
|
||||
"""
|
||||
|
||||
import json
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from core import config
|
||||
from core.logger import log
|
||||
from core.utils import FFprobeUtil
|
||||
|
||||
READY, PREP, TRANSCODE, BLOCKED = "READY", "PREP", "TRANSCODE", "BLOCKED"
|
||||
_ORDER = {READY: 0, PREP: 1, TRANSCODE: 2, BLOCKED: 3}
|
||||
|
||||
|
||||
@dataclass
|
||||
class PreflightResult:
|
||||
verdict: str = READY
|
||||
reasons: list = field(default_factory=list)
|
||||
actions: list = field(default_factory=list)
|
||||
info: dict = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def summary(self) -> str:
|
||||
return f"{self.verdict}" + (f" | {', '.join(self.reasons)}" if self.reasons else "")
|
||||
|
||||
|
||||
class PreflightService:
|
||||
"""ffprobe 体检 + 补 AC3 音轨 + 报告输出。"""
|
||||
|
||||
# 电视(Amlogic S905X3 + Jellyfin Android TV 0.20)实测可直传的编码
|
||||
VIDEO_OK = {"hevc", "h264"}
|
||||
SUB_OK = {
|
||||
"ass", "ssa", "subrip", "srt", "webvtt", "mov_text",
|
||||
"hdmv_pgs_subtitle", "dvd_subtitle", "dvb_subtitle", "idx",
|
||||
}
|
||||
HDR_TRANSFERS = {"smpte2084", "arib-std-b67"}
|
||||
ASS_OK = {"ass", "ssa"}
|
||||
|
||||
# ------------------------------------------------------------------ 评估
|
||||
|
||||
@classmethod
|
||||
def _raise(cls, r: PreflightResult, level: str, reason: str) -> None:
|
||||
r.reasons.append(reason)
|
||||
if _ORDER[level] > _ORDER[r.verdict]:
|
||||
r.verdict = level
|
||||
|
||||
@staticmethod
|
||||
def _primary_video(streams: list) -> dict | None:
|
||||
for s in streams:
|
||||
if s.get("codec_type") != "video":
|
||||
continue
|
||||
if (s.get("disposition") or {}).get("attached_pic"):
|
||||
continue # 封面图(mjpeg/png)
|
||||
return s
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _dv_profile(video: dict) -> int | None:
|
||||
for sd in video.get("side_data_list") or []:
|
||||
name = str(sd.get("side_data_type", "")).lower()
|
||||
if "dovi" in name or "dolby vision" in name:
|
||||
profile = sd.get("dv_profile")
|
||||
return int(profile) if profile is not None else None
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def evaluate(cls, path: Path, use_cache: bool = True) -> PreflightResult:
|
||||
cached = cls._cache_get(path) if use_cache else None
|
||||
if cached:
|
||||
return cached
|
||||
|
||||
r = PreflightResult()
|
||||
data = FFprobeUtil.get_json(path, "-show_format", "-show_streams")
|
||||
if not data:
|
||||
r.verdict, r.reasons = BLOCKED, ["ffprobe 读取失败"]
|
||||
return r
|
||||
|
||||
streams = data.get("streams", [])
|
||||
fmt = data.get("format", {})
|
||||
size_gb = int(fmt.get("size") or 0) / 1e9
|
||||
v = cls._primary_video(streams)
|
||||
if not v:
|
||||
r.verdict, r.reasons = BLOCKED, ["无主视频轨"]
|
||||
return r
|
||||
|
||||
codec = (v.get("codec_name") or "").lower()
|
||||
height = int(v.get("height") or 0)
|
||||
width = int(v.get("width") or 0)
|
||||
level = v.get("level")
|
||||
v_bitrate = int(v.get("bit_rate") or 0) or int(fmt.get("bit_rate") or 0)
|
||||
mbps = v_bitrate / 1e6
|
||||
dv_profile = cls._dv_profile(v)
|
||||
transfer = (v.get("color_transfer") or "").lower()
|
||||
|
||||
audios = []
|
||||
for s in streams:
|
||||
if s.get("codec_type") != "audio":
|
||||
continue
|
||||
audios.append({
|
||||
"codec": (s.get("codec_name") or "").lower(),
|
||||
"channels": int(s.get("channels") or 0),
|
||||
"language": (s.get("tags") or {}).get("language", ""),
|
||||
"title": (s.get("tags") or {}).get("title", ""),
|
||||
"default": bool((s.get("disposition") or {}).get("default")),
|
||||
})
|
||||
subs = [
|
||||
{"codec": (s.get("codec_name") or "").lower(),
|
||||
"language": (s.get("tags") or {}).get("language", "")}
|
||||
for s in streams if s.get("codec_type") == "subtitle"
|
||||
]
|
||||
|
||||
r.info.update(
|
||||
codec=codec, width=width, height=height, level=level,
|
||||
mbps=round(mbps, 1), dv_profile=dv_profile,
|
||||
hdr=transfer in cls.HDR_TRANSFERS, color_transfer=transfer,
|
||||
size_gb=round(size_gb, 1), audio=audios, subs=subs,
|
||||
duration=int(float(fmt.get("duration") or 0)),
|
||||
)
|
||||
|
||||
# 1. 容器
|
||||
if path.suffix.lower() not in {".mkv", ".mp4"}:
|
||||
cls._raise(r, TRANSCODE, f"容器 {path.suffix} 需重新封装或转码")
|
||||
r.actions.append("server_transcode")
|
||||
# 2. 视频编码
|
||||
if codec not in cls.VIDEO_OK:
|
||||
cls._raise(r, TRANSCODE, f"视频编码 {codec} 电视无法解码,需服务端转码")
|
||||
r.actions.append("server_transcode")
|
||||
# 3. 分辨率
|
||||
if height > 2160:
|
||||
cls._raise(r, TRANSCODE, f"{height}p 超过 4K,需服务端缩放转码")
|
||||
r.actions.append("server_transcode")
|
||||
# 4. HEVC level(153 = 5.1):仅提示,很多片源 tag 偏高但实际能解
|
||||
if codec == "hevc" and isinstance(level, int) and level > 153:
|
||||
r.reasons.append(f"HEVC level {level}(>5.1,实际解码可能仍正常)")
|
||||
# 5. Dolby Vision
|
||||
if dv_profile == 5:
|
||||
cls._raise(r, TRANSCODE, "纯 DV Profile 5 无 HDR10 兼容层,需服务端 tonemap 转码")
|
||||
r.actions.append("server_tonemap")
|
||||
elif dv_profile == 7:
|
||||
# 有 HDR10 基座:Jellyfin 会剥掉 DV 元数据后视频直传(Direct Stream),不重编码
|
||||
r.reasons.append("DV Profile 7(HDR10 基座),视频可去 DV 元数据直传")
|
||||
# 6. 码率
|
||||
if mbps > config.MAX_DIRECT_MBPS:
|
||||
cls._raise(r, TRANSCODE, f"码率 {mbps:.1f} Mbps 超过直传上限 {config.MAX_DIRECT_MBPS:g},需转码")
|
||||
r.actions.append("transcode_bitrate")
|
||||
# 7. 音频:只记录,不参与判定(默认音轨保持原样,音频是否转码交给 Jellyfin)
|
||||
# 8. 字幕编码
|
||||
# 8. 字幕编码
|
||||
bad = [s["codec"] for s in subs if s["codec"] not in cls.SUB_OK]
|
||||
if bad:
|
||||
r.reasons.append(f"未知字幕编码: {sorted(set(bad))}")
|
||||
# 9. 大文件内嵌 ASS:客户端首次播放要现场抽取,会超时
|
||||
has_ass = any(s["codec"] in cls.ASS_OK for s in subs)
|
||||
if has_ass and size_gb > config.PRE_EXTRACT_ASS_GB and 'ass' not in config.SUBTITLE_EXPORT:
|
||||
cls._raise(r, PREP, f"内嵌 ASS + {size_gb:.0f}GB 大文件,需提前抽外挂")
|
||||
r.actions.append("extract_ass")
|
||||
|
||||
cls._cache_set(path, r)
|
||||
return r
|
||||
|
||||
# ------------------------------------------------------------------ 缓存
|
||||
|
||||
@staticmethod
|
||||
def _cache_path() -> Path:
|
||||
return config.PREFLIGHT_CACHE_PATH
|
||||
|
||||
@classmethod
|
||||
def _load_cache(cls) -> dict:
|
||||
try:
|
||||
if cls._cache_data is None:
|
||||
p = cls._cache_path()
|
||||
raw = json.loads(p.read_text("utf-8")) if p.exists() else {}
|
||||
if isinstance(raw, dict) and raw.get("version") == config.PREFLIGHT_CACHE_VERSION:
|
||||
cls._cache_data = raw.get("entries", {})
|
||||
else:
|
||||
cls._cache_data = {} # 旧版本/格式不匹配,丢弃重建
|
||||
except Exception:
|
||||
cls._cache_data = {}
|
||||
return cls._cache_data
|
||||
|
||||
_cache_data = None
|
||||
|
||||
@classmethod
|
||||
def _cache_key(cls, path: Path) -> str:
|
||||
st = path.stat()
|
||||
return f"{path}|{st.st_size}|{int(st.st_mtime)}"
|
||||
|
||||
@classmethod
|
||||
def _cache_get(cls, path: Path) -> PreflightResult | None:
|
||||
try:
|
||||
entry = cls._load_cache().get(cls._cache_key(path))
|
||||
except OSError:
|
||||
return None
|
||||
if not entry:
|
||||
return None
|
||||
r = PreflightResult(verdict=entry.get("verdict", READY),
|
||||
reasons=entry.get("reasons", []),
|
||||
actions=entry.get("actions", []),
|
||||
info=entry.get("info", {}))
|
||||
return r
|
||||
|
||||
@classmethod
|
||||
def _cache_set(cls, path: Path, result: PreflightResult) -> None:
|
||||
cache = cls._load_cache()
|
||||
try:
|
||||
cache[cls._cache_key(path)] = {
|
||||
"verdict": result.verdict, "reasons": result.reasons,
|
||||
"actions": result.actions, "info": result.info,
|
||||
"ts": int(time.time()),
|
||||
}
|
||||
except OSError:
|
||||
return
|
||||
try:
|
||||
cls._cache_path().write_text(
|
||||
json.dumps({"version": config.PREFLIGHT_CACHE_VERSION, "entries": cache},
|
||||
ensure_ascii=False, indent=1),
|
||||
"utf-8")
|
||||
except Exception as e:
|
||||
log.debug(f"preflight 缓存写入失败: {e}")
|
||||
|
||||
# ------------------------------------------------------------------ 报告
|
||||
|
||||
HEADERS = ["path", "verdict", "codec", "height", "mbps", "dv_profile",
|
||||
"audio_codecs", "sub_codecs", "actions", "reasons"]
|
||||
|
||||
@classmethod
|
||||
def _report_rows(cls, results: list) -> list:
|
||||
order = {BLOCKED: 0, TRANSCODE: 1, PREP: 2, READY: 3}
|
||||
rows = []
|
||||
for path, r in sorted(results, key=lambda x: (order.get(x[1].verdict, 9), str(x[0]))):
|
||||
i = r.info
|
||||
audio = "/".join(f"{a['codec']}{a['channels']}" for a in i.get("audio", []))
|
||||
subs = "/".join(sorted({s["codec"] for s in i.get("subs", [])}))
|
||||
rows.append((path, r, [
|
||||
str(path), r.verdict, i.get("codec", ""), i.get("height", ""),
|
||||
i.get("mbps", ""), i.get("dv_profile") or "",
|
||||
audio, subs, "/".join(r.actions), " | ".join(r.reasons),
|
||||
]))
|
||||
return rows
|
||||
|
||||
@staticmethod
|
||||
def _prune_reports() -> None:
|
||||
"""只保留最近 N 份报告([Compatibility] report_keep,<=0 表示不清理)。"""
|
||||
keep = config.PREFLIGHT_REPORT_KEEP
|
||||
if keep <= 0:
|
||||
return
|
||||
try:
|
||||
files = [p for p in config.PREFLIGHT_REPORT_DIR.glob("preflight-*.*")
|
||||
if p.is_file() and p.suffix.lower() in {".xlsx", ".csv"}]
|
||||
files.sort(key=lambda p: p.stat().st_mtime, reverse=True)
|
||||
except OSError:
|
||||
return
|
||||
for old in files[keep:]:
|
||||
try:
|
||||
old.unlink()
|
||||
log.debug(f"🧹 清理旧报告: {old.name}")
|
||||
except OSError as e:
|
||||
log.warning(f"⚠️ 清理旧报告失败: {old.name} -> {e}")
|
||||
|
||||
@staticmethod
|
||||
def _report_path(ext: str) -> Path:
|
||||
"""集中目录 + 时间戳:<report_dir>/preflight-YYYYmmdd-HHMMSS.<ext>"""
|
||||
report_dir = config.PREFLIGHT_REPORT_DIR
|
||||
report_dir.mkdir(parents=True, exist_ok=True)
|
||||
stamp = time.strftime("%Y%m%d-%H%M%S")
|
||||
path = report_dir / f"preflight-{stamp}.{ext}"
|
||||
n = 2
|
||||
while path.exists():
|
||||
path = report_dir / f"preflight-{stamp}-{n}.{ext}"
|
||||
n += 1
|
||||
return path
|
||||
|
||||
@classmethod
|
||||
def write_report(cls, root: Path, results: list, only_issues: bool = False) -> Path | None:
|
||||
"""results: [(path, PreflightResult)],输出 root/preflight_report.xlsx(无 openpyxl 时退回 csv)。"""
|
||||
if not config.PREFLIGHT_REPORT or not results:
|
||||
return None
|
||||
if only_issues:
|
||||
results = [(p, r) for p, r in results if r.verdict != READY]
|
||||
if not results:
|
||||
return None
|
||||
|
||||
rows = cls._report_rows(results)
|
||||
|
||||
try:
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment, Font, PatternFill
|
||||
from openpyxl.utils import get_column_letter
|
||||
except ImportError:
|
||||
log.warning("⚠️ 未安装 openpyxl,报告退回 CSV(pip install openpyxl 可启用 xlsx)")
|
||||
return cls._write_csv(root, rows)
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "preflight"
|
||||
ws.append(cls.HEADERS)
|
||||
|
||||
header_fill = PatternFill("solid", fgColor="305496")
|
||||
for cell in ws[1]:
|
||||
cell.font = Font(bold=True, color="FFFFFF")
|
||||
cell.fill = header_fill
|
||||
cell.alignment = Alignment(vertical="center")
|
||||
|
||||
fills = {
|
||||
BLOCKED: PatternFill("solid", fgColor="F8CBAD"),
|
||||
TRANSCODE: PatternFill("solid", fgColor="BDD7EE"),
|
||||
PREP: PatternFill("solid", fgColor="FFE699"),
|
||||
}
|
||||
for path, r, values in rows:
|
||||
ws.append(values)
|
||||
row_idx = ws.max_row
|
||||
if r.verdict in fills:
|
||||
for cell in ws[row_idx]:
|
||||
cell.fill = fills[r.verdict]
|
||||
|
||||
last_col = get_column_letter(len(cls.HEADERS))
|
||||
ws.auto_filter.ref = f"A1:{last_col}{ws.max_row}"
|
||||
# verdict 列(0-based colId=1)默认只勾选 PREP/BLOCKED,并把 READY 行隐藏;
|
||||
# 若整份报告全是 READY,就保持全部可见,避免打开是空表
|
||||
has_issues = any(r.verdict != READY for _, r, _ in rows)
|
||||
if has_issues:
|
||||
ws.auto_filter.add_filter_column(1, [PREP, TRANSCODE, BLOCKED])
|
||||
for offset, (_, r, _) in enumerate(rows):
|
||||
if r.verdict == READY:
|
||||
ws.row_dimensions[offset + 2].hidden = True
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
widths = {"A": 80, "B": 10, "C": 11, "D": 8, "E": 9, "F": 10,
|
||||
"G": 26, "H": 32, "I": 22, "J": 60}
|
||||
for col, width in widths.items():
|
||||
ws.column_dimensions[col].width = width
|
||||
|
||||
report = cls._report_path("xlsx")
|
||||
wb.save(report)
|
||||
cls._prune_reports()
|
||||
log.info(f"📄 兼容性报告: {report}")
|
||||
return report
|
||||
|
||||
@classmethod
|
||||
def _write_csv(cls, root: Path, rows: list) -> Path:
|
||||
report = cls._report_path("csv")
|
||||
lines = [",".join(cls.HEADERS) + "\n"]
|
||||
for _, _, values in rows:
|
||||
lines.append(",".join('"' + str(v).replace('"', '""') + '"' for v in values) + "\n")
|
||||
report.write_text("".join(lines), "utf-8")
|
||||
cls._prune_reports()
|
||||
log.info(f"📄 兼容性报告(CSV): {report}")
|
||||
return report
|
||||
|
||||
@classmethod
|
||||
def scan(cls, root: Path) -> list:
|
||||
"""check 模式:只体检不动文件。"""
|
||||
results = []
|
||||
files = [
|
||||
p for p in root.rglob("*")
|
||||
if p.is_file() and p.suffix.lower() in config.SUPPORTED_EXTS
|
||||
and not any(excl in str(p) for excl in config.EXCLUDE_DIRS)
|
||||
]
|
||||
for p in sorted(files):
|
||||
r = cls.evaluate(p)
|
||||
results.append((p, r))
|
||||
mark = {"READY": "✅", "PREP": "🟡", "TRANSCODE": "🎞️", "BLOCKED": "⛔"}.get(r.verdict, "?")
|
||||
detail = f"{r.info.get('codec')} {r.info.get('height')}p {r.info.get('mbps')}Mbps"
|
||||
log.info(f"{mark} {r.verdict:<7} {p.name} [{detail}]"
|
||||
+ (f" | {', '.join(r.reasons)}" if r.reasons else ""))
|
||||
|
||||
counts = {}
|
||||
for _, r in results:
|
||||
counts[r.verdict] = counts.get(r.verdict, 0) + 1
|
||||
log.info(f"📊 共 {len(results)} 个文件: " +
|
||||
", ".join(f"{k}={v}" for k, v in sorted(counts.items())))
|
||||
cls.write_report(root, results)
|
||||
return results
|
||||
|
||||
|
||||
Reference in New Issue
Block a user