Peach: Local-first video metadata scraper and media manager.
feat(media): 缺 ctts 的 MP4 改为重建头无损播,不再实时转码
longmeidaodced01c93dfc
diff --git a/docs/REUSE.md b/docs/REUSE.mdindex c274ab6f7..4a637a44f 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -160,6 +160,7 @@ CloudDrive 为外部应用,本项目不捆绑其二进制或依赖其管理 AP| 自研实现 | 被拒绝的候选 | 不可替代约束 ||---|---|---|| `mp4index.py` 有界 MP4 关键帧索引 | PyAV、`pymp4`、Bento4 | PyAV 需要 demux,`pymp4` 依赖旧 Construct,Bento4 是额外二进制;都不能证明在云盘文件上保留「只读 moov/stss/stts、避免整片流量」的约束。 |+| `mp4repair.py` 重建缺失的 `ctts`,新头存成边车 | `ffmpeg -c copy` 重封装、`untrunc`、Bento4 `mp4edit` | ffmpeg 的 h264 解复用器拿不回显示顺序(实测重封装后仍有 986/2015 帧倒着走),`untrunc` 修的是截断不是缺表,`mp4edit` 只会原地重写整个文件——网盘上的片子改一个字节就是几 GB 重传。约束是「原文件一个字节不动、播放时拼出合规 MP4」。 || `certs.py` 固定项目 CA 与短期叶证书(编码继续调用 OpenSSL) | mkcert、cryptography | mkcert 会接管本机 CA 安装/私钥,不能保持跨设备固定项目 CA;cryptography 只替换证书编码且增加原生依赖,不能删除 Peach 的 Apple 398 天与 CA 生命周期策略。 || `migrations.py` SQLite 迁移 | Alembic | Alembic 会引入 SQLAlchemy/Mako/greenlet;现有范围只需顺序 SQL、校验和、备份与 PyInstaller 资源定位,没有 ORM 消费者。 || Gofile API 直接 HTTP | 社区 wrapper | 官方没有维护中的 Python SDK;社区 wrapper 只是薄封装,不能绕过 Premium `contents` 权限,也不能减少 Peach 的 Bearer 隔离与媒体规范化。 |@@ -194,6 +195,7 @@ CloudDrive 为外部应用,本项目不捆绑其二进制或依赖其管理 AP- 缓存型资产路由一律先问缓存,不先解析源文件:`media_engine.file_for()` 里那句存在性检查落在 CloudDrive 挂的网盘上,实测一次 137–402 毫秒,一屏几十张缩略图全部命中缓存也要为这几十次往返等好几秒。缩好之后源文件在不在都不改变响应,`/photo-thumb` 因此先问 `photo_service.cached()`。- 账本路径在 Windows 只做 `abspath`,不 `resolve()`:PikPak 的 A: 是 WinFsp 映射的网络驱动器,实测(2026-09-13)`resolve()` 一条文件路径 7.5 秒、结果是 UNC 形态,对它 stat 14 秒、open 7 秒,同一文件走盘符 1 毫秒;115 的 B: 不受影响。播放链路里每个请求都要经过 `file_for()`,这一处决定 PikPak 的 stream-plan 与每个 Range 请求是几十秒还是零点几秒。- 不兼容片源(HEVC、mp3 以外的音轨、非 MP4 容器)一律按 6 秒片重编码给 HLS,账本没记时长或记成负数时用 ffprobe 报的时长切;探测也拿不到才回 Range。分片重编码链与整片转码相同(CUDA 解码加 NVENC、软件解码加 NVENC、libx264),同一分片并发只起一个 FFmpeg,Range 响应按 1 MiB 读文件、客户端一断开就停读。uvicorn 断开后 `send()` 静默返回、Starlette 的 `FileResponse` 不监听断开,`BufferedFileResponse` 因此自己盯 `http.disconnect`;实测(2026-09-13)不盯的话拖一次进度条就留下一个幽灵读者,把 115 上整部片剩下的几 GB 经 CloudDrive 拉完,新位置排在它后面,直到整部片进缓存才能播。+- 有 B 帧却没有 `ctts` 的 MP4 只是时间戳错乱:容器声明的显示时刻其实是解码顺序,浏览器把倒着走的帧全丢掉(6297 实测整片掉两成,PotPlayer 与 FFmpeg 按解码器输出重排所以本地看着正常)。这类片源不重编码,改为重建一份 `moov`(游程编码的 `ctts`、编辑列表补整体平移、`stco`/`co64` 按头长差平移)存成 `transcode_root` 里的 `.mp4hdr` 边车,`/stream` 用「边车的头 + 原文件那段 mdat」拼出虚拟文件按 Range 发。显示顺序由一趟 `ffprobe -ignore_editlist 1 -show_entries frame=pts` 取得——解码器按显示顺序出帧、每帧的 pts 原样来自它那个样本;`pkt_dts` 记的是出帧时最后喂进去的包,不能用。边车没算出来前照旧走 HLS 转码,同一部片后台只算一次,算不出来就不再试。- 「只采集」对齐全的行(番号已落库、字段有着落或已在候选表、封面在位)不碰磁盘;文件在不在看目录列表,同目录只列一次;候选 CSV 每 5 秒落盘一次、被打断也在收尾写全;扫描从目录列表自带的大小与时间登记文件,不逐个 stat。账本副本、外部来源换桩、媒体挂载只读的实测(2026-09-13):本地盘 2553 行 2 秒,115 每秒约 65 行、PikPak 约 35 行,进入首行前的准备 0.4 秒;真实运行每条缺资料的行另加联网时间,联网仍是串行。- 一个控件在两页出现时,选中态怎么表现也归它,不只是外框和材质:首页与资料页的「全部/没看过/稍后看/已标记」共用 `syncViewGlide` 那块滑动玻璃,填充只由玻璃给,两排各自不铺底。找那一排按结构(`#viewPills,.entityviews`)加「此刻量得出宽度」,不按 id:两排在同一份文档里一直都在,另一页开着的时候只是被祖先收起来,写死 id 会一直取到看不见的那一排。- 统计与口味两页按登录态 Vercel Analytics/Speed Insights 的当前页面重做,排行与数据源共用父网格的引导线。diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex f7a03f0aa..887a83b97 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -55,7 +55,8 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_task_runs.py", "test_task_center_integration.py","test_frame_capture.py", "test_timeline_sheets.py","test_web_timeline_thumbnails.py",- "test_interaction.py", "test_media.py", "test_previews.py",+ "test_interaction.py", "test_media.py", "test_mp4repair.py",+ "test_previews.py","test_providers.py", "test_segments.py", "test_streaming.py","test_subtitles.py", "test_transcodes.py"),"sync": ("test_sync*.py", "test_platform.py", "test_mount.py", "test_tray.py", "test_log_retention.py",@@ -159,6 +160,7 @@ AUTO_SCOPE_PREFIXES: tuple[tuple[str, str | tuple[str, ...]], ...] = (("src/peach/media.py", "media"),# 关键帧与 ctts 都从 moov 读,测试住在 `test_segments.py` 里。("src/peach/mp4index.py", "media"),+ ("src/peach/mp4repair.py", "media"),("src/peach/desktop_startup.py", "tooling"),("src/peach/desktop_uninstall.py", "tooling"),("src/peach/peach_proxy.py", "tooling"),diff --git a/src/peach/api.py b/src/peach/api.pyindex 7a4d44fb4..64b26c8d8 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -48,6 +48,7 @@ from .media import (MediaUnavailable,)from .mdns import create_mdns_publisher+from .mp4repair import HeaderRepairStorefrom .previews import PhotoThumbnailService, PreviewServicefrom .providers import OpenCodeGoClient, default_registryfrom .repository import LedgerDatabase, LedgerRepository@@ -141,6 +142,7 @@ def create_app()photo_service = PhotoThumbnailService(settings.photo_root)transcode_service = TranscodeService(resolver, settings.transcode_root)+ header_repairs = HeaderRepairStore(settings.transcode_root, resolver)hls_plan_executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="PeachHlsPlan",)@@ -241,6 +243,7 @@ def create_app(app.state.preview_service = preview_serviceapp.state.photo_service = photo_serviceapp.state.transcode_service = transcode_service+ app.state.header_repairs = header_repairsapp.state.hls_plan_executor = hls_plan_executorapp.state.hls_service = hls_serviceapp.state.mdns = mdnsdiff --git a/src/peach/mp4repair.py b/src/peach/mp4repair.pynew file mode 100644index 000000000..a631c31cf--- /dev/null+++ b/src/peach/mp4repair.py@@ -0,0 +1,461 @@+"""给缺 `ctts` 的 MP4 重建一份正确的头,原文件一个字节都不动。++有 B 帧却没有 `ctts` 的片子,容器声明的显示时刻就是解码顺序,浏览器会把倒着走的帧+全丢掉(实测整片掉两成)。缺的只是 `moov` 里那张表,`mdat` 里的码流本身是好的,所以+修法是重新算一份 `moov`、单独存成边车,播放时用「修好的头 + 原文件的 mdat」拼出一个+合规 MP4。不重编码,不动画质,也不必把几 GB 的片子重写一遍——网盘上的文件改一个字节+就是整份重传。++显示顺序从解码器要:`ffprobe` 解一遍,输出的帧本来就是按显示顺序来的,每帧带着来源样本+的 `pts`,于是「解码序 → 显示序」的置换是直接读出来的,不必自己解析 POC。+"""+from __future__ import annotations++import logging+import struct+import subprocess+import threading+from dataclasses import dataclass+from pathlib import Path++from .mp4index import _iter_boxes++LOGGER = logging.getLogger(__name__)++#: 会往下拆的容器盒子,其余一律当成不透明的叶子原样搬。+CONTAINERS = frozenset({b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts"})+#: 头部盒子加起来的上限;超过这个数就不是我们认识的片源,宁可不修。+HEADER_LIMIT = 64 << 20+PROBE_TIMEOUT_SECONDS = 900+SIDECAR_MAGIC = b"PEACHMP4\x01"+SIDECAR_SUFFIX = ".mp4hdr"+++class RepairUnavailable(RuntimeError):+ """这个片源修不了。调用方照旧走转码分片,不要把异常当故障报。"""+++@dataclass(frozen=True)+class RepairedHeader:+ """修好的头,加上原文件里那段照搬的 `mdat` 内容。++ 拼出来的文件是 `prefix + source[payload_start:payload_end] + suffix`。+ """++ prefix: bytes+ payload_start: int+ payload_end: int+ suffix: bytes = b""++ @property+ def size(self) -> int:+ return len(self.prefix) + (self.payload_end - self.payload_start) + len(self.suffix)+++@dataclass+class _Box:+ kind: bytes+ payload: bytes | None+ children: list["_Box"]++ def serialize(self) -> bytes:+ body = self.payload if self.payload is not None else b"".join(+ child.serialize() for child in self.children)+ return struct.pack(">I", len(body) + 8) + self.kind + body++ def find(self, kind: bytes) -> "_Box | None":+ return next((child for child in self.children if child.kind == kind), None)+++def _parse(payload: bytes, start: int, end: int) -> list[_Box]:+ boxes = []+ for kind, body, stop in _iter_boxes(payload, start, end):+ if kind in CONTAINERS:+ boxes.append(_Box(kind, None, _parse(payload, body, stop)))+ else:+ boxes.append(_Box(kind, payload[body:stop], []))+ return boxes+++def _top_level(handle) -> list[tuple[bytes, int, int, int]]:+ """顶层盒子:(类型, 盒子起点, 内容起点, 盒子终点)。"""+ size = handle.seek(0, 2)+ boxes = []+ offset = 0+ while offset < size:+ handle.seek(offset)+ header = handle.read(16)+ if len(header) < 8:+ break+ box_size = int.from_bytes(header[0:4], "big")+ body = offset + 8+ if box_size == 1:+ if len(header) < 16:+ break+ box_size = int.from_bytes(header[8:16], "big")+ body = offset + 16+ elif box_size == 0:+ box_size = size - offset+ if box_size < 8 or offset + box_size > size:+ break+ boxes.append((header[4:8], offset, body, offset + box_size))+ offset += box_size+ return boxes+++def _sample_table(trak: _Box) -> _Box | None:+ mdia = trak.find(b"mdia")+ minf = mdia.find(b"minf") if mdia else None+ return minf.find(b"stbl") if minf else None+++def _is_video(trak: _Box) -> bool:+ mdia = trak.find(b"mdia")+ hdlr = mdia.find(b"hdlr") if mdia else None+ return bool(hdlr and hdlr.payload and hdlr.payload[8:12] == b"vide")+++def _decode_times(stts: bytes) -> list[int]:+ """把游程编码的 `stts` 摊开成每个样本的 dts。"""+ count = struct.unpack_from(">I", stts, 4)[0]+ times: list[int] = []+ elapsed = 0+ cursor = 8+ for _ in range(count):+ if cursor + 8 > len(stts):+ raise RepairUnavailable("stts 长度和声明的条目数对不上")+ run, delta = struct.unpack_from(">II", stts, cursor)+ cursor += 8+ for _ in range(run):+ times.append(elapsed)+ elapsed += delta+ return times+++def _display_order(ffprobe: Path, source: Path, decode_times: list[int]) -> list[int]:+ """每个样本(解码序)的显示名次。++ 解码器吐出来的帧就是显示顺序,每帧的 `pts` 原样来自它那个样本;这里 pts 就等于 dts,+ 所以按 dts 反查解码序即可。用的不是 `pkt_dts`——那记的是出帧时最后喂进去的那个包,+ 跟这一帧不是一回事。`-ignore_editlist` 让时间戳保持样本表里的原值,也让编辑列表+ 盖住的预卷样本照样出帧,否则帧数会少一截。++ 对不上就抛 `RepairUnavailable`:宁可不修,也不能写一张错的表。++ `-threads 0` 不是调参,是补上 ffprobe 默认没开的解码线程:6297 上实测 300 秒内容+ 从 27 秒降到 4 秒,整片从十几分钟降到一两分钟。+ """+ command = (+ str(ffprobe), "-v", "error", "-threads", "0",+ "-ignore_editlist", "1", "-select_streams", "v:0",+ "-show_entries", "frame=pts", "-of", "csv=p=0", str(source),+ )+ try:+ completed = subprocess.run(command, capture_output=True, timeout=PROBE_TIMEOUT_SECONDS)+ except (OSError, subprocess.TimeoutExpired) as exc:+ raise RepairUnavailable(f"ffprobe 没跑完:{exc}") from exc+ if completed.returncode:+ raise RepairUnavailable(f"ffprobe 退出码 {completed.returncode}")++ index_of = {value: index for index, value in enumerate(decode_times)}+ if len(index_of) != len(decode_times):+ raise RepairUnavailable("dts 有重复,认不出哪一帧是哪一帧")+ rank = [-1] * len(decode_times)+ seen = 0+ for line in completed.stdout.decode("utf-8", "replace").splitlines():+ text = line.strip().rstrip(",")+ if not text or text == "N/A":+ raise RepairUnavailable("有帧没有时间戳")+ index = index_of.get(int(text))+ if index is None:+ raise RepairUnavailable("解码器报的时间戳不在 stts 里")+ if rank[index] >= 0:+ raise RepairUnavailable("同一帧被输出了两次")+ rank[index] = seen+ seen += 1+ if seen != len(decode_times):+ raise RepairUnavailable(f"解码出 {seen} 帧,样本表里有 {len(decode_times)} 个")+ return rank+++def _composition_offsets(decode_times: list[int], rank: list[int]) -> tuple[list[int], int]:+ """返回每个样本的 ctts 偏移和整体平移量。++ 显示时间轴就是这些 dts 排好序的样子:一帧显示一次,时长不变,变的只是顺序。+ 偏移要非负(ctts version 0),所以整体平移,平移量由编辑列表补回去。+ """+ timeline = sorted(decode_times)+ offsets = [timeline[rank[index]] - decode_times[index] for index in range(len(decode_times))]+ shift = max(0, -min(offsets))+ return [value + shift for value in offsets], shift+++def _ctts(offsets: list[int]) -> bytes:+ """游程编码的 `ctts`。偏移只取几个值,整片也就一两 KB。"""+ runs: list[tuple[int, int]] = []+ for offset in offsets:+ if runs and runs[-1][1] == offset:+ runs[-1] = (runs[-1][0] + 1, offset)+ else:+ runs.append((1, offset))+ body = struct.pack(">II", 0, len(runs))+ return body + b"".join(struct.pack(">II", run, offset) for run, offset in runs)+++def _retimed_edit_list(elst: bytes | None, shift: int, segment_duration: int) -> bytes:+ """让编辑列表跟上 ctts 的整体平移。++ 平移把每一帧的显示时刻都推后 `shift`,起播点要跟着推同样多,否则音画差这么多。+ 已有的 media_time 正好等于 `shift` 时原样保留:那说明原封装本来就为 ctts 补过这一刀,+ 表丢了而这行留着,加回去就复原了;写成两倍反而会真的切掉两帧。+ 空编辑(media_time 为 -1)是延迟起播,跟显示顺序无关,原样放过。+ """+ if elst is not None and len(elst) >= 8:+ version = elst[0]+ width = 20 if version == 1 else 12+ layout = ">Qq" if version == 1 else ">Ii"+ count = struct.unpack_from(">I", elst, 4)[0]+ if count and len(elst) >= 8 + count * width:+ entries = []+ for index in range(count):+ base = 8 + index * width+ segment, media_time = struct.unpack_from(layout, elst, base)+ if media_time >= 0 and media_time != shift:+ media_time += shift+ entries.append(struct.pack(layout, segment, media_time)+ + elst[base + width - 4:base + width])+ return elst[:8] + b"".join(entries)+ return struct.pack(">IIIiI", 0, 1, segment_duration, shift, 1 << 16)+++def _timed_field(payload: bytes, short_offset: int, long_offset: int) -> int:+ """读 `*hd` 盒子里那种「v0 是 32 位、v1 是 64 位」的字段。"""+ if payload[0] == 1:+ return struct.unpack_from(">Q", payload, long_offset)[0]+ return struct.unpack_from(">I", payload, short_offset)[0]+++def _track_duration(root: _Box, trak: _Box) -> int:+ """轨道时长,单位是影片时间刻度——编辑列表的段长用的就是这个刻度,不是媒体刻度。++ `tkhd` 里那个值可以是 0(有编辑列表时封装器常常不填),这时按媒体时长换算。+ """+ tkhd = trak.find(b"tkhd")+ if tkhd is not None and tkhd.payload:+ duration = _timed_field(tkhd.payload, 16, 24)+ if duration:+ return duration+ mvhd = root.find(b"mvhd")+ mdia = trak.find(b"mdia")+ mdhd = mdia.find(b"mdhd") if mdia else None+ if not (mvhd and mvhd.payload and mdhd and mdhd.payload):+ raise RepairUnavailable("算不出轨道时长")+ movie_scale = struct.unpack_from(">I", mvhd.payload, 20 if mvhd.payload[0] == 1 else 12)[0]+ media_scale = struct.unpack_from(">I", mdhd.payload, 20 if mdhd.payload[0] == 1 else 12)[0]+ if not media_scale:+ raise RepairUnavailable("媒体时间刻度是 0")+ return _timed_field(mdhd.payload, 16, 24) * movie_scale // media_scale+++def _shift_chunk_offsets(box: _Box, delta: int) -> None:+ """头变长了,`mdat` 里每个 chunk 的绝对位置就跟着挪。"""+ if delta == 0:+ return+ for child in box.children:+ if child.payload is None:+ _shift_chunk_offsets(child, delta)+ continue+ if child.kind == b"stco":+ count = struct.unpack_from(">I", child.payload, 4)[0]+ values = [struct.unpack_from(">I", child.payload, 8 + n * 4)[0] + delta for n in range(count)]+ if any(value > 0xFFFFFFFF for value in values):+ raise RepairUnavailable("偏移超出 32 位,这个片源要 co64 才修得了")+ child.payload = child.payload[:8] + b"".join(struct.pack(">I", value) for value in values)+ elif child.kind == b"co64":+ count = struct.unpack_from(">I", child.payload, 4)[0]+ values = [struct.unpack_from(">Q", child.payload, 8 + n * 8)[0] + delta for n in range(count)]+ child.payload = child.payload[:8] + b"".join(struct.pack(">Q", value) for value in values)+++_Span = tuple[bytes, int, int, int]+++def _layout(source: Path) -> tuple[bytes, _Span, _Span]:+ """读出 `mdat` 之前那一整段,并确认这个布局拼得回去。++ 拼接只换头、原样接上 `mdat`,所以 `mdat` 必须是最后一个盒子,前面的东西也得+ 一次读得完。不满足就抛 `RepairUnavailable`,让调用方回到转码那条路。+ """+ with open(source, "rb") as handle:+ boxes = _top_level(handle)+ kinds = {kind for kind, *_ in boxes}+ if not {b"moov", b"mdat"} <= kinds:+ raise RepairUnavailable("顶层缺 moov 或 mdat")+ mdat = next(box for box in boxes if box[0] == b"mdat")+ moov = next(box for box in boxes if box[0] == b"moov")+ if moov[1] > mdat[1]:+ raise RepairUnavailable("moov 在 mdat 之后,这个布局还没支持")+ if any(box[1] > mdat[1] for box in boxes):+ raise RepairUnavailable("mdat 后面还有盒子,这个布局还没支持")+ if mdat[3] - mdat[2] <= 0 or moov[3] - moov[1] > HEADER_LIMIT:+ raise RepairUnavailable("moov 太大或 mdat 是空的")+ handle.seek(0)+ return handle.read(mdat[2]), moov, mdat+++def repaired_header(source: Path, ffprobe: Path) -> RepairedHeader:+ """算出修好的头。修不了就抛 `RepairUnavailable`。"""+ head, moov, mdat = _layout(source)+ tree = _parse(head, moov[2], moov[3])+ root = _Box(b"moov", None, tree)+ traks = [child for child in root.children if child.kind == b"trak"]+ video = next((trak for trak in traks if _is_video(trak)), None)+ stbl = _sample_table(video) if video else None+ if stbl is None:+ raise RepairUnavailable("找不到视频轨的样本表")+ if stbl.find(b"ctts") is not None:+ raise RepairUnavailable("这个片源已经有 ctts")+ stts = stbl.find(b"stts")+ if stts is None or stts.payload is None:+ raise RepairUnavailable("视频轨没有 stts")++ decode_times = _decode_times(stts.payload)+ offsets, shift = _composition_offsets(+ decode_times, _display_order(ffprobe, source, decode_times))+ if not shift and all(value == 0 for value in offsets):+ raise RepairUnavailable("显示顺序本来就等于解码顺序,没有要修的")++ stbl.children.insert(stbl.children.index(stts) + 1, _Box(b"ctts", _ctts(offsets), []))+ edts = video.find(b"edts")+ elst = edts.find(b"elst") if edts else None+ payload = _retimed_edit_list(+ elst.payload if elst and elst.payload else None, shift, _track_duration(root, video))+ if elst is not None:+ elst.payload = payload+ elif edts is not None:+ edts.children.append(_Box(b"elst", payload, []))+ else:+ video.children.insert(1, _Box(b"edts", None, [_Box(b"elst", payload, [])]))++ rebuilt = root.serialize()+ delta = len(rebuilt) - (moov[3] - moov[1])+ _shift_chunk_offsets(root, delta)+ rebuilt = root.serialize()+ prefix = head[:moov[1]] + rebuilt + head[moov[3]:]+ if len(prefix) - mdat[2] != delta:+ raise RepairUnavailable("重建后的头长度对不上")+ return RepairedHeader(prefix=prefix, payload_start=mdat[2], payload_end=mdat[3])+++def write_sidecar(path: Path, header: RepairedHeader) -> None:+ """边车只存头和那段 mdat 的坐标;几十 KB,和原片放两处互不影响。"""+ path.parent.mkdir(parents=True, exist_ok=True)+ temporary = path.with_name(path.name + ".tmp")+ temporary.write_bytes(+ SIDECAR_MAGIC+ + struct.pack(">QQQQ", len(header.prefix), len(header.suffix),+ header.payload_start, header.payload_end)+ + header.prefix + header.suffix)+ temporary.replace(path)+++def read_sidecar(path: Path) -> RepairedHeader | None:+ """读不出来就当没有边车:调用方照旧走转码分片。"""+ try:+ blob = path.read_bytes()+ except OSError:+ return None+ if not blob.startswith(SIDECAR_MAGIC) or len(blob) < len(SIDECAR_MAGIC) + 32:+ return None+ prefix_len, suffix_len, start, end = struct.unpack_from(">QQQQ", blob, len(SIDECAR_MAGIC))+ body = blob[len(SIDECAR_MAGIC) + 32:]+ if len(body) != prefix_len + suffix_len:+ return None+ return RepairedHeader(prefix=body[:prefix_len], payload_start=start, payload_end=end,+ suffix=body[prefix_len:])+++class HeaderRepairStore:+ """按资产存修好的头,并负责那一趟解码要花的时间。++ 文件名带上原片的大小和修改时间,源文件一换边车自然失效——和整片转码缓存同一套判据,+ 也住在同一个目录里,资产删掉时由同一段清理逻辑回收。++ 算一份头要把整部片解一遍(挂载盘上按几十 MB/s 算,一部两三 GB 的片子一分多钟),+ 所以只在后台算、一次只算一部,算不出来就记下来别再试——调用方照旧走转码分片。+ """++ def __init__(self, root: Path, resolver, *, max_concurrent: int = 1, cached: int = 4):+ self.root = Path(root)+ self.resolver = resolver+ self._slots = threading.Semaphore(max(1, max_concurrent))+ self._running: set[str] = set()+ self._failed: set[str] = set()+ # 一份头有几 MB(整个 moov 加 ctts),而播放时每个 Range 请求都要问一次。+ # 同时在播的片子就那么一两部,留最近几份在手边,别反复读同一个文件。+ self._cached: dict[str, RepairedHeader] = {}+ self._cache_size = max(1, cached)+ self._guard = threading.Lock()++ def _name(self, asset_id: int, source: Path) -> str | None:+ try:+ stat = source.stat()+ except OSError:+ return None+ return f"{asset_id}-{stat.st_size}-{stat.st_mtime_ns}{SIDECAR_SUFFIX}"++ def lookup(self, asset_id: int, source: Path) -> RepairedHeader | None:+ """已经算好的头;没有就返回 None,不去算。"""+ name = self._name(asset_id, source)+ if not name:+ return None+ with self._guard:+ header = self._cached.get(name)+ if header is not None:+ return header+ header = read_sidecar(self.root / name)+ if header is not None:+ with self._guard:+ if len(self._cached) >= self._cache_size:+ self._cached.pop(next(iter(self._cached)))+ self._cached[name] = header+ return header++ def request(self, asset_id: int, source: Path) -> None:+ """在后台补一份头。播放请求不能为此等一分钟,所以这里只管开线程。"""+ name = self._name(asset_id, source)+ if not name:+ return+ with self._guard:+ if name in self._running or name in self._failed:+ return+ threading.Thread(+ target=self.repair_now, args=(asset_id, source),+ name=f"PeachMp4Header-{asset_id}", daemon=True,+ ).start()++ def repair_now(self, asset_id: int, source: Path) -> bool:+ """当场算一份头并存下来。已经有、正在算或上次算不出来都返回 False。"""+ name = self._name(asset_id, source)+ if not name or self.resolver.ffprobe() is None or (self.root / name).exists():+ return False+ with self._guard:+ if name in self._running or name in self._failed:+ return False+ self._running.add(name)+ try:+ with self._slots:+ write_sidecar(self.root / name,+ repaired_header(source, Path(self.resolver.ffprobe())))+ for stale in self.root.glob(f"{asset_id}-*{SIDECAR_SUFFIX}"):+ if stale.name != name:+ stale.unlink(missing_ok=True)+ return True+ except (RepairUnavailable, OSError, struct.error) as exc:+ LOGGER.info("mp4 header repair unavailable for asset %s: %s", asset_id, exc)+ with self._guard:+ self._failed.add(name)+ return False+ finally:+ with self._guard:+ self._running.discard(name)diff --git a/src/peach/routes_media.py b/src/peach/routes_media.pyindex 50e166844..23ebd5236 100644--- a/src/peach/routes_media.py+++ b/src/peach/routes_media.py@@ -48,7 +48,7 @@ from .platform import within_rootfrom .previews import PreviewUnavailablefrom .routes_auth import require_authfrom .segments import SegmentCancelled, SegmentUnavailable, build_hls_playlist-from .streaming import BufferedFileResponse, CancellableFileResponse+from .streaming import BufferedFileResponse, CancellableFileResponse, SplicedMp4Responsefrom .transcodes import TranscodeCancelled, TranscodeUnavailablerouter = APIRouter()@@ -127,19 +127,51 @@ def _attachment_disposition(title: str, url: str) -> str:return f"attachment; filename=\"{ascii_name}\"; filename*=UTF-8''{quote(name)}"-def _hls_plan(state, asset_id: int, session: str = ""):+def _repaired_header(state, asset_id: int, source: Path):+ """已经修好的 MP4 头;没有就是 None。只查不算,算是 `_needs_conversion` 的事。"""+ store = getattr(state, "header_repairs", None)+ return None if store is None else store.lookup(asset_id, source)+++def _needs_conversion(state, asset_id: int, source: Path, session: str) -> bool:+ """起播时要不要转码。只有 `/api/stream-plan` 问这一句。++ 缺 ctts 的片子只是时间戳错乱,重建一份头就能直接按 Range 播,不必重编码。头还没+ 算出来时先照旧走 HLS,同时在后台补上;补好之后同一部片下次起播就走 Range。++ HLS 那两个端点不问:一次播放的分片计划要在整段会话里保持同一个形状,边车中途落地+ 会让固定 6 秒的计划换成按关键帧切的,剩下的分片索引全对不上。+ """+ if not state.transcode_service.requires_conversion(+ source, session=session, registry=state.stream_sessions):+ return False+ store = getattr(state, "header_repairs", None)+ if store is None or not state.transcode_service.decode_order_timestamps(+ source, session=session, registry=state.stream_sessions):+ return True+ if store.lookup(asset_id, source) is not None:+ return False+ store.request(asset_id, source)+ return True+++def _hls_plan(state, asset_id: int, session: str = "", conversion: bool | None = None):"""解析 HLS 的片源路径与分片计划;任何一步不成立就返回 None 走 Range。要重编码的片源按固定 6 秒切,时长先看账本,账本没记或记成负数就用 ffprobe 报的;探测也拿不到才放弃,否则浏览器只能退回 `/stream`,那条路要先把整部片转完才出第一个字节。原样封装的 HLS 仍要账本时长与关键帧表。++ `conversion` 是起播时已经得出的结论。给不出时按片源本身判:播放列表和分片端点走的+ 就是这条,它们不看重建好的 MP4 头,理由见 `_needs_conversion`。"""asset = state.media_engine.asset(asset_id)# 播放列表和分片端点本身就是 HLS 路径,按 ADR-0016 显式要计划,不受默认值影响。choice = state.media_engine.stream_plan(asset_id, mode="hls")source = state.media_engine.filesystem.file_for(asset, thumbnail=False)duration = asset.duration if asset.duration and asset.duration > 0 else 0.0- if state.transcode_service.requires_conversion(source, session=session, registry=state.stream_sessions):+ if conversion if conversion is not None else state.transcode_service.requires_conversion(+ source, session=session, registry=state.stream_sessions):duration = duration or state.transcode_service.media_duration(source, session=session, registry=state.stream_sessions)plan = state.hls_service.conversion_plan(duration) if duration > 0 else []@@ -155,6 +187,11 @@ def stream(request: Request, id: int, session: str = "", args: dict[str, str] =state = request.app.stateasset = state.media_engine.asset(id)path = state.media_engine.filesystem.file_for(asset, thumbnail=False)+ header = _repaired_header(state, id, path)+ if header is not None:+ return SplicedMp4Response(+ path, header, session=session, registry=state.stream_sessions,+ )try:path, transcoded = state.transcode_service.browser_path(id, path, session=session, registry=state.stream_sessions,@@ -188,9 +225,9 @@ def stream_plan(request: Request, id: int, session: str = "", mode: str = "", arplan = state.media_engine.stream_plan(id, mode=mode or "auto")# 只有真的能读出关键帧才宣告 HLS,否则客户端会拿到一个必然 404 的播放列表。source_path = state.media_engine.filesystem.file_for(asset, thumbnail=False)- conversion = state.transcode_service.requires_conversion(- source_path, session=session, registry=state.stream_sessions)- resolved = _hls_plan(state, id, session) if conversion or plan.protocol == "hls" else None+ conversion = _needs_conversion(state, id, source_path, session)+ resolved = (_hls_plan(state, id, session, conversion)+ if conversion or plan.protocol == "hls" else None)if resolved and session:return {"id": id,diff --git a/src/peach/streaming.py b/src/peach/streaming.pyindex 134f2db7f..64c64e110 100644--- a/src/peach/streaming.py+++ b/src/peach/streaming.py@@ -11,6 +11,8 @@ from typing import Anyfrom starlette.responses import FileResponse, Responsefrom starlette.types import Receive, Scope, Send+RANGE_PREFIX = "bytes="+class StreamSessionRegistry:"""Track addressable browser stream requests so the UI can cancel them."""@@ -99,6 +101,20 @@ async def _wait_for_disconnect(receive: Receive) -> None:return+async def _send_until_disconnect(inner, scope: Scope, receive: Receive, send: Send) -> None:+ """跑 `inner` 发响应,客户端一断开就把它掐掉。"""+ respond = asyncio.ensure_future(inner(scope, receive, send))+ watch = asyncio.ensure_future(_wait_for_disconnect(receive))+ try:+ await asyncio.wait({respond, watch}, return_when=asyncio.FIRST_COMPLETED)+ finally:+ respond.cancel()+ watch.cancel()+ await asyncio.gather(respond, watch, return_exceptions=True)+ if not respond.cancelled():+ respond.result()++class BufferedFileResponse(FileResponse):"""按 1 MiB 读文件再发,客户端一断开就停止读。@@ -118,16 +134,7 @@ class BufferedFileResponse(FileResponse):if scope["type"] != "http":await super().__call__(scope, receive, send)return- respond = asyncio.ensure_future(super().__call__(scope, receive, send))- watch = asyncio.ensure_future(_wait_for_disconnect(receive))- try:- await asyncio.wait({respond, watch}, return_when=asyncio.FIRST_COMPLETED)- finally:- respond.cancel()- watch.cancel()- await asyncio.gather(respond, watch, return_exceptions=True)- if not respond.cancelled():- respond.result()+ await _send_until_disconnect(super().__call__, scope, receive, send)class CancellableFileResponse(BufferedFileResponse):@@ -157,3 +164,147 @@ class CancellableFileResponse(BufferedFileResponse):raisefinally:self.registry.unregister(self.session, task)+++def _overlap(blob: bytes, base: int, start: int, end: int):+ """`blob` 铺在虚拟文件的 `base` 处,取它和闭区间 [start, end] 相交的那一段。"""+ begin = max(start, base)+ stop = min(end + 1, base + len(blob))+ if begin < stop:+ yield blob[begin - base:stop - base]+++def _requested_range(scope: Scope, total: int) -> tuple[int, int, bool] | None:+ """解析单段 Range,返回 (起, 止, 是不是按 Range 答的);要不起的区间返回 None。++ 末位的布尔值决定回 206 还是 200:整份内容也要回 206,有播放器把 200 读成「这个+ 服务端不支持 Range」,接着就把拖动关掉。+ 多段 Range 当没有 Range 处理:浏览器播视频从不这么请求,为它写一套 multipart+ 没有真实需求。+ """+ raw = ""+ for key, value in scope.get("headers", ()):+ if key.lower() == b"range":+ raw = value.decode("latin-1").strip()+ break+ if not raw.startswith(RANGE_PREFIX) or "," in raw:+ return 0, total - 1, False+ first, _, last = raw[len(RANGE_PREFIX):].partition("-")+ try:+ if not first:+ length = int(last)+ if length <= 0:+ return 0, total - 1, False+ return total - min(length, total), total - 1, True+ start = int(first)+ end = int(last) if last else total - 1+ except ValueError:+ return 0, total - 1, False+ end = min(end, total - 1)+ return None if start > end or start >= total else (start, end, True)+++class SplicedMp4Response(Response):+ """把「修好的头 + 原文件里那一段 mdat」当成一个虚拟文件发出去。++ Starlette 的 `FileResponse` 按磁盘上那个文件的大小和偏移切 Range,而这里要发的字节+ 序列在磁盘上并不存在:头在边车里,内容是原文件中间的一段。所以 Range 自己算。+ 断开就停读,理由和 `BufferedFileResponse` 一样。+ """++ chunk_size = 1 << 20++ def __init__(+ self,+ path: str | Path,+ header,+ *,+ session: str = "",+ registry: StreamSessionRegistry | None = None,+ ) -> None:+ super().__init__(b"", media_type="video/mp4")+ self.path = Path(path)+ self.header = header+ self.session = session+ self.registry = registry++ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:+ if scope["type"] != "http":+ await super().__call__(scope, receive, send)+ return+ task = asyncio.current_task()+ tracked = bool(self.session and self.registry is not None)+ if tracked and (task is None or not self.registry.register(self.session, task)):+ await Response(status_code=410, headers={"Cache-Control": "no-store"})(scope, receive, send)+ return+ try:+ await _send_until_disconnect(self._respond, scope, receive, send)+ except asyncio.CancelledError:+ logging.getLogger(__name__).info("stream session cancelled: %s", self.session)+ raise+ finally:+ if tracked and task is not None:+ self.registry.unregister(self.session, task)++ async def _respond(self, scope: Scope, receive: Receive, send: Send) -> None:+ total = self.header.size+ window = _requested_range(scope, total)+ if window is None:+ await Response(+ status_code=416,+ headers={"Content-Range": f"bytes */{total}", "Cache-Control": "no-store"},+ )(scope, receive, send)+ return+ start, end, ranged = window+ headers = [+ (b"content-type", b"video/mp4"),+ (b"accept-ranges", b"bytes"),+ (b"cache-control", b"no-store"),+ (b"content-length", str(end - start + 1).encode("latin-1")),+ ]+ if ranged:+ headers.append((b"content-range", f"bytes {start}-{end}/{total}".encode("latin-1")))+ await send({+ "type": "http.response.start",+ "status": 206 if ranged else 200,+ "headers": headers,+ })+ if scope.get("method", "GET").upper() == "HEAD":+ await send({"type": "http.response.body", "body": b"", "more_body": False})+ return+ stream = self._chunks(start, end)+ try:+ async for chunk in stream:+ await send({"type": "http.response.body", "body": chunk, "more_body": True})+ finally:+ await stream.aclose()+ await send({"type": "http.response.body", "body": b"", "more_body": False})++ async def _chunks(self, start: int, end: int):+ """按虚拟文件的坐标取字节:先头、再原文件那一段、最后尾。"""+ body_start = len(self.header.prefix)+ body_end = body_start + (self.header.payload_end - self.header.payload_start)+ for chunk in _overlap(self.header.prefix, 0, start, end):+ yield chunk+ if end >= body_start and start < body_end:+ async for chunk in self._source_chunks(+ max(start, body_start) - body_start, min(end + 1, body_end) - body_start,+ ):+ yield chunk+ for chunk in _overlap(self.header.suffix, body_end, start, end):+ yield chunk++ async def _source_chunks(self, begin: int, stop: int):+ """整段共用一个句柄:挂载盘上每开一次文件都要多走一趟握手。"""+ handle = await asyncio.to_thread(open, self.path, "rb")+ try:+ await asyncio.to_thread(handle.seek, self.header.payload_start + begin)+ remaining = stop - begin+ while remaining > 0:+ chunk = await asyncio.to_thread(handle.read, min(self.chunk_size, remaining))+ if not chunk:+ return+ yield chunk+ remaining -= len(chunk)+ finally:+ handle.close()diff --git a/src/peach/transcodes.py b/src/peach/transcodes.pyindex c602a59c0..dc54e5c97 100644--- a/src/peach/transcodes.py+++ b/src/peach/transcodes.py@@ -79,6 +79,18 @@ class TranscodeService:profile = self._profile_for(source, session, registry)return profile is None or not self._browser_compatible(source, profile)+ def decode_order_timestamps(self, source: Path, *, session: str = "", registry=None) -> bool:+ """是不是只有时间戳错乱的那一类:有 B 帧却没有 ctts,码流本身浏览器解得出来。++ 这类片源不必重编码,重建一份头就够了;其余不兼容的原因(编码、像素格式、容器)+ 换不掉,只能转码。+ """+ if self.needs_transcode(source) or self.resolver.ffprobe() is None:+ return False+ profile = self._profile_for(source, session, registry)+ return bool(profile and profile.decode_order_timestamps+ and self._decodes_in_browser(source, profile))+def media_duration(self, source: Path, *, session: str = "", registry=None) -> float:"""ffprobe 报的总时长(秒);账本没记时长的片源靠它切片。探测不到返回 0。"""if self.resolver.ffprobe() is None:diff --git a/src/peach/web_resource_sync.py b/src/peach/web_resource_sync.pyindex 5a8878c4d..45bf0606d 100644--- a/src/peach/web_resource_sync.py+++ b/src/peach/web_resource_sync.py@@ -225,7 +225,8 @@ def _resource_orphan_plan(contract: ResourceSyncContract, excluded_ids: Sequencepatterns = ((contract.poster_root, "posters", re.compile(r"^(\d+)_\d+\.jpg$")),(contract.photo_root, "photo-thumbs", re.compile(r"^(\d+)\.jpg$")),- (contract.transcode_root, "transcodes", re.compile(r"^(\d+)-.+\.mp4$")),+ # 重建的 MP4 头(`.mp4hdr`)和整片转码缓存住在一起,判据和回收也共用一套。+ (contract.transcode_root, "transcodes", re.compile(r"^(\d+)-.+\.(?:mp4|mp4hdr)$")),)for root, kind, pattern in patterns:if not _managed_cache_root(contract, root) or not root.is_dir():diff --git a/tests/support/mp4.py b/tests/support/mp4.pyindex 2595ab1c7..ca8647dc4 100644--- a/tests/support/mp4.py+++ b/tests/support/mp4.py@@ -1,17 +1,27 @@-"""测试用的最小 MP4:只有时间表,没有真实媒体数据。+"""测试用的最小 MP4:时间表是真的,样本数据是可预测的填充字节。`peach.mp4index` 只读 `moov`,关键帧表、时长表和显示时间偏移表都能这样造出来,-用例因此不必依赖 FFmpeg 或真实片源。+用例因此不必依赖 FFmpeg 或真实片源。`peach.mp4repair` 还要改写块偏移和编辑列表,+所以 `mvhd`、`tkhd`、`stsz`、`stco` 也一并造齐,`mdat` 里放真实长度的样本字节。"""from __future__ import annotationsimport struct+SAMPLE_SIZE = 16+#: 影片时间刻度。编辑列表的段长用它,媒体时间刻度用 `timescale`。+MOVIE_TIMESCALE = 1000+def box(kind: bytes, payload: bytes) -> bytes:return struct.pack(">I", len(payload) + 8) + kind + payload+def sample_bytes(samples: int) -> bytes:+ """每个字节都能推算出来,拼接出的文件因此可以逐字节断言。"""+ return bytes((index * 7 + 11) % 251 for index in range(samples * SAMPLE_SIZE))++def minimal_mp4(*,timescale: int,@@ -19,14 +29,22 @@ def minimal_mp4(samples: int,keyframe_every: int,composition_offsets: bool = False,+ edit_list: tuple[int, int] | None = None,) -> bytes:- """够 `peach.mp4index` 解析关键帧的最小 MP4。+ """够 `peach.mp4index` 解析关键帧、够 `peach.mp4repair` 重建头的最小 MP4。`composition_offsets` 决定视频轨里有没有 `ctts`。有 B 帧的片源缺了这张表,容器声明的显示时刻就是解码顺序,浏览器会把倒着走的帧全丢掉。+ `edit_list` 是 `(段长, media_time)`,给不出就不写 `edts`。"""+ duration = samples * sample_delta+ mvhd = box(b"mvhd", struct.pack(">IIIII", 0, 0, 0, MOVIE_TIMESCALE, duration)+ + bytes(80))+ tkhd = box(b"tkhd", struct.pack(">IIIIII", 0, 0, 0, 1, 0, duration) + bytes(60))+ edts = box(b"edts", box(b"elst", struct.pack(">IIIiI", 0, 1, *edit_list, 1 << 16))+ ) if edit_list else b""mdhd = box(b"mdhd", struct.pack(">4sIIII HH", bytes(4), 0, 0, timescale,- samples * sample_delta, 0, 0))+ duration, 0, 0))hdlr = box(b"hdlr", struct.pack(">4sI4s", bytes(4), 0, b"vide") + bytes(12))stts = box(b"stts", struct.pack(">IIII", 0, 1, samples, sample_delta))sync = [n for n in range(1, samples + 1) if (n - 1) % keyframe_every == 0]@@ -34,8 +52,17 @@ def minimal_mp4(+ b"".join(struct.pack(">I", n) for n in sync))ctts = (box(b"ctts", struct.pack(">IIII", 0, 1, samples, sample_delta))if composition_offsets else b"")- stbl = box(b"stbl", stts + stss + ctts)- mdia = box(b"mdia", mdhd + hdlr + box(b"minf", stbl))- return (box(b"ftyp", b"isom" + bytes(8))- + box(b"moov", box(b"trak", mdia))- + box(b"mdat", bytes(64)))+ stsc = box(b"stsc", struct.pack(">IIIII", 0, 1, 1, 1, 1))+ stsz = box(b"stsz", struct.pack(">III", 0, SAMPLE_SIZE, samples))++ def head(chunk_start: int) -> bytes:+ stco = box(b"stco", struct.pack(">II", 0, samples) + b"".join(+ struct.pack(">I", chunk_start + index * SAMPLE_SIZE) for index in range(samples)))+ stbl = box(b"stbl", stts + stss + ctts + stsc + stsz + stco)+ mdia = box(b"mdia", mdhd + hdlr + box(b"minf", stbl))+ return (box(b"ftyp", b"isom" + bytes(8))+ + box(b"moov", mvhd + box(b"trak", tkhd + edts + mdia))+ + struct.pack(">I", samples * SAMPLE_SIZE + 8) + b"mdat")++ # 块偏移是文件内的绝对位置,得先知道头有多长;条目数固定,两遍长度必然相同。+ return head(len(head(0))) + sample_bytes(samples)diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex b7fc13d95..d502660eb 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -1899,6 +1899,54 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(response.headers["content-type"], "video/mp2t")self.assertTrue(segment.exists(), "片段要留在缓存里,重复请求不该再跑一次 FFmpeg")+ async def test_a_repaired_header_takes_a_broken_timestamp_file_off_the_transcode_path(self):+ """时间戳错乱的片子一旦有了修好的头,就该按 Range 无损播,不再实时转码。"""+ from peach.mp4repair import RepairedHeader++ source = self.media_root / "decode-order.mp4"+ source.write_bytes(b"OLDHEAD" + bytes(range(64)))+ header = RepairedHeader(prefix=b"NEWHEADER", payload_start=7, payload_end=71)+ con = sqlite3.connect(self.db)+ con.execute("UPDATE asset SET path=?, duration=13.5 WHERE id=1", (str(source),))+ con.commit()+ con.close()+ service = self.app.state.transcode_service++ with patch.object(service, "requires_conversion", return_value=True), \+ patch.object(service, "decode_order_timestamps", return_value=True), \+ patch.object(service, "browser_path",+ side_effect=AssertionError("whole movie conversion")), \+ patch.object(self.app.state.header_repairs, "lookup", return_value=header), \+ patch.object(self.app.state.header_repairs, "request",+ side_effect=AssertionError("已经有头了还要再算一遍")):+ plan = (await self.client.get("/api/stream-plan?id=1&session=s&t=secret")).json()+ response = await self.client.get(+ "/stream?id=1", headers={"X-Token": "secret", "Range": "bytes=5-12"})++ self.assertEqual(plan["protocol"], "range")+ self.assertEqual(response.status_code, 206)+ self.assertEqual(response.content, (b"NEWHEADER" + bytes(range(64)))[5:13])+ self.assertEqual(response.headers["content-type"], "video/mp4")++ async def test_a_broken_timestamp_file_without_a_header_still_slices_and_asks_for_one(self):+ """头还没算出来时照旧走 HLS,同时在后台补一份,下次播就换成 Range。"""+ con = sqlite3.connect(self.db)+ con.execute("UPDATE asset SET path=?, duration=13.5 WHERE id=1", (str(self.hls_file),))+ con.commit()+ con.close()+ service = self.app.state.transcode_service+ asked: list[int] = []++ with patch.object(service, "requires_conversion", return_value=True), \+ patch.object(service, "decode_order_timestamps", return_value=True), \+ patch.object(self.app.state.header_repairs, "lookup", return_value=None), \+ patch.object(self.app.state.header_repairs, "request",+ new=lambda asset_id, source: asked.append(asset_id)):+ plan = (await self.client.get("/api/stream-plan?id=1&session=s&t=secret")).json()++ self.assertEqual(plan["protocol"], "hls")+ self.assertEqual(asked, [1])+async def test_transcoded_stream_has_browser_mime_and_marker(self):avi = self.media_root / "two.avi"avi.write_bytes(b"avi-source")diff --git a/tests/test_mp4repair.py b/tests/test_mp4repair.pynew file mode 100644index 000000000..eaacc558c--- /dev/null+++ b/tests/test_mp4repair.py@@ -0,0 +1,276 @@+"""缺 `ctts` 的 MP4 重建头。++用例不跑解码器:显示顺序那一步换成已知的置换,剩下的全是头里的算术,可以逐字节断言。+"""+from __future__ import annotations++import struct+import unittest+from pathlib import Path+from tempfile import TemporaryDirectory+from unittest.mock import patch++from peach import mp4repair+from peach.mp4index import _find, _iter_boxes, _video_stbl+from peach.mp4repair import (+ HeaderRepairStore, RepairUnavailable, RepairedHeader, read_sidecar,+ repaired_header, write_sidecar,+)++from support.mp4 import SAMPLE_SIZE, minimal_mp4, sample_bytes++#: 解码序 I P B B P B B …,显示序 I B B P B B P …;每组三帧里 P 要等两帧才显示。+DECODE_TO_DISPLAY = (0, 3, 1, 2, 6, 4, 5, 9, 7, 8, 12, 10, 11)+++def moov_of(blob: bytes) -> bytes:+ for kind, body, stop in _iter_boxes(blob, 0, len(blob)):+ if kind == b"moov":+ return blob[body:stop]+ raise AssertionError("没有 moov")+++def table(moov: bytes, kind: bytes) -> bytes | None:+ found = _video_stbl(moov, 0, len(moov))+ assert found is not None+ span = _find(moov, *found[1], kind)+ return None if span is None else moov[span[0]:span[1]]+++def entries(payload: bytes, layout: str) -> list[tuple[int, ...]]:+ width = struct.calcsize(layout)+ count = struct.unpack_from(">I", payload, 4)[0]+ return [struct.unpack_from(layout, payload, 8 + index * width) for index in range(count)]+++def composition_times(moov: bytes, sample_delta: int) -> list[int]:+ """每个样本的显示时刻:解码时刻加上 `ctts` 里的偏移。"""+ offsets: list[int] = []+ for run, offset in entries(table(moov, b"ctts"), ">Ii"):+ offsets.extend([offset] * run)+ return [index * sample_delta + offset for index, offset in enumerate(offsets)]+++class Mp4HeaderRepairTests(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = TemporaryDirectory()+ self.root = Path(self._temporary.name)+ self.addCleanup(self._temporary.cleanup)++ def broken_mp4(self, path: Path, **options) -> Path:+ path.write_bytes(minimal_mp4(+ timescale=1000, sample_delta=400, samples=len(DECODE_TO_DISPLAY),+ keyframe_every=6, **options))+ return path++ def repair(self, path: Path, order=DECODE_TO_DISPLAY) -> RepairedHeader:+ """把「解一遍片子问显示顺序」换成已知答案,只验头里的算术。"""+ with patch.object(mp4repair, "_display_order",+ lambda ffprobe, source, times: list(order)):+ return repaired_header(path, Path("ffprobe"))++ def test_a_rebuilt_header_puts_every_frame_back_in_display_order(self):+ source = self.broken_mp4(self.root / "broken.mp4")+ header = self.repair(source)+ times = composition_times(moov_of(header.prefix), 400)++ self.assertEqual(sorted(times), sorted(set(times)), "两帧显示在同一时刻")+ self.assertEqual([index for index, _ in sorted(enumerate(times), key=lambda pair: pair[1])],+ [DECODE_TO_DISPLAY.index(rank) for rank in range(len(DECODE_TO_DISPLAY))])+ self.assertTrue(all(time >= index * 400 for index, time in enumerate(times)),+ "有帧的显示时刻早于它的解码时刻")++ def test_the_spliced_file_keeps_the_original_media_bytes(self):+ source = self.broken_mp4(self.root / "broken.mp4")+ header = self.repair(source)+ blob = source.read_bytes()++ self.assertEqual(blob[header.payload_start:header.payload_end],+ sample_bytes(len(DECODE_TO_DISPLAY)))+ self.assertEqual(header.size, len(header.prefix) + len(sample_bytes(len(DECODE_TO_DISPLAY))))++ def test_chunk_offsets_move_with_the_longer_header(self):+ source = self.broken_mp4(self.root / "broken.mp4")+ header = self.repair(source)+ delta = len(header.prefix) - header.payload_start+ before = entries(table(moov_of(source.read_bytes()), b"stco"), ">I")+ after = entries(table(moov_of(header.prefix), b"stco"), ">I")++ self.assertGreater(delta, 0)+ self.assertEqual([value + delta for (value,) in before], [value for (value,) in after])+ self.assertEqual(after[0][0], len(header.prefix))+ self.assertEqual(after[-1][0],+ header.size - SAMPLE_SIZE, "最后一个块没落在文件末尾那一段上")++ def test_an_edit_list_that_already_compensates_the_shift_is_left_alone(self):+ """封装器为 ctts 补过的那一刀要原样留着,再补一次会真的切掉开头那两帧。"""+ source = self.broken_mp4(self.root / "broken.mp4", edit_list=(5200, 400))+ header = self.repair(source)++ self.assertEqual(entries(self.edit_list(header), ">IiI"), [(5200, 400, 1 << 16)])++ def test_a_real_trim_keeps_its_own_start_and_takes_the_shift_on_top(self):+ source = self.broken_mp4(self.root / "broken.mp4", edit_list=(4000, 2000))+ header = self.repair(source)++ self.assertEqual(entries(self.edit_list(header), ">IiI"), [(4000, 2400, 1 << 16)])++ def test_a_file_without_an_edit_list_gets_one_that_starts_at_the_shift(self):+ source = self.broken_mp4(self.root / "broken.mp4")+ header = self.repair(source)++ self.assertEqual(entries(self.edit_list(header), ">IiI"), [(5200, 400, 1 << 16)])++ def edit_list(self, header: RepairedHeader) -> bytes:+ moov = moov_of(header.prefix)+ trak = _find(moov, 0, len(moov), b"trak")+ assert trak is not None+ edts = _find(moov, *trak, b"edts")+ assert edts is not None+ elst = _find(moov, *edts, b"elst")+ assert elst is not None+ return moov[elst[0]:elst[1]]++ def test_a_file_that_already_has_composition_offsets_is_refused(self):+ source = self.broken_mp4(self.root / "fine.mp4", composition_offsets=True)++ with self.assertRaises(RepairUnavailable):+ self.repair(source)++ def test_a_display_order_equal_to_the_decode_order_is_refused(self):+ source = self.broken_mp4(self.root / "fine.mp4")++ with self.assertRaises(RepairUnavailable):+ self.repair(source, order=range(len(DECODE_TO_DISPLAY)))++ def test_the_display_order_is_the_order_the_decoder_hands_frames_back(self):+ """解码器按显示顺序出帧,每帧的时间戳原样来自它那个样本,所以置换是读出来的。"""+ with patch.object(mp4repair.subprocess, "run",+ lambda *args, **options: _Probe(b"0\n800\n1200\n400\n")):+ order = mp4repair._display_order(Path("ffprobe"), Path("movie.mp4"),+ [0, 400, 800, 1200])++ self.assertEqual(order, [0, 3, 1, 2])++ def test_a_decode_that_loses_frames_is_refused_instead_of_guessed(self):+ """少一帧就说明这份表和码流对不上,宁可不修,也不能写一张错的 ctts。"""+ with patch.object(mp4repair.subprocess, "run",+ lambda *args, **options: _Probe(b"0\n800\n")):+ with self.assertRaises(RepairUnavailable):+ mp4repair._display_order(Path("ffprobe"), Path("movie.mp4"), [0, 400, 800])+++class SidecarTests(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = TemporaryDirectory()+ self.root = Path(self._temporary.name)+ self.addCleanup(self._temporary.cleanup)++ def test_a_sidecar_reads_back_exactly_what_was_written(self):+ header = RepairedHeader(prefix=b"head", payload_start=7, payload_end=99, suffix=b"tail")+ path = self.root / "9-1-2.mp4hdr"+ write_sidecar(path, header)++ self.assertEqual(read_sidecar(path), header)++ def test_a_truncated_sidecar_reads_as_missing(self):+ path = self.root / "9-1-2.mp4hdr"+ write_sidecar(path, RepairedHeader(prefix=b"head", payload_start=7, payload_end=99))+ path.write_bytes(path.read_bytes()[:-1])++ self.assertIsNone(read_sidecar(path))++ def test_a_missing_sidecar_reads_as_missing(self):+ self.assertIsNone(read_sidecar(self.root / "nothing.mp4hdr"))+++class HeaderRepairStoreTests(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = TemporaryDirectory()+ self.root = Path(self._temporary.name)+ self.addCleanup(self._temporary.cleanup)+ self.source = self.root / "movie.mp4"+ self.source.write_bytes(b"x" * 64)+ self.store = HeaderRepairStore(self.root / "cache", _Resolver())+ self.header = RepairedHeader(prefix=b"head", payload_start=8, payload_end=64)++ def sidecar(self) -> Path:+ stat = self.source.stat()+ return self.store.root / f"6297-{stat.st_size}-{stat.st_mtime_ns}.mp4hdr"++ def test_a_stored_header_is_found_again_for_the_same_file(self):+ write_sidecar(self.sidecar(), self.header)++ self.assertEqual(self.store.lookup(6297, self.source), self.header)++ def test_a_changed_source_file_invalidates_the_stored_header(self):+ write_sidecar(self.sidecar(), self.header)+ self.source.write_bytes(b"y" * 65)++ self.assertIsNone(self.store.lookup(6297, self.source))++ def test_a_missing_source_file_answers_none_instead_of_raising(self):+ self.assertIsNone(self.store.lookup(6297, self.root / "gone.mp4"))++ def test_a_looked_up_header_is_kept_for_the_next_range_request(self):+ """一份头有几 MB,拖动一次进度条就是十几个 Range,不能每个都回去读文件。"""+ sidecar = self.sidecar()+ write_sidecar(sidecar, self.header)+ self.assertEqual(self.store.lookup(6297, self.source), self.header)+ sidecar.unlink()++ self.assertEqual(self.store.lookup(6297, self.source), self.header)++ def test_a_source_that_cannot_be_repaired_is_not_tried_again(self):+ """修不了的片子每次播放都重解一遍,就是把一分多钟的整片读白扔一次。"""+ attempts: list[Path] = []++ def build(source: Path, ffprobe: Path):+ attempts.append(source)+ raise RepairUnavailable("测试用:这个片源修不了")++ with patch.object(mp4repair, "repaired_header", build):+ outcomes = [self.store.repair_now(6297, self.source) for _ in range(3)]++ self.assertEqual(outcomes, [False, False, False])+ self.assertEqual(len(attempts), 1)+ self.assertIsNone(self.store.lookup(6297, self.source))++ def test_a_stored_header_is_not_computed_a_second_time(self):+ write_sidecar(self.sidecar(), self.header)++ with patch.object(mp4repair, "repaired_header", _never_called):+ self.assertFalse(self.store.repair_now(6297, self.source))++ def test_a_fresh_header_replaces_the_one_left_by_an_older_copy(self):+ stale = self.store.root / "6297-1-1.mp4hdr"+ write_sidecar(stale, self.header)++ with patch.object(mp4repair, "repaired_header", lambda source, ffprobe: self.header):+ self.assertTrue(self.store.repair_now(6297, self.source))++ self.assertFalse(stale.exists())+ self.assertEqual(self.store.lookup(6297, self.source), self.header)+++def _never_called(source: Path, ffprobe: Path):+ raise AssertionError("不该再算一遍")+++class _Probe:+ """`subprocess.run` 的返回值里,`_display_order` 只看这两样。"""++ def __init__(self, stdout: bytes, returncode: int = 0) -> None:+ self.stdout = stdout+ self.returncode = returncode+++class _Resolver:+ """够 `HeaderRepairStore` 用的 FFmpeg 定位器。"""++ def ffprobe(self) -> str:+ return "ffprobe"+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_streaming.py b/tests/test_streaming.pyindex ff2a9cab0..f6263b5d7 100644--- a/tests/test_streaming.py+++ b/tests/test_streaming.py@@ -8,6 +8,29 @@ from peach.mp4index import segment_planfrom peach.segments import build_hls_playlist+async def _collect(response, requested: bytes | None, method: str = "GET"):+ """把一个 ASGI 响应跑完,返回 (状态码, 响应头, 响应体)。"""+ messages: list[dict] = []++ async def receive() -> dict:+ await asyncio.Event().wait()+ return {"type": "http.disconnect"}++ async def send(message: dict) -> None:+ messages.append(message)++ await response({+ "type": "http", "method": method, "path": "/stream",+ "headers": [(b"range", requested)] if requested else [],+ }, receive, send)+ start = messages[0]+ return (+ start["status"],+ {key.decode(): value.decode() for key, value in start["headers"]},+ b"".join(message.get("body", b"") for message in messages[1:]),+ )++class StreamSessionRegistryTests(unittest.IsolatedAsyncioTestCase):async def test_cancel_stops_every_active_request_in_the_session(self):registry = StreamSessionRegistry()@@ -126,6 +149,61 @@ class StreamSessionRegistryTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(BufferedFileResponse.chunk_size, 1 << 20)self.assertEqual(CancellableFileResponse.chunk_size, 1 << 20)+ async def test_a_spliced_file_serves_ranges_across_the_seam(self):+ """头在边车里、内容在原文件中间,跨接缝的 Range 必须拼出连续的字节。"""+ import tempfile+ from pathlib import Path++ from peach.mp4repair import RepairedHeader+ from peach.streaming import SplicedMp4Response++ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / "remote.mp4"+ path.write_bytes(b"OLDHEAD" + bytes(range(64)) + b"TAIL")+ header = RepairedHeader(+ prefix=b"NEWHEADER", payload_start=7, payload_end=71, suffix=b"END")+ whole = b"NEWHEADER" + bytes(range(64)) + b"END"++ for label, requested, status, expected in (+ ("没有 Range 头", None, 200, whole),+ ("整份也按 Range 答", b"bytes=0-", 206, whole),+ ("跨头与内容的接缝", b"bytes=5-12", 206, whole[5:13]),+ ("只要内容", b"bytes=20-30", 206, whole[20:31]),+ ("开区间到尾", b"bytes=70-", 206, whole[70:]),+ ("末尾若干字节", b"bytes=-4", 206, whole[-4:]),+ ):+ with self.subTest(label):+ status_code, headers, body = await _collect(+ SplicedMp4Response(path, header), requested)+ self.assertEqual(status_code, status)+ self.assertEqual(body, expected)+ self.assertEqual(headers["content-length"], str(len(expected)))+ self.assertEqual(headers["accept-ranges"], "bytes")++ status_code, headers, body = await _collect(+ SplicedMp4Response(path, header), b"bytes=999-")+ self.assertEqual(status_code, 416)+ self.assertEqual(headers["content-range"], f"bytes */{len(whole)}")++ async def test_a_spliced_head_request_reports_the_size_without_a_body(self):+ import tempfile+ from pathlib import Path++ from peach.mp4repair import RepairedHeader+ from peach.streaming import SplicedMp4Response++ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / "remote.mp4"+ path.write_bytes(b"OLDHEAD" + bytes(range(64)))+ header = RepairedHeader(prefix=b"NEWHEADER", payload_start=7, payload_end=71)+ status_code, headers, body = await _collect(+ SplicedMp4Response(path, header), None, method="HEAD")++ self.assertEqual(status_code, 200)+ self.assertEqual(headers["content-length"], "73")+ self.assertEqual(headers["content-type"], "video/mp4")+ self.assertEqual(body, b"")+def test_hls_playlist_is_time_addressable_without_full_file_ranges(self):# 分片边界由真实关键帧决定,不再按固定秒数等分(见 tests/test_segments.py)。plan = segment_plan([0.0, 6.0, 12.0], 13.5, 6)