Compare commits

..
Author SHA1 Message Date
hoelee b1b7dbdff1 tracks: hash the carried payload with -f streamhash, never through a PIPE pair
stream_signature() ran ffmpeg -f data - with stdout=PIPE, stderr=PIPE and drained
stdout first, reading stderr only after EOF. A source that floods stderr (a Matroska
with 1,612 'exceeds containing master element' errors = 219,020 bytes) fills the 64 KB
stderr buffer, ffmpeg blocks writing it, stdout never closes and the read loop blocks
for ever - 42 min at 2.1 s of CPU, and the supervisor's gate watchdog killed the same
item three times at 60 min each. p.wait(timeout=1800) cannot help: it is unreachable
until that loop ends.

-f streamhash -hash md5 - lets ffmpeg do the md5 itself (byte-identical: 5cb7483040...
both ways on that file, 2.3 s instead of a 48.9 MB pipe) and one
subprocess.run(capture_output=True, timeout=...) drains both fds on threads, so the
stderr flood cannot wedge and a wedged demuxer costs a bounded wait that returns None
(the gate then says 'could not hash payload', never 'payload differs').

Return shape (nb_packets, md5) and every caller unchanged. test_tracks 55/55,
including 'e2e mkv/mp4: copied streams are byte-identical' on the real fixtures.
2026-11-16 00:36:07 +08:00
hoelee 7c1a243aad trash GC: measure the 72h hold from ARRIVAL, not from the original's mtime
Retiring an original is `os.replace`, which keeps the file's own mtime, so a 2014 movie replaced today
carried a 2014 timestamp into the quarantine and `st_mtime > cutoff` judged it expired on arrival —
measured 2026-11-10 on the owner's library: 86 of 118 quarantined entries were already "expired" the
moment they landed, i.e. the promised 72-hour rollback window was 0 hours for every old file.

New `trash_entry_ts()`: sidecar `ts` (written by move_to_trash, second precision) → `<date>/` directory
name taken as END of that day (a day late, never a second early) → mtime only as the last resort.
`purge_trash()` now gates on it. The three safety invariants are unchanged: a sidecar whose `live` file
is gone is the LAST copy and is never collected, the `.purge` stamp still throttles a directory to one
sweep an hour, and deletion stays per-file (never rmtree).

Tests (hevc-transcode/tests/test_engine_install_gates.py): fake-expiry helpers now backdate the sidecar
`ts` too; two new pins — an old original replaced today must keep its full 72 h, and a missing sidecar
may only ever make an entry look younger.
2026-11-10 09:49:48 +08:00
hoelee 15ddca2e5f fix(install): --dest 是目录时在编码前就拒绝(别再白花一次编码)
安装段现在也会拒,但那是在编码之后 —— 实测 92 s 的短片白跑一遍,一集正片就是一个小时。
把这条判断提到 process() 的入口(probe 之前):0.2 s 返回
`FAIL install target is a directory: … (`--dest` wants a file path)`,源与目录都不动。
2026-11-01 14:31:16 +08:00
hoelee 4b5cbe0ab6 fix(install): --dest 指到目录时拒绝安装,别把目录 rename 进隔离区
端到端实测(Z: 真共享盘,14:18)发现的:`--dest` 要的是文件路径,而第一版在两阶段提交的
"移走目标名上的东西" 一步不区分文件与目录 —— 传一个目录过去就把那个目录整块搬进了
`.transcode_trash`(0 字节、可回滚,但业主会看到目录凭空消失)。

现在:`live` 是目录 → 直接 `FAIL install refused: … exists and is a directory`,
目录与里面的文件一个都不动,源也留在原地(14:26 实测 keepme.txt 还在、源 4713 B 未动)。
同时把回执里的 `install.quarantine` 统一成文件名(原来 pre-publish 记文件名、post-install 记全路径)。
2026-11-01 14:27:55 +08:00
hoelee 46c9177386 feat(install): 三道防坏防丢门禁 —— 尾部实包解码 / 同卷隔离区两阶段提交 / 无缓冲回读
§10.161 的复盘结论不是「再查一遍」,是三个结构性缺口,逐个补上:

① tail_decode_gate():上传后真解码远端副本的最后几秒。
   `+faststart` 把 moov 放在文件头,所以 ffprobe 对截断文件照样报全长 ——
   抽检 1,340 件成品里 6 件截断(1.4 GB 只剩 36.9 MB)全都过了既有门禁。
   窗口 min(5s, dur/2),短片不假阳性;`-map 0:v:0?` 让无视频流不误红。

② 隔离区两阶段提交(move_to_trash / restore_from_trash / purge_trash / publish_staged):
   安装段不再 `os.replace` 覆盖 + `os.remove(src)` 删原件,而是
   目标名上的文件同卷 rename 进 `<dir>/.transcode_trash/<date>/`(0 字节拷贝、可回滚),
   发布成功才让它留在那儿;发布或装后任一闸门失败就地回滚。
   GC 72 h 后回收,且**旁注里的 live 已消失时绝不删**(那是最后一份)。

③ _win_unbuffered_read / _sha_sample_nocache / _sha_remote_sample_nocache:
   抽样回读走 FILE_FLAG_NO_BUFFERING,Dokan/RaiDrive 的缓存池再也答不上话。
   读窗按扇区对齐并按 GetFileSizeEx 裁到最后一个整扇区(无缓冲读不许跨 EOF,
   越过末尾是 ERROR_INVALID_PARAMETER 而不是 EOF);末尾 < 4 KB 的零头用普通读补。
   短读抛 _ShortRead 并**不许**退回缓存读;只有文件系统拒绝该 flag 才降级,
   并把 bypassed=False 写进回执。

隔离区对引擎 collect() 不可见(否则退休的原件会被重新入队)。
门禁默认全开,`--no-tail-gate` 只是紧急刹车,`--trash-ttl-hours` 默认 72。
真共享盘端到端实测:源 213,827 B → hvc1 25,854 B,原件逐字节躺在隔离区,cache_bypass=true。
版本 1.2.0 → 1.3.0(contract 3 不变)。
2026-11-01 14:15:29 +08:00
hoelee 005b824e4f fix(verify): AAC 从 TS 换封装到 MP4 不是掉包,别再判 payload differs
MPEG-TS 里的 AAC 是 ADTS 帧(每帧 7 字节头),MP4 存同样的帧但不带头、配置进
AudioSpecificConfig。`-f data` 直接把包负载吐出来,于是同一条音轨、同一个包数
(实测 157137 / 157137)却被判 `a 0: payload differs (src .../342d39a4, out .../38f9b7e6)`,
一份好片被记成 infra 失败、退避三次后进 #block-infra。

实测(KODV-0081.ts / 20 s 窗口):
  raw    src=87f3e5b6  out=955905a0   不一致 -> 假阳性
  bsf    src=955905a0  out=955905a0   一致
  pcm    src=d86dbbed  out=d86dbbed   一致
故两边都过 `-bsf:a aac_adtstoasc`(TS 侧剥 ADTS 头,MP4 侧无操作)。编解码器从
ffprobe 现读(`plan_` 里的 codec 是「copy」动作名,不是流的真实编码)。
截断的副本仍然被拒,测试里两条都钉住了。
2026-10-30 02:58:56 +08:00
hoelee 0e5c74e5b5 fix(install): 抽样函数改成三返回值后,安装段还在按两值解包 —— 每一件过门禁的好片都在安装前一秒崩
`_sha_sample()` 为了支持五窗口抽样改成返回 (指纹, size, 实读字节),安装段
`smp_loc, smp_n = _sha_sample(...)` 没跟着改,于是抛
`ValueError: too many values to unpack (expected 2, got 3)`,
被队列判成 `infra: 引擎跑完了,但一个闸门数字都没产出`,退避三次后转 failed:
队列看起来什么都没完成,而日志里 SSIM 明明是过的。

实测三例:gpu 2169 KODV-0081.ts(4 infra -> failed)、cpu 3297 GOD-076.avi、
cpu3 3405。`_sha_remote_sample` 仍是两值(指纹, 实读字节),四个调用点都对得上。
2026-10-30 02:13:23 +08:00
hoelee 94350f18b3 fix(mux): -disposition 只对 MP4 写;hev1 源原地降级为 copy 重封装
顾问 Q-16 / Q-17(轮次 3 裁定):

- tracks.py::ffmpeg_args 的 -disposition 回写整块包进 container=="mp4"。
  不传时 matroska muxer 会从输入流继承整条 disposition 掩码(original/comment/
  hearing_impaired…),而 plan() 只提取 default/forced —— 显式传就是用单一标志
  覆盖整条掩码,抹掉 MKV 保真标记
- library_run.py::encode 在 tier_for_bpp 之后加一个分支:mp4 + hevc + tag!=hvc1 +
  yuv420p + 时间轴健康 → 直接 tier="copy"。走 -c:v copy -tag:v hvc1 无损重封装
  (copy 档本就跳过 SSIM),不再为一颗标签重编整片
2026-10-30 02:00:34 +08:00
hoelee 8b3d979eb3 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 时整项拦下,不再静默丢弃。
2026-10-30 01:20:22 +08:00
hoelee fc3d1ff022 fix(tracks): ffprobe / ffmpeg 子进程统一 CREATE_NO_WINDOW
Windows 上每次探测轨道、取流摘要都会闪一个黑窗(命令行窗口),
批量扫描几百个文件时尤其明显。ffprobe 的 subprocess.run 与
_stream_digest 的 ffmpeg Popen/run 全部加 creationflags=NOWIN,
与 library_run.py / transcode.py 的既有做法保持一致。

scripts.test_tracks 55/55。
2026-10-29 08:03:18 +08:00
hoelee e66551200f fix(install): rename 到幽灵名失败时改用「直写最终名 + 回读 sha256」
实测(2026-10-28, Z:\Temporary\短视频\_io-test):.mov → .mp4 装不进去,三次都死在
os.replace('…new.mp4','…hevc-pcm.mp4') 的 WinError 32,而同一目录手搓 os.replace 全成功 ——
是幽灵条目:os.path.exists 说存在、ls 同一目录看不到,服务端已忘记该名字,任何 rename 都失败。

- 先按「短暂占用」重试 5 次退避(实测无效,5 秒内全失败)
- 最终处理:还剩本地已验证产物,就直接写到最终名并回读 sha256 比对,再清 staged 名
实测:19 MB -> 18 MB (93%) | copy,audio=aac、video md5 与源逐位相同。

同时把这条 .mov 样本的 io 链路跑通(前两轮分别是 win32 占用与幽灵名),
三条样本现在全部 hevc hvc1 + aac mp4a。
2026-10-28 22:24:29 +08:00
hoelee 6950f75d26 fix(copy): --overwrite 现在真的生效 —— 已是 HEVC hvc1 但音轨非 AAC 时重封音轨而不是 SKIP
--overwrite 从加进 argparse 起就没被读过(只在 help 里)。控制面换了规则之后需要一个
「视频没问题、这条仍要跑」的开关:kind="audio" 的行(hevc + ac3/mp3/pcm)在 copy 挡位
只能被 SKIP,结果是控制面把行标成 done 而音轨一条没动。

audio_only_remux = args.overwrite and acodec not in (aac, mp4a, "") → 不吃 already_hevc 的
SKIP,走正常 copy 流程;实测输出 video md5 与源逐位相同、audio 转成 aac。
2026-10-28 22:02:07 +08:00
hoelee 64a80d2234 fix(gate): the space-reclaim class is about the PICTURES, not the audio codec
An h264 mp4 with an mp3 track was excluded from the 0.990 second tier, but encode() already
re-encodes non-AAC audio to AAC in the same pass (-c:a aac -b:a <source kbps>), so that track is
fixed whichever picture bar applies. Holding the PICTURE to 0.995 because of it is exactly the
rule that the size ceiling makes unreachable. Renamed plays_everywhere -> space_reclaim_source
to say what it actually decides (owner 2026-10-25: 「把音轨转 AAC 后也按二档跑」).
2026-10-25 04:32:18 +08:00
hoelee 57e950da8f fix(gate): an already-playable source gets the 0.990 second tier - 0.995 and the size ceiling are mutually exclusive
Measured on 用超富集植物种植金属 (1280x720@30, 1832 kbps source, 96 s):
  crf 19 under -maxrate 1832k -> 20.6 MB, SSIM mean 0.99192   REFUSED
  crf 14 under the SAME ceiling -> 22.9 MB, SSIM mean 0.99195   five steps, +0.00003
  crf 19 uncapped              -> 40.6 MB, SSIM mean 0.99648   passes at 172% of the source
Reaching 0.995 needs >=125% of the source's own bitrate, which SIZE_CEIL=1.0 forbids, so
every gear below the ceiling produces the same file. Production: 487 FAIL quality rounds,
106.2 h of encoding; 194 of 202 files with two measured rounds moved < 0.0015.

Rule (owner 2026-10-25): a source that already plays everywhere (h264+avc1, aac/mp4a, mp4/m4v/mov)
is a space-reclaim job - the same situation SSIM_MEAN_MIN_REDO already rules on - so when 0.995
is missed it is accepted at SSIM_MEAN_MIN_FALLBACK (0.990), and the provably inert quality+2
retry is skipped. Unplayable sources keep 0.995; a frame-share defect is still refused at any tier.

Also: numpy is now a declared dependency and its absence is an INSTALL PROBLEM, not a silent
fallback - 305 of 418 production run logs were measured with the flat-frame scan skipped.
2026-10-25 03:58:02 +08:00
hoelee 68a2265026 fix(tracks): honour TRANSCODE_FFPROBE instead of the bare name
packaged builds ship ffmpeg inside their own tree; tracks.py called `ffprobe` by
bare name, which only resolved because this host has ffmpeg on PATH. The bundle
acceptance strips PATH on purpose, so probe() raised FileNotFoundError [WinError 2]
two seconds into the item and the queue logged it as a quality refusal.
Mirror transcode.py:36-37 (TRANSCODE_*/RT_* with a bare fallback).
2026-10-24 08:53:39 +08:00
Hermes Agent f088ae78e3 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).
2026-10-24 03:56:30 +08:00
8 changed files with 1754 additions and 77 deletions

No files matched your search

+8
View File
@@ -37,6 +37,14 @@ There are **no credentials** in this project, so there is no `SECRETS.md`.
6. **Never write encode output straight to a network share.** Encode to local disk, verify,
then copy the complete file across; a streaming `.part` write leaves a corrupt stub on any
blip. If the destination is remote, keep the output local.
7. **Never read one child PIPE while leaving the other undrained.** `subprocess.run(...,
capture_output=True, timeout=…)` (or sending the noisy fd to a file) is the default; a
`while p.stdout.read():` loop with `p.stderr` still holding a PIPE will deadlock the moment
the child fills that pipe — measured 2026-11-15: a corrupt Matroska emitted 219 KB of
container errors, ffmpeg blocked writing stderr, the gate sat 42 min at 2.1 s CPU and the
supervisor killed the item three times (see `STATE.md` bug 14). `p.wait(timeout=)` does
NOT save you: it is unreachable until that read loop ends. A loop that drains a child owes
itself a deadline.
## 3. Layout
+11 -4
View File
@@ -176,12 +176,19 @@ from a small runner instead:
2. encode locally, with the same mandatory flags (`-fps_mode cfr`, `-pix_fmt yuv420p`)
3. run the structural gate **and** a full decode pass on the local output
4. upload to `<name>.new.mp4` (never the final name)
5. read the share copy back end-to-end and compare **SHA-256 + byte count** with the local file
6. only then `os.replace()` it over the original, and re-probe the result on the share
5. read the uploaded copy back with the **Windows cache bypassed** (`FILE_FLAG_NO_BUFFERING`) and
compare **SHA-256 + byte count** with the local file, then really **decode its last seconds**
(`-sseof -5 -f null -`)
6. only then **two-phase-commit** it: move the original into the same-volume quarantine
`<dir>/.transcode_trash/<date>/` (an inode rename — never a delete), publish the verified file,
and roll the original back if the publish or any post-install gate fails
Step 5 costs one extra network read (~1 h per 330 GiB) and is the only thing that actually
proves the remote copy is complete — `getsize()` cannot, and neither can a duration probe:
with `+faststart` the `moov` is written first, so a truncated file still reports full duration.
proves the remote copy is complete — `getsize()` cannot, a duration probe cannot (with
`+faststart` the `moov` is written first, so a truncated file still reports full duration), and a
buffered read cannot either: Dokan/RaiDrive answer sampled windows from the local cache pool while
the server holds a fraction of the file. Step 6 is what makes a failed install recoverable: the
original is in the quarantine, not gone.
Keep a JSONL ledger and a per-file skip test ("already HEVC hvc1") so a reboot resumes safely.
A single instance only; the lock matters even more here because two runs would race on `dst`.
+45 -2
View File
@@ -320,8 +320,16 @@ live = HEVC hvc1 **且**音轨是 AAC(真能播)**且**本次是从快照原
- [ ] **等业主定 D-07(队列仓 PLAN §7)**:`0705机械宇宙` 按指示跑过 `--crf 24`,仍是 mean **0.9120**、坏帧 **8.93%**、
`vmaf480` **59.41** —— 与 crf29 逐位相同 ⇒ **源档缺陷**(引擎自己标了 non-uniform cadence),别再降参数;
要么接受原档,要么单独走"源档缺陷"口径。同类还有 3 项 `engine-skip`(park 满 2 轮)。
- [ ] **cpu(x265)档门槛问题**:crf29 在 bpp 0.0147–0.0293 带成立(0.9958/0.9968),但 **bpp ≳0.05 那一带 4/4 落到
0.9926–0.9946**(720p、源 ~1.17 Mbps)→ 每项白烧 2 次整片编码后 park。选项 A `cpu_crf→24` / B 放行到 0.990。
- [x] **cpu(x265)档门槛问题**(2026-10-25 结案):crf29 在 bpp 0.0147–0.0293 带成立(0.9958/0.9968),但 bpp ≳0.05
那一带 4/4 落到 0.9926–0.9946(720p、源 ~1.17 Mbps)→ 每项白烧 2 次整片编码后 park。
**根因不是档位,是 `SIZE_CEIL=1.0` 的 `-maxrate` 与 0.995 互斥**:实测 720p/1832 kbps 源,
crf 19 在上限内 = 0.99192(87% 大小)、**crf 14 在同一上限内 = 0.99195**(五档只动 0.00003)、
放开上限 crf 19 = 0.99648 但要 **172%** 大小 ⇒ 到 0.995 需源码率的 **125%** 以上。
**已定(业主 2026-10-25)**:走选项 B,但只对「本来就能播的源」——`plays_everywhere()`(h264+aac+mp4/m4v/mov)
在 0.995 不过时直接按 `SSIM_MEAN_MIN_FALLBACK`(0.990) 收下,判决写
`second tier 0.990: the source already plays everywhere, so this is a space-reclaim job`;
不可播源仍 0.995,帧占比缺陷任何档位都拒。同时**不再跑那次注定无效的 quality+2 重试**。
同机实测:同一文件由 `FAIL quality 0.9923` 变为 `ok`,87.5% 大小,单次编码 120 s。
- [ ] 两档跑完 → **全库落地审计**:`D:\dev\hevc-transcode\cache\install_audit.py`(核对线上文件真实大小 + 编码器;曾一次抓到"报告成功没落地")+ `copy_land_check.py`(copy 档用音轨 aac/mp3 判定)。
- [ ] 失败项:无需清单,新一轮自动重做(失败时文件原样)。
- [ ] `2022年/0723 《走出强迫症》/走出强迫症.mp4` 用新下载(`D:\Download\0723走出强迫症.mp4`,618,696,954 B)已转好装好(450,502,893 B,HEVC+AAC,SSIM min 0.997,时长 3399.81 s)✓。**快照里那份仍是坏的**(618,697,011 B,moov 缺失)→ 待定:是否用干净副本替换快照里的坏档,以免将来"从原档重转"踩坑。
@@ -438,6 +446,41 @@ work 盘只剩 3.9 GB → 队列守卫拒绝所有新项,两条 lane 空转 30
回归:`scripts/test_stage_cleanup.py` 6 项(另一 lane 不动 / 死残留删 / 在编 tag 保全 / 台账不动 / 字节数正确)。
## 第 14 个 bug:gate 阶段的 payload 指纹把 stderr 管道锁死(2026-11-15)
**症状**:控制面看板显示某条 CPU 车道「校验」42 分钟不动(`phase_s` 一直涨),引擎日志停在
`carry: …` 那一行之后再没写过字。看门狗按 `stalled in gate for 60 min with no I/O progress`
连杀三次,每条白烧一小时;同一个铁轨上还有 1,484 条待办。
**真因**:`tracks.stream_signature()` 用
`ffmpeg … -f data -` 把整个音频 payload(这个片 48.9 MB)打到 stdout,`stdout=PIPE,
stderr=PIPE`,然后 `while True: p.stdout.read(1 << 20)` 读干 stdout,**stderr 只有 EOF 之后
才读**。这个 Matroska 结构是坏的(1,612 处 `Element … exceeds containing master element`),
ffmpeg 往 stderr 吐了 219,020 字节 / 1,630 行;Windows 匿名管道缓冲 4–64 KB,写满后
ffmpeg 阻塞在写 stderr,stdout 永不 EOF,父进程永久阻塞。`p.wait(timeout=1800)` 的 timeout
在 stdout 读完之前根本用不上 —— 等于没有超时。
**证据(同一文件、同一 ffmpeg)**:
| 跑法 | 结果 |
|---|---|
| 引擎里的写法(stderr 挂管道不读) | 42 分钟/2.1 s CPU,永远不回 |
| 同命令 pipe → `md5sum`(stderr 走终端) | 11.7 s,`5cb7483040621df964779a9e0fb21d45` |
| `-f streamhash -hash md5 -` | 2.3 s,**同一 md5** |
**修**:`-f streamhash -hash md5 -` 让 ffmpeg 自己算 md5(payload 不再穿过本进程),
并改成**一次** `subprocess.run(capture_output=True, timeout=…)` —— `communicate()` 用线程
同时抽干 fd,stderr 再大也堵不住,超时就杀子进程并返回 `None`(闸门按「拿不到指纹」处理,
绝不会把一次超时误判成「payload 不同」)。包数仍由 ffprobe 给,返回形状
`(nb_packets, md5)` 不变。
**回归**:`python -m unittest test_tracks` 55/55(含 `e2e mkv/mp4: copied streams are
byte-identical`);真文件上 `stream_signature(src) == stream_signature(out)` 且 6.9 s 完成。
**教训(已写进 AGENTS §2 第 7 条)**:子进程的 stdout/stderr 要么都交给
`subprocess.run(capture_output=True)`,要么至少有一个落文件;**不许**在一个 PIPE 上边读边
等另一个 PIPE。任何"读干子进程输出"的循环都必须带自己的 deadline,不能指望 `wait(timeout=)`。
## 红线(用户明确要求过)
- **绝不删除/覆盖快照原档**(`#snapshot` 是唯一的干净档案)。
+18 -6
View File
@@ -142,10 +142,20 @@ Per item, in this order:
4. **SSIM vs the source window >= target** (section 2).
5. **Size assertion**, per the regime in section 1: hard `out <= src` where the source has
headroom; runaway guard `out <= 1.25x src` where the pre-flight says it is already compressed.
6. **Upload to a temp name, read the share copy back end-to-end, compare SHA-256 + byte count**,
then replace atomically. A duration probe is not enough: with `+faststart` the `moov` is written
first, so a truncated upload still reports the full duration.
7. **Re-probe on the share** after the replace.
6. **Upload to a temp name, then read it back with the Windows cache bypassed**
(`FILE_FLAG_NO_BUFFERING`) and compare SHA-256 + byte count. A duration probe is not enough:
with `+faststart` the `moov` is written first, so a truncated upload still reports the full
duration — and a *buffered* read can be answered from the Dokan/RaiDrive cache pool while the
server holds a fraction of the file.
7. **Decode the last seconds of the uploaded copy** (`ffmpeg -v error -xerror -sseof -5 -i TMP
-map 0:v:0? -f null -`). This is the only check that forces ffmpeg to the physical tail; a
short file ends in `partial file` / `Invalid NAL unit size` instead of silence.
8. **Two-phase commit, never `os.replace` over the original**: move whatever occupies the target
name into a same-volume quarantine `<dir>/.transcode_trash/<date>/` (an inode rename: 0 bytes
copied, reversible), publish the verified file, and roll the original straight back if the
publish or any post-install gate fails. The quarantine is collected after 72 h — and an entry
whose installed file is gone is never collected, because that is the last copy.
9. **Re-probe on the share** after the publish.
Cheap confidence check on a healthy file, one distinct value expected:
@@ -278,8 +288,10 @@ Measured audit of such a set (54 files converted at `-cq 27` + a fixed 256k audi
* the encode reads the **original**, the tier is classified from the **original's** bpp, and the
gates compare against the **original** - the converted file is never used as a reference;
* `dst` stays the live path, so the output replaces the (bloated) converted file;
* **the original is never modified or deleted** - `os.remove(src)` is suppressed whenever the
source came from the origin tree. Getting this backwards would destroy the only clean copy.
* **the original is never modified or deleted** - the quarantine move is suppressed whenever the
source came from the origin tree (and so is `--keep-source`). Getting this backwards would
destroy the only clean copy. For a normal in-place install the source is *retired into the
quarantine*, not deleted: `purge_trash()` is the only thing that ever unlinks one, 72 h later.
## 9. CPU and GPU tiers in parallel
+784 -65
View File
File diff suppressed because it is too large. Load diff
+258
View File
@@ -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 (`<control-plane>/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)
+568
View File
@@ -0,0 +1,568 @@
"""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 <x> ... 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 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`.
ONE exception to "container-independent", and it is an ADTS one: an AAC stream in MPEG-TS is
carried as ADTS frames (7-byte header per frame), while MP4 stores the same frames raw with a
single `AudioSpecificConfig`. `-f data` therefore returns different bytes for the SAME audio,
and the gate reported `a 0: payload differs (src 157137 packets/342d39a4, out 157137
packets/38f9b7e6)` - identical packet counts, one extra header per frame. Measured on
KODV-0081.ts: raw dumps disagree (87f3e5b6 / 955905a0), both sides through
`-bsf:a aac_adtstoasc` agree (955905a0 / 955905a0), and the decoded PCM agrees too. So for
AAC the dump goes through that bitstream filter on BOTH sides - it strips ADTS where it exists
and is a pass-through where it does not.
One hard-won constraint on HOW it is computed (measured 2026-11-15, IMOG-159.mkv): the
payload must NOT be piped through this process. The previous version ran
`ffmpeg ... -f data -` with `stdout=PIPE, stderr=PIPE` and drained stdout in a read loop
while stderr was read only after EOF. A source that floods stderr - that Matroska emitted
219,020 bytes / 1,630 container-error lines - fills the ~64 KB stderr pipe, ffmpeg blocks
writing it, the stdout pipe never closes and the loop blocks for ever: 42 minutes at 2.1 s
of CPU, and the supervisor's 60 min stall watchdog had already killed the same item twice.
`-f streamhash` lets FFMPEG do the md5 itself (same 32 hex, byte-identical to the pipe
dump: 5cb7483040621df964779a9e0fb21d45 both ways on that file, 2.3 s instead of a 48.9 MB
pipe), and `capture_output=True` drains both pipes concurrently, so nothing can wedge.
"""
bsf = []
r = subprocess.run([FFPROBE, "-v", "error", "-select_streams", sel, "-count_packets",
"-show_entries", "stream=codec_name,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:
parts = (r.stdout or "").strip().splitlines()[0].split(",")
codec_name, nb = (parts[0].strip(), int(parts[1]))
except Exception: # noqa: BLE001
return None
# 编解码器从 ffprobe 现读,而不是相信调用方传进来的字符串:`plan_` 里存的 `codec` 是
# 「copy」这个动作,不是流的真实编码;而这一条 bsf 必须按**真实编码**决定。
if codec_name.lower() in ("aac", "aac_latm"):
bsf = ["-bsf:a", "aac_adtstoasc"]
# `-f streamhash` = ffmpeg's own md5 of the packet payloads (no container bytes), so there is
# no payload in flight between us and it. ONE capture_output call drains stdout AND stderr on
# separate threads (`communicate`), which is what makes the stderr flood harmless - and on
# `timeout` the child is killed, so a wedged demuxer costs one bounded wait instead of a lane.
try:
p = subprocess.run([FFMPEG, "-v", "error", "-i", path, "-map", "0:" + sel, "-c", "copy"] + bsf +
["-f", "streamhash", "-hash", "md5", "-"],
capture_output=True, text=True, encoding="utf-8", errors="replace",
timeout=timeout, creationflags=NOWIN)
except subprocess.TimeoutExpired:
return None
if p.returncode != 0:
return None
md5 = ""
for line in (p.stdout or "").splitlines():
# `0,a,MD5=<hex>` - the leading index is the output stream, `a` its type
if "MD5=" in line:
md5 = line.rsplit("MD5=", 1)[1].strip().lower()
break
if len(md5) != 32:
return None
return nb, md5
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 `<stem>.mkv`)."""
ext = suffix_for(container)
if os.path.splitext(src)[1].lower() == ext:
return src
return os.path.splitext(src)[0] + ext
+62
View File
@@ -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),
}