Peach: Local-first video metadata scraper and media manager.
fix: bound and cancel browser transcodes
longmeidao8902576b29c9
diff --git a/src/peach/api.py b/src/peach/api.pyindex 7df22f4fd..2f4c8f915 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -2,7 +2,9 @@ import hmacimport asyncioimport htmlimport logging+from concurrent.futures import ThreadPoolExecutorfrom contextlib import asynccontextmanager+from functools import partialfrom typing import Anyfrom urllib.parse import parse_qs, quote@@ -38,7 +40,7 @@ from .segments import (from .stash import StashClientfrom .streaming import CancellableFileResponse, StreamSessionRegistryfrom .sync import LedgerSync-from .transcodes import TranscodeService, TranscodeUnavailable+from .transcodes import TranscodeCancelled, TranscodeService, TranscodeUnavailableLOGGER = logging.getLogger(__name__)@@ -126,6 +128,9 @@ def create_app(settings.avatar_root, settings.logo_root, settings.legacy_snapshot_roots,)transcode_service = TranscodeService(resolver, settings.transcode_root)+ hls_plan_executor = ThreadPoolExecutor(+ max_workers=2, thread_name_prefix="PeachHlsPlan",+ )hls_service = HlsSegmentService(resolver, settings.stream_root)mdns = create_mdns_publisher(settings.mdns_name, settings.mdns_port, secure=settings.tls_enabled,@@ -152,6 +157,7 @@ def create_app(if sync is not None:await asyncio.to_thread(sync.stop)http_transport.close()+ hls_plan_executor.shutdown(wait=False, cancel_futures=True)app = FastAPI(title="Peach API",@@ -168,6 +174,7 @@ def create_app(app.state.media_engine = media_engineapp.state.preview_service = preview_serviceapp.state.transcode_service = transcode_service+ app.state.hls_plan_executor = hls_plan_executorapp.state.hls_service = hls_serviceapp.state.mdns = mdnsapp.state.providers = providers@@ -325,7 +332,11 @@ def create_app(except MediaUnavailable:return JSONResponse({"error": "unavailable"}, status_code=404)try:- path, transcoded = transcode_service.browser_path(id, path)+ path, transcoded = transcode_service.browser_path(+ id, path, session=session, registry=stream_sessions,+ )+ except TranscodeCancelled:+ return Response(status_code=410, headers={"Cache-Control": "no-store"})except TranscodeUnavailable:logging.getLogger(__name__).exception("browser transcode failed for asset %s", id)return JSONResponse({"error": "transcode unavailable"}, status_code=503)@@ -341,7 +352,7 @@ def create_app(response.headers["Cache-Control"] = "no-store"return response- def _hls_plan(asset_id: int):+ def _hls_plan(asset_id: int, session: str = ""):"""解析 HLS 的片源路径与关键帧分片计划;任何一步不成立就返回 None 走 Range。"""asset = media_engine.asset(asset_id)# 播放列表和分片端点本身就是 HLS 路径,按 ADR-0016 显式要计划,不受默认值影响。@@ -349,7 +360,9 @@ def create_app(if choice.protocol != "hls" or not asset.duration:return Nonesource = media_engine.filesystem.file_for(asset, thumbnail=False)- source, _ = transcode_service.browser_path(asset_id, source)+ source, _ = transcode_service.browser_path(+ asset_id, source, session=session, registry=stream_sessions,+ )plan = hls_service.plan(source, asset.duration)return None if not plan else (asset, source, plan)@@ -408,7 +421,7 @@ def create_app(if stream_sessions.is_cancelled(session):return PlainTextResponse("stream cancelled", status_code=410)try:- resolved = _hls_plan(id)+ resolved = _hls_plan(id, session)except MediaNotFound:return JSONResponse({"error": "no such id"}, status_code=404)except MediaOffline as exc:@@ -435,7 +448,10 @@ def create_app(if stream_sessions.is_cancelled(session):return Response(status_code=410, headers={"Cache-Control": "no-store"})try:- resolved = await asyncio.to_thread(_hls_plan, id)+ loop = asyncio.get_running_loop()+ resolved = await loop.run_in_executor(+ hls_plan_executor, partial(_hls_plan, id, session),+ )if resolved is None:return JSONResponse({"error": "hls unavailable"}, status_code=404)_, source, plan = resolved@@ -454,6 +470,8 @@ def create_app(return JSONResponse({"error": "unavailable"}, status_code=404)except SegmentCancelled:return Response(status_code=410, headers={"Cache-Control": "no-store"})+ except TranscodeCancelled:+ return Response(status_code=410, headers={"Cache-Control": "no-store"})except TranscodeUnavailable:logging.getLogger(__name__).exception("browser transcode failed for asset %s", id)return JSONResponse({"error": "transcode unavailable"}, status_code=503)diff --git a/src/peach/transcodes.py b/src/peach/transcodes.pyindex b7849d5cb..3e2d36885 100644--- a/src/peach/transcodes.py+++ b/src/peach/transcodes.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport osimport subprocessimport threading+import timeimport uuidfrom pathlib import Path@@ -16,20 +17,29 @@ class TranscodeUnavailable(RuntimeError):pass+class TranscodeCancelled(TranscodeUnavailable):+ pass++class TranscodeService:"""Create immutable browser-playable MP4 cache entries without touching sources."""- def __init__(self, resolver: FFmpegResolver, cache_root: Path):+ def __init__(+ self, resolver: FFmpegResolver, cache_root: Path, *, max_concurrent: int = 2,+ ):self.resolver = resolverself.cache_root = cache_rootself._locks: dict[int, threading.Lock] = {}self._locks_guard = threading.Lock()+ self._slots = threading.Semaphore(max(1, max_concurrent))@staticmethoddef needs_transcode(source: Path) -> bool:return source.suffix.lower() not in BROWSER_NATIVE_SUFFIXES- def browser_path(self, asset_id: int, source: Path) -> tuple[Path, bool]:+ def browser_path(+ self, asset_id: int, source: Path, *, session: str = "", registry=None,+ ) -> tuple[Path, bool]:if not self.needs_transcode(source):return source, False@@ -60,19 +70,43 @@ class TranscodeService:"-movflags", "+faststart", str(temporary),]creationflags = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0+ process = None+ registered = Falsetry:- result = subprocess.run(- command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,- stderr=subprocess.PIPE, timeout=3600, check=False,- creationflags=creationflags,- )- if result.returncode or not temporary.is_file() or not temporary.stat().st_size:- detail = result.stderr.decode("utf-8", "replace")[-1000:]+ with self._slots:+ process = subprocess.Popen(+ command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,+ stderr=subprocess.PIPE, creationflags=creationflags,+ )+ if registry is not None and session:+ registered = registry.register_process(session, process)+ if not registered:+ process.kill()+ process.communicate()+ raise TranscodeCancelled(session)+ deadline = time.monotonic() + 3600+ while True:+ try:+ _stdout, stderr = process.communicate(timeout=0.5)+ break+ except subprocess.TimeoutExpired:+ if registry is not None and session and registry.is_cancelled(session):+ process.kill()+ process.communicate()+ raise TranscodeCancelled(session)+ if time.monotonic() >= deadline:+ process.kill()+ process.communicate()+ raise TranscodeUnavailable("ffmpeg timed out")+ if process.returncode or not temporary.is_file() or not temporary.stat().st_size:+ detail = (stderr or b"").decode("utf-8", "replace")[-1000:]raise TranscodeUnavailable(detail or "ffmpeg failed")temporary.replace(target)- except (OSError, subprocess.TimeoutExpired) as exc:+ except OSError as exc:raise TranscodeUnavailable("ffmpeg failed") from excfinally:+ if registered:+ registry.unregister_process(session, process)temporary.unlink(missing_ok=True)for stale in self.cache_root.glob(f"{asset_id}-*.mp4"):diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex ae6246cf3..6241c5059 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -1,4 +1,3 @@-import asyncioimport csvimport importlib.utilimport json@@ -614,13 +613,17 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):self.assertEqual((asset_id, index, session), (1, 1, "hls-test"))return segment- real_to_thread = asyncio.to_threadwith patch.object(self.app.state.hls_service, "generate", new=generate):- with patch("peach.api.asyncio.to_thread", wraps=real_to_thread) as offload:+ with patch.object(+ self.app.state.hls_plan_executor,+ "submit",+ wraps=self.app.state.hls_plan_executor.submit,+ ) as submit:response = await self.client.get("/stream/hls/1/1.ts?session=hls-test&t=secret",)- offload.assert_awaited_once()+ submit.assert_called_once()+ self.assertEqual(self.app.state.hls_plan_executor._max_workers, 2)self.assertEqual(response.status_code, 200)self.assertEqual(response.content, b"one segment")self.assertEqual(response.headers["content-type"], "video/mp2t")diff --git a/tests/test_transcodes.py b/tests/test_transcodes.pyindex 58590c191..d8efa0909 100644--- a/tests/test_transcodes.py+++ b/tests/test_transcodes.py@@ -5,7 +5,7 @@ from pathlib import Pathfrom unittest.mock import patchfrom peach.ffmpeg import BinaryChoice-from peach.transcodes import TranscodeService, TranscodeUnavailable+from peach.transcodes import TranscodeCancelled, TranscodeService, TranscodeUnavailableclass _Resolver:@@ -34,11 +34,17 @@ class TranscodeServiceTests(unittest.TestCase):source.write_bytes(b"avi")service = TranscodeService(_Resolver(root / "ffmpeg.exe"), root / "cache")- def run(command, **_kwargs):- Path(command[-1]).write_bytes(b"mp4")- return subprocess.CompletedProcess(command, 0, b"", b"")+ class Process:+ returncode = 0- with patch("peach.transcodes.subprocess.run", side_effect=run) as execute:+ def __init__(self, command, **_kwargs):+ self.command = command++ def communicate(self, timeout=None):+ Path(self.command[-1]).write_bytes(b"mp4")+ return b"", b""++ with patch("peach.transcodes.subprocess.Popen", side_effect=Process) as execute:first, transcoded = service.browser_path(9, source)second, cached = service.browser_path(9, source)@@ -47,3 +53,49 @@ class TranscodeServiceTests(unittest.TestCase):self.assertEqual(first.read_bytes(), b"mp4")self.assertEqual(execute.call_count, 1)self.assertIn("libx264", execute.call_args.args[0])++ def test_session_cancellation_kills_an_active_transcode(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ source = root / "movie.avi"+ source.write_bytes(b"avi")+ service = TranscodeService(_Resolver(root / "ffmpeg.exe"), root / "cache")++ class Process:+ returncode = None+ killed = False+ calls = 0++ def __init__(self, _command, **_kwargs):+ pass++ def communicate(self, timeout=None):+ self.calls += 1+ if self.calls == 1:+ raise subprocess.TimeoutExpired("ffmpeg", timeout)+ return b"", b""++ def kill(self):+ self.killed = True+ self.returncode = -9++ process = Process([])++ class Registry:+ def register_process(self, session, registered):+ self.registered = (session, registered)+ return True++ def is_cancelled(self, _session):+ return True++ def unregister_process(self, session, registered):+ self.unregistered = (session, registered)++ registry = Registry()+ with patch("peach.transcodes.subprocess.Popen", return_value=process):+ with self.assertRaises(TranscodeCancelled):+ service.browser_path(9, source, session="s1", registry=registry)+ self.assertTrue(process.killed)+ self.assertEqual(registry.registered, ("s1", process))+ self.assertEqual(registry.unregistered, ("s1", process))