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).
This commit is contained in:
1 parent
72a8971d3f
commit
f088ae78e3
3 files changed
+868
-30
No files matched your search
+103
-30
@@ -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),
|
||||
<stem>.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 `<stem><container ext>`.
|
||||
|
||||
`container` arrived with the carry-over work (2026-10-24): the fidelity policy writes
|
||||
Matroska, and a `.mp4` source therefore becomes `<stem>.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:
|
||||
|
||||
Reference in new issue
Block a user