Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ba6ee3fc3b | ||
|
|
16d5c3a27c | ||
|
|
e5b150b08e | ||
|
|
3f868b53b5 | ||
|
|
d64f02f87d |
+10
-2
@@ -125,7 +125,11 @@ assets/ # 图标
|
||||
- 视频直传:HEVC、H.264、VC-1、MPEG-2;需转码:MPEG-4、DV Profile 5(tonemap)
|
||||
- DV Profile 7:HDR10 基座,Jellyfin 剥 DV 元数据后可直传
|
||||
- 音频:AC3 / EAC3 / DTS / TrueHD(App 开比特流)
|
||||
- 字幕:PGS / ASS / SRT 客户端渲染;**转码片源的内嵌字幕投递不稳**,自动补外挂 SRT
|
||||
- 字幕:PGS / ASS / SRT 客户端渲染;**转码片源的内嵌字幕投递不稳**,自动补外挂文本字幕(默认 ASS)
|
||||
- 大文件(> `[Compatibility] pre_extract_ass_gb`,默认 15GB)含内嵌 ASS(ass/ssa)时,即使判 READY(直传)也在整理阶段提前抽外挂:
|
||||
Jellyfin 首播现场从 60GB 级 REMUX 抽字幕实测要 4 分钟以上。总开关 `auto_extract_ass`。
|
||||
同一部片的 ass 轨合并成一次 `mkvextract tracks` 读盘导出,逐轨判重、缺哪条补哪条。
|
||||
PGS 图形字幕不在此列:客户端直接渲染,**不抽**(如《超凡蜘蛛侠2》49GB 纯 PGS,整理时零任务)。
|
||||
|
||||
报告:`preflight-YYYYmmdd-HHMMSS.xlsx` → `/hdd/sda1/Quark-Down/_reports/`
|
||||
(表头冻结、AutoFilter、默认只看非 READY、保留最近 6 份,见 `[Compatibility]`)。
|
||||
@@ -134,6 +138,9 @@ assets/ # 图标
|
||||
## 8. Jellyfin
|
||||
|
||||
- 版本 12.4.0;容器内访问宿主机用 `http://172.17.0.1:8096`(`127.0.0.1` 不通)。
|
||||
- 容器以 `user: "1000:1000"` 运行(`tools/docker-compose.yaml`);`group_add: ["video", "105"]`
|
||||
(105=render)+ `devices: /dev/dri` 才保留硬件转码;`HOME=/config` 让 DataProtection key 持久化。
|
||||
`/config`、`/cache`、`/media` 属主统一 1000;改回 root 前注意 Jellyfin 会重新写出 root 属主 NFO/封面。
|
||||
- **Tone mapping 必须开**(`EnableTonemapping` / `EnableVppTonemapping` / `bt2390` / QSV),
|
||||
关掉 DV5 会立刻发灰。原备份在 `/tmp/encoding-backup.json`;`/tmp` 可能被清,动之前自行再备份。
|
||||
- 客户端:AC3/EAC3/DTS/TrueHD 比特流全开;PGS/ASS 直传;转码时不烧录字幕。
|
||||
@@ -148,7 +155,8 @@ assets/ # 图标
|
||||
|---|---|
|
||||
| 容器 `/tmp` 与宿主不共享 | 传文件走 `/python` ↔ `/home/ali/docker/tools/python` |
|
||||
| 容器访问宿主机 | `172.17.0.1:8096`,不是 `127.0.0.1` |
|
||||
| NFO 属主是 root | 写 NFO 用 `MEDIA_UID=0`,或 `docker exec -u 0` |
|
||||
| NFO/封面属主 | Jellyfin 以 1000 运行,属主是 ali;`jellyfin-fix` 直接跑,不需要 `MEDIA_UID=0`。旧库残留 root 文件:`sudo find /hdd/sda1/media -user root -exec chown ali:ali {} +` |
|
||||
| 媒体目录属主不是 ali | 旧 root 目录/其他 root 服务;`media-archive` 移动前预检并给出 chown 命令,不会半途留下部分文件。修复:`sudo find /hdd/sda1/media -type d ! -user ali -exec chown ali:ali {} +` |
|
||||
| MP4 装不了 subrip | 重封装回退 `-c:s mov_text`,否则 ffmpeg 报 codec not supported |
|
||||
| `sed` 处理 `[tmdbid-xxx]` | 报 `Invalid range end`,路径一律用 Python 处理 |
|
||||
| 整库改名 | 用 `--rename-only` 跳过抽字幕/广告清理等重活 |
|
||||
|
||||
@@ -26,13 +26,14 @@
|
||||
|
||||
```bash
|
||||
# 演练:只报告会改哪些条目/NFO/实体,不落盘
|
||||
MEDIA_UID=0 media-rename -p /hdd/sda1/media jellyfin-fix --dry-run
|
||||
media-rename -p /hdd/sda1/media jellyfin-fix --dry-run
|
||||
|
||||
# 真修
|
||||
MEDIA_UID=0 media-rename -p /hdd/sda1/media jellyfin-fix --yes
|
||||
media-rename -p /hdd/sda1/media jellyfin-fix --yes
|
||||
```
|
||||
|
||||
- 必须 `MEDIA_UID=0`:NFO 属主是 root(见 `docs/HANDOFF.md`「已知坑」)。
|
||||
- Jellyfin 以 1000 运行,NFO 属主是 ali;直接跑即可。旧库若还有 root 属主文件,
|
||||
先对该文件/目录 `sudo chown ali:ali`(不要无差别全库 chown)。
|
||||
- 不带 `--yes` 且是交互终端时会先列清单再问 `[y/n/q]`。
|
||||
- 修完写 `adfix-report.json`(容器 `/python/SceneMarshal/adfix-report.json` ↔ 宿主机
|
||||
`/home/ali/docker/tools/python/SceneMarshal/adfix-report.json`)。
|
||||
@@ -83,7 +84,7 @@ MEDIA_UID=0 media-rename -p /hdd/sda1/media jellyfin-fix --yes
|
||||
整理流水线(`auto` / `clean-ads`)负责文件侧,跑完如果 Jellyfin 界面还有残留:
|
||||
|
||||
```bash
|
||||
MEDIA_UID=0 media-rename -p /hdd/sda1/media jellyfin-fix --yes
|
||||
media-rename -p /hdd/sda1/media jellyfin-fix --yes
|
||||
```
|
||||
|
||||
先 `--dry-run` 看清单,再真跑。整轮约 2 分钟(全库条目拉两遍 + 5630 个 NFO 解析)。
|
||||
|
||||
+3
-2
@@ -24,14 +24,15 @@
|
||||
- 特征全部来自 `[Ads] keywords/patterns`;新广告只加配置,不改代码。
|
||||
- 文件侧:重封装丢全局标签;NFO 侧:`MetaCleanService.clean_nfo` 只删命中字段。
|
||||
- **匹配要容错**:广告串会被截断/拼接(历史:`High Efficiency Video Coding(Windows NT 10.0`、`WOW64) Advanced Audio Codec...`),用子串/正则,不要 `==` 精确比较。
|
||||
- NFO 属主可能是 root,写失败 `log.warning` 后继续,不中断整批。
|
||||
- NFO 写失败(历史 root 属主/只读)时 `log.warning` 后继续,不中断整批;Jellyfin 以 1000 运行后正常属主是 ali。
|
||||
|
||||
## R21 Jellyfin
|
||||
|
||||
- 特典放置只能 `POST /Items/{id}` 写 `AirsBeforeSeasonNumber` 等;NFO 的 `airsbefore_*` 不生效。
|
||||
- 库内元数据修复用 `jellyfin-fix`,先 `--dry-run` 看报告。
|
||||
- 容器内访问宿主机 Jellyfin 用 `172.17.0.1:8096`,不是 `127.0.0.1`。
|
||||
- 写 Jellyfin 生成的 root 属主 NFO:用 `MEDIA_UID=0 media-rename ...`,不要全库 `chown`。
|
||||
- Jellyfin 以 1000 运行,NFO/图片属主是 ali,`jellyfin-fix` 直接跑;遇到历史 root 文件用
|
||||
`sudo find /hdd/sda1/media -user root -exec chown ali:ali {} +` 定点修,不要无差别全库 chown。
|
||||
|
||||
## R22 时间与路径
|
||||
|
||||
|
||||
+2
-1
@@ -50,7 +50,8 @@
|
||||
- `media-rename` 前台运行 + `trap HUP/INT/TERM`:SSH 断开时清理容器内同目标进程,避免孤儿跑几小时(`97a71d5`)。
|
||||
- 清理要精确:按 `src/main.py -p <目标路径>` 匹配 `/proc/<pid>/cmdline`;没有明确目标就不清理,避免误杀并发任务。
|
||||
- 路径白名单只有 `/hdd/sda1`、`/python`;新增挂载目录必须同步 `ALLOWED_PREFIXES`,否则直接拒绝。
|
||||
- 需要写 root 属主文件(Jellyfin 生成的 NFO)时用 `MEDIA_UID=0`,不要 `chown -R` 整个库。
|
||||
- Jellyfin 以 1000 运行,NFO/图片属主是 ali;写 NFO 不需要 `MEDIA_UID=0`。遇到历史 root 属主文件用
|
||||
`sudo find /hdd/sda1/media -user root -exec chown ali:ali {} +` 定点修,不要无差别全库 chown。
|
||||
- 部署失败要显式 `throw`/非零退出,不要"看起来跑完了"。
|
||||
- `deploy` 只同步 `src/main.py` + `core` + `services` + `scripts`;`docs/`、`rules/`、`AGENTS.md`、`assets/`、`config.ini` 不参与运行同步,文档改动不需要部署。
|
||||
- 验证用不带 `-Commit` 的 `deploy`(只同步 + compileall);`deploy -Commit` 会 commit + push,必须先获得用户批准(`rules/delivery.md` R31)。
|
||||
|
||||
@@ -17,11 +17,15 @@
|
||||
· 同名且大小相同 → 视为重复下载,跳过
|
||||
· 同名但大小不同,或同集号(SxxEyy)已存在不同文件 → 冲突,跳过并留在源目录
|
||||
需要旧的「目标存在就报错」行为时加 --no-merge。
|
||||
|
||||
目标目录不可写(例如 Jellyfin 以 root 保存元数据时创建的目录)会在移动前中止,
|
||||
并给出 chown 命令,避免半途失败留下部分已移动文件。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import configparser
|
||||
import errno
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -223,11 +227,55 @@ def resolve_category(root: Path, raw: str, cats: list[str]) -> str | None:
|
||||
|
||||
# --------------------------------------------------------------------- 动作
|
||||
|
||||
def _owner_hint() -> str:
|
||||
"""当前用户的 user:group,用于拼出可直接复制的 chown 命令。"""
|
||||
try:
|
||||
import grp
|
||||
import pwd
|
||||
|
||||
ent = pwd.getpwuid(os.getuid())
|
||||
group = grp.getgrgid(os.getgid()).gr_name
|
||||
return f"{ent.pw_name}:{group}"
|
||||
except (ImportError, KeyError):
|
||||
return f"{os.getuid()}:{os.getgid()}"
|
||||
|
||||
|
||||
def unwritable_targets(dest: Path, rels: list[Path] | None) -> list[Path]:
|
||||
"""返回落点中当前用户不可写的目录(去重保序)。
|
||||
|
||||
rels=None 表示整目录移动,只检查 dest 的父目录;否则按新增文件逐个
|
||||
向上找最近的已存在父目录。Jellyfin 以 root 保存元数据时会创建 root
|
||||
目录,普通用户无法写入,移动会半路 PermissionError 并留下已移动的部分
|
||||
文件,所以执行前先统一预检。
|
||||
"""
|
||||
parents = [dest.parent] if rels is None else [(dest / rel).parent for rel in rels]
|
||||
bad: list[Path] = []
|
||||
for parent in parents:
|
||||
probe = parent
|
||||
while not probe.exists() and probe != probe.parent and probe != dest.parent:
|
||||
probe = probe.parent
|
||||
if probe.exists() and not os.access(probe, os.W_OK | os.X_OK) and probe not in bad:
|
||||
bad.append(probe)
|
||||
return bad
|
||||
|
||||
|
||||
def report_unwritable(bad: list[Path]) -> None:
|
||||
quoted = " ".join(f'"{p}"' for p in bad)
|
||||
die(
|
||||
"目标目录不可写,已中止(未移动任何文件):\n"
|
||||
+ "\n".join(f" - {p}" for p in bad)
|
||||
+ "\n 常见原因:Jellyfin 以 root 保存元数据时创建了目录。"
|
||||
+ f"\n 修复:sudo chown -R {_owner_hint()} {quoted}"
|
||||
)
|
||||
|
||||
|
||||
def move_to(src: Path, dest: Path) -> None:
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
os.rename(src, dest)
|
||||
except OSError:
|
||||
except OSError as exc:
|
||||
if exc.errno != errno.EXDEV:
|
||||
raise
|
||||
shutil.move(str(src), str(dest))
|
||||
|
||||
|
||||
@@ -299,7 +347,9 @@ def merge_into(src: Path, dest: Path) -> dict:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
os.rename(path, target)
|
||||
except OSError:
|
||||
except OSError as exc:
|
||||
if exc.errno != errno.EXDEV:
|
||||
raise
|
||||
shutil.move(str(path), str(target))
|
||||
moved += 1
|
||||
try:
|
||||
@@ -460,6 +510,10 @@ def main() -> int:
|
||||
print("(dry-run,未执行移动)")
|
||||
return 0
|
||||
|
||||
bad_targets = unwritable_targets(dest, merge_plan["new"] if merging else None)
|
||||
if bad_targets:
|
||||
report_unwritable(bad_targets)
|
||||
|
||||
if not args.yes:
|
||||
try:
|
||||
confirm = unicodedata.normalize("NFKC", input("确认归档?[Y/n]: ")).strip().lower()
|
||||
|
||||
+3
-2
@@ -197,9 +197,10 @@ nfo_tags = plot,outline,genre,tagline,comment,studio,tag
|
||||
[Compatibility]
|
||||
# 电视直传码率上限(Mbps),超过就判 TRANSCODE
|
||||
max_direct_mbps = 70
|
||||
# 超过该体积(GB)且含内嵌 ASS 时,提前抽外挂字幕
|
||||
# 超过该体积(GB)且含内嵌 ASS(ass/ssa;PGS 图形字幕客户端直接渲染,不抽)时,
|
||||
# 整理阶段提前抽外挂字幕。直传片源也抽:Jellyfin 首播现场抽取 60GB 级 REMUX 实测要 4 分钟以上
|
||||
pre_extract_ass_gb = 15
|
||||
# 大文件自动抽 ASS(当前 export=ass 时已天然满足)
|
||||
# 大文件自动抽 ASS 总开关;false 时只有 TRANSCODE 源 / 手动 extract-subs 才抽
|
||||
auto_extract_ass = true
|
||||
# 必须转码的片源补外挂 SRT(仅当 [Subtitles] export 不含 ass 时启用)
|
||||
export_text_subs = true
|
||||
|
||||
+38
-7
@@ -267,6 +267,26 @@ class MediaPipeline:
|
||||
stripped += 1
|
||||
log.info(f"🧹 广告元数据清理完成:{stripped}/{len(hits)} 个文件已重封装")
|
||||
|
||||
@staticmethod
|
||||
def _needs_ass_pre_extract(pf) -> bool:
|
||||
"""大体积且含内嵌 ASS 时,直传片源也要提前抽外挂字幕。
|
||||
|
||||
Jellyfin 首次播放要现场从几十 GB 的 REMUX 里抽字幕,实测 4 分钟以上;
|
||||
直传不省这一步,所以按体积阈值提前抽。开关/阈值:
|
||||
[Compatibility] auto_extract_ass / pre_extract_ass_gb。
|
||||
"""
|
||||
if not config.AUTO_EXTRACT_ASS:
|
||||
return False
|
||||
info = pf.info or {}
|
||||
try:
|
||||
size_gb = float(info.get("size_gb") or 0)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
if size_gb <= config.PRE_EXTRACT_ASS_GB:
|
||||
return False
|
||||
return any((s.get("codec") or "").lower() in config.ASS_CODECS
|
||||
for s in info.get("subs") or [])
|
||||
|
||||
def _generate_plan(self):
|
||||
if not self.auto_execute: log.info("📝 正在生成执行计划...")
|
||||
dir_video_counts = {f.parent: 0 for f, *_ in self.valid_files}
|
||||
@@ -312,24 +332,34 @@ class MediaPipeline:
|
||||
else:
|
||||
dest_dir = f.parent
|
||||
|
||||
# 大文件内嵌 ASS:即使判 READY(直传)也提前抽,避免 Jellyfin 首播现场抽取几分钟。
|
||||
# 不在这里判断「是否已有副本」:同一部片可能只抽了部分语言,逐轨判重交给
|
||||
# scan_subtitles/_plan_ass,缺哪条补哪条。
|
||||
pre_extract_ass = (self.args.mode != "clean-ads"
|
||||
and not getattr(self.args, "rename_only", False)
|
||||
and self._needs_ass_pre_extract(pf))
|
||||
if pre_extract_ass:
|
||||
log.debug(f"⏩ 大文件内嵌 ASS({pf.info.get('size_gb', 0):g}GB),检查外挂字幕: {f.name}")
|
||||
|
||||
# 「<目标名>-描述」视为已规范:综艺整理会在技术标签后用「-期名」补充说明,
|
||||
# 整库扫描不应把它当作错名再改回去。
|
||||
is_perfect = (f.name == f"{target_stem}{f.suffix.lower()}"
|
||||
or f.stem.startswith(f"{target_stem}-"))
|
||||
skip_heavy = config.SKIP_PERFECT_MATCH and is_perfect and self.args.mode not in ["clean-ads", "extract-subs"]
|
||||
skip_heavy = (config.SKIP_PERFECT_MATCH and is_perfect
|
||||
and self.args.mode not in ["clean-ads", "extract-subs"])
|
||||
|
||||
if skip_heavy and not self.auto_execute:
|
||||
if skip_heavy and not pre_extract_ass and not self.auto_execute:
|
||||
if self.args.extract_internal:
|
||||
log.info(f"💡 [特权放行] {f.name} 检测到强制参数,放行底层扫描。")
|
||||
else:
|
||||
log.debug(f"✨ [完美豁免] {f.name} 已达最高工业标准,直接放行~")
|
||||
|
||||
if self.args.mode != "clean-ads" and not getattr(self.args, "rename_only", False):
|
||||
# 文本字幕(ASS / SRT)外置化只对必须转码的片源做:
|
||||
# 直传片源的内嵌字幕客户端能直接渲染,不需要外挂副本。
|
||||
# 文本字幕(ASS / SRT)外置化:TRANSCODE 源必抽(内嵌字幕投递不稳);
|
||||
# 直传片源只在「大文件 + 内嵌 ASS」时提前抽(Jellyfin 首播现场抽取太慢);
|
||||
# 显式 extract-subs 或 --extract-internal 视为强制,不受此限制。
|
||||
forced_subs = bool(self.args.extract_internal) or self.args.mode == "extract-subs"
|
||||
want_text_subs = forced_subs or pf.verdict == TRANSCODE
|
||||
want_text_subs = forced_subs or pf.verdict == TRANSCODE or pre_extract_ass
|
||||
|
||||
# 外挂 SRT 兜底:只在没配置 ASS 导出时启用,
|
||||
# 否则同一语言会同时出现 .internal.<lang>.ass 和 .srt 两份。
|
||||
@@ -348,7 +378,7 @@ class MediaPipeline:
|
||||
# 🎯 内嵌字幕优先:先看内嵌,有就不再处理外挂
|
||||
internal_subs = 0
|
||||
if want_text_subs:
|
||||
if not skip_heavy or forced_subs:
|
||||
if not skip_heavy or forced_subs or pre_extract_ass:
|
||||
internal_subs = SubtitleService.scan_subtitles(f, self.task_mgr, target_stem, dest_dir)
|
||||
elif SubtitleService.has_internal_sub(dest_dir, target_stem):
|
||||
# 完美文件名豁免时不做 ffprobe,但仍需识别"已有内嵌字幕"
|
||||
@@ -359,7 +389,8 @@ class MediaPipeline:
|
||||
else:
|
||||
# 旧行为:外挂优先,没有外挂(或强制)时才提取内嵌
|
||||
has_ext_sub = RenamerService.scan_existing_subtitles(f, target_stem, m_type, dest_dir, self.task_mgr)
|
||||
if want_text_subs and (not has_ext_sub or forced_subs) and (not skip_heavy or forced_subs):
|
||||
if (want_text_subs and (not has_ext_sub or forced_subs or pre_extract_ass)
|
||||
and (not skip_heavy or forced_subs or pre_extract_ass)):
|
||||
SubtitleService.scan_subtitles(f, self.task_mgr, target_stem, dest_dir)
|
||||
|
||||
# 内嵌字体附件(ASS 特效字体还原):只有抽了 ASS 才有意义
|
||||
|
||||
@@ -135,6 +135,9 @@ class RenamerService:
|
||||
for asset in sorted(f_path.parent.iterdir()):
|
||||
if not asset.is_file() or asset.suffix.lower() not in config.SIDECAR_EXTS:
|
||||
continue
|
||||
# 抽字幕/字体的临时文件(.scenemarshal-*.ass、.*.part*)还在写,别当成外挂字幕认领
|
||||
if asset.name.startswith('.'):
|
||||
continue
|
||||
rest = RenamerService._sidecar_rest(asset, f_path, single_video)
|
||||
if rest is None:
|
||||
continue
|
||||
|
||||
+93
-10
@@ -125,7 +125,9 @@ class SubtitleService:
|
||||
def scan_subtitles(file_path: Path, task_mgr, target_stem: str, dest_dir: Path) -> int:
|
||||
"""扫描内置文本字幕轨道,按 config.ini [Subtitles] export 排队导出。
|
||||
|
||||
返回"该集已有/已排队的内嵌字幕数",供流水线判断是否还要处理外挂字幕。
|
||||
返回“该集已有/已排队的内嵌字幕数”,供流水线判断是否还要处理外挂字幕。
|
||||
ASS 轨先收集,最后交给 _queue_ass_exports 统一排队:
|
||||
mkv 里的 ass 轨走一次 mkvextract(一次读盘导出多条),其余仍走 ffmpeg。
|
||||
"""
|
||||
data = FFprobeUtil.get_json(file_path, "-show_streams", "-select_streams", "s")
|
||||
if not data:
|
||||
@@ -137,6 +139,7 @@ class SubtitleService:
|
||||
return 0
|
||||
|
||||
queued = 0
|
||||
ass_specs = []
|
||||
try:
|
||||
lang_counts = {}
|
||||
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]}"
|
||||
|
||||
if want_ass:
|
||||
queued += SubtitleService._queue_ass(
|
||||
file_path, task_mgr, target_stem, dest_dir, stream_idx, codec, lang_code, suffix)
|
||||
present, spec = SubtitleService._plan_ass(
|
||||
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:
|
||||
queued += SubtitleService._queue_srt(
|
||||
file_path, task_mgr, target_stem, dest_dir, stream_idx, lang_code, suffix)
|
||||
except Exception as e:
|
||||
log.warning(f"⚠️ 内置字幕扫描失败: {file_path.name} -> {e}")
|
||||
|
||||
if ass_specs:
|
||||
SubtitleService._queue_ass_exports(file_path, task_mgr, ass_specs)
|
||||
return queued
|
||||
|
||||
@staticmethod
|
||||
@@ -181,23 +191,52 @@ class SubtitleService:
|
||||
return None
|
||||
|
||||
@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"
|
||||
if out_ass.exists() and out_ass.stat().st_size > 0:
|
||||
log.debug(f"✨ [跳过导出] 目标内置 ASS 已存在: {out_ass.name}")
|
||||
return 1
|
||||
return True, None
|
||||
existing = SubtitleService._existing_sidecar(dest_dir, target_stem, lang_code, suffix)
|
||||
if existing is not None:
|
||||
log.debug(f"✨ [跳过导出] 同语言外挂字幕已存在: {existing.name}")
|
||||
return 1
|
||||
return True, None
|
||||
|
||||
temp_ass = dest_dir / f".scenemarshal-{uuid4().hex[:12]}.ass"
|
||||
return False, {"index": stream_idx, "codec": codec,
|
||||
"temp": temp_ass, "out": out_ass}
|
||||
|
||||
@staticmethod
|
||||
def _queue_ass_exports(file_path, task_mgr, specs) -> int:
|
||||
"""把待抽 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} (轨道 {stream_idx}) --> {out_ass.name}",
|
||||
SubtitleService.do_export_ass,
|
||||
(file_path, stream_idx, temp_ass, out_ass, codec),
|
||||
f"[导出内置 ASS] {file_path.name} (轨道 {tracks}) --> {names}",
|
||||
SubtitleService.do_export_ass_multi,
|
||||
(file_path, batchable),
|
||||
)
|
||||
return 1
|
||||
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
|
||||
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}")
|
||||
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
|
||||
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)]
|
||||
|
||||
Reference in New Issue
Block a user