Peach: Local-first video metadata scraper and media manager.
perf(stream): 不兼容片源没有账本时长也按片切,不整片转码
longmeidaofe9ce668c781
diff --git a/src/peach/routes_media.py b/src/peach/routes_media.pyindex a5d86a925..a0c3f5eba 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 CancellableFileResponse+from .streaming import BufferedFileResponse, CancellableFileResponsefrom .transcodes import TranscodeCancelled, TranscodeUnavailablerouter = APIRouter()@@ -128,18 +128,25 @@ def _attachment_disposition(title: str, url: str) -> str:def _hls_plan(state, asset_id: int, session: str = ""):- """解析 HLS 的片源路径与关键帧分片计划;任何一步不成立就返回 None 走 Range。"""+ """解析 HLS 的片源路径与分片计划;任何一步不成立就返回 None 走 Range。++ 要重编码的片源按固定 6 秒切,时长先看账本,账本没记或记成负数就用 ffprobe 报的;+ 探测也拿不到才放弃,否则浏览器只能退回 `/stream`,那条路要先把整部片转完才出第一个字节。+ 原样封装的 HLS 仍要账本时长与关键帧表。+ """asset = state.media_engine.asset(asset_id)# 播放列表和分片端点本身就是 HLS 路径,按 ADR-0016 显式要计划,不受默认值影响。choice = state.media_engine.stream_plan(asset_id, mode="hls")- if not asset.duration:- return Nonesource = state.media_engine.filesystem.file_for(asset, thumbnail=False)+ duration = asset.duration if asset.duration and asset.duration > 0 else 0.0if state.transcode_service.requires_conversion(source, session=session, registry=state.stream_sessions):- return asset, source, state.hls_service.conversion_plan(asset.duration), True- if choice.protocol != "hls":+ 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 []+ return (asset, source, plan, True) if plan else None+ if choice.protocol != "hls" or duration <= 0:return None- plan = state.hls_service.plan(source, asset.duration)+ plan = state.hls_service.plan(source, duration)return None if not plan else (asset, source, plan, False)@@ -162,7 +169,7 @@ def stream(request: Request, id: int, session: str = "", args: dict[str, str] =CancellableFileResponse(path, session=session, registry=state.stream_sessions, media_type=media_type,)- if session else FileResponse(path, media_type=media_type)+ if session else BufferedFileResponse(path, media_type=media_type))if transcoded:response.headers["X-Peach-Transcoded"] = "1"@@ -189,7 +196,7 @@ def stream_plan(request: Request, id: int, session: str = "", mode: str = "", ar"id": id,"protocol": "hls","mime_type": "application/vnd.apple.mpegurl",- "duration": asset.duration,+ "duration": round(sum(length for _, length in resolved[2]), 3),"segment_seconds": plan.segment_seconds,"segments": len(resolved[2]),"src": f"/stream/hls/{id}/index.m3u8?session={quote(session, safe='')}",diff --git a/src/peach/transcodes.py b/src/peach/transcodes.pyindex f2ab4d770..923d68433 100644--- a/src/peach/transcodes.py+++ b/src/peach/transcodes.py@@ -24,6 +24,8 @@ class _MediaProfile:video_codec: strpixel_format: straudio_codec: str+ #: 容器报的总时长(秒);探测不到时为 0,切片计划据此决定能不能按时间切。+ duration: float = 0.0@dataclass(frozen=True)@@ -71,6 +73,21 @@ class TranscodeService:return Trueif self.resolver.ffprobe() is None:return False+ profile = self._profile_for(source, session, registry)+ return profile is None or not self._browser_compatible(source, profile)++ def media_duration(self, source: Path, *, session: str = "", registry=None) -> float:+ """ffprobe 报的总时长(秒);账本没记时长的片源靠它切片。探测不到返回 0。"""+ if self.resolver.ffprobe() is None:+ return 0.0+ try:+ profile = self._profile_for(source, session, registry)+ except OSError:+ return 0.0+ return profile.duration if profile is not None else 0.0++ def _profile_for(self, source: Path, session: str, registry) -> _MediaProfile | None:+ """按 (路径, 大小, mtime) 缓存探测结果;同一个文件只问 ffprobe 一次。"""stat = source.stat()key = (str(source), stat.st_size, stat.st_mtime_ns)with self._locks_guard:@@ -83,7 +100,7 @@ class TranscodeService:if len(self._native_profiles) >= 512:self._native_profiles.pop(next(iter(self._native_profiles)))self._native_profiles[key] = profile- return profile is None or not self._browser_compatible(source, profile)+ return profiledef browser_path(self, asset_id: int, source: Path, *, session: str = "", registry=None,@@ -93,20 +110,9 @@ class TranscodeService:if self.resolver.ffprobe() is None:return source, Falsetry:- stat = source.stat()+ profile = self._profile_for(source, session, registry)except OSError as exc:raise TranscodeUnavailable("source unavailable") from exc- key = (str(source), stat.st_size, stat.st_mtime_ns)- with self._locks_guard:- profile = self._native_profiles.get(key)- if profile is None:- profile = self._probe(source, session, registry,- time.monotonic() + PROBE_TIMEOUT_SECONDS)- if profile is not None:- with self._locks_guard:- if len(self._native_profiles) >= 512:- self._native_profiles.pop(next(iter(self._native_profiles)))- self._native_profiles[key] = profileif profile is not None and self._browser_compatible(source, profile):return source, False@@ -192,7 +198,7 @@ class TranscodeService:return Nonecommand = (str(choice.path), "-v", "error", "-show_entries",- "stream=codec_type,codec_name,pix_fmt", "-of", "json", str(source),+ "stream=codec_type,codec_name,pix_fmt:format=duration", "-of", "json", str(source),)try:returncode, stdout, _stderr = self._execute(@@ -210,7 +216,8 @@ class TranscodeService:if returncode:return Nonetry:- streams = json.loads(stdout.decode("utf-8", "replace")).get("streams", ())+ report = json.loads(stdout.decode("utf-8", "replace"))+ streams = report.get("streams", ())except (AttributeError, json.JSONDecodeError):return Nonevideo = next((item for item in streams if item.get("codec_type") == "video"), {})@@ -218,10 +225,15 @@ class TranscodeService:codec = str(video.get("codec_name") or "").lower()if not codec:return None+ try:+ duration = float((report.get("format") or {}).get("duration") or 0.0)+ except (TypeError, ValueError):+ duration = 0.0return _MediaProfile(video_codec=codec,pixel_format=str(video.get("pix_fmt") or "").lower(),audio_codec=str(audio.get("codec_name") or "").lower(),+ duration=max(0.0, duration),)def _attempts(diff --git a/tests/test_complexity_ratchet.py b/tests/test_complexity_ratchet.pyindex c2ac3885c..b0f818749 100644--- a/tests/test_complexity_ratchet.py+++ b/tests/test_complexity_ratchet.py@@ -56,7 +56,6 @@ BASELINE: dict[str, int] = {"scripts/merge_duplicate_identities.py:collect_repeated_projections": 34,"src/peach/fc2_similarity.py:media_evidence": 34,"scripts/clean_names.py:run": 33,- "src/peach/transcodes.py:TranscodeService.browser_path": 33,"scripts/harvest_studio_icons.py:icon_row": 32,"scripts/smoke_desktop.py:main": 32,"src/peach/follow_check.py:run_check": 32,diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex 68f392d33..097d88819 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -1816,6 +1816,35 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(playlist.status_code, 200)self.assertIn('#EXTINF:0.280', playlist.text)+ async def test_unknown_ledger_duration_still_slices_by_the_probed_duration(self):+ """账本没记时长(或记成 -1)的 HEVC MP4 也按片切:时长取 ffprobe 报的,不走整片转码。"""+ from peach.transcodes import _MediaProfile+ con = sqlite3.connect(self.db)+ con.execute("UPDATE asset SET duration=-1 WHERE id=1")+ con.commit()+ con.close()+ with patch.object(self.app.state.transcode_service, "_probe",+ return_value=_MediaProfile("hevc", "yuv420p", "mp3", duration=13.5)), \+ patch.object(self.app.state.transcode_service, "browser_path",+ side_effect=AssertionError("whole movie conversion")):+ plan = (await self.client.get("/api/stream-plan?id=1&session=s&t=secret")).json()+ self.assertEqual((plan["protocol"], plan["segments"], plan["duration"]), ("hls", 3, 13.5))+ playlist = await self.client.get("/stream/hls/1/index.m3u8?session=s&t=secret")+ self.assertEqual(playlist.status_code, 200)+ self.assertEqual(playlist.text.count("#EXTINF:"), 3)++ async def test_unprobeable_file_without_duration_gets_range_and_a_404_playlist(self):+ """moov 缺失的文件 ffprobe 读不出、账本也没时长:计划回 Range,播放列表回 404,不是 500。"""+ con = sqlite3.connect(self.db)+ con.execute("UPDATE asset SET duration=-1 WHERE id=1")+ con.commit()+ con.close()+ with patch.object(self.app.state.transcode_service, "_probe", return_value=None):+ plan = (await self.client.get("/api/stream-plan?id=1&session=s&t=secret")).json()+ playlist = await self.client.get("/stream/hls/1/index.m3u8?session=s&t=secret")+ self.assertEqual(plan["protocol"], "range")+ self.assertEqual(playlist.status_code, 404)+async def test_hls_segment_is_generated_for_one_requested_time_slice(self):con = sqlite3.connect(self.db)con.execute("UPDATE asset SET location='115', duration=13.5, path=? WHERE id=1",diff --git a/tests/test_transcodes.py b/tests/test_transcodes.pyindex 65592714b..61100a7c1 100644--- a/tests/test_transcodes.py+++ b/tests/test_transcodes.py@@ -35,7 +35,7 @@ class _FakeTranscode:return b"", b""-def _media_process(commands, profile, fail=None):+def _media_process(commands, profile, fail=None, duration=None):class Process:def __init__(self, command, **_kwargs):self.command = list(command)@@ -44,7 +44,10 @@ def _media_process(commands, profile, fail=None):def communicate(self, timeout=None):if Path(self.command[0]).stem.lower() == "ffprobe":- return json.dumps({"streams": profile}).encode(), b""+ report = {"streams": profile}+ if duration is not None:+ report["format"] = {"duration": duration}+ return json.dumps(report).encode(), b""if fail is not None and fail(self.command):self.returncode = 1return b"", b"hardware unavailable"@@ -99,6 +102,30 @@ class TranscodeServiceTests(unittest.TestCase):with self.assertRaises(TranscodeUnavailable):service.browser_path(1, Path("movie.avi"))+ def test_probe_reports_the_container_duration_for_slicing(self):+ """账本没记时长的片源按 ffprobe 报的时长切片;同一个文件只探测一次,探测不到给 0。"""+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp).resolve()+ source = root / "movie.mp4"+ source.write_bytes(b"source")+ service = TranscodeService(+ _Resolver(root / "ffmpeg.exe", root / "ffprobe.exe"),+ root / "cache", prefer_hardware=False,+ )+ commands = []+ streams = [+ {"codec_type": "video", "codec_name": "hevc", "pix_fmt": "yuv420p"},+ {"codec_type": "audio", "codec_name": "mp3"},+ ]+ with patch("peach.transcodes.subprocess.Popen",+ side_effect=_media_process(commands, streams, duration="2543.416667")):+ self.assertTrue(service.requires_conversion(source))+ self.assertAlmostEqual(service.media_duration(source), 2543.417, places=3)+ self.assertEqual(sum("ffprobe" in c[0] for c in commands), 1)+ self.assertIn("format=duration", commands[0][commands[0].index("-show_entries") + 1])+ self.assertEqual(service.media_duration(root / "missing.mp4"), 0.0)+ self.assertEqual(TranscodeService(_Resolver(None), root / "cache").media_duration(source), 0.0)+def test_avi_is_transcoded_once_and_cached(self):with tempfile.TemporaryDirectory() as tmp:root = Path(tmp)