Skip to content

armgit / peach

Public Imported from GitHub
0

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

perf(hls): 分片重编码走 NVENC 链,同一分片只起一个 FFmpeg,Range 按 1 MiB 读

longmeidao7adb15aeb980
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 6255de523..c7d9a9bd9 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -190,6 +190,8 @@ CloudDrive 为外部应用,本项目不捆绑其二进制或依赖其管理 AP
- 图片灯箱在本地照片和关注在线图片间复用同一套 Swiper,在线图片只显示来源、合集序号和浏览器实际解析结果;照片标签进入分页图片墙,点开才按原图比例呈现。
- 两处图片墙(资料页照片、关注在线图片)共用大小与固定比例/瀑布流设置,大小由顶部按钮控制,筛选浮层控制布局。关注图片的「仅显示图片」开关独立保存,隐藏卡片文字与信息角标。瀑布流使用 CSS 多栏、`break-inside:avoid` 和图片 `aspect-ratio:auto 1`:懒加载前保留非零高度,加载后使用天然比例;机制见 [MDN aspect-ratio](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/aspect-ratio)。图片 `alt` 保留给读屏,字色透明避免加载时铺满文件名。
- 缓存型资产路由一律先问缓存,不先解析源文件:`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 读文件。
- 「只采集」对齐全的行(番号已落库、字段有着落或已在候选表、封面在位)不碰磁盘;文件在不在看目录列表,同目录只列一次;候选 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/src/peach/api.py b/src/peach/api.py
index 5fd0539dd..7a4d44fb4 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -144,7 +144,9 @@ def create_app(
hls_plan_executor = ThreadPoolExecutor(
max_workers=2, thread_name_prefix="PeachHlsPlan",
)
- hls_service = HlsSegmentService(resolver, settings.stream_root)
+ hls_service = HlsSegmentService(
+ resolver, settings.stream_root, prefer_hardware=transcode_service.prefer_hardware,
+ )
mdns = create_mdns_publisher(
settings.mdns_name, settings.mdns_port, secure=settings.tls_enabled,
address=settings.mdns_address,
diff --git a/src/peach/segments.py b/src/peach/segments.py
index fa1c82cc7..77c5e9b55 100644
--- a/src/peach/segments.py
+++ b/src/peach/segments.py
@@ -57,15 +57,21 @@ class HlsSegmentService:
segment_seconds: int = HLS_SEGMENT_SECONDS,
max_concurrent: int | None = None,
cache_bytes: int = DEFAULT_CACHE_BYTES,
+ prefer_hardware: bool = False,
):
self.resolver = resolver
self.work_root = work_root
self.segment_seconds = segment_seconds
self.cache_bytes = cache_bytes
+ # 重编码的分片先试 NVENC,失败再退回 libx264;与整片转码用同一个偏好。
+ self.prefer_hardware = prefer_hardware
# 每个分片请求都会起一个 FFmpeg;播放器本身就并发预取,多设备同看能把机器打满。
self._limit = max_concurrent or max(1, (os.cpu_count() or 4) // 2)
self._semaphore: asyncio.Semaphore | None = None
self._plans: OrderedDict[tuple, list[tuple[float, float]]] = OrderedDict()
+ # 同一分片常被并发请求:播放器预取、重连、多设备同看都会撞上同一个目标文件。
+ # 同目标只放一个生成者,后到者等它完事后直接用缓存,不再各起一个 FFmpeg 重读网盘。
+ self._generation_locks: dict[Path, asyncio.Lock] = {}
def _gate(self) -> asyncio.Semaphore:
if self._semaphore is None:
@@ -141,90 +147,116 @@ class HlsSegmentService:
if target.is_file() and target.stat().st_size:
os.utime(target, None) # 命中即续期,淘汰按最后访问时间
return target
+ lock = self._generation_locks.setdefault(target, asyncio.Lock())
+ try:
+ async with lock:
+ # 等到锁的可能是排在生成者后面的请求,先看缓存再决定要不要自己跑。
+ if target.is_file() and target.stat().st_size:
+ os.utime(target, None)
+ return target
+ return await self._generate_uncached(
+ source, start, duration, target,
+ session=session, registry=registry, transcode=transcode,
+ )
+ finally:
+ if not lock.locked():
+ self._generation_locks.pop(target, None)
+
+ async def _generate_uncached(
+ self, source: Path, start: float, duration: float, target: Path, *,
+ session: str, registry: StreamSessionRegistry, transcode: bool,
+ ) -> Path:
choice = self.resolver.ffmpeg()
if choice is None:
raise SegmentUnavailable("ffmpeg unavailable")
if registry.is_cancelled(session):
raise SegmentCancelled(session)
-
target.parent.mkdir(parents=True, exist_ok=True)
- temporary = target.with_name(f"{uuid.uuid4().hex}.tmp.ts")
- command = [
- str(choice.path), "-hide_banner", "-loglevel", "error", "-nostdin", "-y",
- # 终点必须写成绝对时间戳。-copyts 保留原始时间轴后,-t 会被当成绝对结束时刻
- # 而不是片段时长,于是除了开头那一两段,每段的 -t 都早已过期,ffmpeg 以
- # 退出码 0、空 stderr 写出 0 字节,服务端只能报一句没有内容的 ffmpeg failed。
- "-ss", f"{start:.3f}", "-i", str(source), "-to", f"{start + duration:.3f}",
- "-map", "0:v:0", "-map", "0:a:0?", "-sn", "-dn", "-c", "copy",
- # 保留原始时间戳,让每段接着上一段走。用 -avoid_negative_ts make_zero
- # 把每段归零的话,每段都自称从 0 秒开始,拖动进度条时容易跳错位置。
- "-copyts", "-muxdelay", "0", "-muxpreload", "0",
- "-f", "mpegts", str(temporary),
- ]
- if transcode:
- command = [
- str(choice.path), "-hide_banner", "-loglevel", "error", "-nostdin", "-y",
- "-ss", f"{start:.3f}", "-i", str(source), "-t", f"{duration:.3f}",
- "-map", "0:v:0", "-map", "0:a:0?", "-sn", "-dn",
- "-c:v", "libx264", "-preset", "veryfast", "-crf", "21",
- "-pix_fmt", "yuv420p", "-threads", "2", "-c:a", "aac", "-b:a", "160k",
- "-output_ts_offset", f"{start:.3f}", "-muxdelay", "0", "-muxpreload", "0",
- "-f", "mpegts", str(temporary),
- ]
- creationflags = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0
- process = None
- successful = False
+ detail = ""
async with self._gate():
- try:
+ for name, build in self._attempts(choice.path, source, start, duration, transcode):
+ temporary = target.with_name(f"{uuid.uuid4().hex}.tmp.ts")
try:
- process = await asyncio.create_subprocess_exec(
- *command,
- stdin=subprocess.DEVNULL,
- stdout=subprocess.DEVNULL,
- stderr=asyncio.subprocess.PIPE,
- creationflags=creationflags,
- )
- except OSError as exc:
- raise SegmentUnavailable("ffmpeg failed to start") from exc
-
- if not registry.register_process(session, process):
- _kill_process(process)
- await process.communicate()
- raise SegmentCancelled(session)
-
- try:
- _, stderr = await process.communicate()
- finally:
- registry.unregister_process(session, process)
- if (process.returncode != 0 or not temporary.is_file()
- or not temporary.stat().st_size):
- detail = (stderr or b"").decode("utf-8", "replace")[-1000:]
+ returncode, stderr = await self._run(build(temporary), session, registry)
+ if returncode == 0 and temporary.is_file() and temporary.stat().st_size:
+ temporary.replace(target)
+ self._evict()
+ return target
if registry.is_cancelled(session):
raise SegmentCancelled(session)
+ detail = stderr.decode("utf-8", "replace")[-1000:]
if not detail:
# FFmpeg 可以退出码 0、stderr 全空却写出 0 字节(时间窗取错就是
# 这样)。此时光报 "ffmpeg failed" 等于没报,把能观测到的都说出来。
size = temporary.stat().st_size if temporary.is_file() else None
detail = (
- f"ffmpeg wrote no data: returncode={process.returncode} "
+ f"ffmpeg wrote no data: returncode={returncode} "
f"bytes={'缺文件' if size is None else size} "
f"ss={start:.3f} to={start + duration:.3f}"
)
- raise SegmentUnavailable(detail)
- # 同一片段可能被并发请求各生成一次;原子改名让后到的覆盖同样内容即可。
- temporary.replace(target)
- successful = True
- self._evict()
- return target
- except asyncio.CancelledError:
- if process is not None:
- _kill_process(process)
- await process.communicate()
- registry.unregister_process(session, process)
- raise
- finally:
- if not successful:
+ detail = f"{name}: {detail}"
+ finally:
temporary.unlink(missing_ok=True)
+ raise SegmentUnavailable(detail)
+
+ def _attempts(self, ffmpeg: Path, source: Path, start: float, duration: float, transcode: bool):
+ """依次尝试的命令,每项是 (名字, 接收临时文件路径的构造函数)。
+
+ 封装复制只有一种。重编码与整片转码用同一条链:CUDA 解码加 NVENC、软件解码加 NVENC、
+ 最后 libx264;没有显卡的机器只是多失败两次,不会没有分片。
+ """
+ prefix = [str(ffmpeg), "-hide_banner", "-loglevel", "error", "-nostdin", "-y"]
+ mapping = ["-map", "0:v:0", "-map", "0:a:0?", "-sn", "-dn"]
+ mux = ["-muxdelay", "0", "-muxpreload", "0", "-f", "mpegts"]
+ if not transcode:
+ # 终点必须写成绝对时间戳。-copyts 保留原始时间轴后,-t 会被当成绝对结束时刻
+ # 而不是片段时长,于是除了开头那一两段,每段的 -t 都早已过期,ffmpeg 以
+ # 退出码 0、空 stderr 写出 0 字节,服务端只能报一句没有内容的 ffmpeg failed。
+ # 保留原始时间戳,让每段接着上一段走。用 -avoid_negative_ts make_zero
+ # 把每段归零的话,每段都自称从 0 秒开始,拖动进度条时容易跳错位置。
+ window = ["-ss", f"{start:.3f}", "-i", str(source), "-to", f"{start + duration:.3f}"]
+ return [("copy", lambda out: prefix + window + mapping + ["-c", "copy", "-copyts"] + mux + [str(out)])]
+ window = ["-ss", f"{start:.3f}", "-i", str(source), "-t", f"{duration:.3f}"]
+ audio = ["-c:a", "aac", "-b:a", "160k", "-output_ts_offset", f"{start:.3f}"]
+ nvenc = ["-c:v", "h264_nvenc", "-preset", "p1", "-tune", "hq", "-rc", "vbr", "-cq", "21", "-b:v", "0"]
+ attempts = []
+ if self.prefer_hardware:
+ cuda = ["-hwaccel", "cuda", "-hwaccel_output_format", "cuda"]
+ attempts.append(("cuda-nvenc", lambda out: prefix + cuda + window + mapping
+ + ["-vf", "scale_cuda=format=nv12"] + nvenc + audio + mux + [str(out)]))
+ attempts.append(("nvenc", lambda out: prefix + window + mapping
+ + nvenc + ["-pix_fmt", "yuv420p"] + audio + mux + [str(out)]))
+ attempts.append(("libx264", lambda out: prefix + window + mapping + [
+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "21", "-pix_fmt", "yuv420p", "-threads", "2",
+ ] + audio + mux + [str(out)]))
+ return attempts
+
+ async def _run(self, command: list[str], session: str, registry: StreamSessionRegistry) -> tuple[int, bytes]:
+ """跑一次 FFmpeg 并把进程登记到会话,取消时能被杀掉。返回 (退出码, stderr)。"""
+ creationflags = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0
+ try:
+ process = await asyncio.create_subprocess_exec(
+ *command,
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=asyncio.subprocess.PIPE,
+ creationflags=creationflags,
+ )
+ except OSError as exc:
+ raise SegmentUnavailable("ffmpeg failed to start") from exc
+ if not registry.register_process(session, process):
+ _kill_process(process)
+ await process.communicate()
+ raise SegmentCancelled(session)
+ try:
+ _, stderr = await process.communicate()
+ except asyncio.CancelledError:
+ _kill_process(process)
+ await process.communicate()
+ raise
+ finally:
+ registry.unregister_process(session, process)
+ return process.returncode, stderr or b""
def _kill_process(process) -> None:
diff --git a/src/peach/streaming.py b/src/peach/streaming.py
index 7da5acdbc..f69f8db01 100644
--- a/src/peach/streaming.py
+++ b/src/peach/streaming.py
@@ -91,8 +91,18 @@ class StreamSessionRegistry:
return len(self._active.get(session, ()))
-class CancellableFileResponse(FileResponse):
- """FileResponse whose active ASGI task can be cancelled by a session id."""
+class BufferedFileResponse(FileResponse):
+ """按 1 MiB 读文件再发。
+
+ Starlette 默认每次读 64 KiB,浏览器缓冲一段 Range 要向 CloudDrive 发几十次小读;
+ 读大一点只是少跑几趟挂载层,Range 语义不变。
+ """
+
+ chunk_size = 1 << 20
+
+
+class CancellableFileResponse(BufferedFileResponse):
+ """能按会话取消正在发送任务的 FileResponse。"""
def __init__(
self,
diff --git a/tests/test_segments.py b/tests/test_segments.py
index d37d9a225..2cf41bb60 100644
--- a/tests/test_segments.py
+++ b/tests/test_segments.py
@@ -206,6 +206,93 @@ class SegmentCommandTests(unittest.TestCase):
self.assertGreater(end, start)
self.assertAlmostEqual(end, round(index * 9.993, 3) + 9.993, places=2)
+ def test_concurrent_requests_generate_one_copy_of_the_same_segment(self):
+ """播放器预取与重连会同时要同一段:同目标只许一个 FFmpeg,其余等它写完直接用缓存。"""
+ calls = 0
+ release = None
+
+ class _Process:
+ returncode = 0
+
+ async def communicate(self):
+ await release.wait()
+ return b"", b""
+
+ async def fake_exec(*command, **_kwargs):
+ nonlocal calls
+ calls += 1
+ Path(command[-1]).write_bytes(b"segment")
+ return _Process()
+
+ async def drive():
+ nonlocal release
+ release = asyncio.Event()
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ source = root / "clip.mp4"
+ source.write_bytes(bytes(1024))
+ service = HlsSegmentService(
+ resolver=mock.Mock(ffmpeg=lambda: type("C", (), {"path": "ffmpeg"})),
+ work_root=root / "cache",
+ )
+ registry = StreamSessionRegistry()
+ with mock.patch("asyncio.create_subprocess_exec", fake_exec):
+ tasks = [asyncio.create_task(service.generate(
+ source, 0, 6, asset_id=6562, index=0, session=f"s{n}", registry=registry,
+ )) for n in range(3)]
+ await asyncio.sleep(0)
+ release.set()
+ results = await asyncio.gather(*tasks)
+ self.assertEqual(len({str(item) for item in results}), 1)
+ self.assertEqual(results[0].read_bytes(), b"segment")
+ self.assertEqual(service._generation_locks, {}, "锁在没人用时要从字典里消失")
+
+ asyncio.run(drive())
+ self.assertEqual(calls, 1)
+
+ def test_hardware_encode_failure_falls_back_to_libx264_for_the_slice(self):
+ """没有 NVENC 的机器分片不能缺席:CUDA 解码、软件解码两条 NVENC 路都失败后走 libx264。"""
+ captured: list[list[str]] = []
+
+ class _Process:
+ def __init__(self, returncode):
+ self.returncode = returncode
+
+ async def communicate(self):
+ return b"", (b"nvenc unavailable" if self.returncode else b"")
+
+ async def fake_exec(*command, **_kwargs):
+ captured.append(list(command))
+ if "h264_nvenc" in command:
+ return _Process(1)
+ Path(command[-1]).write_bytes(b"segment")
+ return _Process(0)
+
+ async def drive():
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ source = root / "clip.mp4"
+ source.write_bytes(bytes(1024))
+ service = HlsSegmentService(
+ resolver=mock.Mock(ffmpeg=lambda: type("C", (), {"path": "ffmpeg"})),
+ work_root=root / "cache", prefer_hardware=True,
+ )
+ with mock.patch("asyncio.create_subprocess_exec", fake_exec):
+ target = await service.generate(
+ source, 12.0, 6.0, asset_id=6562, index=2, session="s",
+ registry=StreamSessionRegistry(), transcode=True,
+ )
+ self.assertEqual(target.read_bytes(), b"segment")
+
+ asyncio.run(drive())
+ self.assertEqual([c[c.index("-c:v") + 1] for c in captured], ["h264_nvenc", "h264_nvenc", "libx264"])
+ self.assertIn("-hwaccel", captured[0])
+ self.assertNotIn("-hwaccel", captured[1])
+ for command in captured:
+ self.assertEqual(command[command.index("-output_ts_offset") + 1], "12.000")
+ self.assertEqual(command[command.index("-t") + 1], "6.000")
+ self.assertEqual(command[command.index("-f") + 1], "mpegts")
+
class PlanCacheTests(unittest.TestCase):
"""计划缓存一满就 clear() 等于没有缓存;改成 LRU 后热条目要能活下来。"""
diff --git a/tests/test_streaming.py b/tests/test_streaming.py
index 83dd9b7d9..854f0a844 100644
--- a/tests/test_streaming.py
+++ b/tests/test_streaming.py
@@ -71,6 +71,13 @@ class StreamSessionRegistryTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(headers["content-length"], "64")
self.assertEqual(body, bytes(range(64)))
+ def test_range_bodies_are_read_one_mebibyte_at_a_time(self):
+ """Starlette 默认 64 KiB 一读,浏览器缓冲一段 Range 要跑几十趟 CloudDrive 挂载层。"""
+ from peach.streaming import BufferedFileResponse
+
+ self.assertEqual(BufferedFileResponse.chunk_size, 1 << 20)
+ self.assertEqual(CancellableFileResponse.chunk_size, 1 << 20)
+
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)