stream_signature() ran ffmpeg -f data - with stdout=PIPE, stderr=PIPE and drained stdout first, reading stderr only after EOF. A source that floods stderr (a Matroska with 1,612 'exceeds containing master element' errors = 219,020 bytes) fills the 64 KB stderr buffer, ffmpeg blocks writing it, stdout never closes and the read loop blocks for ever - 42 min at 2.1 s of CPU, and the supervisor's gate watchdog killed the same item three times at 60 min each. p.wait(timeout=1800) cannot help: it is unreachable until that loop ends. -f streamhash -hash md5 - lets ffmpeg do the md5 itself (byte-identical: 5cb7483040... both ways on that file, 2.3 s instead of a 48.9 MB pipe) and one subprocess.run(capture_output=True, timeout=...) drains both fds on threads, so the stderr flood cannot wedge and a wedged demuxer costs a bounded wait that returns None (the gate then says 'could not hash payload', never 'payload differs'). Return shape (nb_packets, md5) and every caller unchanged. test_tracks 55/55, including 'e2e mkv/mp4: copied streams are byte-identical' on the real fixtures.
569 lines
28 KiB
Python
569 lines
28 KiB
Python
"""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
|