Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(media): 有 B 帧却没有 ctts 的 MP4 改走转码

longmeidao19233bab8d40
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 354a189ae..f7a03f0aa 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -157,6 +157,8 @@ AUTO_SCOPE_FILES: dict[str, tuple[str, ...]] = {
# tooling 里的脚本策略门槛验它的形态。
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/desktop_startup.py", "tooling"),
("src/peach/desktop_uninstall.py", "tooling"),
("src/peach/peach_proxy.py", "tooling"),
diff --git a/src/peach/mp4index.py b/src/peach/mp4index.py
index e4099690b..ddb16eca9 100644
--- a/src/peach/mp4index.py
+++ b/src/peach/mp4index.py
@@ -6,6 +6,9 @@ HLS 分片必须切在关键帧上,所以要先知道关键帧在哪。用
MP4 把关键帧表(`stss`)和时长表(`stts`)都放在 `moov` 里,通常位于文件开头,
读几 MB 就够。解析不出来就返回 None,由调用方回退到标准 Range,绝不猜。
+
+同一份 `moov` 还回答另一个问题:视频轨有没有 `ctts`(显示时间偏移表)。有 B 帧的片子
+靠它才能把解码顺序还原成显示顺序,缺了它容器声明的显示时刻就是解码顺序。
"""
from __future__ import annotations
@@ -43,8 +46,8 @@ def _find(payload: bytes, start: int, end: int, kind: bytes):
return None
-def _video_sample_table(payload: bytes, start: int, end: int):
- """返回视频轨的 (timescale, stts 区间, stss 区间)。"""
+def _video_stbl(payload: bytes, start: int, end: int):
+ """返回视频轨的 (timescale, stbl 区间)。"""
for box, body, stop in _iter_boxes(payload, start, end):
if box != b"trak":
continue
@@ -63,13 +66,22 @@ def _video_sample_table(payload: bytes, start: int, end: int):
continue
version = payload[mdhd[0]]
timescale = struct.unpack_from(">I", payload, mdhd[0] + (20 if version == 1 else 12))[0]
- stts = _find(payload, *stbl, b"stts")
- stss = _find(payload, *stbl, b"stss")
- if timescale and stts and stss:
- return timescale, stts, stss
+ if timescale:
+ return timescale, stbl
return None
+def _video_sample_table(payload: bytes, start: int, end: int):
+ """返回视频轨的 (timescale, stts 区间, stss 区间)。"""
+ found = _video_stbl(payload, start, end)
+ if found is None:
+ return None
+ timescale, stbl = found
+ stts = _find(payload, *stbl, b"stts")
+ stss = _find(payload, *stbl, b"stss")
+ return (timescale, stts, stss) if stts and stss else None
+
+
def _sync_sample_seconds(payload: bytes, timescale: int, stts, stss) -> list[float]:
body, stop = stts
count = struct.unpack_from(">I", payload, body + 4)[0]
@@ -143,13 +155,34 @@ def _read_moov(handle, limit: int) -> bytes | None:
offset += size
-def keyframe_seconds(path: Path | str, probe_bytes: int = HEADER_PROBE_BYTES) -> list[float] | None:
- """返回 MP4 的关键帧时间(秒)。拿不到就返回 None,由调用方回退到标准 Range。"""
+def _moov_of(path: Path | str, probe_bytes: int) -> bytes | None:
try:
with open(path, "rb") as handle:
- moov = _read_moov(handle, probe_bytes)
+ return _read_moov(handle, probe_bytes)
except OSError:
return None
+
+
+def composition_offsets_present(
+ path: Path | str, probe_bytes: int = HEADER_PROBE_BYTES,
+) -> bool | None:
+ """视频轨里有没有 `ctts`。读不出 `moov` 或没有视频轨返回 None。
+
+ 回答的是「有没有这张表」,不是「该不该有」:没有 B 帧的片子本来就不需要 ctts。
+ 调用方要把它和帧重排深度(ffprobe 的 `has_b_frames`)放在一起看才有结论。
+ """
+ moov = _moov_of(path, probe_bytes)
+ if not moov:
+ return None
+ found = _video_stbl(moov, 0, len(moov))
+ if found is None:
+ return None
+ return _find(moov, *found[1], b"ctts") is not None
+
+
+def keyframe_seconds(path: Path | str, probe_bytes: int = HEADER_PROBE_BYTES) -> list[float] | None:
+ """返回 MP4 的关键帧时间(秒)。拿不到就返回 None,由调用方回退到标准 Range。"""
+ moov = _moov_of(path, probe_bytes)
if not moov:
return None
table = _video_sample_table(moov, 0, len(moov))
diff --git a/src/peach/transcodes.py b/src/peach/transcodes.py
index 923d68433..c602a59c0 100644
--- a/src/peach/transcodes.py
+++ b/src/peach/transcodes.py
@@ -7,10 +7,11 @@ import threading
import time
import uuid
from contextlib import contextmanager
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from pathlib import Path
from .ffmpeg import FFmpegResolver
+from .mp4index import composition_offsets_present
BROWSER_NATIVE_SUFFIXES = frozenset({".mp4", ".m4v", ".webm", ".ogv", ".ogg"})
@@ -26,6 +27,8 @@ class _MediaProfile:
audio_codec: str
#: 容器报的总时长(秒);探测不到时为 0,切片计划据此决定能不能按时间切。
duration: float = 0.0
+ #: 有 B 帧却没有 ctts:容器声明的显示时刻其实是解码顺序,直接播会掉帧。
+ decode_order_timestamps: bool = False
@dataclass(frozen=True)
@@ -113,7 +116,7 @@ class TranscodeService:
profile = self._profile_for(source, session, registry)
except OSError as exc:
raise TranscodeUnavailable("source unavailable") from exc
- if profile is not None and self._browser_compatible(source, profile):
+ if profile is not None and self._decodes_in_browser(source, profile):
return source, False
choice = self.resolver.ffmpeg()
@@ -183,7 +186,8 @@ class TranscodeService:
if source.suffix.lower() in {".mp4", ".m4v"}:
return (profile.video_codec == "h264"
and profile.pixel_format in DIRECT_MP4_PIXEL_FORMATS
- and profile.audio_codec in {"", "aac", "mp3"})
+ and profile.audio_codec in {"", "aac", "mp3"}
+ and not profile.decode_order_timestamps)
if source.suffix.lower() == ".webm":
return (profile.video_codec in {"vp8", "vp9", "av1"}
and profile.audio_codec in {"", "opus", "vorbis"})
@@ -198,7 +202,8 @@ class TranscodeService:
return None
command = (
str(choice.path), "-v", "error", "-show_entries",
- "stream=codec_type,codec_name,pix_fmt:format=duration", "-of", "json", str(source),
+ "stream=codec_type,codec_name,pix_fmt,has_b_frames:format=duration",
+ "-of", "json", str(source),
)
try:
returncode, stdout, _stderr = self._execute(
@@ -234,8 +239,42 @@ class TranscodeService:
pixel_format=str(video.get("pix_fmt") or "").lower(),
audio_codec=str(audio.get("codec_name") or "").lower(),
duration=max(0.0, duration),
+ decode_order_timestamps=self._decode_order_timestamps(source, video),
)
+ @staticmethod
+ def _decodes_in_browser(source: Path, profile: _MediaProfile) -> bool:
+ """浏览器能不能解出画面。时间戳错乱不算解不出来。
+
+ 整片转码要占满一个编码位、写一份和原片同量级的缓存,只有编码本身不被支持才值得。
+ 缺 `ctts` 的片源画面解得出来,错的只是容器写的显示顺序,交给 HLS 转码分片按需修
+ 就够。卡片悬停预览直接打 `/stream`,鼠标划过一张卡片不能启动一次整片转码。
+ """
+ return TranscodeService._browser_compatible(
+ source, replace(profile, decode_order_timestamps=False),
+ )
+
+ @staticmethod
+ def _decode_order_timestamps(source: Path, video: dict) -> bool:
+ """有 B 帧却没有 `ctts` 的 MP4,容器声明的显示时刻就是解码顺序。
+
+ 浏览器信容器的时间戳,凡是比已显示帧更早的一律丢掉,于是整片掉两成帧、看着
+ 持续卡顿;FFmpeg 和本地播放器按解码器输出顺序排,同一个文件反而正常。这类片子
+ 原样送给浏览器修不好,播放要走转码分片,让编码器重新写一份对的时间轴。
+
+ 判据放在探测里做一次,结论跟 profile 一起缓存:`moov` 动辄几 MB,每个分片请求
+ 都读一遍等于把挂载网盘反复拉一遍。
+ """
+ if source.suffix.lower() not in {".mp4", ".m4v"}:
+ return False
+ try:
+ reorder_depth = int(video.get("has_b_frames") or 0)
+ except (TypeError, ValueError):
+ return False
+ if reorder_depth <= 0:
+ return False
+ return composition_offsets_present(source) is False
+
def _attempts(
self,
ffmpeg: Path,
diff --git a/tests/support/mp4.py b/tests/support/mp4.py
new file mode 100644
index 000000000..2595ab1c7
--- /dev/null
+++ b/tests/support/mp4.py
@@ -0,0 +1,41 @@
+"""测试用的最小 MP4:只有时间表,没有真实媒体数据。
+
+`peach.mp4index` 只读 `moov`,关键帧表、时长表和显示时间偏移表都能这样造出来,
+用例因此不必依赖 FFmpeg 或真实片源。
+"""
+from __future__ import annotations
+
+import struct
+
+
+def box(kind: bytes, payload: bytes) -> bytes:
+ return struct.pack(">I", len(payload) + 8) + kind + payload
+
+
+def minimal_mp4(
+ *,
+ timescale: int,
+ sample_delta: int,
+ samples: int,
+ keyframe_every: int,
+ composition_offsets: bool = False,
+) -> bytes:
+ """够 `peach.mp4index` 解析关键帧的最小 MP4。
+
+ `composition_offsets` 决定视频轨里有没有 `ctts`。有 B 帧的片源缺了这张表,容器
+ 声明的显示时刻就是解码顺序,浏览器会把倒着走的帧全丢掉。
+ """
+ mdhd = box(b"mdhd", struct.pack(">4sIIII HH", bytes(4), 0, 0, timescale,
+ samples * sample_delta, 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]
+ stss = box(b"stss", struct.pack(">II", 0, len(sync))
+ + 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)))
diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.py
index d8abd6004..b7fc13d95 100644
--- a/tests/test_fastapi_api.py
+++ b/tests/test_fastapi_api.py
@@ -2,7 +2,6 @@ import csv
import importlib.util
import json
import sqlite3
-import struct
import tempfile
import unittest
from contextlib import closing
@@ -10,6 +9,7 @@ from pathlib import Path
from unittest.mock import patch
from peach import __version__
+from support.mp4 import minimal_mp4
ROOT = Path(__file__).resolve().parents[1]
@@ -104,10 +104,6 @@ VALUES('local-default','local','Default',1,'{}','2026-08-14T12:17:23Z','2026-08-
"""
-def _box(kind: bytes, payload: bytes) -> bytes:
- return struct.pack(">I", len(payload) + 8) + kind + payload
-
-
def tiny_jpeg(tone: int, width: int = 64, height: int = 48) -> bytes:
"""一张真的能解开的小图。
@@ -121,22 +117,6 @@ def tiny_jpeg(tone: int, width: int = 64, height: int = 48) -> bytes:
return bytes(cv2.imencode(".jpg", canvas)[1])
-def minimal_mp4(*, timescale: int, sample_delta: int, samples: int, keyframe_every: int) -> bytes:
- """只含时间表的最小 MP4:够 peach.mp4index 解析关键帧,不含真实媒体数据。"""
- mdhd = _box(b"mdhd", struct.pack(">4sIIII HH", bytes(4), 0, 0, timescale,
- samples * sample_delta, 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]
- stss = _box(b"stss", struct.pack(">II", 0, len(sync))
- + b"".join(struct.pack(">I", n) for n in sync))
- stbl = _box(b"stbl", stts + stss)
- 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)))
-
-
class MediaCacheHeaderTests(unittest.TestCase):
"""生成物的缓存时长只许在一处写死。
diff --git a/tests/test_segments.py b/tests/test_segments.py
index 2cf41bb60..d517cd7b9 100644
--- a/tests/test_segments.py
+++ b/tests/test_segments.py
@@ -1,31 +1,13 @@
"""HLS 分片:关键帧对齐、时间戳连续、播放列表报真实时长。"""
import asyncio
-import struct
import tempfile
import unittest
from pathlib import Path
from unittest import mock
-from peach.mp4index import keyframe_seconds, segment_plan
+from peach.mp4index import composition_offsets_present, keyframe_seconds, segment_plan
from peach.segments import HlsSegmentService, StreamSessionRegistry, build_hls_playlist
-
-
-def box(kind: bytes, payload: bytes) -> bytes:
- return struct.pack(">I", len(payload) + 8) + kind + payload
-
-
-def synthetic_mp4(timescale: int, sample_delta: int, samples: int, keyframe_every: int) -> bytes:
- """构造一个只含时间表的最小 MP4:足够 stss/stts 解析,不含真实媒体数据。"""
- mdhd = box(b"mdhd", struct.pack(">4sIIII HH", b"\0\0\0\0", 0, 0, timescale, samples * sample_delta, 0, 0))
- hdlr = box(b"hdlr", struct.pack(">4sI4s", b"\0\0\0\0", 0, b"vide") + b"\0" * 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]
- stss = box(b"stss", struct.pack(">II", 0, len(sync)) + b"".join(struct.pack(">I", n) for n in sync))
- stbl = box(b"stbl", stts + stss)
- minf = box(b"minf", stbl)
- mdia = box(b"mdia", mdhd + hdlr + minf)
- trak = box(b"trak", mdia)
- return box(b"ftyp", b"isom" + b"\0" * 8) + box(b"moov", trak) + box(b"mdat", b"\0" * 64)
+from support.mp4 import minimal_mp4
class Mp4IndexTests(unittest.TestCase):
@@ -43,12 +25,12 @@ class Mp4IndexTests(unittest.TestCase):
def test_keyframe_times_come_from_the_sync_sample_table(self):
# 1000 刻度、每样本 40 刻度(25fps),每 25 个样本一个关键帧 = 每秒一个。
- path = self.write(synthetic_mp4(1000, 40, 250, 25))
+ path = self.write(minimal_mp4(timescale=1000, sample_delta=40, samples=250, keyframe_every=25))
self.assertEqual(keyframe_seconds(path)[:5], [0.0, 1.0, 2.0, 3.0, 4.0])
def test_moov_at_the_end_is_still_found(self):
"""非 faststart 的文件把 moov 放在结尾;顺序读到它可能要拉几个 GB。"""
- full = synthetic_mp4(1000, 40, 100, 25)
+ full = minimal_mp4(timescale=1000, sample_delta=40, samples=100, keyframe_every=25)
moov_start = full.index(b"moov") - 4
moov_size = int.from_bytes(full[moov_start:moov_start + 4], "big")
moov = full[moov_start:moov_start + moov_size]
@@ -59,6 +41,21 @@ class Mp4IndexTests(unittest.TestCase):
self.assertIsNone(keyframe_seconds(self.write(b"not an mp4 at all")))
self.assertIsNone(keyframe_seconds(self.root / "missing.mp4"))
+ def test_composition_offsets_are_read_from_the_video_track(self):
+ """有 B 帧却没有 ctts 的片源要改走转码,所以这张表在不在必须答得准。"""
+ plain = self.write(minimal_mp4(
+ timescale=1000, sample_delta=40, samples=100, keyframe_every=25))
+ reordered = self.write(minimal_mp4(
+ timescale=1000, sample_delta=40, samples=100, keyframe_every=25,
+ composition_offsets=True), name="reordered.mp4")
+ self.assertIs(composition_offsets_present(plain), False)
+ self.assertIs(composition_offsets_present(reordered), True)
+
+ def test_unreadable_moov_answers_none_instead_of_guessing(self):
+ """读不出 moov 就不知道有没有这张表;猜「没有」会把好片源推去转码。"""
+ self.assertIsNone(composition_offsets_present(self.write(b"not an mp4 at all")))
+ self.assertIsNone(composition_offsets_present(self.root / "missing.mp4"))
+
def test_plan_snaps_to_keyframes_and_covers_the_whole_duration(self):
keyframes = [round(value * 8.33, 2) for value in range(12)]
plan = segment_plan(keyframes, 100.0, 6)
diff --git a/tests/test_transcodes.py b/tests/test_transcodes.py
index 61100a7c1..55b760bf6 100644
--- a/tests/test_transcodes.py
+++ b/tests/test_transcodes.py
@@ -8,6 +8,7 @@ from unittest.mock import patch
from peach.ffmpeg import BinaryChoice
from peach.transcodes import TranscodeCancelled, TranscodeService, TranscodeUnavailable
+from support.mp4 import minimal_mp4
class _Resolver:
@@ -92,6 +93,69 @@ class TranscodeServiceTests(unittest.TestCase):
if expected:
self.assertEqual(result[0].read_bytes(), b"mp4")
+ def test_b_frames_without_composition_offsets_are_sent_to_transcode(self):
+ """有 B 帧却没有 ctts 的 MP4,容器声明的显示时刻是解码顺序。
+
+ 浏览器照单全收,凡是比已显示帧更早的一律丢掉,整片掉两成帧;本地播放器按解码器
+ 输出顺序排,同一个文件看着正常。没有 B 帧的片源本来就不需要这张表,缺了不算毛病。
+ """
+ cases = (
+ (2, False, True),
+ (2, True, False),
+ (0, False, False),
+ )
+ for reorder_depth, composition_offsets, expected in cases:
+ with self.subTest(has_b_frames=reorder_depth, ctts=composition_offsets):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp).resolve()
+ source = root / "movie.mp4"
+ source.write_bytes(minimal_mp4(
+ timescale=1000, sample_delta=40, samples=100, keyframe_every=25,
+ composition_offsets=composition_offsets))
+ service = TranscodeService(
+ _Resolver(root / "ffmpeg.exe", root / "ffprobe.exe"),
+ root / "cache", prefer_hardware=False,
+ )
+ commands = []
+ streams = [
+ {"codec_type": "video", "codec_name": "h264", "pix_fmt": "yuv420p",
+ "has_b_frames": reorder_depth},
+ {"codec_type": "audio", "codec_name": "aac"},
+ ]
+ with patch("peach.transcodes.subprocess.Popen",
+ side_effect=_media_process(commands, streams)):
+ self.assertEqual(service.requires_conversion(source), expected)
+ entries = commands[0][commands[0].index("-show_entries") + 1]
+ self.assertIn("has_b_frames", entries)
+
+ def test_a_broken_timestamp_table_never_starts_a_whole_file_transcode(self):
+ """缺 ctts 的片源照原样发,播放由 HLS 转码分片修。
+
+ 整片转码写一份和原片同量级的缓存,只有编码本身不被支持才值得。卡片悬停预览
+ 直接打 `/stream`,鼠标划过一张卡片不能启动一次整片转码。
+ """
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp).resolve()
+ source = root / "movie.mp4"
+ source.write_bytes(minimal_mp4(
+ timescale=1000, sample_delta=40, samples=100, keyframe_every=25))
+ service = TranscodeService(
+ _Resolver(root / "ffmpeg.exe", root / "ffprobe.exe"),
+ root / "cache", prefer_hardware=False,
+ )
+ commands = []
+ streams = [
+ {"codec_type": "video", "codec_name": "h264", "pix_fmt": "yuv420p",
+ "has_b_frames": 2},
+ {"codec_type": "audio", "codec_name": "aac"},
+ ]
+ with patch("peach.transcodes.subprocess.Popen",
+ side_effect=_media_process(commands, streams)):
+ self.assertTrue(service.requires_conversion(source))
+ self.assertEqual(service.browser_path(7, source), (source, False))
+ self.assertEqual(
+ [c for c in commands if Path(c[0]).stem.lower() == "ffmpeg"], [])
+
def test_native_mp4_is_returned_without_ffmpeg(self):
source = Path("movie.mp4")
service = TranscodeService(_Resolver(None), Path("cache"))