"""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 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`. """ 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, creationflags=NOWIN) 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, creationflags=NOWIN) 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