fix(screenshot): recover adb after empty screencap output
Windows Package CI / package-fresh-install (push) Waiting to run

This commit is contained in:
Your Name committed 2026-06-29 00:35:07 +08:00
1 parent 329b7756f4
commit 60306dd4e0
2 files changed
+125 -45

No files matched your search

+72 -45
View File
@@ -224,60 +224,84 @@ class ScreenshotOperations:
_ops_log(f"[截图] shell stdout回退失败:{e}")
return False
def _format_adb_stderr(value: bytes | str | None) -> str:
if value is None:
return ""
if isinstance(value, bytes):
text = value.decode("utf-8", errors="replace")
else:
text = str(value)
text = " ".join(text.strip().split())
return text[-500:]
adb_recovered = False
def _recover_adb_once(reason: str) -> None:
nonlocal adb_recovered
if adb_recovered:
return
adb_recovered = True
_ops_log(f"[截图] ADB截图输出异常,尝试重启ADB服务后重试: {reason}", "WARNING")
for args, timeout in (
([adb, "kill-server"], 5),
([adb, "start-server"], 8),
):
try:
proc = subprocess.run(
args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
timeout=timeout,
)
if proc.returncode != 0:
err = _format_adb_stderr(proc.stderr or proc.stdout)
_ops_log(f"[截图] ADB恢复命令返回异常 rc={proc.returncode} err={err}", "WARNING")
except Exception as exc:
_ops_log(f"[截图] ADB恢复命令执行失败: {exc}", "WARNING")
time.sleep(0.5)
# 优先走 exec-out:只需 1 次 adb 调用;不在手机端落盘,减少 I/O 与卡顿
# 为避免被并发读取到"半写入文件",写入 tmp 后再原子替换。
for _ in range(2):
for attempt in range(2):
try:
try:
if os.path.exists(tmp_file):
os.remove(tmp_file)
except Exception:
pass
# 使用 Popen 流式读取,边接收数据边写入文件,提高性能
t_exec_start = time.time()
try:
process = subprocess.Popen(
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
result = subprocess.run(
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
timeout=10,
)
exec_ms = (time.time() - t_exec_start) * 1000
timetag2 = datetime.now().strftime("%H:%M:%S")
out = result.stdout or b""
err = _format_adb_stderr(result.stderr)
if result.returncode != 0:
reason = f"rc={result.returncode} bytes={len(out)} err={err or '<empty>'}"
_ops_log(f"[截图] exec-out 返回异常: {reason}", "WARNING")
if result.returncode == 4294967295:
_ops_log(f"[截图] exec-out 异常:设备连接失败或ADB服务异常 (设备ID: {device_id})")
if attempt == 0:
_recover_adb_once(reason)
continue
if not _write_valid_png_bytes(out):
reason = f"rc=0 bytes={len(out)} err={err or '<empty>'}"
_ops_log(
f"[截图] exec-out 输出无效: {reason} attempt={attempt + 1}/2",
"WARNING",
)
# 流式写入文件,避免等待整个命令完成
with open(tmp_file, "wb") as f:
while True:
chunk = process.stdout.read(65536) # 64KB 缓冲
if not chunk:
break
f.write(chunk)
# 确保数据落盘,避免后续读取到半写文件
try:
f.flush()
os.fsync(f.fileno())
except Exception:
pass
# 等待进程完成并检查返回码
return_code = process.wait(timeout=10)
if return_code != 0:
# 特殊处理常见的adb错误码
if return_code == 4294967295: # 0xFFFFFFFF
raise subprocess.CalledProcessError(
return_code,
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
f"设备连接失败或ADB服务异常 (错误码: {return_code})"
)
else:
raise subprocess.CalledProcessError(return_code, [adb, "-s", device_id, "exec-out", "screencap", "-p"])
t_exec_end = time.time()
exec_ms = (t_exec_end - t_exec_start) * 1000
timetag2 = datetime.now().strftime("%H:%M:%S")
_ops_log(f"[{timetag2}] [DEBUG] exec-out duration: {exec_ms:.0f}ms (device_id={device_id})")
except subprocess.TimeoutExpired:
# Popen 超时,记录并重新抛出异常
_ops_log(f"[截图] exec-out 流式读取超时")
raise
if attempt == 0:
_recover_adb_once(reason)
continue
_ops_log(
f"[{timetag2}] [DEBUG] exec-out duration: {exec_ms:.0f}ms bytes={len(out)} (device_id={device_id})"
)
if _valid_png(tmp_file):
# 使用安全的文件替换函数并二次验证目标文件,避免写入截断导致后续读取失败
if _safe_replace_file(tmp_file, out_file):
@@ -301,7 +325,10 @@ class ScreenshotOperations:
_ops_log(f"[{timetag}] [截图] 文件替换失败,但截图已保存到临时文件,将尝试回退方案")
except subprocess.TimeoutExpired:
# 超时异常,记录并继续重试
_ops_log(f"[截图] exec-out 超时,尝试重试或回退方案")
reason = f"timeout device_id={device_id}"
_ops_log(f"[截图] exec-out 超时,尝试重试或回退方案", "WARNING")
if attempt == 0:
_recover_adb_once(reason)
try:
if os.path.exists(tmp_file):
os.remove(tmp_file)
+53
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
from io import BytesIO
from types import SimpleNamespace
from unittest.mock import patch
@@ -132,3 +133,55 @@ def test_capture_screenshot_direct_tries_stdout_after_invalid_pull_file(tmp_path
assert result is True
assert (pic_dir / "screenshot.png").read_bytes().startswith(b"\x89PNG")
assert any(cmd[:5] == ["adb", "-s", "MOCK", "shell", "screencap"] and len(cmd) == 6 for cmd in calls)
def test_screenshot_operations_recovers_after_zero_byte_execout(tmp_path, monkeypatch):
from douyin.core import path_config
from PIL import Image
from operations import screenshot_operations
pic_dir = tmp_path / "pic"
pic_dir.mkdir()
buf = BytesIO()
image = Image.new("RGB", (256, 256))
image.putdata(
[
((x * 17 + y * 3) % 255, (y * 19 + x * 5) % 255, (x * y) % 255)
for y in range(256)
for x in range(256)
]
)
image.save(buf, format="PNG")
png_bytes = buf.getvalue()
calls: list[list[str]] = []
execout_count = 0
def fake_run(cmd, **_kwargs):
nonlocal execout_count
calls.append(list(cmd))
if cmd[:4] == ["adb", "-s", "MOCK", "exec-out"]:
execout_count += 1
if execout_count == 1:
return SimpleNamespace(returncode=0, stdout=b"", stderr=b"")
return SimpleNamespace(returncode=0, stdout=png_bytes, stderr=b"")
if cmd == ["adb", "kill-server"] or cmd == ["adb", "start-server"]:
return SimpleNamespace(returncode=0, stdout=b"", stderr=b"")
raise AssertionError(f"unexpected command: {cmd}")
monkeypatch.setenv("ADB_EXECUTABLE", "adb")
monkeypatch.setattr(
path_config,
"get_pic_dir",
lambda: str(pic_dir),
raising=False,
)
monkeypatch.setattr(screenshot_operations.subprocess, "run", fake_run)
monkeypatch.setattr(screenshot_operations, "_mirror_screenshot_to_external", lambda *_: None)
result = screenshot_operations.ScreenshotOperations().get_screenshot("MOCK", use_service=False)
assert result is True
assert (pic_dir / "screenshot.png").read_bytes().startswith(b"\x89PNG")
assert ["adb", "kill-server"] in calls
assert ["adb", "start-server"] in calls