# 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 音轨 + 报告输出。""" # 电视能力边界全部来自 config.ini [Compatibility]: # direct_video_codecs / direct_sub_codecs / ass_codecs / hdr_transfers # direct_containers / max_height # 换电视或换播放器时改配置即可,不用动代码。 # 历史实测(Amlogic S905X3 + Jellyfin Android TV): # HEVC / H.264 / VC-1(的士速递4)/ MPEG-2(功夫、非洲和尚)可 DirectPlay; # MPEG-4 实测被转码(花儿与少年 S03),故缺省不列入。 # ------------------------------------------------------------------ 评估 @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 config.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 config.DIRECT_CONTAINERS: cls._raise(r, TRANSCODE, f"容器 {path.suffix} 需重新封装或转码") r.actions.append("server_transcode") # 2. 视频编码 if codec not in config.DIRECT_VIDEO_CODECS: cls._raise(r, TRANSCODE, f"视频编码 {codec} 电视无法解码,需服务端转码") r.actions.append("server_transcode") # 3. 分辨率 if height > config.MAX_HEIGHT: cls._raise(r, TRANSCODE, f"{height}p 超过 {config.MAX_HEIGHT}p,需服务端缩放转码") 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 config.DIRECT_SUB_CODECS] if bad: r.reasons.append(f"未知字幕编码: {sorted(set(bad))}") # 9. 大文件内嵌 ASS:客户端首次播放要现场抽取,会超时 has_ass = any(s["codec"] in config.ASS_CODECS 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: """集中目录 + 时间戳:/preflight-YYYYmmdd-HHMMSS.""" 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