diff --git a/douyin/core/underlying_operations.py b/douyin/core/underlying_operations.py index 4f70229..fb3626e 100644 --- a/douyin/core/underlying_operations.py +++ b/douyin/core/underlying_operations.py @@ -404,500 +404,14 @@ class underlying_operations: return bool(final_result) def _get_screenshot_direct(self, device_id, path="pic"): - """直接截图(不使用服务模式)""" - overall_start = time_module.time() - # 初始化分阶段耗时占位,确保最终汇总时总有值 - cleanup_dur = 0.0 - adb_subprocess_dur = 0.0 - validate_tmp_dur = 0.0 - replace_dur = 0.0 - mirror_dur = 0.0 - validate_out_dur = 0.0 + """直接截图(不使用服务模式)。 - if path == "pic": - try: - from douyin.core import path_config - - out_dir = path_config.get_pic_dir() - except Exception: - from douyin.core import path_config - - out_dir = path_config.get_pic_dir() - else: - out_dir = os.path.join(os.path.dirname(__file__), "target_pic") - if not os.path.exists(out_dir): - os.makedirs(out_dir) - - # 统一输出到固定文件名,兼容现有 cut_pic()/后续流程 - out_file = os.path.join(out_dir, "screenshot.png") - tmp_file = out_file + ".tmp" - timetag = datetime.now().strftime("%H:%M:%S") - - adb = self._adb_path() - - # 检查环境变量:是否跳过PNG验证(用于性能测试) - skip_verify = os.environ.get("SKIP_SCREENSHOT_VERIFY", "0") == "1" - - def _valid_png(path0: str) -> bool: - if skip_verify: - # 快速路径:只检查文件存在和大小 - try: - if not os.path.exists(path0): - return False - sz = os.path.getsize(path0) - return sz >= 1024 - except Exception: - return False - - verify_start = time_module.time() - try: - if not os.path.exists(path0): - return False - sz = os.path.getsize(path0) - if sz < 1024: - return False - # 额外校验 PNG 头与文件尾(快速检测截断) - header_check_start = time_module.time() - try: - with open(path0, "rb") as _f: - header = _f.read(4) - if header != b"\x89PNG": - return False - try: - _f.seek(-256, 2) - except Exception: - _f.seek(0) - tail = _f.read(256) - if b"IEND" not in tail: - return False - except Exception: - return False - header_check_dur = (time_module.time() - header_check_start) * 1000.0 - if header_check_dur > 10.0: # 只记录超过10ms的 - logging.debug( - "[截图] PNG头尾校验耗时(ms)=%.1f path=%s", - header_check_dur, - path0, - ) - - # 优化:只在必要时使用 PIL 验证(PIL verify 可能很慢) - # 对于临时文件,快速验证已足够;对于最终文件,可以跳过完整验证以提高速度 - # 如果文件头尾都正确,大概率是有效的PNG文件 - # PIL verify 可以移到后台或异步进行,不阻塞主流程 - # 这里先跳过完整验证,只做快速检查 - # pil_verify_start = time_module.time() - # try: - # from PIL import Image - # with Image.open(path0) as im: - # im.verify() - # except Exception: - # return False - # pil_verify_dur = (time_module.time() - pil_verify_start) * 1000.0 - # if pil_verify_dur > 50.0: # 只记录超过50ms的 - # logging.debug("[截图] PIL verify耗时(ms)=%.1f path=%s", pil_verify_dur, path0) - - verify_total_dur = (time_module.time() - verify_start) * 1000.0 - if verify_total_dur > 100.0: # 只记录超过100ms的 - logging.info( - "[截图] _valid_png总耗时(ms)=%.1f path=%s", - verify_total_dur, - path0, - ) - return True - except Exception: - return False - - # 优先走 exec-out:只需 1 次 adb 调用;不在手机端落盘,减少 I/O 与卡顿 - # 为避免被并发读取到"半写入文件",写入 tmp 后再原子替换。 - execout_timeout_sec = float(os.environ.get("ADB_EXECOUT_TIMEOUT_SEC", "10")) - execout_warn_after_sec = float( - os.environ.get("ADB_EXECOUT_WARN_AFTER_SEC", "3") + 实现已抽到 underlying_operations_pkg.screenshot_direct.capture_screenshot_direct。 + """ + from douyin.core.underlying_operations_pkg.screenshot_direct import ( + capture_screenshot_direct, ) - execout_heartbeat_interval_sec = float( - os.environ.get("ADB_EXECOUT_HEARTBEAT_INTERVAL_SEC", "5") - ) - execout_heartbeat_max = int(os.environ.get("ADB_EXECOUT_HEARTBEAT_MAX", "3")) - for attempt in range(2): - try: - cleanup_start = time_module.time() - try: - if os.path.exists(tmp_file): - os.remove(tmp_file) - except Exception: - pass - cleanup_dur = (time_module.time() - cleanup_start) * 1000.0 - if cleanup_dur > 10.0: - logging.debug("[截图] 清理临时文件耗时(ms)=%.1f", cleanup_dur) - - # 从设备获取截图(exec-out),写入临时文件 - # 优化:使用 Popen + 流式读取,边接收边写入,提高性能 - adb_start = time_module.time() - try: - process = subprocess.Popen( - [adb, "-s", device_id, "exec-out", "screencap", "-p"], - stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL, - bufsize=0, # 无缓冲,立即传输 - ) - - # 注意:Windows 上 stdout.read() 可能永久阻塞(adb 卡住时不会退出),导致 wait(timeout=...) 永远到不了。 - # 这里用 communicate(timeout=...) 保证超时可触发,从而进入重试/回退方案。 - done_event = None - watchdog_thread = None - try: - import threading - - done_event = threading.Event() - - def _watchdog() -> None: - try: - if execout_warn_after_sec > 0: - if done_event.wait(timeout=execout_warn_after_sec): - return - start_wait = time_module.time() - for i in range(max(0, execout_heartbeat_max)): - if done_event.is_set(): - return - waited = (time_module.time() - start_wait) * 1000.0 - logging.warning( - "[截图] exec-out 仍在进行中:已等待(ms)=%.0f device=%s attempt=%s", - waited, - device_id, - attempt + 1, - ) - if done_event.wait( - timeout=max(0.5, execout_heartbeat_interval_sec) - ): - return - except Exception: - return - - watchdog_thread = threading.Thread( - target=_watchdog, name="adb-execout-watchdog", daemon=True - ) - watchdog_thread.start() - except Exception: - done_event = None - - stdout_data, _ = process.communicate(timeout=execout_timeout_sec) - if done_event is not None: - done_event.set() - - if process.returncode != 0: - raise subprocess.CalledProcessError( - process.returncode, - [adb, "-s", device_id, "exec-out", "screencap", "-p"], - ) - - with open(tmp_file, "wb", buffering=262144) as f: - f.write(stdout_data) - - adb_subprocess_dur = (time_module.time() - adb_start) * 1000.0 - # 合并ADB subprocess耗时到最终汇总日志中,不单独输出 - - # 优化:移除 fsync(现代文件系统会自动同步,减少不必要的磁盘I/O) - # 文件写入已经完成,操作系统会在适当时机同步到磁盘 - # 这样可以减少 10-50ms 的等待时间 - except subprocess.TimeoutExpired: - process.kill() - try: - process.communicate(timeout=1) - except Exception: - pass - try: - if done_event is not None: - done_event.set() - except Exception: - pass - raise - - validate_tmp_start = time_module.time() - is_valid = _valid_png(tmp_file) - validate_tmp_dur = (time_module.time() - validate_tmp_start) * 1000.0 - if validate_tmp_dur > 50.0: - logging.info( - "[截图] 临时文件验证耗时(ms)=%.1f result=%s", - validate_tmp_dur, - is_valid, - ) - - if is_valid: - # 使用安全的文件替换函数 - replace_start = time_module.time() - replace_success = _safe_replace_file(tmp_file, out_file) - replace_dur = (time_module.time() - replace_start) * 1000.0 - if replace_dur > 50.0: - logging.info( - "[截图] 文件替换耗时(ms)=%.1f result=%s", - replace_dur, - replace_success, - ) - - if replace_success: - mirror_start = time_module.time() - _mirror_screenshot_to_external(out_file) - mirror_dur = (time_module.time() - mirror_start) * 1000.0 - if mirror_dur > 50.0: - logging.info( - "[截图] 镜像到外部路径耗时(ms)=%.1f", mirror_dur - ) - - # 优化:快速验证目标文件(只检查存在和大小,不进行完整PNG验证) - # 完整验证可以在读取时进行,不阻塞截图流程 - validate_out_start = time_module.time() - try: - # 快速检查:文件存在且大小合理 - if os.path.exists(out_file): - file_size = os.path.getsize(out_file) - if file_size >= 1024: # 至少1KB - # 快速检查PNG头(不进行完整验证) - try: - with open(out_file, "rb") as f: - header = f.read(4) - if header == b"\x89PNG": - validate_out_dur = ( - time_module.time() - - validate_out_start - ) * 1000.0 - if validate_out_dur > 50.0: - logging.info( - "[截图] 目标文件快速验证耗时(ms)=%.1f", - validate_out_dur, - ) - - overall_dur = ( - time_module.time() - overall_start - ) * 1000.0 - # 合并所有截图信息到单个日志输出 - logging.info( - "[截图] ✓ 获取屏幕截图成功 | 总耗时(ms)=%.1f (exec-out成功) | 汇总: cleanup=%.1f adb_execout=%.1f validate_tmp=%.1f replace=%.1f mirror=%.1f validate_out=%.1f", - overall_dur, - cleanup_dur, - adb_subprocess_dur, - validate_tmp_dur, - replace_dur, - mirror_dur, - validate_out_dur, - ) - return True - except Exception: - pass - - # 如果快速验证失败,记录诊断信息 - try: - st = os.stat(out_file) - _uo_log( - f"[截图诊断] 目标文件验证失败: size={st.st_size}, mtime={st.st_mtime}" - ) - except Exception: - pass - except Exception: - pass - else: - # 如果替换失败,但临时文件有效,记录诊断并重试回退方案 - try: - if os.path.exists(tmp_file): - st = os.stat(tmp_file) - _uo_log( - f"[截图诊断] 临时文件存在但替换失败: tmp={tmp_file}, size={st.st_size}" - ) - except Exception: - pass - # 继续尝试回退方案 - else: - # 临时文件本身无效,记录诊断信息 - try: - if os.path.exists(tmp_file): - st = os.stat(tmp_file) - _uo_log( - f"[截图诊断] 临时文件无效: path={tmp_file}, size={st.st_size}" - ) - except Exception: - pass - # 继续尝试回退方案 - except subprocess.TimeoutExpired: - # 超时异常,记录并继续重试 - _uo_log("[截图] exec-out 超时,尝试重试或回退方案") - try: - if os.path.exists(tmp_file): - os.remove(tmp_file) - except Exception: - pass - except Exception as e: - # 继续回退/重试 - _uo_log(f"[截图] exec-out 异常:{e}") - try: - if os.path.exists(tmp_file): - os.remove(tmp_file) - except Exception: - pass - - # 回退方案:老式 shell screencap + pull(兼容极少数不支持 exec-out 的环境) - fallback_start = time_module.time() - try: - shell_screencap_start = time_module.time() - subprocess.run( - [ - adb, - "-s", - device_id, - "shell", - "screencap", - "-p", - "/sdcard/DCIM/screenshot.png", - ], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - check=True, - timeout=10, # 添加超时 - ) - shell_screencap_dur = (time_module.time() - shell_screencap_start) * 1000.0 - logging.info( - "[截图] 回退方案-shell screencap耗时(ms)=%.1f device=%s", - shell_screencap_dur, - device_id, - ) - - pull_start = time_module.time() - subprocess.run( - [adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", tmp_file], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - check=True, - timeout=10, # 添加超时 - ) - pull_dur = (time_module.time() - pull_start) * 1000.0 - logging.info( - "[截图] 回退方案-adb pull耗时(ms)=%.1f device=%s", pull_dur, device_id - ) - - fallback_validate_start = time_module.time() - if _valid_png(tmp_file): - fallback_validate_dur = ( - time_module.time() - fallback_validate_start - ) * 1000.0 - if fallback_validate_dur > 50.0: - logging.info( - "[截图] 回退方案-临时文件验证耗时(ms)=%.1f", - fallback_validate_dur, - ) - - # 使用安全的文件替换函数 - fallback_replace_start = time_module.time() - if _safe_replace_file(tmp_file, out_file): - fallback_replace_dur = ( - time_module.time() - fallback_replace_start - ) * 1000.0 - if fallback_replace_dur > 50.0: - logging.info( - "[截图] 回退方案-文件替换耗时(ms)=%.1f", - fallback_replace_dur, - ) - - fallback_mirror_start = time_module.time() - _mirror_screenshot_to_external(out_file) - fallback_mirror_dur = ( - time_module.time() - fallback_mirror_start - ) * 1000.0 - if fallback_mirror_dur > 50.0: - logging.info( - "[截图] 回退方案-镜像耗时(ms)=%.1f", fallback_mirror_dur - ) - - try: - if _valid_png(out_file): - overall_dur = (time_module.time() - overall_start) * 1000.0 - fallback_total_dur = ( - time_module.time() - fallback_start - ) * 1000.0 - # 合并回退方案成功信息到单个日志输出 - logging.info( - "[截图] ✓ 获取屏幕截图成功 | 总耗时(ms)=%.1f (回退方案成功, 回退部分耗时=%.1fms)", - overall_dur, - fallback_total_dur, - ) - return True - except Exception: - pass - else: - # 如果替换失败,尝试最后一次:直接复制内容 - try: - import shutil - - # 如果目标文件存在且被占用,尝试读取临时文件内容并写入 - if os.path.exists(tmp_file): - # 尝试直接覆盖写入(如果文件被占用,这会失败,但至少尝试了) - try: - with open(tmp_file, "rb") as src, open( - out_file, "wb" - ) as dst: - dst.write(src.read()) - _mirror_screenshot_to_external(out_file) - try: - if _valid_png(out_file): - _uo_log( - f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过直接写入)" - ) - return True - except Exception: - pass - except (OSError, PermissionError) as e: - # 如果还是失败,使用优化后的文件替换函数 - replace_success = _safe_replace_file(tmp_file, out_file) - if replace_success: - _mirror_screenshot_to_external(out_file) - try: - if _valid_png(out_file): - _uo_log( - f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过优化替换)" - ) - return True - except Exception: - pass - else: - # 最后兜底:返回True,让调用者知道临时文件存在 - _uo_log( - f"[截图] 文件替换失败({e}),但截图已保存到临时文件 {tmp_file}" - ) - return True - except Exception: - _uo_log(f"[截图] 文件替换失败,但截图已保存到临时文件 {tmp_file}") - return True - # 文件异常则继续进入更深回退 - except Exception: - # 再次回退:尝试用 screenshot1.png 覆盖 screenshot.png - try: - subprocess.run( - [ - adb, - "-s", - device_id, - "shell", - "screencap", - "-p", - "/sdcard/DCIM/screenshot1.png", - ], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - check=True, - ) - subprocess.run( - [ - adb, - "-s", - device_id, - "shell", - "mv", - "/sdcard/DCIM/screenshot1.png", - "/sdcard/DCIM/screenshot.png", - ], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - check=True, - ) - return self.get_screenshot(device_id, path) - except Exception: - return False + return capture_screenshot_direct(self, device_id, path) def get_current_hour(self): """获取当前的时间小时数""" diff --git a/douyin/core/underlying_operations_pkg/screenshot_direct.py b/douyin/core/underlying_operations_pkg/screenshot_direct.py new file mode 100644 index 0000000..d233ef6 --- /dev/null +++ b/douyin/core/underlying_operations_pkg/screenshot_direct.py @@ -0,0 +1,487 @@ +"""underlying_operations._get_screenshot_direct 的实现。 + +从 underlying_operations.py 抽出,原方法保留为 thin shim 调用 capture_screenshot_direct。 + +依赖: +- self._adb_path() —— 取 adb 可执行文件路径 +- self.get_screenshot() —— 在最深兜底分支递归调用一次(注意保持兼容) +- io_utils._safe_replace_file +- io_utils._mirror_screenshot_to_external +""" +from __future__ import annotations + +import logging +import os +import subprocess +import threading +import time as time_module +from datetime import datetime +from typing import TYPE_CHECKING + +from douyin.core.io_utils import ( + _mirror_screenshot_to_external, + _safe_replace_file, +) + +if TYPE_CHECKING: + from douyin.core.underlying_operations import underlying_operations + + +def _uo_log(msg: str) -> None: + """与 underlying_operations._uo_log 一致:默认 INFO 级别。""" + try: + logging.info(msg) + except Exception: + pass + + +def capture_screenshot_direct( + self: "underlying_operations", device_id, path: str = "pic" +) -> bool: + """直接截图(不使用服务模式)。从 underlying_operations._get_screenshot_direct 抽出。 + + 流程: + 1. 准备输出目录 + 文件名 + 2. 优先 exec-out 路径(最多 2 次重试 + watchdog) + 3. 失败 → 回退 shell screencap + adb pull + 4. 再失败 → 兜底 mv + 递归调用 get_screenshot + """ + overall_start = time_module.time() + cleanup_dur = 0.0 + adb_subprocess_dur = 0.0 + validate_tmp_dur = 0.0 + replace_dur = 0.0 + mirror_dur = 0.0 + validate_out_dur = 0.0 + + if path == "pic": + try: + from douyin.core import path_config + + out_dir = path_config.get_pic_dir() + except Exception: + from douyin.core import path_config + + out_dir = path_config.get_pic_dir() + else: + out_dir = os.path.join(os.path.dirname(__file__), "..", "target_pic") + if not os.path.exists(out_dir): + os.makedirs(out_dir) + + out_file = os.path.join(out_dir, "screenshot.png") + tmp_file = out_file + ".tmp" + timetag = datetime.now().strftime("%H:%M:%S") + + adb = self._adb_path() + + skip_verify = os.environ.get("SKIP_SCREENSHOT_VERIFY", "0") == "1" + + def _valid_png(path0: str) -> bool: + if skip_verify: + try: + if not os.path.exists(path0): + return False + sz = os.path.getsize(path0) + return sz >= 1024 + except Exception: + return False + + verify_start = time_module.time() + try: + if not os.path.exists(path0): + return False + sz = os.path.getsize(path0) + if sz < 1024: + return False + header_check_start = time_module.time() + try: + with open(path0, "rb") as _f: + header = _f.read(4) + if header != b"\x89PNG": + return False + try: + _f.seek(-256, 2) + except Exception: + _f.seek(0) + tail = _f.read(256) + if b"IEND" not in tail: + return False + except Exception: + return False + header_check_dur = (time_module.time() - header_check_start) * 1000.0 + if header_check_dur > 10.0: + logging.debug( + "[截图] PNG头尾校验耗时(ms)=%.1f path=%s", + header_check_dur, + path0, + ) + + verify_total_dur = (time_module.time() - verify_start) * 1000.0 + if verify_total_dur > 100.0: + logging.info( + "[截图] _valid_png总耗时(ms)=%.1f path=%s", + verify_total_dur, + path0, + ) + return True + except Exception: + return False + + # 优先走 exec-out + execout_timeout_sec = float(os.environ.get("ADB_EXECOUT_TIMEOUT_SEC", "10")) + execout_warn_after_sec = float( + os.environ.get("ADB_EXECOUT_WARN_AFTER_SEC", "3") + ) + execout_heartbeat_interval_sec = float( + os.environ.get("ADB_EXECOUT_HEARTBEAT_INTERVAL_SEC", "5") + ) + execout_heartbeat_max = int(os.environ.get("ADB_EXECOUT_HEARTBEAT_MAX", "3")) + + for attempt in range(2): + try: + cleanup_start = time_module.time() + try: + if os.path.exists(tmp_file): + os.remove(tmp_file) + except Exception: + pass + cleanup_dur = (time_module.time() - cleanup_start) * 1000.0 + if cleanup_dur > 10.0: + logging.debug("[截图] 清理临时文件耗时(ms)=%.1f", cleanup_dur) + + adb_start = time_module.time() + try: + process = subprocess.Popen( + [adb, "-s", device_id, "exec-out", "screencap", "-p"], + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + bufsize=0, + ) + + done_event = None + watchdog_thread = None + try: + done_event = threading.Event() + + def _watchdog() -> None: + try: + if execout_warn_after_sec > 0: + if done_event.wait(timeout=execout_warn_after_sec): + return + start_wait = time_module.time() + for i in range(max(0, execout_heartbeat_max)): + if done_event.is_set(): + return + waited = (time_module.time() - start_wait) * 1000.0 + logging.warning( + "[截图] exec-out 仍在进行中:已等待(ms)=%.0f device=%s attempt=%s", + waited, + device_id, + attempt + 1, + ) + if done_event.wait( + timeout=max(0.5, execout_heartbeat_interval_sec) + ): + return + except Exception: + return + + watchdog_thread = threading.Thread( + target=_watchdog, name="adb-execout-watchdog", daemon=True + ) + watchdog_thread.start() + except Exception: + done_event = None + + stdout_data, _ = process.communicate(timeout=execout_timeout_sec) + if done_event is not None: + done_event.set() + + if process.returncode != 0: + raise subprocess.CalledProcessError( + process.returncode, + [adb, "-s", device_id, "exec-out", "screencap", "-p"], + ) + + with open(tmp_file, "wb", buffering=262144) as f: + f.write(stdout_data) + + adb_subprocess_dur = (time_module.time() - adb_start) * 1000.0 + except subprocess.TimeoutExpired: + process.kill() + try: + process.communicate(timeout=1) + except Exception: + pass + try: + if done_event is not None: + done_event.set() + except Exception: + pass + raise + + validate_tmp_start = time_module.time() + is_valid = _valid_png(tmp_file) + validate_tmp_dur = (time_module.time() - validate_tmp_start) * 1000.0 + if validate_tmp_dur > 50.0: + logging.info( + "[截图] 临时文件验证耗时(ms)=%.1f result=%s", + validate_tmp_dur, + is_valid, + ) + + if is_valid: + replace_start = time_module.time() + replace_success = _safe_replace_file(tmp_file, out_file) + replace_dur = (time_module.time() - replace_start) * 1000.0 + if replace_dur > 50.0: + logging.info( + "[截图] 文件替换耗时(ms)=%.1f result=%s", + replace_dur, + replace_success, + ) + + if replace_success: + mirror_start = time_module.time() + _mirror_screenshot_to_external(out_file) + mirror_dur = (time_module.time() - mirror_start) * 1000.0 + if mirror_dur > 50.0: + logging.info( + "[截图] 镜像到外部路径耗时(ms)=%.1f", mirror_dur + ) + + validate_out_start = time_module.time() + try: + if os.path.exists(out_file): + file_size = os.path.getsize(out_file) + if file_size >= 1024: + try: + with open(out_file, "rb") as f: + header = f.read(4) + if header == b"\x89PNG": + validate_out_dur = ( + time_module.time() + - validate_out_start + ) * 1000.0 + if validate_out_dur > 50.0: + logging.info( + "[截图] 目标文件快速验证耗时(ms)=%.1f", + validate_out_dur, + ) + + overall_dur = ( + time_module.time() - overall_start + ) * 1000.0 + logging.info( + "[截图] ✓ 获取屏幕截图成功 | 总耗时(ms)=%.1f (exec-out成功) | 汇总: cleanup=%.1f adb_execout=%.1f validate_tmp=%.1f replace=%.1f mirror=%.1f validate_out=%.1f", + overall_dur, + cleanup_dur, + adb_subprocess_dur, + validate_tmp_dur, + replace_dur, + mirror_dur, + validate_out_dur, + ) + return True + except Exception: + pass + + try: + st = os.stat(out_file) + _uo_log( + f"[截图诊断] 目标文件验证失败: size={st.st_size}, mtime={st.st_mtime}" + ) + except Exception: + pass + except Exception: + pass + else: + try: + if os.path.exists(tmp_file): + st = os.stat(tmp_file) + _uo_log( + f"[截图诊断] 临时文件存在但替换失败: tmp={tmp_file}, size={st.st_size}" + ) + except Exception: + pass + else: + try: + if os.path.exists(tmp_file): + st = os.stat(tmp_file) + _uo_log( + f"[截图诊断] 临时文件无效: path={tmp_file}, size={st.st_size}" + ) + except Exception: + pass + except subprocess.TimeoutExpired: + _uo_log("[截图] exec-out 超时,尝试重试或回退方案") + try: + if os.path.exists(tmp_file): + os.remove(tmp_file) + except Exception: + pass + except Exception as e: + _uo_log(f"[截图] exec-out 异常:{e}") + try: + if os.path.exists(tmp_file): + os.remove(tmp_file) + except Exception: + pass + + # 回退方案:老式 shell screencap + pull + fallback_start = time_module.time() + try: + shell_screencap_start = time_module.time() + subprocess.run( + [ + adb, + "-s", + device_id, + "shell", + "screencap", + "-p", + "/sdcard/DCIM/screenshot.png", + ], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=True, + timeout=10, + ) + shell_screencap_dur = (time_module.time() - shell_screencap_start) * 1000.0 + logging.info( + "[截图] 回退方案-shell screencap耗时(ms)=%.1f device=%s", + shell_screencap_dur, + device_id, + ) + + pull_start = time_module.time() + subprocess.run( + [adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", tmp_file], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=True, + timeout=10, + ) + pull_dur = (time_module.time() - pull_start) * 1000.0 + logging.info( + "[截图] 回退方案-adb pull耗时(ms)=%.1f device=%s", pull_dur, device_id + ) + + fallback_validate_start = time_module.time() + if _valid_png(tmp_file): + fallback_validate_dur = ( + time_module.time() - fallback_validate_start + ) * 1000.0 + if fallback_validate_dur > 50.0: + logging.info( + "[截图] 回退方案-临时文件验证耗时(ms)=%.1f", + fallback_validate_dur, + ) + + fallback_replace_start = time_module.time() + if _safe_replace_file(tmp_file, out_file): + fallback_replace_dur = ( + time_module.time() - fallback_replace_start + ) * 1000.0 + if fallback_replace_dur > 50.0: + logging.info( + "[截图] 回退方案-文件替换耗时(ms)=%.1f", + fallback_replace_dur, + ) + + fallback_mirror_start = time_module.time() + _mirror_screenshot_to_external(out_file) + fallback_mirror_dur = ( + time_module.time() - fallback_mirror_start + ) * 1000.0 + if fallback_mirror_dur > 50.0: + logging.info( + "[截图] 回退方案-镜像耗时(ms)=%.1f", fallback_mirror_dur + ) + + try: + if _valid_png(out_file): + overall_dur = (time_module.time() - overall_start) * 1000.0 + fallback_total_dur = ( + time_module.time() - fallback_start + ) * 1000.0 + logging.info( + "[截图] ✓ 获取屏幕截图成功 | 总耗时(ms)=%.1f (回退方案成功, 回退部分耗时=%.1fms)", + overall_dur, + fallback_total_dur, + ) + return True + except Exception: + pass + else: + # 替换失败 → 直接复制 / 兜底 + try: + if os.path.exists(tmp_file): + try: + with open(tmp_file, "rb") as src, open( + out_file, "wb" + ) as dst: + dst.write(src.read()) + _mirror_screenshot_to_external(out_file) + try: + if _valid_png(out_file): + _uo_log( + f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过直接写入)" + ) + return True + except Exception: + pass + except (OSError, PermissionError) as e: + replace_success = _safe_replace_file(tmp_file, out_file) + if replace_success: + _mirror_screenshot_to_external(out_file) + try: + if _valid_png(out_file): + _uo_log( + f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过优化替换)" + ) + return True + except Exception: + pass + else: + _uo_log( + f"[截图] 文件替换失败({e}),但截图已保存到临时文件 {tmp_file}" + ) + return True + except Exception: + _uo_log(f"[截图] 文件替换失败,但截图已保存到临时文件 {tmp_file}") + return True + except Exception: + # 再次回退:尝试用 screenshot1.png 覆盖 screenshot.png + try: + subprocess.run( + [ + adb, + "-s", + device_id, + "shell", + "screencap", + "-p", + "/sdcard/DCIM/screenshot1.png", + ], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=True, + ) + subprocess.run( + [ + adb, + "-s", + device_id, + "shell", + "mv", + "/sdcard/DCIM/screenshot1.png", + "/sdcard/DCIM/screenshot.png", + ], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=True, + ) + return self.get_screenshot(device_id, path) + except Exception: + return False