fix(io): 共享盘读不再无超时 —— 准备阶段流式哈希、回读改三段抽样

8 小时的车道挂死发生在 copy_remote_to_local() 之后的整文件网络重读校验上
(暂存档 9 秒就拷满 842,854,400 B,进程 8 小时 CPU 只有 2.52 s,线程停在
Wait/Executive)。同一个文件在几秒内被 SMB 读第二遍,对 RaiDrive/Dokan 是纯风险。

- copy_remote_to_local(): 边读边喂 sha256,拷完与本地暂存档比对,
  删掉准备阶段的 _sha_remote(src) 整文件重读。证据强度不降(仍证明本地副本
  == 共享盘服务的字节),远程读流量减半。
- 上传/安装回读: _sha_remote() → _sha_remote_sample(),严格 size + 首/中/尾
  各 8 MB(24 MB 证据)。三类真实损坏(截断、moov/cues 未刷、零填充)都会
  改变抽样窗口。
- copy 档补 -tag:v hvc1: 原来 tag 挂在 color_metadata_args 里,被
  `if tier != "copy"` 整段跳过,HEVC 源 remux 成 mp4 会写成 hev1 ——
  iPad 拒播,而且下次扫描的「已达标跳过」判据命不中。
- tracks: disposition 回写(default/forced),没有标记也显式写 0。
- transcode.probe(): 从 side_data_list 读出 Dolby Vision profile /
  mastering display / max-CLL,新增 dv/mdm/cll 三个键。
- DV 源一律 SKIP 拦截(Profile 5 的 IPT-PQ-C2 不被 libx265 识别,裸编会
  偏绿/偏紫,而安装成功会删源 = 不可逆);HDR10 静态元数据能读到就透传。
- 位图字幕(PGS/VOBSUB)进不了 MP4 时整项拦下,不再静默丢弃。
This commit is contained in:
hoelee committed 2026-10-30 01:20:22 +08:00
1 parent fc3d1ff022
commit 8b3d979eb3
3 files changed
+189 -17

No files matched your search

+113 -17
View File
@@ -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),