import ctypes
import time

import cv2
import numpy as np

# 加载动态链接库
external_renderer = ctypes.CDLL(
    "C:\\Program Files\\NetEase\\MuMu Player 12\\shell\\sdk\\external_renderer_ipc.dll"
)


# 定义函数原型
external_renderer.nemu_connect.argtypes = [ctypes.c_wchar_p, ctypes.c_int]
external_renderer.nemu_connect.restype = ctypes.c_int

external_renderer.nemu_disconnect.argtypes = [ctypes.c_int]
external_renderer.nemu_disconnect.restype = None

external_renderer.nemu_capture_display.argtypes = [
    ctypes.c_int,
    ctypes.c_uint,
    ctypes.c_int,
    ctypes.POINTER(ctypes.c_int),
    ctypes.POINTER(ctypes.c_int),
    ctypes.POINTER(ctypes.c_ubyte),
]
external_renderer.nemu_capture_display.restype = ctypes.c_int

# 设置 emulator 路径和实例
install_path = ctypes.c_wchar_p("C:\\Program Files\\NetEase\\MuMu Player 12")
instance_index = 0

# 连接到 emulator
connection = external_renderer.nemu_connect(install_path, instance_index)

if connection == 0:
    print("连接失败，请确认安装目录正确且实例已经打开")
else:
    print("连接成功")

    pixels = (ctypes.c_ubyte * 8294400)()
    start_time = time.time()

    external_renderer.nemu_capture_display(
        connection,
        0,
        8294400,
        ctypes.byref(ctypes.c_int(1920)),
        ctypes.byref(ctypes.c_int(1080)),
        pixels,
    )

    image = np.frombuffer(pixels, dtype=np.uint8).reshape((1080, 1920, 4))[
        :, :, :3
    ]  # RGBA-RGB
    image = np.flipud(image)  # 翻转
    print(f"像素转换为矩阵：{time.time() - start_time:.4f} 秒")

    image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

    print(f"OpenCV转换BGR，耗时：{time.time() - start_time:.4f} 秒")
    cv2.imwrite("screenshot.png", image_bgr)
    print(f"截图已保存，耗时：{time.time() - start_time:.4f} 秒")

    # 断开连接
    external_renderer.nemu_disconnect(connection)
