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:
@@ -78,22 +78,14 @@ api_key =
|
|||||||
max_direct_mbps = 70
|
max_direct_mbps = 70
|
||||||
# 超过该体积且含内嵌 ASS 时,提前抽外挂字幕
|
# 超过该体积且含内嵌 ASS 时,提前抽外挂字幕
|
||||||
pre_extract_ass_gb = 15
|
pre_extract_ass_gb = 15
|
||||||
# 没有可直传音轨时自动补 AC3(先保持关闭,观察后再开)
|
|
||||||
auto_add_ac3 = false
|
|
||||||
# 大文件自动抽 ASS(当前 export=ass 时已天然满足)
|
# 大文件自动抽 ASS(当前 export=ass 时已天然满足)
|
||||||
auto_extract_ass = true
|
auto_extract_ass = true
|
||||||
# 每次扫描是否输出 preflight_report.csv
|
# 每次扫描是否输出体检报告
|
||||||
write_report = true
|
write_report = true
|
||||||
# 补轨替换后是否触发 Jellyfin 刷新
|
|
||||||
refresh_jellyfin_after_prep = true
|
|
||||||
# 补轨前的原文件备份目录(相对视频所在目录)
|
|
||||||
backup_dir = .preflight_backup
|
|
||||||
# 体检报告集中存放目录(每次生成带时间戳 xlsx)
|
# 体检报告集中存放目录(每次生成带时间戳 xlsx)
|
||||||
report_dir = /hdd/sda1/Quark-Down/_reports
|
report_dir = /hdd/sda1/Quark-Down/_reports
|
||||||
# 报告保留份数(<=0 表示不清理)
|
# 报告保留份数(<=0 表示不清理)
|
||||||
report_keep = 6
|
report_keep = 6
|
||||||
# 电视能直传的音频编码(逗号分隔,按你的电视/客户端实测调整)
|
|
||||||
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
|
||||||
@@ -189,14 +181,8 @@ JELLYFIN_API_KEY = _parser.get('Jellyfin', 'api_key', fallback='').strip()
|
|||||||
# 7.5 入库前兼容性检查
|
# 7.5 入库前兼容性检查
|
||||||
MAX_DIRECT_MBPS = _parser.getfloat('Compatibility', 'max_direct_mbps', fallback=70.0)
|
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)
|
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)
|
AUTO_EXTRACT_ASS = _parser.getboolean('Compatibility', 'auto_extract_ass', fallback=True)
|
||||||
PREFLIGHT_REPORT = _parser.getboolean('Compatibility', 'write_report', 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_PATH = BASE_DIR / 'preflight_cache.json'
|
||||||
PREFLIGHT_CACHE_VERSION = 3
|
PREFLIGHT_CACHE_VERSION = 3
|
||||||
PREFLIGHT_REPORT_DIR = Path(
|
PREFLIGHT_REPORT_DIR = Path(
|
||||||
|
|||||||
@@ -43,10 +43,7 @@ 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("💤 任务已由用户取消。")
|
||||||
@@ -103,22 +100,9 @@ class MediaPipeline:
|
|||||||
log.error(f"⛔ 无法直传,跳过入库: {f.name} | {'; '.join(pf.reasons)}")
|
log.error(f"⛔ 无法直传,跳过入库: {f.name} | {'; '.join(pf.reasons)}")
|
||||||
continue
|
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(
|
target_stem, folder_name = ParserService.get_target_info(
|
||||||
f, m_type, title, year, season_num, is_multi, audio_tag=audio_tag)
|
f, m_type, title, year, season_num, is_multi)
|
||||||
|
|
||||||
# 集数防撞防爆锁
|
# 集数防撞防爆锁
|
||||||
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 = {
|
||||||
'prepare': [], 'extract': [], 'clean': [], 'rename_file': [],
|
'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,7 +55,6 @@ 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))
|
||||||
@@ -78,7 +77,6 @@ class TaskManager:
|
|||||||
log.info("==================== 待执行任务预览 ====================")
|
log.info("==================== 待执行任务预览 ====================")
|
||||||
|
|
||||||
labels = [
|
labels = [
|
||||||
('prepare', '🧪 阶段 0: 入库前预处理(补音轨/抽字幕)'),
|
|
||||||
('extract', '🛠️ 阶段 1: 提取内置文本字幕'),
|
('extract', '🛠️ 阶段 1: 提取内置文本字幕'),
|
||||||
('clean', '🧹 阶段 2: 清理元数据广告'),
|
('clean', '🧹 阶段 2: 清理元数据广告'),
|
||||||
('rename_file', '📄 阶段 3: 视频与外挂字幕规范化重命名'),
|
('rename_file', '📄 阶段 3: 视频与外挂字幕规范化重命名'),
|
||||||
@@ -113,7 +111,7 @@ class TaskManager:
|
|||||||
log.warning("⛔ 无效输入:请输入 y(执行) 或 n/q(取消)")
|
log.warning("⛔ 无效输入:请输入 y(执行) 或 n/q(取消)")
|
||||||
|
|
||||||
def execute(self):
|
def execute(self):
|
||||||
stages = ['prepare', 'extract', 'clean', 'rename_file', 'rename_season_dir', 'rename_root_dir']
|
stages = ['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]:
|
||||||
|
|||||||
@@ -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, 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)
|
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,9 +87,7 @@ 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"
|
||||||
# 预补 AC3 时,命名按处理后的音轨来(避免写入真实文件不存在的音轨)
|
tech = f"{tags['res']}.{source}.{tags['v_codec']}.{tags['bits']}.{tags['a_info']}"
|
||||||
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()
|
||||||
|
|
||||||
|
|||||||
@@ -10,9 +10,6 @@
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import os
|
|
||||||
import shutil
|
|
||||||
import subprocess
|
|
||||||
import time
|
import time
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -42,8 +39,6 @@ class PreflightService:
|
|||||||
|
|
||||||
# 电视(Amlogic S905X3 + Jellyfin Android TV 0.20)实测可直传的编码
|
# 电视(Amlogic S905X3 + Jellyfin Android TV 0.20)实测可直传的编码
|
||||||
VIDEO_OK = {"hevc", "h264"}
|
VIDEO_OK = {"hevc", "h264"}
|
||||||
# 可在 config.ini [Compatibility] direct_audio 里按实测调整
|
|
||||||
AUDIO_OK = set(config.DIRECT_AUDIO_CODECS)
|
|
||||||
SUB_OK = {
|
SUB_OK = {
|
||||||
"ass", "ssa", "subrip", "srt", "webvtt", "mov_text",
|
"ass", "ssa", "subrip", "srt", "webvtt", "mov_text",
|
||||||
"hdmv_pgs_subtitle", "dvd_subtitle", "dvb_subtitle", "idx",
|
"hdmv_pgs_subtitle", "dvd_subtitle", "dvb_subtitle", "idx",
|
||||||
@@ -152,23 +147,14 @@ class PreflightService:
|
|||||||
cls._raise(r, TRANSCODE, "纯 DV Profile 5 无 HDR10 兼容层,需服务端 tonemap 转码")
|
cls._raise(r, TRANSCODE, "纯 DV Profile 5 无 HDR10 兼容层,需服务端 tonemap 转码")
|
||||||
r.actions.append("server_tonemap")
|
r.actions.append("server_tonemap")
|
||||||
elif dv_profile == 7:
|
elif dv_profile == 7:
|
||||||
cls._raise(r, TRANSCODE, "DV Profile 7(HDR10 基座),客户端不支持 DV,需服务端 tonemap 转码")
|
# 有 HDR10 基座:Jellyfin 会剥掉 DV 元数据后视频直传(Direct Stream),不重编码
|
||||||
r.actions.append("server_tonemap")
|
r.reasons.append("DV Profile 7(HDR10 基座),视频可去 DV 元数据直传")
|
||||||
# 6. 码率
|
# 6. 码率
|
||||||
if mbps > config.MAX_DIRECT_MBPS:
|
if mbps > config.MAX_DIRECT_MBPS:
|
||||||
cls._raise(r, TRANSCODE, f"码率 {mbps:.1f} Mbps 超过直传上限 {config.MAX_DIRECT_MBPS:g},需转码")
|
cls._raise(r, TRANSCODE, f"码率 {mbps:.1f} Mbps 超过直传上限 {config.MAX_DIRECT_MBPS:g},需转码")
|
||||||
r.actions.append("transcode_bitrate")
|
r.actions.append("transcode_bitrate")
|
||||||
# 7. 音频
|
# 7. 音频:只记录,不参与判定(默认音轨保持原样,音频是否转码交给 Jellyfin)
|
||||||
playable = [a for a in audios if a["codec"] in cls.AUDIO_OK and 0 < a["channels"] <= 8]
|
# 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. 字幕编码
|
# 8. 字幕编码
|
||||||
bad = [s["codec"] for s in subs if s["codec"] not in cls.SUB_OK]
|
bad = [s["codec"] for s in subs if s["codec"] not in cls.SUB_OK]
|
||||||
if bad:
|
if bad:
|
||||||
@@ -242,71 +228,6 @@ class PreflightService:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.debug(f"preflight 缓存写入失败: {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",
|
HEADERS = ["path", "verdict", "codec", "height", "mbps", "dv_profile",
|
||||||
@@ -461,22 +382,3 @@ class PreflightService:
|
|||||||
cls.write_report(root, results)
|
cls.write_report(root, results)
|
||||||
return 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