# src/services/preflight.py """入库前兼容性体检(Preflight)。 目标:入库后电视点开即播,服务器尽量直传不转码。 结论三档: READY 直接入库 PREP 需要前置处理(补 AC3 / 提前抽外挂 ASS),处理后再入库 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, BLOCKED = "READY", "PREP", "BLOCKED" _ORDER = {READY: 0, PREP: 1, BLOCKED: 2} @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, BLOCKED, f"容器 {path.suffix} 不支持") # 2. 视频编码 if codec not in cls.VIDEO_OK: cls._raise(r, BLOCKED, f"视频编码 {codec} 电视无法解码") # 3. 分辨率 if height > 2160: cls._raise(r, BLOCKED, f"{height}p 超过 4K 上限") # 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, BLOCKED, "纯 Dolby Vision Profile 5,无 HDR10 兼容层") elif dv_profile == 7: cls._raise(r, PREP, "DV Profile 7(增强层),需人工确认") r.actions.append("manual_review") # 6. 码率 if mbps > config.MAX_DIRECT_MBPS: cls._raise(r, PREP, f"码率 {mbps:.1f} Mbps 超过直传上限 {config.MAX_DIRECT_MBPS:g}") r.actions.append("transcode_or_replace") # 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 # ------------------------------------------------------------------ 报告 @classmethod def write_report(cls, root: Path, results: list) -> Path | None: """results: [(path, PreflightResult)],输出 root/preflight_report.csv""" if not config.PREFLIGHT_REPORT or not results: return None report = root / "preflight_report.csv" header = "path,verdict,codec,height,mbps,dv_profile,audio_codecs,sub_codecs,actions,reasons\n" lines = [header] for path, r in results: 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", [])})) row = [ 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), ] lines.append(",".join('"' + str(c).replace('"', '""') + '"' for c in row) + "\n") report.write_text("".join(lines), "utf-8") log.info(f"📄 兼容性报告: {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": "🟡", "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}")