Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1b7dbdff1 | ||
|
|
7c1a243aad | ||
|
|
15ddca2e5f | ||
|
|
4b5cbe0ab6 | ||
|
|
46c9177386 | ||
|
|
005b824e4f | ||
|
|
0e5c74e5b5 | ||
|
|
94350f18b3 | ||
|
|
8b3d979eb3 | ||
|
|
fc3d1ff022 | ||
|
|
e66551200f | ||
|
|
6950f75d26 | ||
|
|
64a80d2234 | ||
|
|
57e950da8f | ||
|
|
68a2265026 | ||
|
|
f088ae78e3 |
No files matched your search
@@ -37,6 +37,14 @@ There are **no credentials** in this project, so there is no `SECRETS.md`.
|
||||
6. **Never write encode output straight to a network share.** Encode to local disk, verify,
|
||||
then copy the complete file across; a streaming `.part` write leaves a corrupt stub on any
|
||||
blip. If the destination is remote, keep the output local.
|
||||
7. **Never read one child PIPE while leaving the other undrained.** `subprocess.run(...,
|
||||
capture_output=True, timeout=…)` (or sending the noisy fd to a file) is the default; a
|
||||
`while p.stdout.read():` loop with `p.stderr` still holding a PIPE will deadlock the moment
|
||||
the child fills that pipe — measured 2026-11-15: a corrupt Matroska emitted 219 KB of
|
||||
container errors, ffmpeg blocked writing stderr, the gate sat 42 min at 2.1 s CPU and the
|
||||
supervisor killed the item three times (see `STATE.md` bug 14). `p.wait(timeout=)` does
|
||||
NOT save you: it is unreachable until that read loop ends. A loop that drains a child owes
|
||||
itself a deadline.
|
||||
|
||||
## 3. Layout
|
||||
|
||||
|
||||
@@ -176,12 +176,19 @@ from a small runner instead:
|
||||
2. encode locally, with the same mandatory flags (`-fps_mode cfr`, `-pix_fmt yuv420p`)
|
||||
3. run the structural gate **and** a full decode pass on the local output
|
||||
4. upload to `<name>.new.mp4` (never the final name)
|
||||
5. read the share copy back end-to-end and compare **SHA-256 + byte count** with the local file
|
||||
6. only then `os.replace()` it over the original, and re-probe the result on the share
|
||||
5. read the uploaded copy back with the **Windows cache bypassed** (`FILE_FLAG_NO_BUFFERING`) and
|
||||
compare **SHA-256 + byte count** with the local file, then really **decode its last seconds**
|
||||
(`-sseof -5 -f null -`)
|
||||
6. only then **two-phase-commit** it: move the original into the same-volume quarantine
|
||||
`<dir>/.transcode_trash/<date>/` (an inode rename — never a delete), publish the verified file,
|
||||
and roll the original back if the publish or any post-install gate fails
|
||||
|
||||
Step 5 costs one extra network read (~1 h per 330 GiB) and is the only thing that actually
|
||||
proves the remote copy is complete — `getsize()` cannot, and neither can a duration probe:
|
||||
with `+faststart` the `moov` is written first, so a truncated file still reports full duration.
|
||||
proves the remote copy is complete — `getsize()` cannot, a duration probe cannot (with
|
||||
`+faststart` the `moov` is written first, so a truncated file still reports full duration), and a
|
||||
buffered read cannot either: Dokan/RaiDrive answer sampled windows from the local cache pool while
|
||||
the server holds a fraction of the file. Step 6 is what makes a failed install recoverable: the
|
||||
original is in the quarantine, not gone.
|
||||
Keep a JSONL ledger and a per-file skip test ("already HEVC hvc1") so a reboot resumes safely.
|
||||
A single instance only; the lock matters even more here because two runs would race on `dst`.
|
||||
|
||||
|
||||
@@ -320,8 +320,16 @@ live = HEVC hvc1 **且**音轨是 AAC(真能播)**且**本次是从快照原
|
||||
- [ ] **等业主定 D-07(队列仓 PLAN §7)**:`0705机械宇宙` 按指示跑过 `--crf 24`,仍是 mean **0.9120**、坏帧 **8.93%**、
|
||||
`vmaf480` **59.41** —— 与 crf29 逐位相同 ⇒ **源档缺陷**(引擎自己标了 non-uniform cadence),别再降参数;
|
||||
要么接受原档,要么单独走"源档缺陷"口径。同类还有 3 项 `engine-skip`(park 满 2 轮)。
|
||||
- [ ] **cpu(x265)档门槛问题**:crf29 在 bpp 0.0147–0.0293 带成立(0.9958/0.9968),但 **bpp ≳0.05 那一带 4/4 落到
|
||||
0.9926–0.9946**(720p、源 ~1.17 Mbps)→ 每项白烧 2 次整片编码后 park。选项 A `cpu_crf→24` / B 放行到 0.990。
|
||||
- [x] **cpu(x265)档门槛问题**(2026-10-25 结案):crf29 在 bpp 0.0147–0.0293 带成立(0.9958/0.9968),但 bpp ≳0.05
|
||||
那一带 4/4 落到 0.9926–0.9946(720p、源 ~1.17 Mbps)→ 每项白烧 2 次整片编码后 park。
|
||||
**根因不是档位,是 `SIZE_CEIL=1.0` 的 `-maxrate` 与 0.995 互斥**:实测 720p/1832 kbps 源,
|
||||
crf 19 在上限内 = 0.99192(87% 大小)、**crf 14 在同一上限内 = 0.99195**(五档只动 0.00003)、
|
||||
放开上限 crf 19 = 0.99648 但要 **172%** 大小 ⇒ 到 0.995 需源码率的 **125%** 以上。
|
||||
**已定(业主 2026-10-25)**:走选项 B,但只对「本来就能播的源」——`plays_everywhere()`(h264+aac+mp4/m4v/mov)
|
||||
在 0.995 不过时直接按 `SSIM_MEAN_MIN_FALLBACK`(0.990) 收下,判决写
|
||||
`second tier 0.990: the source already plays everywhere, so this is a space-reclaim job`;
|
||||
不可播源仍 0.995,帧占比缺陷任何档位都拒。同时**不再跑那次注定无效的 quality+2 重试**。
|
||||
同机实测:同一文件由 `FAIL quality 0.9923` 变为 `ok`,87.5% 大小,单次编码 120 s。
|
||||
- [ ] 两档跑完 → **全库落地审计**:`D:\dev\hevc-transcode\cache\install_audit.py`(核对线上文件真实大小 + 编码器;曾一次抓到"报告成功没落地")+ `copy_land_check.py`(copy 档用音轨 aac/mp3 判定)。
|
||||
- [ ] 失败项:无需清单,新一轮自动重做(失败时文件原样)。
|
||||
- [ ] `2022年/0723 《走出强迫症》/走出强迫症.mp4` 用新下载(`D:\Download\0723走出强迫症.mp4`,618,696,954 B)已转好装好(450,502,893 B,HEVC+AAC,SSIM min 0.997,时长 3399.81 s)✓。**快照里那份仍是坏的**(618,697,011 B,moov 缺失)→ 待定:是否用干净副本替换快照里的坏档,以免将来"从原档重转"踩坑。
|
||||
@@ -438,6 +446,41 @@ work 盘只剩 3.9 GB → 队列守卫拒绝所有新项,两条 lane 空转 30
|
||||
|
||||
回归:`scripts/test_stage_cleanup.py` 6 项(另一 lane 不动 / 死残留删 / 在编 tag 保全 / 台账不动 / 字节数正确)。
|
||||
|
||||
## 第 14 个 bug:gate 阶段的 payload 指纹把 stderr 管道锁死(2026-11-15)
|
||||
|
||||
**症状**:控制面看板显示某条 CPU 车道「校验」42 分钟不动(`phase_s` 一直涨),引擎日志停在
|
||||
`carry: …` 那一行之后再没写过字。看门狗按 `stalled in gate for 60 min with no I/O progress`
|
||||
连杀三次,每条白烧一小时;同一个铁轨上还有 1,484 条待办。
|
||||
|
||||
**真因**:`tracks.stream_signature()` 用
|
||||
`ffmpeg … -f data -` 把整个音频 payload(这个片 48.9 MB)打到 stdout,`stdout=PIPE,
|
||||
stderr=PIPE`,然后 `while True: p.stdout.read(1 << 20)` 读干 stdout,**stderr 只有 EOF 之后
|
||||
才读**。这个 Matroska 结构是坏的(1,612 处 `Element … exceeds containing master element`),
|
||||
ffmpeg 往 stderr 吐了 219,020 字节 / 1,630 行;Windows 匿名管道缓冲 4–64 KB,写满后
|
||||
ffmpeg 阻塞在写 stderr,stdout 永不 EOF,父进程永久阻塞。`p.wait(timeout=1800)` 的 timeout
|
||||
在 stdout 读完之前根本用不上 —— 等于没有超时。
|
||||
|
||||
**证据(同一文件、同一 ffmpeg)**:
|
||||
|
||||
| 跑法 | 结果 |
|
||||
|---|---|
|
||||
| 引擎里的写法(stderr 挂管道不读) | 42 分钟/2.1 s CPU,永远不回 |
|
||||
| 同命令 pipe → `md5sum`(stderr 走终端) | 11.7 s,`5cb7483040621df964779a9e0fb21d45` |
|
||||
| `-f streamhash -hash md5 -` | 2.3 s,**同一 md5** |
|
||||
|
||||
**修**:`-f streamhash -hash md5 -` 让 ffmpeg 自己算 md5(payload 不再穿过本进程),
|
||||
并改成**一次** `subprocess.run(capture_output=True, timeout=…)` —— `communicate()` 用线程
|
||||
同时抽干 fd,stderr 再大也堵不住,超时就杀子进程并返回 `None`(闸门按「拿不到指纹」处理,
|
||||
绝不会把一次超时误判成「payload 不同」)。包数仍由 ffprobe 给,返回形状
|
||||
`(nb_packets, md5)` 不变。
|
||||
|
||||
**回归**:`python -m unittest test_tracks` 55/55(含 `e2e mkv/mp4: copied streams are
|
||||
byte-identical`);真文件上 `stream_signature(src) == stream_signature(out)` 且 6.9 s 完成。
|
||||
|
||||
**教训(已写进 AGENTS §2 第 7 条)**:子进程的 stdout/stderr 要么都交给
|
||||
`subprocess.run(capture_output=True)`,要么至少有一个落文件;**不许**在一个 PIPE 上边读边
|
||||
等另一个 PIPE。任何"读干子进程输出"的循环都必须带自己的 deadline,不能指望 `wait(timeout=)`。
|
||||
|
||||
## 红线(用户明确要求过)
|
||||
|
||||
- **绝不删除/覆盖快照原档**(`#snapshot` 是唯一的干净档案)。
|
||||
|
||||
@@ -142,10 +142,20 @@ Per item, in this order:
|
||||
4. **SSIM vs the source window >= target** (section 2).
|
||||
5. **Size assertion**, per the regime in section 1: hard `out <= src` where the source has
|
||||
headroom; runaway guard `out <= 1.25x src` where the pre-flight says it is already compressed.
|
||||
6. **Upload to a temp name, read the share copy back end-to-end, compare SHA-256 + byte count**,
|
||||
then replace atomically. A duration probe is not enough: with `+faststart` the `moov` is written
|
||||
first, so a truncated upload still reports the full duration.
|
||||
7. **Re-probe on the share** after the replace.
|
||||
6. **Upload to a temp name, then read it back with the Windows cache bypassed**
|
||||
(`FILE_FLAG_NO_BUFFERING`) and compare SHA-256 + byte count. A duration probe is not enough:
|
||||
with `+faststart` the `moov` is written first, so a truncated upload still reports the full
|
||||
duration — and a *buffered* read can be answered from the Dokan/RaiDrive cache pool while the
|
||||
server holds a fraction of the file.
|
||||
7. **Decode the last seconds of the uploaded copy** (`ffmpeg -v error -xerror -sseof -5 -i TMP
|
||||
-map 0:v:0? -f null -`). This is the only check that forces ffmpeg to the physical tail; a
|
||||
short file ends in `partial file` / `Invalid NAL unit size` instead of silence.
|
||||
8. **Two-phase commit, never `os.replace` over the original**: move whatever occupies the target
|
||||
name into a same-volume quarantine `<dir>/.transcode_trash/<date>/` (an inode rename: 0 bytes
|
||||
copied, reversible), publish the verified file, and roll the original straight back if the
|
||||
publish or any post-install gate fails. The quarantine is collected after 72 h — and an entry
|
||||
whose installed file is gone is never collected, because that is the last copy.
|
||||
9. **Re-probe on the share** after the publish.
|
||||
|
||||
Cheap confidence check on a healthy file, one distinct value expected:
|
||||
|
||||
@@ -278,8 +288,10 @@ Measured audit of such a set (54 files converted at `-cq 27` + a fixed 256k audi
|
||||
* the encode reads the **original**, the tier is classified from the **original's** bpp, and the
|
||||
gates compare against the **original** - the converted file is never used as a reference;
|
||||
* `dst` stays the live path, so the output replaces the (bloated) converted file;
|
||||
* **the original is never modified or deleted** - `os.remove(src)` is suppressed whenever the
|
||||
source came from the origin tree. Getting this backwards would destroy the only clean copy.
|
||||
* **the original is never modified or deleted** - the quarantine move is suppressed whenever the
|
||||
source came from the origin tree (and so is `--keep-source`). Getting this backwards would
|
||||
destroy the only clean copy. For a normal in-place install the source is *retired into the
|
||||
quarantine*, not deleted: `purge_trash()` is the only thing that ever unlinks one, 72 h later.
|
||||
|
||||
## 9. CPU and GPU tiers in parallel
|
||||
|
||||
|
||||
+784
-65
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,258 @@
|
||||
#!/usr/bin/env python3
|
||||
"""tracks.py gate: the carry-over plan, its ffmpeg arguments and its verdicts.
|
||||
|
||||
Two layers, deliberately separated:
|
||||
|
||||
* plan/args/verify arithmetic runs against SYNTHETIC ffprobe JSON - every branch is
|
||||
reachable on any machine, and a change in policy shows up as a failed expectation
|
||||
instead of as a surprising file.
|
||||
* one end-to-end pair (MP4 + Matroska) runs only when the fixture from the 2026-10-24
|
||||
research exists (`<control-plane>/cache/research/fixture/src_full.mkv`), because it
|
||||
needs a real source with 3 audio tracks, 2 subtitles and 2 font attachments.
|
||||
|
||||
Run: python scripts/test_tracks.py
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
import tracks as TR # noqa: E402
|
||||
|
||||
checks = {}
|
||||
|
||||
|
||||
def check(name, ok, detail=""):
|
||||
checks[name] = bool(ok)
|
||||
print("%-58s %s%s" % (name, "PASS" if ok else "FAIL", (" " + str(detail)) if detail and not ok else ""))
|
||||
|
||||
|
||||
def field(typ, index, codec, **kw):
|
||||
d = {"index": index, "codec_type": typ, "codec_name": codec,
|
||||
"tags": kw.pop("tags", {}), "disposition": kw.pop("disp", {})}
|
||||
d.update(kw)
|
||||
return d
|
||||
|
||||
|
||||
def fixture_json(n_audio=None):
|
||||
"""A synthetic version of the research fixture: 3 audio, 2 subtitles, 2 attachments."""
|
||||
streams = [
|
||||
field("video", 0, "h264", width=640, height=360, pix_fmt="yuv420p", codec_tag_string="avc1"),
|
||||
field("audio", 1, "aac", channels=2, bit_rate="128000",
|
||||
tags={"language": "eng", "title": "English Original"}, disp={"default": 1}),
|
||||
field("audio", 2, "ac3", channels=6, bit_rate="384000",
|
||||
tags={"language": "jpn", "title": "日本語 コメンタリー"}),
|
||||
field("audio", 3, "flac", channels=2, bit_rate="700000",
|
||||
tags={"language": "zho", "title": "中文配音"}),
|
||||
field("subtitle", 4, "ass", tags={"language": "eng", "title": "English ASS"},
|
||||
disp={"default": 1}),
|
||||
field("subtitle", 5, "subrip", tags={"language": "zho", "title": "中文字幕"},
|
||||
disp={"forced": 1}),
|
||||
field("attachment", 6, "ttf", tags={"filename": "arial.ttf",
|
||||
"mimetype": "application/x-truetype-font"}),
|
||||
field("attachment", 7, "ttf", tags={"filename": "msyh.ttc",
|
||||
"mimetype": "application/x-truetype-font"}),
|
||||
]
|
||||
if n_audio is not None:
|
||||
streams = [s for s in streams if s["codec_type"] != "audio"]
|
||||
streams += [field("audio", 10 + i, "aac", channels=2, bit_rate="128000",
|
||||
tags={"language": "eng"}) for i in range(n_audio)]
|
||||
return {
|
||||
"streams": streams,
|
||||
"format": {"duration": "10.037", "size": "23783193",
|
||||
"tags": {"title": "Carry-over Source", "artist": "Hoelee",
|
||||
"CUSTOM_KEY": "custom value 42",
|
||||
"creation_time": "2021-07-03T10:00:00.000000Z"}},
|
||||
"chapters": [{"start_time": "0", "end_time": "3", "tags": {"title": "Intro"}},
|
||||
{"start_time": "3", "end_time": "7", "tags": {"title": "Mid"}},
|
||||
{"start_time": "7", "end_time": "10", "tags": {"title": "End"}}],
|
||||
}
|
||||
|
||||
|
||||
JS = fixture_json()
|
||||
|
||||
# ---------------------------------------------------------------- MP4 policy
|
||||
p_mp4 = TR.plan(JS, "mp4")
|
||||
check("mp4: all 3 audio tracks are planned", len(p_mp4["audio"]) == 3, p_mp4["audio"])
|
||||
check("mp4: AAC source is copied", p_mp4["audio"][0]["codec"] == "copy", p_mp4["audio"][0])
|
||||
check("mp4: AC-3 becomes AAC", p_mp4["audio"][1]["codec"] == "aac")
|
||||
check("mp4: 5.1 keeps 6 channels (no silent downmix)",
|
||||
p_mp4["audio"][1]["target_channels"] == 6, p_mp4["audio"][1])
|
||||
check("mp4: AAC bitrate follows the source (384k)",
|
||||
p_mp4["audio"][1]["kbps"] == 384, p_mp4["audio"][1])
|
||||
check("mp4: FLAC becomes AAC", p_mp4["audio"][2]["codec"] == "aac")
|
||||
check("mp4: both text subtitles become mov_text",
|
||||
[s["codec"] for s in p_mp4["subtitles"]] == ["mov_text", "mov_text"], p_mp4["subtitles"])
|
||||
check("mp4: font attachments are NOT carried", p_mp4["attachments_carried"] is False)
|
||||
check("mp4: the font loss is warned about",
|
||||
any("attachment" in w for w in p_mp4["warnings"]), p_mp4["warnings"])
|
||||
check("mp4: chapters are counted", p_mp4["chapters"] == 3)
|
||||
check("mp4: per-track titles survive the plan",
|
||||
[a["title"] for a in p_mp4["audio"]] == ["English Original", "日本語 コメンタリー", "中文配音"])
|
||||
|
||||
args = TR.ffmpeg_args(p_mp4)
|
||||
check("args: video is mapped once", args[0:2] == ["-map", "0:v:0"])
|
||||
check("args: all three audio tracks are mapped",
|
||||
[i for i in range(len(args) - 1) if args[i] == "-map" and args[i + 1].startswith("0:a:")]
|
||||
and args.count("0:a:0") == 1 and "0:a:2" in args, args)
|
||||
check("args: never `-map 0` (chapter/text tracks must stay out)", "-map" in args and "0" not in
|
||||
[args[i + 1] for i in range(len(args) - 1) if args[i] == "-map"])
|
||||
check("args: per-track AAC channels are explicit", "-ac:a:1" in args and "6" in args)
|
||||
check("args: track labels are written twice for mp4 (title + handler_name)",
|
||||
"title=English Original" in args and "handler_name=English Original" in args, args)
|
||||
check("args: mp4 subtitle codec is mov_text", "mov_text" in args)
|
||||
check("args: no attachments map for mp4", "0:t" not in args)
|
||||
mux = TR.ffmpeg_mux_args(p_mp4)
|
||||
check("mux: faststart + metadata tags", "+faststart+use_metadata_tags" in mux, mux)
|
||||
check("video tag: hvc1 for mp4", TR.video_tag_args(p_mp4) == ["-tag:v", "hvc1"])
|
||||
|
||||
# ---------------------------------------------------------------- MKV (fidelity)
|
||||
p_mkv = TR.plan(JS, "mkv")
|
||||
check("mkv: every audio track is COPIED",
|
||||
[a["codec"] for a in p_mkv["audio"]] == ["copy", "copy", "copy"], p_mkv["audio"])
|
||||
check("mkv: every subtitle is COPIED",
|
||||
[s["codec"] for s in p_mkv["subtitles"]] == ["copy", "copy"], p_mkv["subtitles"])
|
||||
check("mkv: attachments are carried", p_mkv["attachments_carried"] is True)
|
||||
check("mkv: no lossy warnings", not p_mkv["warnings"], p_mkv["warnings"])
|
||||
margs = TR.ffmpeg_args(p_mkv)
|
||||
check("mkv: attachment map is present", "0:t" in margs)
|
||||
check("mkv: no mov_text", "mov_text" not in margs)
|
||||
check("mkv: no faststart / metadata-whitelist flags", TR.ffmpeg_mux_args(p_mkv) == [])
|
||||
check("mkv: no Apple codec tag", TR.video_tag_args(p_mkv) == [])
|
||||
|
||||
# ---------------------------------------------------------------- downmix opt-out
|
||||
p_dm = TR.plan(JS, "mp4", {"downmix_51": True})
|
||||
check("downmix flag: 5.1 track becomes 2 channels",
|
||||
p_dm["audio"][1]["target_channels"] == 2, p_dm["audio"][1])
|
||||
check("downmix flag: the downmix is announced",
|
||||
any("downmixed" in w for w in p_dm["warnings"]), p_dm["warnings"])
|
||||
|
||||
# ---------------------------------------------------------------- bitmap subtitles
|
||||
JS_BM = fixture_json()
|
||||
JS_BM["streams"].append(field("subtitle", 8, "hdmv_pgs_subtitle", tags={"language": "eng"}))
|
||||
p_bm_mp4 = TR.plan(JS_BM, "mp4")
|
||||
check("PGS: skipped in mp4 (it cannot be carried at all)",
|
||||
len(p_bm_mp4["subtitles"]) == 2 and len(p_bm_mp4["subs_skipped"]) == 1,
|
||||
(p_bm_mp4["subtitles"], p_bm_mp4["subs_skipped"]))
|
||||
check("PGS: the skip names the reason", "graphic" in p_bm_mp4["subs_skipped"][0]["reason"])
|
||||
p_bm_mkv = TR.plan(JS_BM, "mkv")
|
||||
check("PGS: copied in matroska", len(p_bm_mkv["subtitles"]) == 3, p_bm_mkv["subtitles"])
|
||||
p_bm_txt = TR.plan(JS_BM, "mkv", {"subs": "text_only"})
|
||||
check("subs=text_only: PGS skipped even in matroska",
|
||||
len(p_bm_txt["subtitles"]) == 2 and len(p_bm_txt["subs_skipped"]) == 1)
|
||||
|
||||
# ---------------------------------------------------------------- other source shapes
|
||||
JS_MUTE = fixture_json()
|
||||
JS_MUTE["streams"] = [s for s in JS_MUTE["streams"] if s["codec_type"] != "audio"]
|
||||
p_mute = TR.plan(JS_MUTE, "mp4")
|
||||
check("no audio: -an is emitted", "-an" in TR.ffmpeg_args(p_mute))
|
||||
JS_NOSUB = fixture_json()
|
||||
JS_NOSUB["streams"] = [s for s in JS_NOSUB["streams"] if s["codec_type"] != "subtitle"]
|
||||
p_nosub = TR.plan(JS_NOSUB, "mp4")
|
||||
check("no subtitles: -sn is emitted", "-sn" in TR.ffmpeg_args(p_nosub))
|
||||
check("audio-only-in-MP4 policy refuses `copy`", TR.plan(JS, "mp4", {"audio": "copy"})["audio"][1]["codec"] == "aac")
|
||||
|
||||
# ---------------------------------------------------------------- paths
|
||||
check("dst: mp4 source stays in place under mp4 policy",
|
||||
TR.out_path_for("D:/v/a.mp4", "mp4") == "D:/v/a.mp4")
|
||||
check("dst: mp4 source becomes .mkv under the fidelity policy",
|
||||
TR.out_path_for("D:/v/a.mp4", "mkv") == "D:/v/a.mkv")
|
||||
check("dst: mkv stays in place under mkv", TR.out_path_for("D:/v/a.mkv", "mkv") == "D:/v/a.mkv")
|
||||
|
||||
# ---------------------------------------------------------------- verify verdicts
|
||||
def out_json_of(plan_, **over):
|
||||
streams = [field("video", 0, "hevc", width=640, height=360, pix_fmt="yuv420p",
|
||||
codec_tag_string="hvc1" if plan_["container"] == "mp4" else "[0][0][0][0]")]
|
||||
for n, a in enumerate(plan_["audio"]):
|
||||
streams.append(field("audio", 1 + n, "aac" if a["codec"] == "aac" else a["src_codec"],
|
||||
channels=a["target_channels"],
|
||||
tags={"language": a["language"], "title": a["title"]}))
|
||||
for n, s in enumerate(plan_["subtitles"]):
|
||||
streams.append(field("subtitle", 10 + n,
|
||||
"mov_text" if s["codec"] == "mov_text" else s["src_codec"],
|
||||
tags={"language": s["language"], "title": s["title"]}))
|
||||
for n, a in enumerate(plan_["attachments"]):
|
||||
streams.append(field("attachment", 20 + n, "ttf",
|
||||
tags={"filename": a["filename"], "mimetype": a["mimetype"]}))
|
||||
js = {"streams": streams,
|
||||
"format": {"duration": "10.037", "tags": dict(JS["format"]["tags"])},
|
||||
"chapters": list(JS["chapters"])}
|
||||
js.update(over)
|
||||
return js
|
||||
|
||||
|
||||
ok, msg = TR.verify(p_mp4, JS, out_json_of(p_mp4))
|
||||
check("verify: a faithful mp4 plan passes", ok, msg)
|
||||
ok, msg = TR.verify(p_mkv, JS, out_json_of(p_mkv))
|
||||
check("verify: a faithful mkv plan passes", ok, msg)
|
||||
|
||||
bad = out_json_of(p_mp4)
|
||||
bad["streams"] = [s for s in bad["streams"] if not (s["codec_type"] == "audio" and s["index"] == 3)]
|
||||
ok, msg = TR.verify(p_mp4, JS, bad)
|
||||
check("verify: a dropped audio track is caught", not ok and "audio tracks" in msg, msg)
|
||||
|
||||
bad = out_json_of(p_mp4)
|
||||
for s in bad["streams"]:
|
||||
if s["codec_type"] == "video":
|
||||
s["codec_tag_string"] = "hev1"
|
||||
ok, msg = TR.verify(p_mp4, JS, bad)
|
||||
check("verify: hev1 (Apple refuses it) is caught", not ok and "hvc1" in msg, msg)
|
||||
|
||||
bad = out_json_of(p_mkv)
|
||||
bad["format"]["duration"] = "20.0"
|
||||
ok, msg = TR.verify(p_mkv, JS, bad)
|
||||
check("verify: a duration change is caught", not ok and "duration" in msg, msg)
|
||||
|
||||
bad = out_json_of(p_mkv)
|
||||
bad["chapters"] = []
|
||||
ok, msg = TR.verify(p_mkv, JS, bad)
|
||||
check("verify: lost chapters are caught", not ok and "chapters" in msg, msg)
|
||||
|
||||
bad = out_json_of(p_mkv)
|
||||
bad["format"]["tags"].pop("creation_time")
|
||||
ok, msg = TR.verify(p_mkv, JS, bad)
|
||||
check("verify: a lost creation_time is caught", not ok and "creation_time" in msg, msg)
|
||||
|
||||
bad = out_json_of(p_mp4)
|
||||
bad["streams"] = [s for s in bad["streams"] if s["codec_type"] != "subtitle"]
|
||||
ok, msg = TR.verify(p_mp4, JS, bad)
|
||||
check("verify: silently dropped subtitles are caught", not ok and "subtitle" in msg, msg)
|
||||
|
||||
bad = out_json_of(p_mkv)
|
||||
bad["streams"] = [s for s in bad["streams"] if s["codec_type"] != "attachment"]
|
||||
ok, msg = TR.verify(p_mkv, JS, bad)
|
||||
check("verify: lost font attachments are caught", not ok and "attachment" in msg, msg)
|
||||
|
||||
# ---------------------------------------------------------------- end-to-end (fixture only)
|
||||
FIXTURE = os.path.join(os.path.dirname(HERE), "..", "hevc-transcode", "cache", "research",
|
||||
"fixture", "src_full.mkv")
|
||||
FIXTURE = os.path.normpath(FIXTURE)
|
||||
if os.path.exists(FIXTURE) and subprocess.run(["ffmpeg", "-version"], capture_output=True).returncode == 0:
|
||||
tmp = tempfile.mkdtemp(prefix="tracks_e2e_")
|
||||
src = os.path.join(tmp, "src.mkv")
|
||||
subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", FIXTURE, "-map", "0", "-c", "copy", src],
|
||||
check=True, capture_output=True)
|
||||
js = TR.probe(src)
|
||||
for container in ("mkv", "mp4"):
|
||||
out = os.path.join(tmp, "out" + TR.suffix_for(container))
|
||||
pl = TR.plan(js, container)
|
||||
cmd = (["ffmpeg", "-y", "-v", "error", "-i", src] + TR.ffmpeg_args(pl)
|
||||
+ ["-c:v", "copy"] + TR.video_tag_args(pl, "h264") + TR.ffmpeg_mux_args(pl) + [out])
|
||||
r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace")
|
||||
check("e2e %s: ffmpeg accepted the plan" % container, r.returncode == 0,
|
||||
(r.stderr or "").strip()[-300:])
|
||||
if r.returncode == 0:
|
||||
ojs = TR.probe(out)
|
||||
ok, msg = TR.verify(pl, js, ojs, "h264")
|
||||
check("e2e %s: plan verified against the produced file" % container, ok, msg)
|
||||
same, smsg = TR.copy_streams_intact(pl, src, out)
|
||||
check("e2e %s: copied streams are byte-identical" % container, same, smsg)
|
||||
print("\n(e2e fixture used: %s)" % FIXTURE)
|
||||
else:
|
||||
print("\n(e2e skipped: fixture or ffmpeg not available)")
|
||||
|
||||
print("\n%d/%d checks passed" % (sum(checks.values()), len(checks)))
|
||||
sys.exit(0 if all(checks.values()) else 1)
|
||||
@@ -0,0 +1,568 @@
|
||||
"""tracks.py - decide, build and verify the AUDIO / SUBTITLE / ATTACHMENT carry-over.
|
||||
|
||||
Why this module exists (owner decision 2026-10-24, see
|
||||
`docs/PLAN-2026-10-24-轨道携带.md`): the engines used to map `-map 0:v:0 -map 0:a:0?`,
|
||||
i.e. exactly one audio track and no subtitles at all. That silently threw away every
|
||||
extra language track, every subtitle and every attached font - the three things a
|
||||
"keep it the same" promise is judged on.
|
||||
|
||||
The rules it encodes are MEASURED, not assumed (fixtures and the evidence scripts live in
|
||||
the control-plane repo under `cache/research/fixture/`):
|
||||
|
||||
* MP4 accepts ONE subtitle codec: `mov_text` (tx3g). ASS, SRT, WebVTT all fail the
|
||||
muxer outright with `Could not find tag for codec <x> ... not supported in container`
|
||||
- which aborts the WHOLE remux, it does not just drop the track. So text subtitles
|
||||
must be transcoded to mov_text (losing positioning, fades, outline/shadow, fonts -
|
||||
only i/b/u/color/size/face survive) and bitmap subtitles cannot be carried at all.
|
||||
* MP4 accepts a font attachment? No: mapping one in fails with
|
||||
`Could not find tag for codec ttf`. Matroska carries them verbatim.
|
||||
* Matroska carries ASS/SRT/PGS + font attachments + chapters + arbitrary tags
|
||||
bit-for-bit (verified by per-packet md5), which is why "keep the styling" is an
|
||||
MKV-only promise.
|
||||
* `-map 0` is NOT portable: it drags in MP4's QuickTime chapter text track
|
||||
(`data/bin_data/text`) and phone timecode tracks (`tmcd`), and matroska refuses both
|
||||
with `Only audio, video, and subtitles are supported for Matroska`. Every mapping
|
||||
here is therefore explicit per stream.
|
||||
* MP4 drops `creation_time` unless `-map_metadata 0` is given, and drops any tag it
|
||||
does not know (for example every custom key) unless `-movflags +use_metadata_tags`
|
||||
is given. `author` is not mapped by the MP4 muxer at all.
|
||||
* MP4 has no alternate-group writer in ffmpeg (`ffmpeg -h muxer=mp4` has no such
|
||||
option, and every `trak` comes out with alternate_group=0), so extra audio tracks are
|
||||
exposed by VLC/Infuse/MX/Kodi/ExoPlayer but Apple's native player is expected to keep
|
||||
using the default track. Do not promise track switching on iOS.
|
||||
|
||||
The module is deliberately pure: `plan()` takes the ffprobe JSON and a policy and returns
|
||||
plain data, so every branch is unit-testable without touching a video file. The engine
|
||||
turns the plan into ffmpeg arguments (`ffmpeg_args`) and verifies the result against the
|
||||
same plan (`verify`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
NOWIN = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
||||
|
||||
# The supervisor hands every engine child its OWN resolved ffmpeg/ffprobe
|
||||
# (`rt.config.engine_child_env` → TRANSCODE_FFMPEG/TRANSCODE_FFPROBE, mirroring
|
||||
# `transcode.py:36-37`). Honour them here as well: this module used to call the bare
|
||||
# names, which only worked because this host happens to have ffmpeg on PATH.
|
||||
# Measured 2026-10-24: the packaged app ships ffmpeg inside its own tree and the
|
||||
# bundle acceptance strips PATH on purpose ("so only the bundle could have served
|
||||
# it") - `probe()` then died with `FileNotFoundError [WinError 2]` 2 s into the item
|
||||
# and the queue filed it as a quality refusal.
|
||||
FFMPEG = os.environ.get("TRANSCODE_FFMPEG") or os.environ.get("RT_FFMPEG") or "ffmpeg"
|
||||
FFPROBE = os.environ.get("TRANSCODE_FFPROBE") or os.environ.get("RT_FFPROBE") or "ffprobe"
|
||||
|
||||
# ---- codec taxonomy -------------------------------------------------------------------
|
||||
# Text subtitles: transcodable to mov_text (lossy) or copyable into matroska.
|
||||
TEXT_SUB = {
|
||||
"subrip", "srt", "ass", "ssa", "webvtt", "mov_text", "text", "microdvd",
|
||||
"subviewer", "subviewer1", "sami", "realtext", "jacosub", "mpl2", "pjs",
|
||||
"vplayer", "stl", "scc", "ttml", "eia_608",
|
||||
}
|
||||
# Bitmap subtitles: matroska only. `mov_text` refuses them
|
||||
# ("Subtitle encoding currently only possible from text to text or bitmap to bitmap").
|
||||
BITMAP_SUB = {
|
||||
"hdmv_pgs_subtitle", "dvd_subtitle", "dvb_subtitle", "dvb_teletext", "xsub",
|
||||
}
|
||||
# Audio the MP4 container + the Apple/Android player matrix both accept as-is.
|
||||
# DELIBERATELY just AAC: AC-3/E-AC-3 in MP4 are legal on Apple hardware but not on the Android
|
||||
# side of the promise, and the owner's rule is "MP4 = every track as AAC" (2026-10-24). Copying
|
||||
# only what is already AAC also keeps the legacy behaviour byte-for-byte for ordinary files.
|
||||
MP4_AUDIO_COPY = {"aac"}
|
||||
|
||||
CONTAINERS = {"mp4": ".mp4", "mkv": ".mkv"}
|
||||
|
||||
|
||||
# ---- probing --------------------------------------------------------------------------
|
||||
|
||||
def probe(path, timeout=180):
|
||||
"""Full ffprobe JSON (streams + format + chapters). None when unreadable.
|
||||
|
||||
Deliberately a separate call from the engines' `transcode.probe()`: that one keeps the
|
||||
legacy flat dict the gates were written against, and changing its shape would touch
|
||||
every caller. One extra ffprobe per item is cheap next to a decode pass.
|
||||
"""
|
||||
r = subprocess.run([FFPROBE, "-v", "error", "-print_format", "json",
|
||||
"-show_streams", "-show_format", "-show_chapters", path],
|
||||
capture_output=True, text=True, encoding="utf-8", errors="replace",
|
||||
timeout=timeout, creationflags=NOWIN)
|
||||
if r.returncode != 0:
|
||||
return None
|
||||
try:
|
||||
return json.loads(r.stdout or "{}")
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _lang(st):
|
||||
return ((st.get("tags") or {}).get("language") or "").lower()
|
||||
|
||||
|
||||
def _title(st):
|
||||
"""The label a player shows for this track.
|
||||
|
||||
ffmpeg writes `title` to MP4's `udta/name` and `handler_name` to the `hdlr` box; the
|
||||
demuxer only reads the latter back, so a later remux drops `udta/name` silently.
|
||||
Both are therefore always written by `ffmpeg_args`.
|
||||
"""
|
||||
tags = st.get("tags") or {}
|
||||
return (tags.get("title") or tags.get("handler_name") or "").strip()
|
||||
|
||||
|
||||
def audio_tracks(js):
|
||||
return [s for s in (js or {}).get("streams", []) if s.get("codec_type") == "audio"]
|
||||
|
||||
|
||||
def sub_tracks(js):
|
||||
return [s for s in (js or {}).get("streams", []) if s.get("codec_type") == "subtitle"]
|
||||
|
||||
|
||||
def attach_tracks(js):
|
||||
return [s for s in (js or {}).get("streams", []) if s.get("codec_type") == "attachment"]
|
||||
|
||||
|
||||
def chapters_of(js):
|
||||
return (js or {}).get("chapters") or []
|
||||
|
||||
|
||||
def _stream_index_map(js, kind):
|
||||
"""ffprobe's absolute index per stream of `kind`, in file order."""
|
||||
return [s["index"] for s in (js or {}).get("streams", []) if s.get("codec_type") == kind]
|
||||
|
||||
|
||||
def _audio_target_codec(st, policy):
|
||||
if policy.get("audio") == "copy":
|
||||
return "copy"
|
||||
codec = (st.get("codec_name") or "").lower()
|
||||
if codec in MP4_AUDIO_COPY:
|
||||
return "copy"
|
||||
return "aac"
|
||||
|
||||
|
||||
def _audio_target_channels(st, policy):
|
||||
ch = int(st.get("channels") or 2)
|
||||
if policy.get("downmix_51"):
|
||||
return 2
|
||||
return max(1, min(ch, 8))
|
||||
|
||||
|
||||
def _audio_kbps(st, policy):
|
||||
"""AAC at the SOURCE's own bitrate (the engines learned this the hard way: a fixed
|
||||
256k on this library's 128k sources cancelled the video saving by itself)."""
|
||||
floor, ceil = 96, 512
|
||||
try:
|
||||
b = int(st.get("bit_rate") or 0) // 1000
|
||||
except Exception:
|
||||
b = 0
|
||||
if b <= 0:
|
||||
b = 192 if int(st.get("channels") or 2) <= 2 else 384
|
||||
return max(floor, min(ceil, b))
|
||||
|
||||
|
||||
# ---- the plan -------------------------------------------------------------------------
|
||||
|
||||
def plan(js, container="mp4", policy=None):
|
||||
"""Turn ffprobe JSON into a carry-over plan.
|
||||
|
||||
`policy` keys:
|
||||
audio "aac" (default) | "copy" - copy is only legal for matroska
|
||||
downmix_51 False (default) | True - the "compatible stereo" opt-out
|
||||
subs "carry" (default) | "drop" | "text_only" (drop bitmap in matroska too)
|
||||
|
||||
Returns a plain dict; every list entry carries the SOURCE stream index so a verdict
|
||||
can name the track it is talking about.
|
||||
"""
|
||||
policy = dict(policy or {})
|
||||
container = (container or "mp4").lower()
|
||||
if container not in CONTAINERS:
|
||||
raise ValueError("unknown container %r" % (container,))
|
||||
if container == "mkv" and "audio" not in policy:
|
||||
# Fidelity mode means "do not touch what the source already carries".
|
||||
policy["audio"] = "copy"
|
||||
if container == "mp4" and policy.get("audio") == "copy":
|
||||
# Honest refusal: AC-3 in MP4 is legal, DTS/FLAC/Opus/Vorbis are not, and the
|
||||
# player matrix is worse than the container matrix. MP4 = AAC.
|
||||
policy["audio"] = "aac"
|
||||
|
||||
aud = audio_tracks(js)
|
||||
subs = sub_tracks(js)
|
||||
att = attach_tracks(js)
|
||||
warnings = []
|
||||
|
||||
audio = []
|
||||
for n, st in enumerate(aud):
|
||||
codec = (st.get("codec_name") or "").lower()
|
||||
target = _audio_target_codec(st, policy)
|
||||
audio.append({
|
||||
"sel": "0:a:%d" % n, "src_index": st.get("index"), "src_codec": codec,
|
||||
"codec": target,
|
||||
"channels": int(st.get("channels") or 2) if target == "aac" else int(st.get("channels") or 2),
|
||||
"target_channels": _audio_target_channels(st, policy) if target == "aac"
|
||||
else int(st.get("channels") or 2),
|
||||
"kbps": _audio_kbps(st, policy) if target == "aac" else 0,
|
||||
"language": _lang(st), "title": _title(st),
|
||||
"default": bool((st.get("disposition") or {}).get("default")),
|
||||
})
|
||||
if target == "aac" and codec not in MP4_AUDIO_COPY:
|
||||
if int(st.get("channels") or 2) > 2 and policy.get("downmix_51"):
|
||||
warnings.append("audio %d (%s %dch) downmixed to stereo by policy"
|
||||
% (n, codec, int(st.get("channels") or 2)))
|
||||
|
||||
subtitle = []
|
||||
skipped = []
|
||||
if policy.get("subs", "carry") != "drop":
|
||||
for n, st in enumerate(subs):
|
||||
codec = (st.get("codec_name") or "").lower()
|
||||
entry = {"sel": "0:s:%d" % n, "src_index": st.get("index"), "src_codec": codec,
|
||||
"language": _lang(st), "title": _title(st),
|
||||
"default": bool((st.get("disposition") or {}).get("default")),
|
||||
"forced": bool((st.get("disposition") or {}).get("forced"))}
|
||||
if codec in BITMAP_SUB:
|
||||
if container == "mkv" and policy.get("subs", "carry") == "carry":
|
||||
entry["codec"] = "copy"
|
||||
subtitle.append(entry)
|
||||
else:
|
||||
skipped.append({"src_index": st.get("index"), "src_codec": codec,
|
||||
"reason": "graphic subtitle cannot be carried into "
|
||||
+ container.upper()})
|
||||
continue
|
||||
if codec in TEXT_SUB:
|
||||
entry["codec"] = "copy" if container == "mkv" else "mov_text"
|
||||
subtitle.append(entry)
|
||||
if container == "mp4":
|
||||
warnings.append("subtitle %d (%s) converted to mov_text: positioning, "
|
||||
"fades, outline/shadow and fonts are lost" % (n, codec))
|
||||
continue
|
||||
skipped.append({"src_index": st.get("index"), "src_codec": codec,
|
||||
"reason": "unknown subtitle codec"})
|
||||
|
||||
if container == "mp4" and att:
|
||||
warnings.append("%d font attachment(s) cannot be carried into MP4 (matroska only)"
|
||||
% len(att))
|
||||
|
||||
return {
|
||||
"container": container,
|
||||
"ext": CONTAINERS[container],
|
||||
"policy": policy,
|
||||
"video_sel": "0:v:0",
|
||||
"audio": audio,
|
||||
"subtitles": subtitle,
|
||||
"subs_skipped": skipped,
|
||||
# 2026-10-30(顾问 Q-07 Option B):位图字幕(PGS/VOBSUB)在 MP4 下**不是"取舍"而是"内容损失"**
|
||||
# —— 以前只记一条 NOTE 就继续,装好之后源档被删,字幕永久消失且没人知道。
|
||||
# 这里把"需要业主决定"的那几条单独挑出来,让调用方可以拦下这一项而不是默默丢掉。
|
||||
"subs_needs_decision": [s for s in skipped if s["src_codec"] in BITMAP_SUB],
|
||||
"attachments": [{"src_index": a.get("index"),
|
||||
"filename": (a.get("tags") or {}).get("filename"),
|
||||
"mimetype": (a.get("tags") or {}).get("mimetype")}
|
||||
for a in att],
|
||||
"attachments_carried": container == "mkv" and bool(att),
|
||||
"chapters": len(chapters_of(js)),
|
||||
"tags": sorted((((js or {}).get("format") or {}).get("tags") or {}).keys()),
|
||||
"warnings": warnings,
|
||||
"multitrack": len(aud) > 1,
|
||||
}
|
||||
|
||||
|
||||
def ffmpeg_args(plan_):
|
||||
"""The mapping / codec arguments (everything between `-i SRC` and the encoder args)."""
|
||||
p = plan_
|
||||
args = ["-map", p["video_sel"]]
|
||||
for a in p["audio"]:
|
||||
args += ["-map", a["sel"]]
|
||||
for s in p["subtitles"]:
|
||||
args += ["-map", s["sel"]]
|
||||
if p["attachments_carried"]:
|
||||
args += ["-map", "0:t"]
|
||||
# Never `-map 0`: MP4's chapter text track and a phone's tmcd data track would come
|
||||
# along and matroska refuses both outright.
|
||||
args += ["-map_metadata", "0", "-map_chapters", "0"]
|
||||
if not p["audio"]:
|
||||
args += ["-an"]
|
||||
for n, a in enumerate(p["audio"]):
|
||||
if a["codec"] == "copy":
|
||||
args += ["-c:a:%d" % n, "copy"]
|
||||
else:
|
||||
args += ["-c:a:%d" % n, "aac", "-b:a:%d" % n, "%dk" % a["kbps"],
|
||||
"-ac:a:%d" % n, str(a["target_channels"])]
|
||||
for n, s in enumerate(p["subtitles"]):
|
||||
args += ["-c:s:%d" % n, "copy" if s["codec"] == "copy" else "mov_text"]
|
||||
if not p["subtitles"]:
|
||||
args += ["-sn"]
|
||||
# Track LABELS. MP4 stores a label twice: `title` -> udta/name (what Apple shows) and
|
||||
# `handler_name` -> the hdlr box (what ffprobe/VLC/mpv show). ffmpeg's demuxer only reads
|
||||
# the hdlr back, so a later remux silently drops udta/name - write both, every time.
|
||||
for kind, entries in (("a", p["audio"]), ("s", p["subtitles"])):
|
||||
for n, e in enumerate(entries):
|
||||
if not e.get("title"):
|
||||
continue
|
||||
args += ["-metadata:s:%s:%d" % (kind, n), "title=%s" % e["title"]]
|
||||
if p["container"] == "mp4":
|
||||
args += ["-metadata:s:%s:%d" % (kind, n), "handler_name=%s" % e["title"]]
|
||||
# 2026-10-30(顾问 Q-09):`default` / `forced` 以前**只读进来、从不写回去**:
|
||||
# 多音轨素材输出后播放器只能按顺序取第 0 条,"强制字幕"也退化成普通轨。
|
||||
# 显式回写(没有标记的就写 `0`,否则 muxer 会自己挑一条标成 default)。
|
||||
# NB verify() 只做宽松断言,不因 disposition 差异判 FAIL —— 不同 FFmpeg 版本的 MP4
|
||||
# muxer 对默认轨/forced 的处理并不一致,拿它当硬门禁会造出永远修不好的失败。
|
||||
# 顾问 Q-16(2026-10-30):**只对 MP4 写** disposition。
|
||||
# 不传 `-disposition` 时 Matroska muxer 会从输入流完整继承整条 disposition 位掩码
|
||||
# (original / comment / hearing_impaired …),而这里只提取了 default / forced 两个布尔值 ——
|
||||
# 一旦对 MKV 显式传 `-disposition:a:n default|0`,就会**用单一标志覆盖整条掩码**,
|
||||
# 把源片自带的保障性标记抹掉,违背 MKV 保真模式"位等同继承"的承诺。
|
||||
if p["container"] == "mp4":
|
||||
for n, a in enumerate(p["audio"]):
|
||||
args += ["-disposition:a:%d" % n, "default" if a.get("default") else "0"]
|
||||
for n, s in enumerate(p["subtitles"]):
|
||||
disp = [w for w, on in (("default", s.get("default")), ("forced", s.get("forced"))) if on]
|
||||
args += ["-disposition:s:%d" % n, "+".join(disp) if disp else "0"]
|
||||
return args
|
||||
|
||||
|
||||
def ffmpeg_mux_args(plan_):
|
||||
"""Container-specific muxer flags (faststart/tag/metadata whitelist)."""
|
||||
p = plan_
|
||||
if p["container"] == "mp4":
|
||||
# +faststart: moov at the front so a shared file starts playing while downloading.
|
||||
# +use_metadata_tags: without it the muxer silently drops every key it does not
|
||||
# know (measured: a custom `custom_key` survived only with this flag).
|
||||
return ["-movflags", "+faststart+use_metadata_tags"]
|
||||
return []
|
||||
|
||||
|
||||
def video_tag_args(plan_, expect_vcodec="hevc"):
|
||||
"""`-tag:v hvc1` is an MP4/Apple requirement; matroska has no use for it.
|
||||
|
||||
Only for HEVC: an hvc1 tag on an H.264 track is refused outright by the MP4 muxer
|
||||
(`Tag hvc1 incompatible with output codec id '27' (avc1)`), which is exactly what a copy
|
||||
tier produces when the source is H.264.
|
||||
"""
|
||||
if plan_["container"] == "mp4" and _strip(expect_vcodec) == "hevc":
|
||||
return ["-tag:v", "hvc1"]
|
||||
return []
|
||||
|
||||
|
||||
# ---- verification ---------------------------------------------------------------------
|
||||
|
||||
def _strip(s):
|
||||
return (s or "").strip().lower()
|
||||
|
||||
|
||||
def _by_type(js, kind):
|
||||
return [s for s in (js or {}).get("streams", []) if s.get("codec_type") == kind]
|
||||
|
||||
|
||||
def _tag_keys(js):
|
||||
return {k.lower() for k in ((((js or {}).get("format") or {}).get("tags") or {}).keys())}
|
||||
|
||||
|
||||
PROMISED_TAGS = ("title", "artist", "album", "date", "comment", "copyright",
|
||||
"description", "creation_time")
|
||||
|
||||
|
||||
def verify(plan_, src_js, out_js, expect_vcodec="hevc"):
|
||||
"""Structural gate: read the carries back out of the produced file.
|
||||
|
||||
Returns (ok, message). Every claim is checked against the file, not against the plan's
|
||||
own hopes - the same rule the video gate follows.
|
||||
"""
|
||||
p = plan_
|
||||
if not out_js:
|
||||
return False, "output unreadable"
|
||||
oa, os_, ot = _by_type(out_js, "audio"), _by_type(out_js, "subtitle"), _by_type(out_js, "attachment")
|
||||
ov = _by_type(out_js, "video")
|
||||
if not ov:
|
||||
return False, "no video stream in output"
|
||||
|
||||
# duration / resolution / pixel family - the structural claims `transcode.verify()` makes,
|
||||
# restated because this gate serves BOTH containers, and its audio expectations can no longer
|
||||
# be "must be AAC": a copied AC-3 track in Matroska is the feature, not a failure.
|
||||
sf = (src_js or {}).get("format") or {}
|
||||
of = (out_js or {}).get("format") or {}
|
||||
try:
|
||||
sd, od = float(sf.get("duration") or 0), float(of.get("duration") or 0)
|
||||
except (TypeError, ValueError):
|
||||
sd, od = 0.0, 0.0
|
||||
if sd and od and abs(od - sd) > max(1.0, sd * 0.01):
|
||||
return False, "duration %.2f vs source %.2f" % (od, sd)
|
||||
sv = _by_type(src_js, "video")
|
||||
if sv:
|
||||
sw, sh = int(sv[0].get("width") or 0), int(sv[0].get("height") or 0)
|
||||
ow, oh = int(ov[0].get("width") or 0), int(ov[0].get("height") or 0)
|
||||
# A rotated source is re-encoded with the picture physically turned upright (ffmpeg's
|
||||
# autorotate), so a SWAPPED pair is the correct result for it, not a mismatch.
|
||||
if (ow, oh) != (sw, sh) and (ow, oh) != (sh, sw):
|
||||
return False, "resolution %sx%s vs %sx%s" % (ow, oh, sw, sh)
|
||||
if _strip(ov[0].get("pix_fmt")) not in ("yuv420p", "yuvj420p", "yuv420p10le",
|
||||
"yuv420p12le", "p010le"):
|
||||
return False, "pixel format %s (want 8/10-bit 4:2:0)" % ov[0].get("pix_fmt")
|
||||
|
||||
if len(oa) != len(p["audio"]):
|
||||
return False, "audio tracks %d in output, %d planned" % (len(oa), len(p["audio"]))
|
||||
for n, (want, got) in enumerate(zip(p["audio"], oa)):
|
||||
gcodec = _strip(got.get("codec_name"))
|
||||
if _strip(want["codec"]) == "copy":
|
||||
if gcodec != _strip(want["src_codec"]):
|
||||
return False, "audio %d codec %s, source was %s (copy lost the stream)" % (
|
||||
n, gcodec, want["src_codec"])
|
||||
else:
|
||||
if gcodec not in ("aac", "mp4a"):
|
||||
return False, "audio %d codec %s (want aac)" % (n, gcodec)
|
||||
if int(got.get("channels") or 0) != int(want["target_channels"]):
|
||||
return False, "audio %d channels %s, planned %s" % (
|
||||
n, got.get("channels"), want["target_channels"])
|
||||
|
||||
if len(os_) != len(p["subtitles"]):
|
||||
return False, "subtitle tracks %d in output, %d planned" % (len(os_), len(p["subtitles"]))
|
||||
for n, (want, got) in enumerate(zip(p["subtitles"], os_)):
|
||||
gcodec = _strip(got.get("codec_name"))
|
||||
wcodec = "copy" if _strip(want["codec"]) == "copy" else "mov_text"
|
||||
want_codec = _strip(want["src_codec"]) if wcodec == "copy" else "mov_text"
|
||||
# matroska renames some text codecs on the way in (srt -> subrip), so a copy is
|
||||
# accepted when both sides are in the same family.
|
||||
if wcodec == "copy" and (gcodec != want_codec) and not (
|
||||
gcodec in TEXT_SUB and want_codec in TEXT_SUB) and not (
|
||||
gcodec in BITMAP_SUB and want_codec in BITMAP_SUB):
|
||||
return False, "subtitle %d codec %s, source was %s" % (n, gcodec, want["src_codec"])
|
||||
if wcodec == "mov_text" and gcodec != "mov_text":
|
||||
return False, "subtitle %d codec %s (want mov_text)" % (n, gcodec)
|
||||
|
||||
if p["attachments_carried"]:
|
||||
if len(ot) != len(p["attachments"]):
|
||||
return False, "attachments %d in output, %d in source" % (len(ot), len(p["attachments"]))
|
||||
|
||||
# chapters and the tags the product promises to carry
|
||||
want_ch = int(p.get("chapters") or 0)
|
||||
got_ch = len(chapters_of(out_js))
|
||||
if want_ch and got_ch != want_ch:
|
||||
return False, "chapters %d in output, %d in source" % (got_ch, want_ch)
|
||||
src_tags = {k.lower() for k in p.get("tags") or []}
|
||||
missing = [k for k in PROMISED_TAGS if k in src_tags and k not in _tag_keys(out_js)]
|
||||
if missing:
|
||||
return False, "metadata key(s) lost: %s" % ", ".join(sorted(missing))
|
||||
|
||||
if p["container"] == "mp4":
|
||||
if expect_vcodec and _strip(ov[0].get("codec_name")) != _strip(expect_vcodec):
|
||||
return False, "vcodec %s (want %s)" % (ov[0].get("codec_name"), expect_vcodec)
|
||||
if expect_vcodec == "hevc" and _strip(ov[0].get("codec_tag_string")) != "hvc1":
|
||||
return False, "codec tag %s (Apple requires hvc1)" % ov[0].get("codec_tag_string")
|
||||
elif expect_vcodec and _strip(ov[0].get("codec_name")) != _strip(expect_vcodec):
|
||||
return False, "vcodec %s (want %s)" % (ov[0].get("codec_name"), expect_vcodec)
|
||||
return True, "ok"
|
||||
|
||||
|
||||
# ---- evidence -------------------------------------------------------------------------
|
||||
|
||||
def stream_signature(path, sel, timeout=1800):
|
||||
"""(nb_packets, md5 of the concatenated packet payloads) for one stream, or None.
|
||||
|
||||
EXACT, not sampled, and container-independent: `-f data` writes the packet payloads and
|
||||
nothing else - no container headers, no random segment/track UIDs, no timestamps - so the
|
||||
same stream demuxed from Matroska and from MP4 hashes identically.
|
||||
|
||||
The head/tail sampling this replaces could not be made exact: cutting with `-t 30` lands on
|
||||
a different final packet depending on the container's timebase, which reported "payload
|
||||
differs" on streams that were byte-identical (a false failure on a good file is the one
|
||||
outcome this gate must never produce). Cost is one linear read of the stream's payload -
|
||||
~2 s per 10 min of audio - and no giant JSON in memory like `-show_packets`.
|
||||
|
||||
ONE exception to "container-independent", and it is an ADTS one: an AAC stream in MPEG-TS is
|
||||
carried as ADTS frames (7-byte header per frame), while MP4 stores the same frames raw with a
|
||||
single `AudioSpecificConfig`. `-f data` therefore returns different bytes for the SAME audio,
|
||||
and the gate reported `a 0: payload differs (src 157137 packets/342d39a4, out 157137
|
||||
packets/38f9b7e6)` - identical packet counts, one extra header per frame. Measured on
|
||||
KODV-0081.ts: raw dumps disagree (87f3e5b6 / 955905a0), both sides through
|
||||
`-bsf:a aac_adtstoasc` agree (955905a0 / 955905a0), and the decoded PCM agrees too. So for
|
||||
AAC the dump goes through that bitstream filter on BOTH sides - it strips ADTS where it exists
|
||||
and is a pass-through where it does not.
|
||||
|
||||
One hard-won constraint on HOW it is computed (measured 2026-11-15, IMOG-159.mkv): the
|
||||
payload must NOT be piped through this process. The previous version ran
|
||||
`ffmpeg ... -f data -` with `stdout=PIPE, stderr=PIPE` and drained stdout in a read loop
|
||||
while stderr was read only after EOF. A source that floods stderr - that Matroska emitted
|
||||
219,020 bytes / 1,630 container-error lines - fills the ~64 KB stderr pipe, ffmpeg blocks
|
||||
writing it, the stdout pipe never closes and the loop blocks for ever: 42 minutes at 2.1 s
|
||||
of CPU, and the supervisor's 60 min stall watchdog had already killed the same item twice.
|
||||
`-f streamhash` lets FFMPEG do the md5 itself (same 32 hex, byte-identical to the pipe
|
||||
dump: 5cb7483040621df964779a9e0fb21d45 both ways on that file, 2.3 s instead of a 48.9 MB
|
||||
pipe), and `capture_output=True` drains both pipes concurrently, so nothing can wedge.
|
||||
"""
|
||||
bsf = []
|
||||
r = subprocess.run([FFPROBE, "-v", "error", "-select_streams", sel, "-count_packets",
|
||||
"-show_entries", "stream=codec_name,nb_read_packets", "-of", "csv=p=0", path],
|
||||
capture_output=True, text=True, encoding="utf-8", errors="replace",
|
||||
timeout=timeout, creationflags=NOWIN)
|
||||
if r.returncode != 0:
|
||||
return None
|
||||
try:
|
||||
parts = (r.stdout or "").strip().splitlines()[0].split(",")
|
||||
codec_name, nb = (parts[0].strip(), int(parts[1]))
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
# 编解码器从 ffprobe 现读,而不是相信调用方传进来的字符串:`plan_` 里存的 `codec` 是
|
||||
# 「copy」这个动作,不是流的真实编码;而这一条 bsf 必须按**真实编码**决定。
|
||||
if codec_name.lower() in ("aac", "aac_latm"):
|
||||
bsf = ["-bsf:a", "aac_adtstoasc"]
|
||||
# `-f streamhash` = ffmpeg's own md5 of the packet payloads (no container bytes), so there is
|
||||
# no payload in flight between us and it. ONE capture_output call drains stdout AND stderr on
|
||||
# separate threads (`communicate`), which is what makes the stderr flood harmless - and on
|
||||
# `timeout` the child is killed, so a wedged demuxer costs one bounded wait instead of a lane.
|
||||
try:
|
||||
p = subprocess.run([FFMPEG, "-v", "error", "-i", path, "-map", "0:" + sel, "-c", "copy"] + bsf +
|
||||
["-f", "streamhash", "-hash", "md5", "-"],
|
||||
capture_output=True, text=True, encoding="utf-8", errors="replace",
|
||||
timeout=timeout, creationflags=NOWIN)
|
||||
except subprocess.TimeoutExpired:
|
||||
return None
|
||||
if p.returncode != 0:
|
||||
return None
|
||||
md5 = ""
|
||||
for line in (p.stdout or "").splitlines():
|
||||
# `0,a,MD5=<hex>` - the leading index is the output stream, `a` its type
|
||||
if "MD5=" in line:
|
||||
md5 = line.rsplit("MD5=", 1)[1].strip().lower()
|
||||
break
|
||||
if len(md5) != 32:
|
||||
return None
|
||||
return nb, md5
|
||||
|
||||
|
||||
def copy_streams_intact(plan_, src_path, out_path):
|
||||
"""(ok, [messages]) - every `copy` stream must carry identical payload packets.
|
||||
|
||||
Stream selectors are ORDINALS inside the type (`a:1`, `s:0`), which is exactly how the
|
||||
mapping is built too, so source and output are addressed the same way.
|
||||
"""
|
||||
msgs = []
|
||||
ok = True
|
||||
for kind, entries in (("a", plan_["audio"]), ("s", plan_["subtitles"])):
|
||||
for n, e in enumerate(entries):
|
||||
if _strip(e.get("codec")) != "copy":
|
||||
continue
|
||||
sel = "%s:%d" % (kind, n)
|
||||
a = stream_signature(src_path, sel)
|
||||
b = stream_signature(out_path, sel)
|
||||
if not a or not b:
|
||||
msgs.append("%s %d: could not hash payload" % (kind, n))
|
||||
ok = False
|
||||
continue
|
||||
if a != b:
|
||||
msgs.append("%s %d: payload differs (src %s packets/%s, out %s packets/%s)"
|
||||
% (kind, n, a[0], a[1][:8], b[0], b[1][:8]))
|
||||
ok = False
|
||||
return ok, msgs
|
||||
|
||||
|
||||
def suffix_for(container):
|
||||
return CONTAINERS.get((container or "mp4").lower(), ".mp4")
|
||||
|
||||
|
||||
def out_path_for(src, container="mp4"):
|
||||
"""Same-name conversion: keep the name when the extension already matches, else swap
|
||||
the extension (an .mp4 source under the fidelity policy becomes `<stem>.mkv`)."""
|
||||
ext = suffix_for(container)
|
||||
if os.path.splitext(src)[1].lower() == ext:
|
||||
return src
|
||||
return os.path.splitext(src)[0] + ext
|
||||
@@ -67,6 +67,64 @@ def _fps(v):
|
||||
return 0.0
|
||||
|
||||
|
||||
# ---- HDR / Dolby Vision, read from the probe's side data ------------------------------------
|
||||
# 2026-10-30(顾问 Q-06):这两组元数据以前**完全没有读**。后果分两头:
|
||||
# * Dolby Vision Profile 5 用的是专有 IPT-PQ-C2 色彩空间,libx265 不看 RPU,裸编出来会严重偏绿/偏紫,
|
||||
# 而安装成功后会删掉源档 —— 不可逆;
|
||||
# * HDR10 丢了 Mastering display / MaxCLL,电视只能猜着 tone map,观感偏暗或高光溢出。
|
||||
# 探针已经带着 -show_streams 的 side_data_list 回来,读它不需要额外开进程。
|
||||
|
||||
|
||||
def _rat(v, scale):
|
||||
"""'34000/50000' -> 34000 (scaled to 50000ths), or None."""
|
||||
try:
|
||||
n, d = str(v).split("/")
|
||||
return int(round(float(n) / float(d) * scale))
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _dv_profile(v):
|
||||
"""'05' / '08' style Dolby Vision profile, or '' when the stream is not DV."""
|
||||
tag = (v.get("codec_tag_string") or "").lower()
|
||||
for sd in (v.get("side_data_list") or []):
|
||||
if "dovi" in (sd.get("side_data_type") or "").lower() or "dolby vision" in (sd.get("side_data_type") or "").lower():
|
||||
p = sd.get("dv_profile")
|
||||
return ("%02d" % int(p)) if p is not None else "?"
|
||||
if tag in ("dvh1", "dvhe"):
|
||||
return "?"
|
||||
return ""
|
||||
|
||||
|
||||
def _master_display(v):
|
||||
"""x265 `master-display=` string from the probe's mastering-display side data, or ''."""
|
||||
for sd in (v.get("side_data_list") or []):
|
||||
if "mastering display" not in (sd.get("side_data_type") or "").lower():
|
||||
continue
|
||||
gx, gy = _rat(sd.get("green_x"), 50000), _rat(sd.get("green_y"), 50000)
|
||||
bx, by = _rat(sd.get("blue_x"), 50000), _rat(sd.get("blue_y"), 50000)
|
||||
rx, ry = _rat(sd.get("red_x"), 50000), _rat(sd.get("red_y"), 50000)
|
||||
wx, wy = _rat(sd.get("white_point_x"), 50000), _rat(sd.get("white_point_y"), 50000)
|
||||
lmax, lmin = _rat(sd.get("max_luminance"), 10000), _rat(sd.get("min_luminance"), 10000)
|
||||
if None in (gx, gy, bx, by, rx, ry, wx, wy, lmax, lmin):
|
||||
return ""
|
||||
return ("G(%d,%d)B(%d,%d)R(%d,%d)WP(%d,%d)L(%d,%d)"
|
||||
% (gx, gy, bx, by, rx, ry, wx, wy, lmax, lmin))
|
||||
return ""
|
||||
|
||||
|
||||
def _content_light(v):
|
||||
"""`max-cll=a,b` from the content-light-level side data, or ''."""
|
||||
for sd in (v.get("side_data_list") or []):
|
||||
if "content light" not in (sd.get("side_data_type") or "").lower():
|
||||
continue
|
||||
a, b = sd.get("max_content"), sd.get("max_average")
|
||||
if a is None or b is None:
|
||||
return ""
|
||||
return "%d,%d" % (int(a), int(b))
|
||||
return ""
|
||||
|
||||
|
||||
def probe(path):
|
||||
r = run([FFPROBE, "-v", "error", "-print_format", "json",
|
||||
"-show_streams", "-show_format", path], timeout=120)
|
||||
@@ -95,6 +153,10 @@ def probe(path):
|
||||
"fmt": (j.get("format", {}).get("format_name") or "").lower(),
|
||||
"rfps": _fps(v.get("r_frame_rate")), "afps": _fps(v.get("avg_frame_rate")),
|
||||
"hbf": int(v.get("has_b_frames") or 0),
|
||||
# HDR / DV(2026-10-30):'' 表示没有。调用方据此决定"拒编"还是"透传静态元数据"。
|
||||
"dv": _dv_profile(v),
|
||||
"mdm": _master_display(v),
|
||||
"cll": _content_light(v),
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user