Peach: Local-first video metadata scraper and media manager.
feat(media): 优先零编码封装与 NVIDIA 硬件转码
longmeidao92e24e79a3a5
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex a14efd71d..5c5239063 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -149,7 +149,7 @@ Gofile token 是另一份本机可选凭据,只进 Gofile 请求头,不进 U- 导入运维脚本不得触发文件、网络或数据库副作用。`scrape_codes.py` 默认写可续跑复核 CSV;`clean_names.py` 先预览,`--apply` 前把 SQLite 备份到真实库同目录并校验完整性。文件名只按 ledger 已确认的番号规范化,不从名称重新猜番号;大小写单改走同目录临时名,去广告后撞名使用 `(2)` 起的后缀保留两份媒体。复核候选文件可带主机/用途后缀,`web_review.latest_candidate_file` 必须按实际修改时间取最新批次,不能按文件名字典序。FC2CMADB 的 Inertia 文章存档只作为官方商品页镜像证据:标题与保守翻译后的标签写 `fc2-metadata-field-candidates.csv` 并与最新 JAV 元数据批次一起进入 `/review`,不自动写 ledger;封面把列表 `w276` 换成实测存在的 `w1200`,再走 `fetch_jav_covers.py --fc2-only` 的解码、宽度、磁盘和原子落盘门槛,合集不下发共用封面,失败留逐条日志,不回退视频缩略图。批准官方标签时必须用 `(asset_id, tag)` 冲突更新来源与置信度;`asset_tag` 的唯一约束会让 `INSERT OR IGNORE` 保留旧来源,导致值已存在却不显示“官方”。- 切换服务前检查 80、443、8900、9999 端口和实际进程归属。- 115/PikPak 播放依赖 CloudDrive 的 `B:`/`A:`;盘符对 Windows token 可见性不同,最终以 Peach 对已知作品的 `/stream` 实测为准。-- 浏览器不支持的 AVI 等容器由 `TranscodeService` 缓存为 H.264/AAC MP4,再通过同一 Range 端点提供;永不改写原媒体。+- 浏览器不支持的 AVI、MKV 等容器由 `TranscodeService` 缓存为浏览器兼容 MP4,再通过同一 Range 端点提供,永不改写原媒体。缓存未命中时先用同一会话内可取消、最长 20 秒的 ffprobe 探测:H.264 `yuv420p`/`yuvj420p` 保留视频码流,AAC 同时直接复制,其他音频只转 AAC;需要视频转码的 Windows 输入优先保持 CUDA surfaces 走 `scale_cuda` + H.264 NVENC `p1`,NVDEC 不支持时只把编码留给 NVENC,两条都失败才回退原 `libx264 veryfast`。macOS 不试 CUDA,仍先封装复制再走软件转码。探测和每次尝试都受原 2 槽并发闸门、1 小时总时限和 stream session 取消保护;旧缓存继续有效,原媒体、ledger 和 API 契约不变。- 数据库元数据不得插值到 inline JavaScript 事件属性。真实厂牌名中的撇号曾直接造成 Firefox 语法错误。前端 API 包装必须先检查 HTTP 状态再返回 JSON;冲突只读时写端点会返回 `409` 和错误 JSON,把它当普通成功对象会清空选择并重载,用户只会看到条目原样回来。批量处置和详情反馈必须保留当前选择并明确显示失败原因。- 验证分开报告:静态/单元/API、桌面浏览器、390×844 手机、生产服务是否已重启。diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 3b4a9661c..359815d9f 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -42,7 +42,7 @@| JAV 元数据查询 | Javinizer-Go v1.5.1 单来源 JSON CLI(MIT);MetaTube SDK `6a5e6128c725187aeaf921d48ed7d9cd9f30671b`(Apache-2.0)只作来源身份与丰富字段模型参考 | 只发送规范番号;Peach 管 source profile、`provider_id`/`content_id`、逐字段优先级、原始证据、丰富目录证据、健康统计、候选复核与批准后的 ledger 投影 || 已确认厂牌的目录归位 | Javinizer-Go v1.5.1 organizer 只作冲突预检、模板化目录和回滚边界参考,不让它持有 Peach ledger | `rehome_unknown_jav.py` 只消费人工确认映射;先出逐文件 CSV,拒绝扁平化重名与厂牌冲突,SQLite 备份后移动文件并同步 Peach 路径/实体 provenance || FC2 目录元数据与跨号证据 | 已缓存的 fc2cmadb Inertia `article`/评论收获;Javinizer-Go v1.5.1 的 FC2 解析器只作官方商品页字段边界参考 | 2026-08-31 登录态实测旧文章仍提供标题、原始标签、日期、时长、卖家、FC2 CDN 封面与 `comments`;Peach 只把无歧义标签翻译成现有词表,标题/标签进入 `/review`,实测 `w1200` 封面经尺寸与解码门槛落生成产物;稳定 pair、合集/分片保护、hash/时长/尺寸佐证、库外 evidence、健康统计和人工复核仍由 Peach 管,不依赖 FC2-Leak-Detector/JavSP,也不把镜像候选直写 ledger |-| 媒体探测/转码 | Peach 管理的 FFmpeg/ffprobe | 任务策略和 Media Engine 编排 |+| 媒体探测/转码 | Peach 管理的 FFmpeg/ffprobe;Windows 已实测 FFmpeg 9.0.1 full build 的 CUDA/NVDEC、`scale_cuda` 与 NVENC,现有二进制启用 GPL/version3 | 任务策略和 Media Engine 编排:非原生容器先探测,H.264 8-bit 优先只换 MP4 封装;其余 Windows 输入依次尝试 CUDA→H.264 NVENC、软件解码→NVENC、原 `libx264` 回退,macOS 保持封装复制或软件转码。真实 CloudDrive POC 中,H.264/AAC 的 30 秒片段封装耗时 0.64 秒,1080p HEVC 的 30 秒 CUDA/NVENC 转码耗时 1.60 秒;不新增依赖,不改原媒体或 ledger。 || HTML5/HLS/DASH 播放 | Video.js 8.24.0 + 内置 VHS(Apache-2.0,本地固定版本) | 流方案、授权、稳定时长、回退顺序和统计面板 || 播放器设置与影院布局 | Video.js 8.24.0 的 `playbackRate`、既有 QualityLevel、原生 tooltip 与控制栏插槽;YouTube `e937390a` 实际 DOM/CSS/JS 提供可复现的几何、状态、动画和图形证据 | Peach 在现有 DOM 上组合氛围模式、播放速度、真实清晰度和影院模式,并复用 59 px 两排控制栏、40→111 px 横向音量、4→6 px 进度动画、右侧共享胶囊、整行悬停的 274 px 设置菜单和视口级全屏;普通视图 `contain` 保全片源,全屏按用户明确要求改用 `cover` 铺满视口,接受非等比例片源的边缘裁切。全屏命中同时使用 Video.js/原生类和 `isFullscreen()` 同步的 `data-peach-fullscreen`,并覆盖 `body.vjs-full-window` 回退,不能再靠单个 CSS 类推断运行态;标准、WebKit、Gecko 等浏览器专用伪类必须放进 forgiving `:is(...)` 或拆成独立规则,不能在普通 selector list 混写后让某浏览器因未知伪类废掉整组声明。用户要求精准图形的设置项、radio 选中勾、菜单箭头、中央 bezel 与 loading 只 vendoring 当前锁定版本的 SVG path/spinner 结构,音量 hover 与滑轨中心沿用上游外层伪元素和 50% 几何,tooltip 仅补 Peach 两排控制栏需要的显式层级与越界可见;不复制播放器控制逻辑、不迁移到 Video.js 10 Menu,也不引入重复现有质量选择的插件 || 播放器时刻预览 | Video.js 原生进度控件 + Peach 既有 `/poster?id=&c=0…8` 九宫格切片 | 本地媒体用已有接触表提供近似时刻缩略图;在线视频只显示时刻。`videojs-vtt-thumbnails` 与 `videojs-sprite-thumbnails` 都要求另建 sprite/VTT 契约,本项目不为已有能力新增依赖或重复抽帧 |diff --git a/src/peach/transcodes.py b/src/peach/transcodes.pyindex da6d817df..598def139 100644--- a/src/peach/transcodes.py+++ b/src/peach/transcodes.py@@ -1,17 +1,35 @@from __future__ import annotations+import jsonimport osimport subprocessimport threadingimport timeimport uuidfrom contextlib import contextmanager+from dataclasses import dataclassfrom pathlib import Pathfrom .ffmpeg import FFmpegResolverBROWSER_NATIVE_SUFFIXES = frozenset({".mp4", ".m4v", ".webm", ".ogv", ".ogg"})+DIRECT_MP4_PIXEL_FORMATS = frozenset({"yuv420p", "yuvj420p"})+TRANSCODE_TIMEOUT_SECONDS = 3600+PROBE_TIMEOUT_SECONDS = 20+++@dataclass(frozen=True)+class _MediaProfile:+ video_codec: str+ pixel_format: str+ audio_codec: str+++@dataclass(frozen=True)+class _TranscodeAttempt:+ name: str+ command: tuple[str, ...]class TranscodeUnavailable(RuntimeError):@@ -26,10 +44,18 @@ class TranscodeService:"""Create immutable browser-playable MP4 cache entries without touching sources."""def __init__(- self, resolver: FFmpegResolver, cache_root: Path, *, max_concurrent: int = 2,+ self,+ resolver: FFmpegResolver,+ cache_root: Path,+ *,+ max_concurrent: int = 2,+ prefer_hardware: bool | None = None,):self.resolver = resolverself.cache_root = cache_root+ # 当前生产机是 NVIDIA Windows。macOS 保持原来的软件路径,避免每次先跑两次+ # 必然失败的 CUDA/NVENC 命令;测试和后续平台适配可显式覆盖。+ self.prefer_hardware = os.name == "nt" if prefer_hardware is None else prefer_hardwareself._locks: dict[int, list] = {}self._locks_guard = threading.Lock()self._slots = threading.Semaphore(max(1, max_concurrent))@@ -62,52 +88,42 @@ class TranscodeService:return target, Trueself.cache_root.mkdir(parents=True, exist_ok=True)temporary = target.with_name(f"{target.stem}.{uuid.uuid4().hex}.tmp.mp4")- command = [- str(choice.path), "-hide_banner", "-loglevel", "error", "-nostdin",- "-y", "-i", str(source),- "-map", "0:v:0", "-map", "0:a:0?",- "-c:v", "libx264", "-preset", "veryfast", "-crf", "21",- "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "160k",- "-movflags", "+faststart", str(temporary),- ]- creationflags = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0- process = None- registered = False+ deadline = time.monotonic() + TRANSCODE_TIMEOUT_SECONDS+ last_detail = ""+ completed = Falsetry: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:+ self._raise_if_cancelled(session, registry)+ profile = self._probe(source, session, registry, deadline)+ for attempt in self._attempts(+ choice.path, source, temporary, profile,+ ):+ temporary.unlink(missing_ok=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)+ returncode, _stdout, stderr = self._execute(+ attempt.command,+ session=session,+ registry=registry,+ deadline=deadline,+ label=attempt.name,+ )+ except TranscodeCancelled:+ raise+ except (OSError, TranscodeUnavailable) as exc:+ last_detail = f"{attempt.name}: {exc}"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 as exc:- raise TranscodeUnavailable("ffmpeg failed") from exc+ break+ continue+ if (returncode == 0 and temporary.is_file()+ and temporary.stat().st_size):+ temporary.replace(target)+ completed = True+ break+ detail = (stderr or b"").decode("utf-8", "replace")[-1000:]+ last_detail = f"{attempt.name}: {detail or 'ffmpeg failed'}"+ if not completed:+ raise TranscodeUnavailable(last_detail or "ffmpeg failed")finally:- if registered:- registry.unregister_process(session, process)temporary.unlink(missing_ok=True)for stale in self.cache_root.glob(f"{asset_id}-*.mp4"):@@ -115,6 +131,163 @@ class TranscodeService:stale.unlink(missing_ok=True)return target, True+ def _probe(+ self, source: Path, session: str, registry, deadline: float,+ ) -> _MediaProfile | None:+ choice = self.resolver.ffprobe()+ if choice is None:+ return None+ command = (+ str(choice.path), "-v", "error", "-show_entries",+ "stream=codec_type,codec_name,pix_fmt", "-of", "json", str(source),+ )+ try:+ returncode, stdout, _stderr = self._execute(+ command,+ session=session,+ registry=registry,+ deadline=min(deadline, time.monotonic() + PROBE_TIMEOUT_SECONDS),+ label="ffprobe",+ capture_stdout=True,+ )+ except TranscodeCancelled:+ raise+ except (OSError, TranscodeUnavailable):+ return None+ if returncode:+ return None+ try:+ streams = json.loads(stdout.decode("utf-8", "replace")).get("streams", ())+ except (AttributeError, json.JSONDecodeError):+ return None+ video = next((item for item in streams if item.get("codec_type") == "video"), {})+ audio = next((item for item in streams if item.get("codec_type") == "audio"), {})+ codec = str(video.get("codec_name") or "").lower()+ if not codec:+ return None+ return _MediaProfile(+ video_codec=codec,+ pixel_format=str(video.get("pix_fmt") or "").lower(),+ audio_codec=str(audio.get("codec_name") or "").lower(),+ )++ def _attempts(+ self,+ ffmpeg: Path,+ source: Path,+ temporary: Path,+ profile: _MediaProfile | None,+ ) -> tuple[_TranscodeAttempt, ...]:+ prefix = (+ str(ffmpeg), "-hide_banner", "-loglevel", "error", "-nostdin", "-y",+ )+ mapping = ("-map", "0:v:0", "-map", "0:a:0?", "-sn", "-dn")+ finish = ("-movflags", "+faststart", str(temporary))+ attempts: list[_TranscodeAttempt] = []++ if (profile is not None and profile.video_codec == "h264"+ and profile.pixel_format in DIRECT_MP4_PIXEL_FORMATS):+ audio = (+ ("-c:a", "copy")+ if profile.audio_codec in {"", "aac"}+ else ("-c:a", "aac", "-b:a", "160k")+ )+ attempts.append(_TranscodeAttempt(+ "video-copy",+ prefix + ("-i", str(source)) + mapping + ("-c:v", "copy") + audio + finish,+ ))++ fast_audio = (+ ("-c:a", "copy")+ if profile is not None and profile.audio_codec in {"", "aac"}+ else ("-c:a", "aac", "-b:a", "160k")+ )+ nvenc = (+ "-c:v", "h264_nvenc", "-preset", "p1", "-tune", "hq",+ "-rc", "vbr", "-cq", "21", "-b:v", "0",+ )+ if self.prefer_hardware:+ # CUDA surfaces stay on the GPU; scale_cuda also converts common 10-bit HEVC+ # inputs to NV12 so H.264 NVENC does not have to fall back to a CPU transfer.+ attempts.append(_TranscodeAttempt(+ "cuda-nvenc",+ prefix + (+ "-hwaccel", "cuda", "-hwaccel_output_format", "cuda",+ "-i", str(source),+ ) + mapping + ("-vf", "scale_cuda=format=nv12") + nvenc + fast_audio + finish,+ ))+ # Some codecs have no NVDEC path but can still keep the expensive encode on NVENC.+ attempts.append(_TranscodeAttempt(+ "nvenc",+ prefix + ("-i", str(source)) + mapping + nvenc + (+ "-pix_fmt", "yuv420p",+ ) + fast_audio + finish,+ ))++ # Final compatibility path: preserve the previous encoder and always normalize audio.+ attempts.append(_TranscodeAttempt(+ "libx264",+ prefix + ("-i", str(source)) + mapping + (+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "21",+ "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "160k",+ ) + finish,+ ))+ return tuple(attempts)++ def _execute(+ self,+ command: tuple[str, ...],+ *,+ session: str,+ registry,+ deadline: float,+ label: str,+ capture_stdout: bool = False,+ ) -> tuple[int, bytes, bytes]:+ creationflags = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0+ process = subprocess.Popen(+ command,+ stdin=subprocess.DEVNULL,+ stdout=subprocess.PIPE if capture_stdout else subprocess.DEVNULL,+ stderr=subprocess.PIPE,+ creationflags=creationflags,+ )+ registered = False+ try:+ if registry is not None and session:+ registered = registry.register_process(session, process)+ if not registered:+ process.kill()+ process.communicate()+ raise TranscodeCancelled(session)+ 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(f"{label} timed out")+ self._raise_if_cancelled(session, registry)+ return (+ process.returncode if process.returncode is not None else -1,+ stdout or b"",+ stderr or b"",+ )+ finally:+ if registered:+ registry.unregister_process(session, process)++ @staticmethod+ def _raise_if_cancelled(session: str, registry) -> None:+ if registry is not None and session and registry.is_cancelled(session):+ raise TranscodeCancelled(session)+@contextmanagerdef _lock_for(self, asset_id: int):"""同一 asset 的转码互斥;引用归零的条目随手清掉,长跑不再只增不减。diff --git a/tests/test_transcodes.py b/tests/test_transcodes.pyindex 1549418d9..5642bbc90 100644--- a/tests/test_transcodes.py+++ b/tests/test_transcodes.py@@ -1,3 +1,4 @@+import jsonimport subprocessimport tempfileimport threading@@ -10,12 +11,16 @@ from peach.transcodes import TranscodeCancelled, TranscodeService, TranscodeUnavclass _Resolver:- def __init__(self, binary: Path | None):+ def __init__(self, binary: Path | None, probe: Path | None = None):self.binary = binary+ self.probe = probedef ffmpeg(self):return BinaryChoice(self.binary, "test") if self.binary else None+ def ffprobe(self):+ return BinaryChoice(self.probe, "test") if self.probe else None+class _FakeTranscode:"""让 Popen 立即产出缓存文件的最小替身。"""@@ -30,6 +35,25 @@ class _FakeTranscode:return b"", b""+def _media_process(commands, profile, fail=None):+ class Process:+ def __init__(self, command, **_kwargs):+ self.command = list(command)+ self.returncode = 0+ commands.append(self.command)++ def communicate(self, timeout=None):+ if Path(self.command[0]).stem.lower() == "ffprobe":+ return json.dumps({"streams": profile}).encode(), b""+ if fail is not None and fail(self.command):+ self.returncode = 1+ return b"", b"hardware unavailable"+ Path(self.command[-1]).write_bytes(b"mp4")+ return b"", b""++ return Process++class TranscodeServiceTests(unittest.TestCase):def test_native_mp4_is_returned_without_ffmpeg(self):source = Path("movie.mp4")@@ -46,7 +70,9 @@ class TranscodeServiceTests(unittest.TestCase):root = Path(tmp)source = root / "movie.avi"source.write_bytes(b"avi")- service = TranscodeService(_Resolver(root / "ffmpeg.exe"), root / "cache")+ service = TranscodeService(+ _Resolver(root / "ffmpeg.exe"), root / "cache", prefer_hardware=False,+ )class Process:returncode = 0@@ -68,13 +94,131 @@ class TranscodeServiceTests(unittest.TestCase):self.assertEqual(execute.call_count, 1)self.assertIn("libx264", execute.call_args.args[0])+ def test_h264_aac_mkv_is_remuxed_without_video_or_audio_encoding(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ source = root / "movie.mkv"+ source.write_bytes(b"mkv")+ service = TranscodeService(+ _Resolver(root / "ffmpeg.exe", root / "ffprobe.exe"),+ root / "cache",+ prefer_hardware=True,+ )+ commands = []+ profile = [+ {"codec_type": "video", "codec_name": "h264", "pix_fmt": "yuv420p"},+ {"codec_type": "audio", "codec_name": "aac"},+ ]++ with patch(+ "peach.transcodes.subprocess.Popen",+ side_effect=_media_process(commands, profile),+ ):+ path, transcoded = service.browser_path(9, source)++ self.assertTrue(transcoded and path.is_file())+ transcodes = [command for command in commands if "ffprobe" not in command[0]]+ self.assertEqual(len(transcodes), 1)+ self.assertEqual(transcodes[0][transcodes[0].index("-c:v") + 1], "copy")+ self.assertEqual(transcodes[0][transcodes[0].index("-c:a") + 1], "copy")+ self.assertNotIn("h264_nvenc", transcodes[0])+ self.assertNotIn("libx264", transcodes[0])++ def test_h264_with_incompatible_audio_copies_video_and_encodes_aac(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ source = root / "movie.mkv"+ source.write_bytes(b"mkv")+ service = TranscodeService(+ _Resolver(root / "ffmpeg.exe", root / "ffprobe.exe"),+ root / "cache",+ prefer_hardware=True,+ )+ commands = []+ profile = [+ {"codec_type": "video", "codec_name": "h264", "pix_fmt": "yuv420p"},+ {"codec_type": "audio", "codec_name": "ac3"},+ ]++ with patch(+ "peach.transcodes.subprocess.Popen",+ side_effect=_media_process(commands, profile),+ ):+ service.browser_path(9, source)++ command = [item for item in commands if "ffprobe" not in item[0]][0]+ self.assertEqual(command[command.index("-c:v") + 1], "copy")+ self.assertEqual(command[command.index("-c:a") + 1], "aac")++ def test_hevc_prefers_cuda_decode_and_nvenc_encode(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ source = root / "movie.mkv"+ source.write_bytes(b"mkv")+ service = TranscodeService(+ _Resolver(root / "ffmpeg.exe", root / "ffprobe.exe"),+ root / "cache",+ prefer_hardware=True,+ )+ commands = []+ profile = [+ {"codec_type": "video", "codec_name": "hevc", "pix_fmt": "yuv420p10le"},+ {"codec_type": "audio", "codec_name": "aac"},+ ]++ with patch(+ "peach.transcodes.subprocess.Popen",+ side_effect=_media_process(commands, profile),+ ):+ service.browser_path(9, source)++ command = [item for item in commands if "ffprobe" not in item[0]][0]+ self.assertEqual(command[command.index("-hwaccel") + 1], "cuda")+ self.assertIn("scale_cuda=format=nv12", command)+ self.assertIn("h264_nvenc", command)+ self.assertIn("p1", command)+ self.assertNotIn("libx264", command)++ def test_nvenc_failure_falls_back_to_previous_libx264_path(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ source = root / "movie.mkv"+ source.write_bytes(b"mkv")+ service = TranscodeService(+ _Resolver(root / "ffmpeg.exe", root / "ffprobe.exe"),+ root / "cache",+ prefer_hardware=True,+ )+ commands = []+ profile = [+ {"codec_type": "video", "codec_name": "hevc", "pix_fmt": "yuv420p"},+ {"codec_type": "audio", "codec_name": "aac"},+ ]++ with patch(+ "peach.transcodes.subprocess.Popen",+ side_effect=_media_process(+ commands, profile, fail=lambda command: "h264_nvenc" in command,+ ),+ ):+ path, transcoded = service.browser_path(9, source)++ self.assertTrue(transcoded and path.is_file())+ transcodes = [command for command in commands if "ffprobe" not in command[0]]+ self.assertEqual(len(transcodes), 3)+ self.assertIn("-hwaccel", transcodes[0])+ self.assertIn("h264_nvenc", transcodes[1])+ self.assertIn("libx264", transcodes[2])+def test_lock_entries_do_not_accumulate_after_transcodes(self):"""每把 per-asset 锁在没人持有、没人等待时必须从字典里消失。"""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")+ service = TranscodeService(+ _Resolver(root / "ffmpeg.exe"), root / "cache", prefer_hardware=False,+ )with patch("peach.transcodes.subprocess.Popen", side_effect=_FakeTranscode):service.browser_path(9, source)@@ -86,7 +230,9 @@ class TranscodeServiceTests(unittest.TestCase):root = Path(tmp)source = root / "movie.avi"source.write_bytes(b"avi")- service = TranscodeService(_Resolver(root / "ffmpeg.exe"), root / "cache")+ service = TranscodeService(+ _Resolver(root / "ffmpeg.exe"), root / "cache", prefer_hardware=False,+ )start = threading.Barrier(2)outcomes: list[bool] = []@@ -112,7 +258,9 @@ class TranscodeServiceTests(unittest.TestCase):root = Path(tmp)source = root / "movie.avi"source.write_bytes(b"avi")- service = TranscodeService(_Resolver(root / "ffmpeg.exe"), root / "cache")+ service = TranscodeService(+ _Resolver(root / "ffmpeg.exe"), root / "cache", prefer_hardware=False,+ )class Process:returncode = None@@ -140,7 +288,7 @@ class TranscodeServiceTests(unittest.TestCase):return Truedef is_cancelled(self, _session):- return True+ return process.calls > 0def unregister_process(self, session, registered):self.unregistered = (session, registered)