diff --git a/scripts/library_run.py b/scripts/library_run.py index 50b192e..e378d77 100644 --- a/scripts/library_run.py +++ b/scripts/library_run.py @@ -499,6 +499,61 @@ def _sha_remote(path, label="remote", tries=3): raise last +SAMPLE_CHUNK = 8 << 20 # 24 MB of evidence per file, instead of every byte twice + + +def _sha_sample(path, size, label="sampled"): + """SHA-256 over the FIRST / MIDDLE / LAST 8 MB of a file of `size` bytes. + + Why not the whole file: the share is a RaiDrive/Dokan mount, so every byte read comes over SMB + and every full re-read is another chance to meet a zombie handle that never returns (that is + exactly how lane cpu2 died for 8 hours on 2026-10-29). Why not "size only": size says nothing + about the four corruptions actually observed here - truncation, an unflushed `moov`/`cues` tail, + zero-fill, and a cached OLD file served under the right name. All four change one of the three + sampled windows, and the structural read-back (`probe` + `verify`) covers the rest. + """ + h = hashlib.sha256() + size = int(size) + if size <= 3 * SAMPLE_CHUNK: + spans = [(0, size)] + else: + mid = ((size - SAMPLE_CHUNK) // 2) & ~0xFFFFF # 1 MB 对齐,读起来更快 + spans = [(0, SAMPLE_CHUNK), (mid, SAMPLE_CHUNK), (size - SAMPLE_CHUNK, SAMPLE_CHUNK)] + got = 0 + with open(path, "rb") as f: + for off, ln in spans: + f.seek(off) + b = f.read(ln) + if len(b) != ln: + raise IOError("%s: short sampled read at %d+%d (got %d)" % (label, off, ln, len(b))) + h.update(b) + got += len(b) + return h.hexdigest(), size, got + + +def _sha_remote_sample(path, size, label="remote", tries=3): + """`_sha_sample` over the share, with the size ASSERTED first. + + The size check is the one part that must never be relaxed: a truncated upload is exactly what + RaiDrive does while reporting success (`copy_local_to_remote` returned with 12.5 MB of 403 MB + once). A stale `getsize` only costs a retry, never a false pass, because the sampled reads are + the second opinion. + """ + last = None + for attempt in range(1, tries + 1): + try: + n = os.path.getsize(path) + if n != int(size): + raise IOError("%s size %d != expected %d" % (label, n, int(size))) + d, _, got = _sha_sample(path, size, label) + return d, got + except (OSError, MemoryError) as e: + last = e + log(" ! %s sampled read attempt %d failed: %s" % (label, attempt, e)) + time.sleep(5 * attempt) + raise last + + def copy_remote_to_local(remote, local, expect_size=None, tries=5): """Network -> local. Retried; a short read is a failure, never a silent pass. @@ -507,16 +562,26 @@ def copy_remote_to_local(remote, local, expect_size=None, tries=5): the same time). Smaller chunks, more attempts and a longer backoff ride those hiccups out instead of losing the file - and each failed attempt costs minutes on a 1 GB source, so the point is to stop retrying as fast as we can. + + 2026-10-30: the verification pass is now FREE of extra network reads. It used to re-open the + share copy and hash it a second time (`_sha_remote(remote)`), i.e. a whole second full read of + the same file seconds after the first one - and that read has no timeout, so a zombie SMB handle + blocked it forever (measured 2026-10-29: lane cpu2 sat 8 h on item 3116 with the staged copy + already complete at 842,854,400 bytes and 2.5 s of CPU time). The hash is now computed FROM THE + BYTES AS THEY ARE READ, so it still proves "the local copy is exactly what the share served", + without a second pass that can hang. """ for attempt in range(1, tries + 1): try: n = 0 + h = hashlib.sha256() with open(remote, "rb") as fi, open(local, "wb") as fo: while True: b = fi.read(4 << 20) if not b: break fo.write(b) + h.update(b) n += len(b) fo.flush() os.fsync(fo.fileno()) @@ -525,14 +590,12 @@ def copy_remote_to_local(remote, local, expect_size=None, tries=5): # A read of the RIGHT LENGTH can still be wrong on this share: RaiDrive reports stale # sizes, and a listing read here stopped halfway with no error at all (it looked like a # truncated file and was not). A corrupt staged source would be encoded into a corrupt - # output, so pay for one more pass and compare hashes of what we wrote against a fresh - # read of the share copy. + # output, so compare what the share SERVED against what actually landed on local disk. if n > (64 << 20): - a = _sha_local(local, "staged source") - b = _sha_remote(remote, "share source") - if a != b: - raise IOError("staged source hash mismatch (local %s.. != share %s..)" - % (a[:12], b[:12])) + a, n_loc = _sha_local(local, "staged source") + if (a, n_loc) != (h.hexdigest(), n): + raise IOError("staged source hash mismatch (share stream %s/%d != local %s/%d)" + % (h.hexdigest()[:12], n, a[:12], n_loc)) return n except (OSError, MemoryError) as e: log(" ! source copy attempt %d/%d failed: %s" % (attempt, tries, e)) @@ -1174,6 +1237,13 @@ def color_metadata_args(info, tier, container="mp4"): args.extend(["-color_range", c_range]) x265_range = "full" if c_range == "pc" else "limited" vui_items.append("range=%s" % x265_range) + # HDR10 静态元数据(2026-10-30):探针从 side_data_list 读到的母版亮度/色域原样交给 x265。 + # 10-bit + PQ 只是"能放",这两项才决定电视怎么做 tone mapping —— 缺了它观感会偏暗或高光溢出。 + # 只在真的读到元数据时追加(SDR 源一条都不写,免得给编码器塞无意义的默认值)。 + if info.get("mdm"): + vui_items.append("master-display=%s" % info["mdm"]) + if info.get("cll"): + vui_items.append("max-cll=%s" % info["cll"]) return args, ":".join(vui_items), is_10bit @@ -1218,6 +1288,13 @@ def encode(src_local, dst_local, info, args, tier, vbps, q_off=0, plan=None): cmd += ["-maxrate", str(int(vbps * SIZE_CEIL)), "-bufsize", str(int(vbps * SIZE_CEIL * 2.5))] if tier != "copy": cmd += color_args + else: + # 2026-10-30(顾问轮次 2:格式审查发现的实现脱节):`-tag:v hvc1` 挂在 color_args 里, + # 而 color_args 在 copy 档被整段跳过 —— 于是「只换封装 / 只转音频」的 HEVC 源被 MP4 muxer + # 默认写成 `hev1`:iPad 拒播,而且下次扫描因 codec_tag != hvc1 永远命不中「已达标跳过」判据。 + # video_tag_args 对 H.264 源安全返回 [](hvc1 标签套在 avc1 轨上会被 muxer 直接拒绝)。 + cmd += TR.video_tag_args(plan or {"container": container}, + expect_vcodec=info.get("vcodec") or "") if plan is not None: pass # per-track audio args already came from TR.ffmpeg_args(plan) elif info["acodec"] in ("aac", "mp4a", ""): @@ -1361,6 +1438,13 @@ def process(src, args, dest=None, origin=None): tjs = TR.probe(src) if not tjs: return "FAIL unreadable (track probe)", None + # 2026-10-30(顾问 Q-06 Option A):Dolby Vision 源一律不裸编。 + # Profile 5 用专有 IPT-PQ-C2 色彩空间,libx265 完全不看 RPU → 画面严重偏绿/偏紫, + # 而安装成功后会删掉源档 —— 这是不可逆的内容损坏,不是画质取舍。交回业主决定 + # (保真 MKV / 放弃转换),并把 profile 写进理由里,别让人再去翻日志。 + if info.get("dv"): + return ("SKIP unsupported: dolby vision (profile %s) - 需人工决定(建议保真 MKV 或保留原档)" + % info["dv"]), None plan = TR.plan(tjs, container=container, policy={ "audio": "copy" if container == "mkv" else "aac", "downmix_51": bool(getattr(args, "audio_downmix", False)), @@ -1375,6 +1459,14 @@ def process(src, args, dest=None, origin=None): for s in plan["subs_skipped"]: log(" NOTE: subtitle %s (%s) skipped: %s" % ( s["src_index"], s["src_codec"], s["reason"])) + # 2026-10-30(顾问 Q-07 Option B):图形字幕进不了 MP4 时**拦下整项**,不静默丢弃。 + # 装好之后源档会被删除,丢字幕是不可逆的内容损失 —— 必须让人选择"改走 MKV 保真模式"或"明确放弃"。 + if plan.get("subs_needs_decision"): + return ("SKIP needs decision: %d bitmap subtitle track(s) (%s) cannot be carried into %s " + "- 改用保真 MKV,或明确同意丢弃图形字幕" + % (len(plan["subs_needs_decision"]), + ",".join(sorted({s["src_codec"] for s in plan["subs_needs_decision"]})), + container.upper())), None os.makedirs(STAGE, exist_ok=True) tag = hashlib.sha1(src.encode("utf-8")).hexdigest()[:12] @@ -1555,17 +1647,19 @@ def process(src, args, dest=None, origin=None): # "operation didn't complete within specific time limit" toast arrives afterwards. So a # mismatch is retried rather than reported straight away. h_loc, n_loc = _sha_local(loc_out) + # 抽样指纹(首/中/尾各 8 MB)—— 与共享盘上的副本比对,不再整文件回读。 + smp_loc, smp_n = _sha_sample(loc_out, n_loc, "encoded output") last = "" for up in range(1, 3): if not copy_local_to_remote(loc_out, remote_tmp): last = "FAIL upload" time.sleep(10 * up) continue - h_rem, n_rem = _sha_remote(remote_tmp) - if (h_loc, n_loc) == (h_rem, n_rem): + h_rem, n_rem = _sha_remote_sample(remote_tmp, n_loc, "uploaded temp") + if (h_rem, n_rem) == (smp_loc, smp_n): break last = "FAIL read-back mismatch local=%s/%d remote=%s/%d" % ( - h_loc[:12], n_loc, h_rem[:12], n_rem) + smp_loc[:12], smp_n, h_rem[:12], n_rem) log(" ! %s (upload %d) - retrying" % (last, up)) try: os.remove(remote_tmp) @@ -1601,10 +1695,10 @@ def process(src, args, dest=None, origin=None): if not copy_local_to_remote(loc_out, live): return ("FAIL install: the share refused both the rename (%s) and a direct " "write of %s" % (str(e)[:70], live)), None - h_re, n_re = _sha_remote(live) - if (h_re, n_re) != (h_loc, n_loc): + h_re, n_re = _sha_remote_sample(live, n_loc, "installed file") + if (h_re, n_re) != (smp_loc, smp_n): return ("FAIL install read-back: %s is %s/%d, encoded was %s/%d" - % (live, h_re[:12], n_re, h_loc[:12], n_loc)), None + % (live, h_re[:12], n_re, smp_loc[:12], smp_n)), None try: os.remove(remote_tmp) except OSError: @@ -1618,7 +1712,9 @@ 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") and plan["container"] == "mp4" + # copy 档也要查 hvc1:HEVC 源走 copy 时标签同样必须落成 hvc1(否则 iOS 拒播 + 幂等判据失效) + tag_needed = (plan["container"] == "mp4" + and (tier != "copy" or (info.get("vcodec") or "").lower() == "hevc")) 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): @@ -1632,13 +1728,13 @@ def process(src, args, dest=None, origin=None): # with nothing anywhere reporting an error. So read the installed file back and compare its # hash with what we encoded - the only check that cannot be served from a cache. try: - h_back, n_back = _sha_remote(live) + h_back, n_back = _sha_remote_sample(live, n_loc, "installed file") except OSError as e: return "FAIL install verify: cannot read the installed file back: %s" % e, None - if (h_back, n_back) != (h_loc, n_loc): + if (h_back, n_back) != (smp_loc, smp_n): return ("FAIL install verify: the live file is NOT the encode we made " "(live %s/%d bytes vs ours %s/%d) - the replace did not land" - % (h_back[:12], n_back, h_loc[:12], n_loc)), None + % (h_back[:12], n_back, smp_loc[:12], smp_n)), None return "ok", {"sha256": h_loc, "bytes": n_loc, "src_bytes": n_in, "src_mb": round(info["size"] / 1e6, 1), "out_mb": round(n_loc / 1e6, 1), diff --git a/scripts/tracks.py b/scripts/tracks.py index 1f39bc2..17f5b87 100644 --- a/scripts/tracks.py +++ b/scripts/tracks.py @@ -252,6 +252,10 @@ def plan(js, container="mp4", policy=None): "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")} @@ -299,6 +303,16 @@ def ffmpeg_args(plan_): 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 的处理并不一致,拿它当硬门禁会造出永远修不好的失败。 + 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 diff --git a/scripts/transcode.py b/scripts/transcode.py index 7e6891c..40cd22a 100644 --- a/scripts/transcode.py +++ b/scripts/transcode.py @@ -67,6 +67,64 @@ def _fps(v): return 0.0 +# ---- HDR / Dolby Vision, read from the probe's side data ------------------------------------ +# 2026-10-30(顾问 Q-06):这两组元数据以前**完全没有读**。后果分两头: +# * Dolby Vision Profile 5 用的是专有 IPT-PQ-C2 色彩空间,libx265 不看 RPU,裸编出来会严重偏绿/偏紫, +# 而安装成功后会删掉源档 —— 不可逆; +# * HDR10 丢了 Mastering display / MaxCLL,电视只能猜着 tone map,观感偏暗或高光溢出。 +# 探针已经带着 -show_streams 的 side_data_list 回来,读它不需要额外开进程。 + + +def _rat(v, scale): + """'34000/50000' -> 34000 (scaled to 50000ths), or None.""" + try: + n, d = str(v).split("/") + return int(round(float(n) / float(d) * scale)) + except Exception: + return None + + +def _dv_profile(v): + """'05' / '08' style Dolby Vision profile, or '' when the stream is not DV.""" + tag = (v.get("codec_tag_string") or "").lower() + for sd in (v.get("side_data_list") or []): + if "dovi" in (sd.get("side_data_type") or "").lower() or "dolby vision" in (sd.get("side_data_type") or "").lower(): + p = sd.get("dv_profile") + return ("%02d" % int(p)) if p is not None else "?" + if tag in ("dvh1", "dvhe"): + return "?" + return "" + + +def _master_display(v): + """x265 `master-display=` string from the probe's mastering-display side data, or ''.""" + for sd in (v.get("side_data_list") or []): + if "mastering display" not in (sd.get("side_data_type") or "").lower(): + continue + gx, gy = _rat(sd.get("green_x"), 50000), _rat(sd.get("green_y"), 50000) + bx, by = _rat(sd.get("blue_x"), 50000), _rat(sd.get("blue_y"), 50000) + rx, ry = _rat(sd.get("red_x"), 50000), _rat(sd.get("red_y"), 50000) + wx, wy = _rat(sd.get("white_point_x"), 50000), _rat(sd.get("white_point_y"), 50000) + lmax, lmin = _rat(sd.get("max_luminance"), 10000), _rat(sd.get("min_luminance"), 10000) + if None in (gx, gy, bx, by, rx, ry, wx, wy, lmax, lmin): + return "" + return ("G(%d,%d)B(%d,%d)R(%d,%d)WP(%d,%d)L(%d,%d)" + % (gx, gy, bx, by, rx, ry, wx, wy, lmax, lmin)) + return "" + + +def _content_light(v): + """`max-cll=a,b` from the content-light-level side data, or ''.""" + for sd in (v.get("side_data_list") or []): + if "content light" not in (sd.get("side_data_type") or "").lower(): + continue + a, b = sd.get("max_content"), sd.get("max_average") + if a is None or b is None: + return "" + return "%d,%d" % (int(a), int(b)) + return "" + + def probe(path): r = run([FFPROBE, "-v", "error", "-print_format", "json", "-show_streams", "-show_format", path], timeout=120) @@ -95,6 +153,10 @@ def probe(path): "fmt": (j.get("format", {}).get("format_name") or "").lower(), "rfps": _fps(v.get("r_frame_rate")), "afps": _fps(v.get("avg_frame_rate")), "hbf": int(v.get("has_b_frames") or 0), + # HDR / DV(2026-10-30):'' 表示没有。调用方据此决定"拒编"还是"透传静态元数据"。 + "dv": _dv_profile(v), + "mdm": _master_display(v), + "cll": _content_light(v), }