perf(subtitle): mkv 多 ASS 轨合并为一次 mkvextract 导出
This commit is contained in:
+95
-12
@@ -125,7 +125,9 @@ class SubtitleService:
|
|||||||
def scan_subtitles(file_path: Path, task_mgr, target_stem: str, dest_dir: Path) -> int:
|
def scan_subtitles(file_path: Path, task_mgr, target_stem: str, dest_dir: Path) -> int:
|
||||||
"""扫描内置文本字幕轨道,按 config.ini [Subtitles] export 排队导出。
|
"""扫描内置文本字幕轨道,按 config.ini [Subtitles] export 排队导出。
|
||||||
|
|
||||||
返回"该集已有/已排队的内嵌字幕数",供流水线判断是否还要处理外挂字幕。
|
返回“该集已有/已排队的内嵌字幕数”,供流水线判断是否还要处理外挂字幕。
|
||||||
|
ASS 轨先收集,最后交给 _queue_ass_exports 统一排队:
|
||||||
|
mkv 里的 ass 轨走一次 mkvextract(一次读盘导出多条),其余仍走 ffmpeg。
|
||||||
"""
|
"""
|
||||||
data = FFprobeUtil.get_json(file_path, "-show_streams", "-select_streams", "s")
|
data = FFprobeUtil.get_json(file_path, "-show_streams", "-select_streams", "s")
|
||||||
if not data:
|
if not data:
|
||||||
@@ -137,6 +139,7 @@ class SubtitleService:
|
|||||||
return 0
|
return 0
|
||||||
|
|
||||||
queued = 0
|
queued = 0
|
||||||
|
ass_specs = []
|
||||||
try:
|
try:
|
||||||
lang_counts = {}
|
lang_counts = {}
|
||||||
for s in data.get('streams', []):
|
for s in data.get('streams', []):
|
||||||
@@ -153,13 +156,20 @@ class SubtitleService:
|
|||||||
suffix = "" if lang_counts[lang_code] == 1 else f".{lang_counts[lang_code]}"
|
suffix = "" if lang_counts[lang_code] == 1 else f".{lang_counts[lang_code]}"
|
||||||
|
|
||||||
if want_ass:
|
if want_ass:
|
||||||
queued += SubtitleService._queue_ass(
|
present, spec = SubtitleService._plan_ass(
|
||||||
file_path, task_mgr, target_stem, dest_dir, stream_idx, codec, lang_code, suffix)
|
target_stem, dest_dir, stream_idx, codec, lang_code, suffix)
|
||||||
|
if spec is not None:
|
||||||
|
ass_specs.append(spec)
|
||||||
|
if present or spec is not None:
|
||||||
|
queued += 1
|
||||||
if want_srt:
|
if want_srt:
|
||||||
queued += SubtitleService._queue_srt(
|
queued += SubtitleService._queue_srt(
|
||||||
file_path, task_mgr, target_stem, dest_dir, stream_idx, lang_code, suffix)
|
file_path, task_mgr, target_stem, dest_dir, stream_idx, lang_code, suffix)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.warning(f"⚠️ 内置字幕扫描失败: {file_path.name} -> {e}")
|
log.warning(f"⚠️ 内置字幕扫描失败: {file_path.name} -> {e}")
|
||||||
|
|
||||||
|
if ass_specs:
|
||||||
|
SubtitleService._queue_ass_exports(file_path, task_mgr, ass_specs)
|
||||||
return queued
|
return queued
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -181,23 +191,52 @@ class SubtitleService:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _queue_ass(file_path, task_mgr, target_stem, dest_dir, stream_idx, codec, lang_code, suffix) -> int:
|
def _plan_ass(target_stem, dest_dir, stream_idx, codec, lang_code, suffix):
|
||||||
|
"""判断该 ASS 轨是否还要抽;返回 (已有外挂副本, 待抽 spec)。
|
||||||
|
|
||||||
|
已有(含旧命名)只计数、不排队;待抽 spec 由 _queue_ass_exports
|
||||||
|
决定合并成一次 mkvextract 还是逐条 ffmpeg。
|
||||||
|
"""
|
||||||
out_ass = dest_dir / f"{target_stem}.internal.{lang_code}{suffix}.ass"
|
out_ass = dest_dir / f"{target_stem}.internal.{lang_code}{suffix}.ass"
|
||||||
if out_ass.exists() and out_ass.stat().st_size > 0:
|
if out_ass.exists() and out_ass.stat().st_size > 0:
|
||||||
log.debug(f"✨ [跳过导出] 目标内置 ASS 已存在: {out_ass.name}")
|
log.debug(f"✨ [跳过导出] 目标内置 ASS 已存在: {out_ass.name}")
|
||||||
return 1
|
return True, None
|
||||||
existing = SubtitleService._existing_sidecar(dest_dir, target_stem, lang_code, suffix)
|
existing = SubtitleService._existing_sidecar(dest_dir, target_stem, lang_code, suffix)
|
||||||
if existing is not None:
|
if existing is not None:
|
||||||
log.debug(f"✨ [跳过导出] 同语言外挂字幕已存在: {existing.name}")
|
log.debug(f"✨ [跳过导出] 同语言外挂字幕已存在: {existing.name}")
|
||||||
return 1
|
return True, None
|
||||||
|
|
||||||
temp_ass = dest_dir / f".scenemarshal-{uuid4().hex[:12]}.ass"
|
temp_ass = dest_dir / f".scenemarshal-{uuid4().hex[:12]}.ass"
|
||||||
task_mgr.add_extract(
|
return False, {"index": stream_idx, "codec": codec,
|
||||||
f"[导出内置 ASS] {file_path.name} (轨道 {stream_idx}) --> {out_ass.name}",
|
"temp": temp_ass, "out": out_ass}
|
||||||
SubtitleService.do_export_ass,
|
|
||||||
(file_path, stream_idx, temp_ass, out_ass, codec),
|
@staticmethod
|
||||||
)
|
def _queue_ass_exports(file_path, task_mgr, specs) -> int:
|
||||||
return 1
|
"""把待抽 ASS 排成任务:mkv 的 ass 轨合并成一次 mkvextract,其余逐条 ffmpeg。
|
||||||
|
|
||||||
|
逐条 ffmpeg 每次都要把整部片读一遍,60GB 级 REMUX 每条轨约 10 分钟;
|
||||||
|
一次 mkvextract 导出多条只读一遍,多轨影片能省掉 N-1 遍读盘。
|
||||||
|
"""
|
||||||
|
log.info(f"🎞️ 待导出内置 ASS: {file_path.name}({len(specs)} 条轨)")
|
||||||
|
batchable = [s for s in specs
|
||||||
|
if s["codec"] == "ass" and file_path.suffix.lower() in {".mkv", ".mka"}]
|
||||||
|
if batchable:
|
||||||
|
tracks = ", ".join(str(s["index"]) for s in batchable)
|
||||||
|
names = "、".join(s["out"].name for s in batchable)
|
||||||
|
task_mgr.add_extract(
|
||||||
|
f"[导出内置 ASS] {file_path.name} (轨道 {tracks}) --> {names}",
|
||||||
|
SubtitleService.do_export_ass_multi,
|
||||||
|
(file_path, batchable),
|
||||||
|
)
|
||||||
|
for spec in specs:
|
||||||
|
if spec in batchable:
|
||||||
|
continue
|
||||||
|
task_mgr.add_extract(
|
||||||
|
f"[导出内置 ASS] {file_path.name} (轨道 {spec['index']}) --> {spec['out'].name}",
|
||||||
|
SubtitleService.do_export_ass,
|
||||||
|
(file_path, spec["index"], spec["temp"], spec["out"], spec["codec"]),
|
||||||
|
)
|
||||||
|
return len(specs)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _queue_srt(file_path, task_mgr, target_stem, dest_dir, stream_idx, lang_code, suffix) -> int:
|
def _queue_srt(file_path, task_mgr, target_stem, dest_dir, stream_idx, lang_code, suffix) -> int:
|
||||||
@@ -309,6 +348,50 @@ class SubtitleService:
|
|||||||
f"ffmpeg={res.returncode} {detail}")
|
f"ffmpeg={res.returncode} {detail}")
|
||||||
temp_ass.unlink(missing_ok=True)
|
temp_ass.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def do_export_ass_multi(file_path, specs):
|
||||||
|
"""一次 mkvextract 读出多条 ASS 轨:同一部片只读一遍盘。
|
||||||
|
|
||||||
|
60GB 级 REMUX 逐条 ffmpeg 抽取时每条轨都要读完整部片(约 10 分钟/条),
|
||||||
|
多轨影片用 mkvextract 合并成一次读取;失败时回退逐条 ffmpeg。
|
||||||
|
"""
|
||||||
|
log.info(f"🎞️ 批量导出内置 ASS: {file_path.name}({len(specs)} 条轨)")
|
||||||
|
cmd = ["mkvextract", "tracks", str(file_path)]
|
||||||
|
cmd += [f"{spec['index']}:{spec['temp']}" for spec in specs]
|
||||||
|
try:
|
||||||
|
res = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
|
||||||
|
text=True, errors="ignore", timeout=config.REMUX_TIMEOUT)
|
||||||
|
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||||
|
log.warning(f"⚠️ mkvextract 批量导出失败: {file_path.name} -> {exc};回退 ffmpeg 逐条抽取")
|
||||||
|
for spec in specs:
|
||||||
|
SubtitleService.do_export_ass(file_path, spec["index"], spec["temp"],
|
||||||
|
spec["out"], spec["codec"])
|
||||||
|
return
|
||||||
|
|
||||||
|
failed = []
|
||||||
|
for spec in specs:
|
||||||
|
temp, out = spec["temp"], spec["out"]
|
||||||
|
if res.returncode == 0 and temp.exists() and temp.stat().st_size > 0:
|
||||||
|
try:
|
||||||
|
temp.replace(out)
|
||||||
|
log.debug(f"🎞️ 已导出内置 ASS: {out.name}")
|
||||||
|
except OSError as exc:
|
||||||
|
log.warning(f"⚠️ 重命名 ASS 失败: {out.name} -> {exc}")
|
||||||
|
temp.unlink(missing_ok=True)
|
||||||
|
failed.append(spec)
|
||||||
|
else:
|
||||||
|
temp.unlink(missing_ok=True)
|
||||||
|
failed.append(spec)
|
||||||
|
|
||||||
|
if failed:
|
||||||
|
tail = [line for line in (res.stderr or "").strip().splitlines() if line.strip()]
|
||||||
|
detail = tail[-1][:200] if tail else ""
|
||||||
|
log.warning(f"⚠️ mkvextract 批量导出失败 {len(failed)}/{len(specs)} 条"
|
||||||
|
f"(mkvextract={res.returncode}){detail};回退 ffmpeg 逐条抽取")
|
||||||
|
for spec in failed:
|
||||||
|
SubtitleService.do_export_ass(file_path, spec["index"], spec["temp"],
|
||||||
|
spec["out"], spec["codec"])
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def do_extract(file_path, stream_index, temp_ass, out_srt):
|
def do_extract(file_path, stream_index, temp_ass, out_srt):
|
||||||
cmd = ["ffmpeg", "-i", str(file_path), "-map", f"0:{stream_index}", "-c:s", "ass", "-f", "ass", "-y", str(temp_ass)]
|
cmd = ["ffmpeg", "-i", str(file_path), "-map", f"0:{stream_index}", "-c:s", "ass", "-f", "ass", "-y", str(temp_ass)]
|
||||||
|
|||||||
Reference in New Issue
Block a user