From f088ae78e33491bef51ad70914c4a1e87420eaca Mon Sep 17 00:00:00 2001 From: Hermes Agent Date: Sat, 24 Oct 2026 03:46:14 +0800 Subject: [PATCH] feat(tracks): carry every audio track, subtitle and font attachment MP4 (default) keeps the 'opens anywhere' promise: all audio tracks become AAC at the source's own channel layout (5.1 stays 5.1), text subtitles become mov_text, bitmap subtitles are skipped with a logged note, font attachments are not carried. container=mkv is the explicit fidelity mode: every audio/subtitle/attachment stream is copied bit-for-bit, chapters and tags ride along. New scripts/tracks.py holds the pure plan + the container-aware gate; library_run.py uses it for mapping, per-track codecs, container extension, install-path names and the hvc1 check (Matroska has no codec tag). Capability report gains container/audio_downmix/ subs and 'containers' (contract 3, version 1.2.0). Verified: scripts/test_tracks.py 55/55 (both containers end to end, per-packet md5), plus two real library_run.py runs (MP4 3x AAC incl. 6ch + 2x mov_text; MKV bit-exact). --- scripts/library_run.py | 133 ++++++++--- scripts/test_tracks.py | 258 +++++++++++++++++++++ scripts/tracks.py | 507 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 868 insertions(+), 30 deletions(-) create mode 100644 scripts/test_tracks.py create mode 100644 scripts/tracks.py diff --git a/scripts/library_run.py b/scripts/library_run.py index fd86c2c..98793e5 100644 --- a/scripts/library_run.py +++ b/scripts/library_run.py @@ -35,6 +35,7 @@ import time sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import transcode as T # noqa: E402 +import tracks as TR # noqa: E402 (audio/subtitle/attachment carry-over) FFMPEG = T.FFMPEG FFPROBE = T.FFPROBE @@ -1107,7 +1108,7 @@ def qsv_preset_value(name): return v -def color_metadata_args(info, tier): +def color_metadata_args(info, tier, container="mp4"): """Detect 10-bit and build accurate color space / VUI parameters for photography / master preservation.""" pix = (info.get("pix") or "").lower() bits = info.get("bits") or 0 @@ -1145,9 +1146,12 @@ def color_metadata_args(info, tier): args = [ "-profile:v", profile, "-pix_fmt", target_pix, - "-tag:v", "hvc1", "-fps_mode", "cfr" ] + # `-tag:v hvc1` is an Apple/MP4 requirement (hev1 is refused by iOS). Matroska has no use + # for a codec tag and a hand-written one only makes the file look odd to other muxers. + if container == "mp4": + args[4:4] = ["-tag:v", "hvc1"] vui_items = [] if c_prim and c_prim not in ("unknown", "unspecified", "reserved"): @@ -1167,10 +1171,12 @@ def color_metadata_args(info, tier): return args, ":".join(vui_items), is_10bit -def encode(src_local, dst_local, info, args, tier, vbps, q_off=0): +def encode(src_local, dst_local, info, args, tier, vbps, q_off=0, plan=None): + container = (plan or {}).get("container") or "mp4" cmd = [FFMPEG, "-y", "-hide_banner", "-loglevel", "warning", "-stats", - "-i", src_local, "-map", "0:v:0", "-map", "0:a:0?", "-map_metadata", "0"] - color_args, x265_vui, is_10bit = color_metadata_args(info, tier) + "-i", src_local] + (TR.ffmpeg_args(plan) if plan else + ["-map", "0:v:0", "-map", "0:a:0?", "-map_metadata", "0"]) + color_args, x265_vui, is_10bit = color_metadata_args(info, tier, container) if tier == "copy": # Nothing to win: the video is copied bit-for-bit, which is the strongest possible # answer to "same picture quality" and the smallest file that still plays everywhere. @@ -1205,14 +1211,17 @@ def encode(src_local, dst_local, info, args, tier, vbps, q_off=0): cmd += ["-maxrate", str(int(vbps * SIZE_CEIL)), "-bufsize", str(int(vbps * SIZE_CEIL * 2.5))] if tier != "copy": cmd += color_args - if info["acodec"] in ("aac", "mp4a", ""): + if plan is not None: + pass # per-track audio args already came from TR.ffmpeg_args(plan) + elif info["acodec"] in ("aac", "mp4a", ""): cmd += ["-c:a", "copy"] else: # AAC at the SOURCE's own bitrate: a fixed 256k added ~128 kbps for no audible gain on # this library's 128k mp3 sources, which by itself cancelled the video saving. abr = args.audio or ("%dk" % match_audio_kbps(src_local)) cmd += ["-c:a", "aac", "-b:a", abr, "-ac", "2"] - cmd += ["-movflags", "+faststart", dst_local] + cmd += TR.ffmpeg_mux_args(plan) if plan else ["-movflags", "+faststart"] + cmd += [dst_local] t0 = time.time() r = run_watched(cmd, dst_local) return r, time.time() - t0 @@ -1227,31 +1236,43 @@ def decode_check(path): # ---------------------------------------------------------------- per file -def dst_path_for(src): - """In-place: the SAME name for an existing .mp4/.MP4 (the share is case-sensitive), - .mp4 for anything else.""" - if os.path.splitext(src)[1].lower() == ".mp4": - return src - return os.path.splitext(src)[0] + ".mp4" +def dst_path_for(src, container="mp4"): + """In-place: the SAME name when the extension already matches the target container + (the share is case-sensitive), else ``. + + `container` arrived with the carry-over work (2026-10-24): the fidelity policy writes + Matroska, and a `.mp4` source therefore becomes `.mkv` instead of being replaced + by a same-named MP4 that would have dropped its subtitles and fonts. + """ + return TR.out_path_for(src, container) -def already_hevc(src, info): - """Self-describing resume test: the share copy is already HEVC hvc1 and matches.""" - if info["vcodec"] != "hevc" or info["tag"] != "hvc1": +def already_hevc(src, info, container="mp4"): + """Self-describing resume test. + + MP4 is self-describing through `hvc1` (the Apple gate). Matroska is not: a Matroska + HEVC track reports an empty codec tag, so the container itself is the evidence - a + `.mkv` holding HEVC has already been through this engine (it is the only thing that + writes `.mkv` here). + """ + if info["vcodec"] != "hevc": return False - return True + if container == "mp4": + return info["tag"] == "hvc1" + return os.path.splitext(src)[1].lower() == TR.suffix_for(container) def process(src, args, dest=None, origin=None): + container = (getattr(args, "container", None) or "mp4").lower() info = probe(src) if not info: return "FAIL unreadable", None if info["dur"] < 1.0: return "FAIL stub (%.1fs) - needs a re-download, not a transcode" % info["dur"], None - live = dest or dst_path_for(src) + live = dest or dst_path_for(src, container) redo_playable = False # True once we know this run is re-doing a file that ALREADY plays - if info["vcodec"] == "hevc" and info["tag"] == "hvc1" and info["pix"] in ("yuv420p",) \ + if already_hevc(src, info, container) and info["pix"] in ("yuv420p",) \ and not T.unusable_timeline(info, src)[0]: # Already converted. Only worth touching if the ORIGINAL is available and the current # file is BIGGER than it: that is precisely the old settings' damage (a fixed cq27 above @@ -1298,11 +1319,34 @@ def process(src, args, dest=None, origin=None): log(" tier=%s bpp=%.4f src_video=%.0f kbps %sx%s@%.0f %s" % ( tier, bpp, vbps / 1000, info["w"], info["h"], src_fps(info), os.path.basename(src)[:46])) + # ---- carry-over plan: every audio track, every subtitle, every font attachment --------- + # Read from the source, not from the filename: how many tracks a file has is a property of + # the file. MP4 = AAC + mov_text (lossy but plays everywhere); MKV = bit-exact copy of every + # audio/subtitle/attachment (owner decision 2026-10-24: MP4 stays the default, Matroska is + # the explicit fidelity mode). + tjs = TR.probe(src) + if not tjs: + return "FAIL unreadable (track probe)", None + plan = TR.plan(tjs, container=container, policy={ + "audio": "copy" if container == "mkv" else "aac", + "downmix_51": bool(getattr(args, "audio_downmix", False)), + "subs": getattr(args, "subs", None) or "carry", + }) + log(" carry: %d audio (%s), %d subtitle (%s), %d attachment(s), %d chapter(s)" % ( + len(plan["audio"]), "copy" if container == "mkv" else "aac", + len(plan["subtitles"]), "copy" if container == "mkv" else "mov_text", + len(plan["attachments"]), plan["chapters"])) + for w in plan["warnings"]: + log(" NOTE: %s" % w) + for s in plan["subs_skipped"]: + log(" NOTE: subtitle %s (%s) skipped: %s" % ( + s["src_index"], s["src_codec"], s["reason"])) + os.makedirs(STAGE, exist_ok=True) tag = hashlib.sha1(src.encode("utf-8")).hexdigest()[:12] loc_src = os.path.join(STAGE, tag + "_src" + os.path.splitext(src)[1].lower()) - loc_out = os.path.join(STAGE, tag + "_out.mp4") - remote_tmp = live + ".new.mp4" + loc_out = os.path.join(STAGE, tag + "_out" + plan["ext"]) + remote_tmp = live + ".new" + plan["ext"] for p in (loc_src, loc_out): if os.path.exists(p): os.remove(p) @@ -1318,7 +1362,7 @@ def process(src, args, dest=None, origin=None): attempt, q_off, el = 0, 0, 0.0 while True: attempt += 1 - r, el = encode(loc_src, loc_out, info, args, tier, vbps, q_off) + r, el = encode(loc_src, loc_out, info, args, tier, vbps, q_off, plan) if r.returncode != 0 or not os.path.exists(loc_out): # A backend that never STARTED is not a bad encode (Batch 4b-1): say so, so the queue # records "backend unavailable" instead of offering quality remedies for an item whose @@ -1328,7 +1372,14 @@ def process(src, args, dest=None, origin=None): return "FAIL backend %s unavailable: %s" % (which, line), None return "FAIL ffmpeg rc=%s %s" % (r.returncode, (r.stderr or "").strip()[-300:]), None # 3. verify the LOCAL output (structural + full decode) - ok, msg = T.verify(info, loc_out, expect_vc, "aac", check_decode=False) + ok, msg = TR.verify(plan, tjs, TR.probe(loc_out), expect_vc) + if ok and plan["container"] == "mp4" and T.flat_timing(T.probe(loc_out) or {}, loc_out): + ok, msg = False, "flat composition offsets survived (ctts<=1 on a B-frame stream)" + if ok: + # The carry-over promise is only real if the copied payloads are the SAME bytes. + same, smsg = TR.copy_streams_intact(plan, loc_src, loc_out) + if not same: + ok, msg = False, "carry-over: " + "; ".join(smsg[:3]) if not ok: return "FAIL verify: %s" % msg, None if DECODE_CHECK and not args.no_decode_check: @@ -1465,12 +1516,12 @@ def process(src, args, dest=None, origin=None): and os.path.abspath(live) != os.path.abspath(src): os.remove(src) back = probe(live) - tag_needed = (tier != "copy") + tag_needed = (tier != "copy") and plan["container"] == "mp4" if not back or back["vcodec"] != expect_vc \ or (tag_needed and back["tag"] != "hvc1") \ or abs(back["dur"] - info["dur"]) > max(1.0, info["dur"] * 0.01): return "FAIL read-back probe: %s" % (back and (back["vcodec"], back["tag"], back["dur"]),), None - ok, msg = probe_ok(live, info, expect_vc) + ok, msg = TR.verify(plan, tjs, TR.probe(live), expect_vc) if not ok: return "FAIL post-replace gate on share: %s" % msg, None # Metadata can lie on this share. RaiDrive/Dokan serves CACHED attributes, and a rename did @@ -1557,6 +1608,19 @@ def build_parser(): "original, and the original is never modified or deleted") ap.add_argument("--audio", default=None, help="audio bitrate; default = the SOURCE's own bitrate (never a fixed 256k)") + # --- carry-over (2026-10-24): every audio track, every subtitle, every font attachment --- + # MP4 stays the default (owner decision: "opens anywhere" beats "keeps the styling"); + # Matroska is the explicit fidelity mode, where audio/subtitles/attachments are COPIED. + ap.add_argument("--container", choices=["mp4", "mkv"], default="mp4", + help="mp4 = plays everywhere (AAC audio + mov_text subtitles); mkv = fidelity " + "mode (all audio/subtitle/attachment streams copied bit-exactly, but iOS' " + "native player cannot open Matroska)") + ap.add_argument("--audio-downmix", action="store_true", + help="downmix multichannel audio to stereo AAC (the 'compatible stereo' opt-out; " + "the default keeps the source's channel layout - 5.1 stays 5.1)") + ap.add_argument("--subs", choices=["carry", "text_only", "drop"], default="carry", + help="subtitle policy: carry (default), text_only (skip bitmap subtitles even in " + "matroska), drop (no subtitles at all)") ap.add_argument("--nvenc-preset", default=NVENC_PRESET) ap.add_argument("--qsv-quality", type=int, default=None, help="Intel QSV quality (`-global_quality`). NO DEFAULT ON PURPOSE: the scale is " @@ -1603,10 +1667,12 @@ def build_parser(): # copy that can disagree with the code it describes; # * it prints one line and exits BEFORE any run setup (no stage sweep, no mkdir, no lock), so asking # costs nothing and changes nothing. -CAPABILITIES_VERSION = 2 # bump when the SHAPE or the MEANING of the report changes +CAPABILITIES_VERSION = 3 # bump when the SHAPE or the MEANING of the report changes + # 3 (2026-10-24): + flags container/audio_downmix/subs, + `containers` # (1 = Batch 5a introduced it; 2 = 4b-1 added the `qsv` tier and its two # knobs, so `tiers`/`quality_knobs`/`defaults` all gained entries) -__version__ = "1.1.0" # human/ledger build id; the control plane only prints it +__version__ = "1.2.0" # human/ledger build id; the control plane only prints it + # 1.2.0 (2026-10-24): multi-track audio / subtitles / attachments # Which options are quality dials, and their names in the report. The NAME->option mapping has to be # written down (only a human knows which flags are quality knobs), but every VALUE is read back out of @@ -1637,7 +1703,14 @@ def capabilities(ap=None): ("stage_dir", "--stage-dir"), ("dest", "--dest"), ("keep_source", "--keep-source"), - ("lock_tag", "--lock-tag"))}, + ("lock_tag", "--lock-tag"), + # carry-over (2026-10-24): a control plane that asks + # for `--container mkv` must know this build accepts it + ("container", "--container"), + ("audio_downmix", "--audio-downmix"), + ("subs", "--subs"))}, + "containers": list(getattr(act("--container"), "choices", None) or []), + "quality_knobs": {k: knob(v) for k, v in sorted(QUALITY_KNOB_OPTIONS.items())}, "defaults": {"work": WORK, "root": ROOT, "crf": getattr(act("--crf"), "default", None), @@ -1798,7 +1871,7 @@ def main(): cand = None origin = cand if cand and os.path.exists(cand) else None try: - status, extra = process(f, args, dest=args.dest or dst_path_for(f), origin=origin) + status, extra = process(f, args, dest=args.dest or dst_path_for(f, args.container), origin=origin) except Exception as e: status, extra = "FAIL %s: %s" % (type(e).__name__, e), None # Any failure raised out of process() may leave the staged upload target on the @@ -1808,7 +1881,7 @@ def main(): # piled up). Delete it unconditionally - a metadata check on this share can serve # a stale answer, so "not found" is the only outcome that is ignored. try: - staged = (args.dest or dst_path_for(f)) + ".new.mp4" + staged = (args.dest or dst_path_for(f, args.container)) + ".new" + TR.suffix_for(args.container) os.remove(staged) log(" ! removed the orphaned staging file %s" % staged) except FileNotFoundError: diff --git a/scripts/test_tracks.py b/scripts/test_tracks.py new file mode 100644 index 0000000..1e633d9 --- /dev/null +++ b/scripts/test_tracks.py @@ -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 (`/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) diff --git a/scripts/tracks.py b/scripts/tracks.py new file mode 100644 index 0000000..54fee01 --- /dev/null +++ b/scripts/tracks.py @@ -0,0 +1,507 @@ +"""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 ... 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 hashlib +import json +import os +import subprocess + +FFMPEG = "ffmpeg" +FFPROBE = "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) + 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, + "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"]] + 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`. + """ + r = subprocess.run([FFPROBE, "-v", "error", "-select_streams", sel, "-count_packets", + "-show_entries", "stream=nb_read_packets", "-of", "csv=p=0", path], + capture_output=True, text=True, encoding="utf-8", errors="replace", + timeout=timeout) + if r.returncode != 0: + return None + try: + nb = int((r.stdout or "").strip().splitlines()[0]) + except Exception: # noqa: BLE001 + return None + p = subprocess.Popen([FFMPEG, "-v", "error", "-i", path, "-map", "0:" + sel, "-c", "copy", + "-f", "data", "-"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + h = hashlib.md5() + try: + while True: + chunk = p.stdout.read(1 << 20) + if not chunk: + break + h.update(chunk) + finally: + p.stdout.close() + err = p.stderr.read() if p.stderr else b"" + p.stderr.close() + p.wait(timeout=timeout) + if p.returncode != 0: + return None + return nb, h.hexdigest() + + +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 `.mkv`).""" + ext = suffix_for(container) + if os.path.splitext(src)[1].lower() == ext: + return src + return os.path.splitext(src)[0] + ext