"""使用 scrcpy server 模式进行截图(高性能替代方案) scrcpy 通过 server 模式可以实现比 adb screencap 更快的截图速度。 """ from __future__ import annotations import os import subprocess import time import tempfile from typing import Optional from datetime import datetime from operations.screenshot_operations import ScreenshotOperations class ScrcpyScreenshot: """使用 scrcpy server 进行截图""" def __init__(self): self._scrcpy_path: Optional[str] = None self._server_path: Optional[str] = None self._find_scrcpy() def _find_scrcpy(self): """查找 scrcpy 可执行文件""" import shutil # 先检查 PATH which_path = shutil.which('scrcpy') if which_path: self._scrcpy_path = which_path return # 检查常见安装位置 candidates = [ os.path.join(os.getenv('LOCALAPPDATA', ''), 'Programs', 'scrcpy', 'scrcpy.exe'), os.path.join(os.getenv('USERPROFILE', ''), 'AppData', 'Local', 'Programs', 'scrcpy', 'scrcpy.exe'), r'C:\Program Files\scrcpy\scrcpy.exe', r'C:\Program Files (x86)\scrcpy\scrcpy.exe', ] for path in candidates: if path and os.path.exists(path): self._scrcpy_path = path # server 文件通常在同一目录 server_path = os.path.join(os.path.dirname(path), 'scrcpy-server') if os.path.exists(server_path): self._server_path = server_path break def is_available(self) -> bool: """检查 scrcpy 是否可用""" return self._scrcpy_path is not None and os.path.exists(self._scrcpy_path) def get_screenshot(self, device_id: str, output_path: str) -> bool: """使用 scrcpy 进行截图 注意:scrcpy 本身不直接支持单次截图,这里使用变通方法: 1. 启动 scrcpy server(如果支持) 2. 或使用 scrcpy 的录制功能提取帧 参数: device_id: 设备ID output_path: 输出文件路径 返回: 是否成功 """ if not self.is_available(): return False timetag = datetime.now().strftime("%H:%M:%S") start_time = time.time() try: # 方法1: 使用 scrcpy 的 --record 功能(需要停止机制,较复杂) # 方法2: 使用 scrcpy server 模式(推荐,但需要额外配置) # 方法3: 回退到 adb screencap(当前实现) # 由于 scrcpy 不直接支持单次截图,这里先记录日志 # 实际实现需要集成 scrcpy server 或使用第三方库 print(f"[{timetag}] [scrcpy] 注意: scrcpy 不直接支持单次截图") print(f"[{timetag}] [scrcpy] 需要使用 scrcpy server 模式或集成到截图流程") # 暂时回退到标准截图方法 ops = ScreenshotOperations() return ops._get_screenshot_direct(device_id, os.path.dirname(output_path)) except Exception as e: elapsed = (time.time() - start_time) * 1000 print(f"[{timetag}] [scrcpy] 截图失败: {e},耗时: {elapsed:.0f}ms") return False def get_scrcpy_screenshot(device_id: str, output_path: str) -> bool: """获取 scrcpy 截图(便捷函数)""" scrcpy = ScrcpyScreenshot() return scrcpy.get_screenshot(device_id, output_path)