feat(preflight): 入库前兼容性体检 + 补 AC3 + check 模式
新增 services/preflight.py:ffprobe 判定 READY/PREP/BLOCKED - 视频 hevc/h264、≤2160p、HEVC level 仅提示;DV5 BLOCKED / DV7 人工确认 - 音频直传白名单走 [Compatibility] direct_audio(默认含 mp2) - 默认音轨不可直传时提示;无直传轨时 PREP(add_ac3) - 内嵌 ASS + 大文件且 export 不含 ass 时 PREP(extract_ass) - add_ac3_track 保留全部音轨、首轨转 AC3 5.1 并设默认;prepare_ac3 备份原文件后原子替换 - TaskManager 新增 prepare 阶段(阶段 0),pipeline 在生成计划时先体检 - main.py 新增 check 模式:全库只体检、输出 preflight_report.csv - preflight 结果带版本化缓存(preflight_cache.json),避免重复 ffprobe
This commit is contained in:
@@ -73,6 +73,24 @@ refresh_jellyfin = true
|
|||||||
url = http://127.0.0.1:8096
|
url = http://127.0.0.1:8096
|
||||||
api_key =
|
api_key =
|
||||||
|
|
||||||
|
[Compatibility]
|
||||||
|
# 电视直传码率上限(1x1 WiFi 实测 ~70Mbps)
|
||||||
|
max_direct_mbps = 70
|
||||||
|
# 超过该体积且含内嵌 ASS 时,提前抽外挂字幕
|
||||||
|
pre_extract_ass_gb = 15
|
||||||
|
# 没有可直传音轨时自动补 AC3(先保持关闭,观察后再开)
|
||||||
|
auto_add_ac3 = false
|
||||||
|
# 大文件自动抽 ASS(当前 export=ass 时已天然满足)
|
||||||
|
auto_extract_ass = true
|
||||||
|
# 每次扫描是否输出 preflight_report.csv
|
||||||
|
write_report = true
|
||||||
|
# 补轨替换后是否触发 Jellyfin 刷新
|
||||||
|
refresh_jellyfin_after_prep = true
|
||||||
|
# 补轨前的原文件备份目录(相对视频所在目录)
|
||||||
|
backup_dir = .preflight_backup
|
||||||
|
# 电视能直传的音频编码(逗号分隔,按你的电视/客户端实测调整)
|
||||||
|
direct_audio = ac3,eac3,dts,truehd,aac,mp3,mp2,flac,opus,vorbis,pcm_s16le,pcm_s24le,pcm_s32le,pcm_bluray,mlp
|
||||||
|
|
||||||
[System]
|
[System]
|
||||||
log_file_path = media_manager.log
|
log_file_path = media_manager.log
|
||||||
tmdb_cache_path = tmdb_data.json
|
tmdb_cache_path = tmdb_data.json
|
||||||
@@ -164,6 +182,20 @@ REFRESH_JELLYFIN = _parser.getboolean('Archive', 'refresh_jellyfin', fallback=Tr
|
|||||||
JELLYFIN_URL = _parser.get('Jellyfin', 'url', fallback='http://127.0.0.1:8096').strip() or 'http://127.0.0.1:8096'
|
JELLYFIN_URL = _parser.get('Jellyfin', 'url', fallback='http://127.0.0.1:8096').strip() or 'http://127.0.0.1:8096'
|
||||||
JELLYFIN_API_KEY = _parser.get('Jellyfin', 'api_key', fallback='').strip()
|
JELLYFIN_API_KEY = _parser.get('Jellyfin', 'api_key', fallback='').strip()
|
||||||
|
|
||||||
|
# 7.5 入库前兼容性检查
|
||||||
|
MAX_DIRECT_MBPS = _parser.getfloat('Compatibility', 'max_direct_mbps', fallback=70.0)
|
||||||
|
PRE_EXTRACT_ASS_GB = _parser.getfloat('Compatibility', 'pre_extract_ass_gb', fallback=15.0)
|
||||||
|
AUTO_ADD_AC3 = _parser.getboolean('Compatibility', 'auto_add_ac3', fallback=False)
|
||||||
|
AUTO_EXTRACT_ASS = _parser.getboolean('Compatibility', 'auto_extract_ass', fallback=True)
|
||||||
|
PREFLIGHT_REPORT = _parser.getboolean('Compatibility', 'write_report', fallback=True)
|
||||||
|
PREFLIGHT_REFRESH_JELLYFIN = _parser.getboolean('Compatibility', 'refresh_jellyfin_after_prep', fallback=True)
|
||||||
|
PREFLIGHT_BACKUP_DIRNAME = _parser.get('Compatibility', 'backup_dir', fallback='.preflight_backup').strip() or '.preflight_backup'
|
||||||
|
DIRECT_AUDIO_CODECS = _csv_set(
|
||||||
|
'Compatibility', 'direct_audio',
|
||||||
|
fallback='ac3,eac3,dts,truehd,aac,mp3,mp2,flac,opus,vorbis,pcm_s16le,pcm_s24le,pcm_s32le,pcm_bluray,mlp')
|
||||||
|
PREFLIGHT_CACHE_PATH = BASE_DIR / 'preflight_cache.json'
|
||||||
|
PREFLIGHT_CACHE_VERSION = 2
|
||||||
|
|
||||||
# 8. 系统与日志路径
|
# 8. 系统与日志路径
|
||||||
_raw_log_path = _parser.get('System', 'log_file_path', fallback='media_manager.log')
|
_raw_log_path = _parser.get('System', 'log_file_path', fallback='media_manager.log')
|
||||||
LOG_FILE_PATH = BASE_DIR / _raw_log_path if not os.path.isabs(_raw_log_path) else Path(_raw_log_path)
|
LOG_FILE_PATH = BASE_DIR / _raw_log_path if not os.path.isabs(_raw_log_path) else Path(_raw_log_path)
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ from services.parser import ParserService
|
|||||||
from services.subtitle import SubtitleService
|
from services.subtitle import SubtitleService
|
||||||
from services.metadata import MetadataService
|
from services.metadata import MetadataService
|
||||||
from services.renamer import RenamerService
|
from services.renamer import RenamerService
|
||||||
|
from services.preflight import PreflightService, BLOCKED
|
||||||
|
|
||||||
class MediaPipeline:
|
class MediaPipeline:
|
||||||
"""中央流水线协调器:接管扫描、判定与防爆防撞逻辑"""
|
"""中央流水线协调器:接管扫描、判定与防爆防撞逻辑"""
|
||||||
@@ -23,6 +24,7 @@ class MediaPipeline:
|
|||||||
self.media_types_by_root = {}
|
self.media_types_by_root = {}
|
||||||
self.tv_episode_tracker = {}
|
self.tv_episode_tracker = {}
|
||||||
self.valid_files = []
|
self.valid_files = []
|
||||||
|
self.preflight = []
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
self._analyze_files()
|
self._analyze_files()
|
||||||
@@ -31,6 +33,7 @@ class MediaPipeline:
|
|||||||
return
|
return
|
||||||
|
|
||||||
self._generate_plan()
|
self._generate_plan()
|
||||||
|
PreflightService.write_report(self.target_dir, self.preflight)
|
||||||
|
|
||||||
if not self.task_mgr.has_tasks():
|
if not self.task_mgr.has_tasks():
|
||||||
if not self.auto_execute: log.info("✨ 您的媒体库目前处于完美状态,无需任何物理变更。")
|
if not self.auto_execute: log.info("✨ 您的媒体库目前处于完美状态,无需任何物理变更。")
|
||||||
@@ -38,7 +41,10 @@ class MediaPipeline:
|
|||||||
|
|
||||||
if self.task_mgr.preview_and_confirm(self.auto_execute):
|
if self.task_mgr.preview_and_confirm(self.auto_execute):
|
||||||
if not self.auto_execute: log.info("⚙️ 正在执行物理任务...")
|
if not self.auto_execute: log.info("⚙️ 正在执行物理任务...")
|
||||||
|
had_prepare = bool(self.task_mgr.tasks.get('prepare'))
|
||||||
self.task_mgr.execute()
|
self.task_mgr.execute()
|
||||||
|
if had_prepare:
|
||||||
|
PreflightService.refresh_jellyfin()
|
||||||
log.info("🎉 流水线操作圆满落地!")
|
log.info("🎉 流水线操作圆满落地!")
|
||||||
elif not self.auto_execute:
|
elif not self.auto_execute:
|
||||||
log.info("💤 任务已由用户取消。")
|
log.info("💤 任务已由用户取消。")
|
||||||
@@ -50,6 +56,10 @@ class MediaPipeline:
|
|||||||
for f in files_to_process:
|
for f in files_to_process:
|
||||||
if f.is_file() and f.suffix.lower() in config.SUPPORTED_EXTS:
|
if f.is_file() and f.suffix.lower() in config.SUPPORTED_EXTS:
|
||||||
|
|
||||||
|
# 跳过隐藏目录(如 .preflight_backup 备份、.git 等)
|
||||||
|
if any(part.startswith('.') for part in f.relative_to(self.target_dir).parts):
|
||||||
|
continue
|
||||||
|
|
||||||
# 黑名单拦截
|
# 黑名单拦截
|
||||||
if any(excl in str(f) for excl in config.EXCLUDE_DIRS):
|
if any(excl in str(f) for excl in config.EXCLUDE_DIRS):
|
||||||
log.debug(f"🛑 [黑名单拦截] 命中排除规则,跳过扫描: {f.parent.name}/{f.name}")
|
log.debug(f"🛑 [黑名单拦截] 命中排除规则,跳过扫描: {f.parent.name}/{f.name}")
|
||||||
@@ -84,8 +94,29 @@ class MediaPipeline:
|
|||||||
if m_type == "movie": dir_video_counts[f.parent] += 1
|
if m_type == "movie": dir_video_counts[f.parent] += 1
|
||||||
|
|
||||||
for f, m_type, title, year, season_num, target_season_folder, root_dir_path, target_root_folder in self.valid_files:
|
for f, m_type, title, year, season_num, target_season_folder, root_dir_path, target_root_folder in self.valid_files:
|
||||||
|
# 🧪 入库前体检:能否在电视上直传
|
||||||
|
pf = PreflightService.evaluate(f)
|
||||||
|
self.preflight.append((f, pf))
|
||||||
|
if pf.verdict == BLOCKED:
|
||||||
|
log.error(f"⛔ 无法直传,跳过入库: {f.name} | {'; '.join(pf.reasons)}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
audio_tag = None
|
||||||
|
if 'add_ac3' in pf.actions:
|
||||||
|
if config.AUTO_ADD_AC3:
|
||||||
|
tmp = f.with_name(f".{f.stem}.ac3prep{f.suffix}")
|
||||||
|
self.task_mgr.add_prepare(
|
||||||
|
f"[补 AC3 音轨] {f.name}",
|
||||||
|
PreflightService.prepare_ac3,
|
||||||
|
(f, tmp),
|
||||||
|
)
|
||||||
|
audio_tag = 'AC3.5.1'
|
||||||
|
else:
|
||||||
|
log.warning(f"🟡 [需要补 AC3] {f.name} | auto_add_ac3=false,本次仅提示")
|
||||||
|
|
||||||
is_multi = (m_type == "movie" and dir_video_counts.get(f.parent, 0) > 1)
|
is_multi = (m_type == "movie" and dir_video_counts.get(f.parent, 0) > 1)
|
||||||
target_stem, folder_name = ParserService.get_target_info(f, m_type, title, year, season_num, is_multi)
|
target_stem, folder_name = ParserService.get_target_info(
|
||||||
|
f, m_type, title, year, season_num, is_multi, audio_tag=audio_tag)
|
||||||
|
|
||||||
# 集数防撞防爆锁
|
# 集数防撞防爆锁
|
||||||
if m_type == "tv":
|
if m_type == "tv":
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ from services.fileops import FileOpsService
|
|||||||
class TaskManager:
|
class TaskManager:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.tasks = {
|
self.tasks = {
|
||||||
'extract': [], 'clean': [], 'rename_file': [],
|
'prepare': [], 'extract': [], 'clean': [], 'rename_file': [],
|
||||||
'rename_season_dir': [], 'rename_root_dir': []
|
'rename_season_dir': [], 'rename_root_dir': []
|
||||||
}
|
}
|
||||||
self.dir_renames = set()
|
self.dir_renames = set()
|
||||||
@@ -55,6 +55,7 @@ class TaskManager:
|
|||||||
self.claimants[str(final_path.resolve())] = source_name
|
self.claimants[str(final_path.resolve())] = source_name
|
||||||
return final_path
|
return final_path
|
||||||
|
|
||||||
|
def add_prepare(self, desc, func, args): self.tasks['prepare'].append((desc, func, args))
|
||||||
def add_extract(self, desc, func, args): self.tasks['extract'].append((desc, func, args))
|
def add_extract(self, desc, func, args): self.tasks['extract'].append((desc, func, args))
|
||||||
def add_clean(self, desc, func, args): self.tasks['clean'].append((desc, func, args))
|
def add_clean(self, desc, func, args): self.tasks['clean'].append((desc, func, args))
|
||||||
def add_file_rename(self, desc, func, args): self.tasks['rename_file'].append((desc, func, args))
|
def add_file_rename(self, desc, func, args): self.tasks['rename_file'].append((desc, func, args))
|
||||||
@@ -77,6 +78,7 @@ class TaskManager:
|
|||||||
log.info("==================== 待执行任务预览 ====================")
|
log.info("==================== 待执行任务预览 ====================")
|
||||||
|
|
||||||
labels = [
|
labels = [
|
||||||
|
('prepare', '🧪 阶段 0: 入库前预处理(补音轨/抽字幕)'),
|
||||||
('extract', '🛠️ 阶段 1: 提取内置文本字幕'),
|
('extract', '🛠️ 阶段 1: 提取内置文本字幕'),
|
||||||
('clean', '🧹 阶段 2: 清理元数据广告'),
|
('clean', '🧹 阶段 2: 清理元数据广告'),
|
||||||
('rename_file', '📄 阶段 3: 视频与外挂字幕规范化重命名'),
|
('rename_file', '📄 阶段 3: 视频与外挂字幕规范化重命名'),
|
||||||
@@ -111,7 +113,7 @@ class TaskManager:
|
|||||||
log.warning("⛔ 无效输入:请输入 y(执行) 或 n/q(取消)")
|
log.warning("⛔ 无效输入:请输入 y(执行) 或 n/q(取消)")
|
||||||
|
|
||||||
def execute(self):
|
def execute(self):
|
||||||
stages = ['extract', 'clean', 'rename_file', 'rename_season_dir', 'rename_root_dir']
|
stages = ['prepare', 'extract', 'clean', 'rename_file', 'rename_season_dir', 'rename_root_dir']
|
||||||
for cat in stages:
|
for cat in stages:
|
||||||
if not self.tasks[cat]: continue
|
if not self.tasks[cat]: continue
|
||||||
for desc, func, arg in self.tasks[cat]:
|
for desc, func, arg in self.tasks[cat]:
|
||||||
|
|||||||
+7
-1
@@ -8,11 +8,12 @@ from core import config
|
|||||||
from core.shell import check_dependencies
|
from core.shell import check_dependencies
|
||||||
from core.exceptions import MediaDependencyError
|
from core.exceptions import MediaDependencyError
|
||||||
from core.pipeline import MediaPipeline # 💡 引入高度封装的管道中枢
|
from core.pipeline import MediaPipeline # 💡 引入高度封装的管道中枢
|
||||||
|
from services.preflight import PreflightService
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = argparse.ArgumentParser(description="🎬 流媒体高级自动化管理工具")
|
parser = argparse.ArgumentParser(description="🎬 流媒体高级自动化管理工具")
|
||||||
parser.add_argument("mode", nargs='?', default=config.DEFAULT_MODE,
|
parser.add_argument("mode", nargs='?', default=config.DEFAULT_MODE,
|
||||||
choices=["manual", "auto", "clean-ads", "extract-subs", "watch"],
|
choices=["manual", "auto", "clean-ads", "extract-subs", "watch", "check"],
|
||||||
help=f"运行模式(默认取 config.ini [Run] default_mode = {config.DEFAULT_MODE})")
|
help=f"运行模式(默认取 config.ini [Run] default_mode = {config.DEFAULT_MODE})")
|
||||||
parser.add_argument("-p", "--path", default=config.DEFAULT_PATH,
|
parser.add_argument("-p", "--path", default=config.DEFAULT_PATH,
|
||||||
help="扫描目录(默认取 config.ini [Run] default_path,留空为当前目录)")
|
help="扫描目录(默认取 config.ini [Run] default_path,留空为当前目录)")
|
||||||
@@ -32,6 +33,11 @@ def main():
|
|||||||
log.info(f"🚀 启动模式: [{args.mode.upper()}] | 扫描目标: {target_dir}")
|
log.info(f"🚀 启动模式: [{args.mode.upper()}] | 扫描目标: {target_dir}")
|
||||||
log.debug(f"字幕导出格式: {sorted(config.SUBTITLE_EXPORT)} | 内嵌优先: {config.PREFER_INTERNAL}")
|
log.debug(f"字幕导出格式: {sorted(config.SUBTITLE_EXPORT)} | 内嵌优先: {config.PREFER_INTERNAL}")
|
||||||
|
|
||||||
|
# 🧪 只体检不动手:输出 preflight_report.csv
|
||||||
|
if args.mode == "check":
|
||||||
|
PreflightService.scan(target_dir)
|
||||||
|
return
|
||||||
|
|
||||||
if args.mode == "watch":
|
if args.mode == "watch":
|
||||||
try:
|
try:
|
||||||
from core.watcher import start_watch_daemon
|
from core.watcher import start_watch_daemon
|
||||||
|
|||||||
@@ -74,7 +74,7 @@ class ParserService:
|
|||||||
return m_type, title, year, season_num, target_season_folder, root_dir_path, f"{title.replace('.', ' ')} ({year})"
|
return m_type, title, year, season_num, target_season_folder, root_dir_path, f"{title.replace('.', ' ')} ({year})"
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_target_info(f_path: Path, m_type: str, title: str, year: str, season_num: str, is_multi_version: bool = False):
|
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):
|
||||||
tags = MediaInfoService.get_scene_tags(f_path)
|
tags = MediaInfoService.get_scene_tags(f_path)
|
||||||
tmdb = TMDBService.search_media(title, year, m_type, season_num)
|
tmdb = TMDBService.search_media(title, year, m_type, season_num)
|
||||||
|
|
||||||
@@ -87,7 +87,9 @@ class ParserService:
|
|||||||
tid = f"[tmdbid-{tmdb['tmdb_id']}]" if (tmdb and config.INCLUDE_TMDB_ID) else ""
|
tid = f"[tmdbid-{tmdb['tmdb_id']}]" if (tmdb and config.INCLUDE_TMDB_ID) else ""
|
||||||
|
|
||||||
source = "BluRay.REMUX" if tags['is_remux'] else "WEB-DL"
|
source = "BluRay.REMUX" if tags['is_remux'] else "WEB-DL"
|
||||||
tech = f"{tags['res']}.{source}.{tags['v_codec']}.{tags['bits']}.{tags['a_info']}"
|
# 预补 AC3 时,命名按处理后的音轨来(避免写入真实文件不存在的音轨)
|
||||||
|
audio_info = audio_tag or tags['a_info']
|
||||||
|
tech = f"{tags['res']}.{source}.{tags['v_codec']}.{tags['bits']}.{audio_info}"
|
||||||
|
|
||||||
target_folder = f"{title.replace('.', ' ')} ({year}) {tid}".strip()
|
target_folder = f"{title.replace('.', ' ')} ({year}) {tid}".strip()
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,372 @@
|
|||||||
|
# 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}")
|
||||||
Reference in New Issue
Block a user