// Copyright (C) 2020 ~ 2026, Deepin Technology Co., Ltd. <support@deepin.org>
// SPDX-FileCopyrightText: 2022 - 2026 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later

#include "config.h"

#include "mpv_proxy.h"
#include "mpv_glwidget.h"
#include "compositing_manager.h"
#include "player_engine.h"
#include "hwdec_probe.h"

#ifndef _LIBDMR_
#include "dmr_settings.h"
#include "movie_configuration.h"
#endif
#include <mpv/client.h>
#ifdef DTKCORE_CLASS_DConfigFile
#include <DConfig>
#endif

#include <random>
#include <QtWidgets>
#include <QtGlobal>

#include <xcb/xproto.h>
#include <xcb/xcb_aux.h>

#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
#include <QX11Info>
#else
#include <QtGui/private/qtx11extras_p.h>
#include <QtGui/private/qtguiglobal_p.h>
#endif

#include <QLibrary>
#include <va/va_x11.h>
#include <malloc.h>

namespace dmr {
using namespace mpv::qt;

// Timeout for polling end of playback (200 * 5ms = 1 second)
static const int POLLING_END_TIMEOUT = 200;

enum AsyncReplyTag {
    SEEK,
    CHANNEL,
    SPEED
};
typedef enum {
  UN_KNOW = 0, //初始值
  MPEG1 , //下面为各种视频格式
  MPEG2,
  MPEG4,
  H264,
  VC1 ,
  DIVX4 ,
  DIVX5,
  HEVC,
  _MAXNULL //超限处理
}decoder_profile; //视频格式解码请求值
typedef  int VdpBool;
typedef enum  {
  decoder_profiles_MPEG1 = 0,   //     {"MPEG1", VDP_DECODER_PROFILE_MPEG1},
  decoder_profiles_MPEG2_SIMPLE,    //     {"MPEG2_SIMPLE", VDP_DECODER_PROFILE_MPEG2_SIMPLE},
  decoder_profiles_MPEG2_MAIN ,  //     {"MPEG2_MAIN", VDP_DECODER_PROFILE_MPEG2_MAIN},
  decoder_profiles_H264_BASELINE,    //     {"H264_BASELINE", VDP_DECODER_PROFILE_H264_BASELINE},
  decoder_profiles_H264_MAIN,    //     {"H264_MAIN", VDP_DECODER_PROFILE_H264_MAIN},
  decoder_profiles_H264_HIGH,    //     {"H264_HIGH", VDP_DECODER_PROFILE_H264_HIGH},
  decoder_profiles_VC1_SIMPLE ,   //     {"VC1_SIMPLE", VDP_DECODER_PROFILE_VC1_SIMPLE},
  decoder_profiles_VC1_MAIN,    //     {"VC1_MAIN", VDP_DECODER_PROFILE_VC1_MAIN},
  decoder_profiles_VC1_ADVANCED ,   //     {"VC1_ADVANCED", VDP_DECODER_PROFILE_VC1_ADVANCED},
  decoder_profiles_MPEG4_PART2_SP,    //     {"MPEG4_PART2_SP", VDP_DECODER_PROFILE_MPEG4_PART2_SP},
  decoder_profiles_MPEG4_PART2_ASP,    //     {"MPEG4_PART2_ASP", VDP_DECODER_PROFILE_MPEG4_PART2_ASP},
  decoder_profiles_DIVX4_QMOBILE,    //     {"DIVX4_QMOBILE", VDP_DECODER_PROFILE_DIVX4_QMOBILE},
  decoder_profiles_DIVX4_MOBILE,    //     {"DIVX4_MOBILE", VDP_DECODER_PROFILE_DIVX4_MOBILE},
  decoder_profiles_DIVX4_HOME_THEATER ,   //     {"DIVX4_HOME_THEATER", VDP_DECODER_PROFILE_DIVX4_HOME_THEATER},
  decoder_profiles_DIVX4_HD_1080P ,   //     {"DIVX4_HD_1080P", VDP_DECODER_PROFILE_DIVX4_HD_1080P},
  decoder_profiles_DIVX5_QMOBILE,    //     {"DIVX5_QMOBILE", VDP_DECODER_PROFILE_DIVX5_QMOBILE},
  decoder_profiles_DIVX5_MOBILE ,   //     {"DIVX5_MOBILE", VDP_DECODER_PROFILE_DIVX5_MOBILE},
  decoder_profiles_DIVX5_HOME_THEATER,    //     {"DIVX5_HOME_THEATER", VDP_DECODER_PROFILE_DIVX5_HOME_THEATER},
  decoder_profiles_DIVX5_HD_1080P,    //     {"DIVX5_HD_1080P", VDP_DECODER_PROFILE_DIVX5_HD_1080P},
  decoder_profiles_H264_CONSTRAINED_BASELINE ,   //     {"H264_CONSTRAINED_BASELINE", VDP_DECODER_PROFILE_H264_CONSTRAINED_BASELINE},
  decoder_profiles_H264_EXTENDED ,   //     {"H264_EXTENDED", VDP_DECODER_PROFILE_H264_EXTENDED},
  decoder_profiles_H264_PROGRESSIVE_HIGH,    //     {"H264_PROGRESSIVE_HIGH", VDP_DECODER_PROFILE_H264_PROGRESSIVE_HIGH},
  decoder_profiles_H264_CONSTRAINED_HIGH,    //     {"H264_CONSTRAINED_HIGH", VDP_DECODER_PROFILE_H264_CONSTRAINED_HIGH},
  decoder_profiles_H264_HIGH_444_PREDICTIVE,    //     {"H264_HIGH_444_PREDICTIVE", VDP_DECODER_PROFILE_H264_HIGH_444_PREDICTIVE},
  decoder_profiles_HEVC_MAIN ,   //     {"HEVC_MAIN", VDP_DECODER_PROFILE_HEVC_MAIN},
  decoder_profiles_HEVC_MAIN_10,    //     {"HEVC_MAIN_10", VDP_DECODER_PROFILE_HEVC_MAIN_10},
  decoder_profiles_HEVC_MAIN_STILL,    //     {"HEVC_MAIN_STILL", VDP_DECODER_PROFILE_HEVC_MAIN_STILL},
  decoder_profiles_HEVC_MAIN_12,    //     {"HEVC_MAIN_12", VDP_DECODER_PROFILE_HEVC_MAIN_12},
  decoder_profiles_HEVC_MAIN_444,    //     {"HEVC_MAIN_444", VDP_DECODER_PROFILE_HEVC_MAIN_444},
  _decoder_maxnull
}VDP_Decoder_e;
#define  RET_INFO_LENGTH_MAX  (512)
typedef struct  {
  VDP_Decoder_e  func; //具体值的功能查询
  VdpBool is_supported; //是否支持具体值硬解码
  uint32_t max_width;//最大支持视频宽度
  uint32_t max_height;//最大支持视频高度
  uint32_t max_level; //最大支持等级
  uint32_t max_macroblocks;//最大宏块大小
  char ret_info[RET_INFO_LENGTH_MAX];//支持的列表
}VDP_Decoder_t;
//返回值大于0表示支持硬解， index 视频格式解码请求值， result 返回解码支持信息
typedef unsigned int (*gpu_decoderInfo)(decoder_profile index, VDP_Decoder_t *result );

bool isSpecialHWHardware();

static void mpv_callback(void *d)
{
    qDebug() << "DEBUG: Entering mpv_callback.";
    MpvProxy *pMpv = static_cast<MpvProxy *>(d);
    QMetaObject::invokeMethod(pMpv, "has_mpv_events", Qt::QueuedConnection);
    qDebug() << "DEBUG: Exiting mpv_callback.";
}

MpvProxy::MpvProxy(QWidget *parent)
    : Backend(parent)
{
    qDebug() << "Entering MpvProxy constructor.";
    initMember();

    m_pParentWidget = parent;

    if (!CompositingManager::get().composited()) {
        qDebug() << "Compositing manager not composited. Setting window flags for native window.";
        setWindowFlags(Qt::FramelessWindowHint);
        setAttribute(Qt::WA_NativeWindow);
        winId();
    } else {
        qDebug() << "DEBUG: Compositing manager is composited. No special window flags set."; // Add log for else branch
    }
#ifdef _LIBDMR_
    qDebug() << "_LIBDMR_ defined. Performing firstInit.";
    firstInit();
    m_bInited = true;
#else
    qDebug() << "DEBUG: _LIBDMR_ not defined. Skipping firstInit."; // Add log for else branch
#endif

#if defined (__mips__) || defined (__aarch64__)
    qDebug() << "MIPS or AARCH64 detected. Setting WA_TransparentForMouseEvents.";
    setAttribute(Qt::WA_TransparentForMouseEvents, true);
#endif
    qDebug() << "Exiting MpvProxy constructor.";
}

MpvProxy::~MpvProxy()
{
    qDebug() << "DEBUG: Entering MpvProxy destructor.";
    disconnect(this, &MpvProxy::has_mpv_events, this, &MpvProxy::handle_mpv_events);
    qDebug() << "DEBUG: Disconnected has_mpv_events signal.";
    m_bConnectStateChange = false;
    disconnect(window()->windowHandle(), &QWindow::windowStateChanged, nullptr, nullptr);
    qDebug() << "DEBUG: Disconnected windowStateChanged signal.";
    if (CompositingManager::get().composited()) {
        qDebug() << "DEBUG: Compositing manager composited. Disconnecting stateChanged and deleting MpvGLwidget.";
        disconnect(this, &MpvProxy::stateChanged, nullptr, nullptr);
        delete m_pMpvGLwidget;
        m_pMpvGLwidget = nullptr;
    } else {
        qDebug() << "DEBUG: Compositing manager not composited. Skipping MpvGLwidget deletion.";
    }
    qDebug() << "DEBUG: Exiting MpvProxy destructor.";
}

void MpvProxy::setDecodeModel(const QVariant &value)
{
    qDebug() << "DEBUG: Entering MpvProxy::setDecodeModel. Value:" << value;
    m_decodeMode = static_cast<DecodeMode>(value.toInt());
    qDebug() << "DEBUG: Exiting MpvProxy::setDecodeModel. Decode mode set to:" << static_cast<int>(m_decodeMode);
}

QVariant MpvProxy::getDecodeModel()
{
    return QVariant(m_decodeMode);
}

void MpvProxy::initMpvFuns()
{
    qInfo() << "Initializing MPV functions";
    QLibrary mpvLibrary(SysUtils::libPath("libmpv.so"));

    m_waitEvent = reinterpret_cast<mpv_waitEvent>(mpvLibrary.resolve("mpv_wait_event"));
    m_setOptionString = reinterpret_cast<mpv_set_optionString>(mpvLibrary.resolve("mpv_set_option_string"));
    m_setProperty = reinterpret_cast<mpv_setProperty>(mpvLibrary.resolve("mpv_set_property"));
    m_setPropertyAsync = reinterpret_cast<mpv_setProperty_async>(mpvLibrary.resolve("mpv_set_property_async"));
    m_commandNode = reinterpret_cast<mpv_commandNode>(mpvLibrary.resolve("mpv_command_node"));
    m_commandNodeAsync = reinterpret_cast<mpv_commandNode_async>(mpvLibrary.resolve("mpv_command_node_async"));
    m_getProperty = reinterpret_cast<mpv_getProperty>(mpvLibrary.resolve("mpv_get_property"));
    m_observeProperty = reinterpret_cast<mpv_observeProperty>(mpvLibrary.resolve("mpv_observe_property"));
    m_eventName = reinterpret_cast<mpv_eventName>(mpvLibrary.resolve("mpv_event_name"));
    m_creat = reinterpret_cast<mpvCreate>(mpvLibrary.resolve("mpv_create"));
    m_requestLogMessage = reinterpret_cast<mpv_requestLog_messages>(mpvLibrary.resolve("mpv_request_log_messages"));
    m_setWakeupCallback = reinterpret_cast<mpv_setWakeup_callback>(mpvLibrary.resolve("mpv_set_wakeup_callback"));
    m_initialize = reinterpret_cast<mpvinitialize>(mpvLibrary.resolve("mpv_initialize"));
    m_freeNodecontents = reinterpret_cast<mpv_freeNode_contents>(mpvLibrary.resolve("mpv_free_node_contents"));
    qDebug() << "DEBUG: MPV function pointers resolved."; // Log after resolving function pointers

    qInfo() << "MPV functions initialized successfully";
}

void MpvProxy::initGpuInfoFuns()
{
    qInfo() << "Initializing GPU info functions";
    if(!SysUtils::libExist("libgpuinfo.so")) {
        qWarning() << "libgpuinfo.so not found - GPU info functions will be unavailable";
        m_gpuInfo = NULL;
        m_gpuInfoVo = NULL;
        qDebug() << "DEBUG: Exiting MpvProxy::initGpuInfoFuns due to missing libgpuinfo.so."; // Add exit log
        return;
    }
    QLibrary mpvLibrary(SysUtils::libPath("libgpuinfo.so"));
    m_gpuInfo = reinterpret_cast<void *>(mpvLibrary.resolve("vdp_Iter_decoderInfo"));
    m_gpuInfoVo = reinterpret_cast<const char* (*)(void)>(mpvLibrary.resolve("gpuinfo_get_vo"));
    if (m_gpuInfo && m_gpuInfoVo) {
        qInfo() << "GPU info functions initialized successfully";
    } else {
        qWarning() << "GPU info functions initialized error";
    }
}

void MpvProxy::firstInit()
{
    qInfo() << "Performing first initialization of MPV proxy";
/*#ifndef _LIBDMR_
#ifdef __x86_64__
   qDebug() << "DEBUG: Running hardware decode check for x86_64."; // Log for hwdec check
   //第一次运行deepin-movie，检测是否支持硬解
   QString procName = QCoreApplication::applicationFilePath();
   QProcess proc;
   proc.start(procName, QStringList() << "hwdec");
   if (!proc.waitForFinished()) {
       qWarning() << "Hardware decode check process failed to finish";
       return;
   }
   //检测进程退出码
   if(proc.exitCode() != QProcess::NormalExit) {
       qWarning() << "Hardware decode check process exited abnormally";
       CompositingManager::setCanHwdec(false);
       qDebug() << "DEBUG: CompositingManager::setCanHwdec set to false due to abnormal exit."; // Log state change
   } else {//检测进程日志输出
       QByteArray result = proc.readAllStandardError();
       qInfo() << "Hardware decode check result:" << result;
       if(result.toLower().contains("not supported")) {
           qInfo() << "Hardware decode not supported";
           CompositingManager::setCanHwdec(false);
           qDebug() << "DEBUG: CompositingManager::setCanHwdec set to false."; // Log state change
       } else {
           qInfo() << "Hardware decode supported";
           CompositingManager::setCanHwdec(true);
           qDebug() << "DEBUG: CompositingManager::setCanHwdec set to true."; // Log state change
       }
   }
#else
   qDebug() << "DEBUG: Hardware decode check skipped for non-x86_64 platform."; // Log for skipped check
#endif
#else
   qDebug() << "DEBUG: _LIBDMR_ defined, skipping hardware decode check."; // Log for _LIBDMR_ case
#endif*/
    initMpvFuns();
    initGpuInfoFuns();
    if (m_creat) {
        qInfo() << "Creating MPV handle";
        m_handle = MpvHandle::fromRawHandle(mpv_init());
        if (CompositingManager::get().composited()) {
            qInfo() << "Creating MPV GL widget";
            m_pMpvGLwidget = new MpvGLWidget(this, m_handle);
            connect(this, &MpvProxy::stateChanged, this, &MpvProxy::slotStateChanged);
            connect(this, &MpvProxy::elapsedChanged, [ this ]() {
                m_pMpvGLwidget->updateMovieProgress(duration(), elapsed());
                QWidget *top = m_pMpvGLwidget->topLevelWidget();
                QVariant v = top ? top->property("showTimeFullScreen") : QVariant();
                if (top && top->isFullScreen() && v.isValid() && v.toBool())
                    m_pMpvGLwidget->update();
            });
#if defined(USE_DXCB)
            qDebug() << "DEBUG: USE_DXCB defined. Toggling rounded clip to false."; // Log for DXCB
            m_pMpvGLwidget->toggleRoundedClip(false);
#else
            qDebug() << "DEBUG: USE_DXCB not defined. Skipping toggleRoundedClip."; // Log for non-DXCB
#endif
            QHBoxLayout *pLayout = new QHBoxLayout(this);
            pLayout->setContentsMargins(0, 0, 0, 0);
            pLayout->addWidget(m_pMpvGLwidget);
            setLayout(pLayout);
            m_pMpvGLwidget->show();
            qDebug() << "DEBUG: MPV GL widget layout configured and shown."; // Log after showing widget
        } else {
            qDebug() << "DEBUG: Compositing manager not composited. Skipping MPV GL widget creation."; // Add log for else branch
        }
    } else {
        qCritical() << "CRITICAL: Failed to create MPV handle. Initialization aborted."; // Add critical log if m_creat is null
    }

    m_bInited = true;
    initSetting();

    // Set fast profile globally for better playback performance
    my_set_property_async(m_handle, "profile", "fast", 0);
    qInfo() << "Set profile to fast for optimized playback";

    qInfo() << "First initialization completed successfully";
}

void MpvProxy::initSetting()
{
    qDebug() << "DEBUG: Entering MpvProxy::initSetting.";
    QMapIterator<QString, QVariant> mapItor(m_mapWaitSet);
    while (mapItor.hasNext()) {
        mapItor.next();
        my_set_property(m_handle, mapItor.key(), mapItor.value());
        qDebug() << "DEBUG: Setting property from m_mapWaitSet:" << mapItor.key() << "=" << mapItor.value();
    }
    qDebug() << "DEBUG: Finished setting properties from m_mapWaitSet.";

    QVectorIterator<QVariant> vecItor(m_vecWaitCommand);
    while (vecItor.hasNext()) {
        my_command(m_handle, vecItor.peekNext());
        vecItor.next();
    }
    qDebug() << "DEBUG: Finished executing commands from m_vecWaitCommand.";
    qDebug() << "DEBUG: Exiting MpvProxy::initSetting.";
}

void MpvProxy::updateRoundClip(bool roundClip)
{
    qDebug() << "DEBUG: Entering MpvProxy::updateRoundClip. Round clip:" << roundClip;
#ifdef __x86_64__
    m_pMpvGLwidget->toggleRoundedClip(roundClip);
    qDebug() << "DEBUG: Toggled rounded clip for MpvGLWidget on x86_64.";
#else
    qDebug() << "DEBUG: Skipping rounded clip toggle for non-x86_64 platform.";
#endif
    qDebug() << "DEBUG: Exiting MpvProxy::updateRoundClip.";
}

mpv_handle *MpvProxy::mpv_init()
{
    qDebug() << "DEBUG: Entering MpvProxy::mpv_init()";
    mpv_handle *pHandle =  static_cast<mpv_handle *>(m_creat());
    if (!pHandle) {
        qCritical() << "CRITICAL: Failed to create mpv handle.";
        return nullptr;
    }
    qDebug() << "DEBUG: MPV handle created successfully.";
    bool composited = CompositingManager::get().composited();
    qDebug() << "DEBUG: MPV handle created. Composited state:" << composited;

    switch (_debugLevel) {
    case DebugLevel::Info:
        m_requestLogMessage(pHandle, "info");
        qDebug() << "DEBUG: MPV log level set to info.";
        break;

    case DebugLevel::Debug:
    case DebugLevel::Verbose:
        my_set_property(pHandle, "terminal", "yes");
        qDebug() << "DEBUG: MPV terminal output enabled.";
        if (_debugLevel == DebugLevel::Verbose) {
            my_set_property(pHandle, "msg-level", "all=status");
            m_requestLogMessage(pHandle, "info");
            qDebug() << "DEBUG: MPV log level set to verbose (all=status).";

        } else {
            my_set_property(pHandle, "msg-level", "all=v");
            m_requestLogMessage(pHandle, "v");
            qDebug() << "DEBUG: MPV log level set to debug (all=v).";
        }
        break;
    default:
        qDebug() << "DEBUG: Unknown debug level. No specific MPV log level set.";
        break;
    }

#ifdef _LIBDMR_
    if (composited) {
        qDebug() << "DEBUG: _LIBDMR_ defined and composited. Setting gpu-hwdec-interop based on QT_XCB_GL_INTERGRATION.";
        auto interop = QString::fromUtf8("vaapi-glx");
        if (!qEnvironmentVariableIsEmpty("QT_XCB_GL_INTERGRATION")) {
            auto gl_int = qgetenv("QT_XCB_GL_INTERGRATION");
            if (gl_int == "xcb_egl") {
                interop = "vaapi-egl";
                qDebug() << "DEBUG: QT_XCB_GL_INTERGRATION set to xcb_egl, interop: vaapi-egl.";
            } else if (gl_int == "xcb_glx") {
                interop = "vaapi-glx";
                qDebug() << "DEBUG: QT_XCB_GL_INTERGRATION set to xcb_glx, interop: vaapi-glx.";
            } else {
                interop = "auto";
                qDebug() << "DEBUG: QT_XCB_GL_INTERGRATION set to unknown value, interop: auto.";
            }
        } else {
            qDebug() << "DEBUG: QT_XCB_GL_INTERGRATION environment variable is empty. Defaulting to vaapi-glx.";
        }
        my_set_property(pHandle, "gpu-hwdec-interop", interop.toUtf8().constData());
        qInfo() << "set gpu-hwdec-interop = " << interop;
    }
    my_set_property(pHandle, "hwdec", "auto");
    qDebug() << "DEBUG: hwdec set to auto for _LIBDMR_.";

#else
    if (composited) {
        qDebug() << "DEBUG: _LIBDMR_ not defined and composited. Setting gpu-hwdec-interop based on settings.";
        auto disable = Settings::get().disableInterop();
        qDebug() << "DEBUG: Interop disabled setting:" << disable;
        auto forced = Settings::get().forcedInterop();
        qDebug() << "DEBUG: Forced interop setting:" << forced;

        auto interop = QString::fromUtf8("auto");
        switch (CompositingManager::get().interopKind()) {
        case OpenGLInteropKind::INTEROP_AUTO:
            interop = QString::fromUtf8("auto");
            qDebug() << "DEBUG: Interop kind: INTEROP_AUTO.";
            break;

        case OpenGLInteropKind::INTEROP_VAAPI_EGL:
            interop = QString::fromUtf8("vaapi-egl");
            qDebug() << "DEBUG: Interop kind: INTEROP_VAAPI_EGL.";
            break;

        case OpenGLInteropKind::INTEROP_VAAPI_GLX:
            interop = QString::fromUtf8("vaapi-glx");
            qDebug() << "DEBUG: Interop kind: INTEROP_VAAPI_GLX.";
            break;

        case OpenGLInteropKind::INTEROP_VDPAU_GLX:
            interop = QString::fromUtf8("vdpau-glx");
            qDebug() << "DEBUG: Interop kind: INTEROP_VDPAU_GLX.";
            break;

        default:
            qDebug() << "DEBUG: Unknown interop kind.";
            break;

        }

        if (!forced.isEmpty()) {
            QStringList valids {"vaapi-egl", "vaapi-glx", "vdpau-glx", "auto"};
            if (valids.contains(forced)) {
                interop = forced;
                qDebug() << "DEBUG: Forced interop value:" << forced;
            } else {
                qWarning() << "WARNING: Invalid forced interop value:" << forced << ". Falling back to detected interop.";
            }
        }

        if (!disable) {
            my_set_property(pHandle, "gpu-hwdec-interop", interop.toUtf8().constData());
            qInfo() << "-------- set gpu-hwdec-interop = " << interop
                    << (forced.isEmpty() ? "[detected]" : "[forced]");
        } else {
            qInfo() << "-------- gpu-hwdec-interop is disabled by user";
        }
    }
#endif

#ifdef __aarch64__
    if (CompositingManager::get().isOnlySoftDecode()) {
        my_set_property(pHandle, "hwdec", "no");
        qDebug() << "DEBUG: AARCH64: Only soft decode enabled, hwdec set to no.";
    } else {
        my_set_property(pHandle, "hwdec", "auto");
        qDebug() << "DEBUG: AARCH64: Soft decode not forced, hwdec set to auto.";
    }
    qInfo() << "modify HWDEC auto";
#endif

    my_set_property(pHandle, "panscan", 1.0);
    qDebug() << "DEBUG: panscan set to 1.0.";

    qInfo() << "DecodeMode:" << m_decodeMode << "(AUTO:0, HARDWARE:1, SOFTWARE:2, CUSTOM:3)";
    if (DecodeMode::SOFTWARE == m_decodeMode) { //1.设置软解
        qDebug() << "DEBUG: Decode mode set to SOFTWARE. Setting hwdec to no.";
        my_set_property(pHandle, "hwdec", "no");
#if defined(_loongarch) || defined(__loongarch__) || defined(__loongarch64)
        if (!CompositingManager::get().hascard()) {
            qInfo() << "修改音视频同步模式";
            my_set_property(pHandle, "video-sync", "desync");
            my_set_property(pHandle, "vo", "x11");
            m_sInitVo = "x11";
        }
#else
        qDebug() << "DEBUG: Not Loongarch, skipping specific video sync settings.";
#endif
    } else if (DecodeMode::AUTO == m_decodeMode) { //2.设置自动
        qDebug() << "DEBUG: Decode mode set to AUTO. Checking for special hardware.";
        //2.1特殊硬件
        //景嘉微显卡目前只支持vo=xv，等日后升级代码需要酌情修改。
        QFileInfo X100GPU("/dev/x100gpu");
        QFileInfo X100VPU("/dev/vxd0");
        QFileInfo mtfi("/dev/mtgpu.0");
        QFile cpuInfo("/proc/cpuinfo");
        bool isVirtualMachine = false;
        if (cpuInfo.open(QIODevice::ReadOnly | QIODevice::Text)) {
            isVirtualMachine = cpuInfo.readAll().contains("hypervisor");
            cpuInfo.close();
            qDebug() << "DEBUG: CPU info checked. Is virtual machine:" << isVirtualMachine;
        } else {
            qWarning() << "WARNING: Failed to open /proc/cpuinfo.";
        }

        //2.1.1景嘉微
        if (utils::isJjwGPUPresent()) {
            qDebug() << "DEBUG: Jingjiawei GPU detected. Checking driver existence.";
            configureJjwGPU(pHandle, true);
        } else if (QFile::exists("/dev/csmcore")) { //2.1.2中船重工
            qDebug() << "DEBUG: CSMCORE detected. Setting vo to xv,x11 and hwdec to auto.";
            my_set_property(pHandle, "vo", "xv,x11");
            my_set_property(pHandle, "hwdec", "auto");
            if (utils::check_wayland_env()) {
                qDebug() << "DEBUG: Wayland environment detected. Setting wid for CSMCORE.";
                my_set_property(pHandle, "wid", m_pParentWidget->winId());
            }
            m_sInitVo = "xv,x11";
        }  else if (X100GPU.exists() && X100VPU.exists()) {
            qDebug() << "DEBUG: X100 GPU and VPU detected. Setting hwdec to ftomx-copy and vo to gpu.";
            my_set_property(m_handle, "hwdec", "ftomx-copy");
            my_set_property(m_handle, "vo", "gpu");
            m_sInitVo = "gpu";
        } else if (CompositingManager::get().isOnlySoftDecode()) {//2.1.3 鲲鹏920 || 曙光+英伟达 || 浪潮
            qDebug() << "DEBUG: Only soft decode enabled. Setting hwdec to no.";
            my_set_property(pHandle, "hwdec", "no");
        } else if (utils::check_wayland_env() && isSpecialHWHardware()) {
            my_set_property(pHandle, "hwdec", "omx-copy");
        } else if (isVirtualMachine) {
            qDebug() << "DEBUG: Virtual machine detected. Setting vo to x11.";
            my_set_property(pHandle, "vo", "x11");
            m_sInitVo = "x11";
        } else { //2.2非特殊硬件
            qDebug() << "DEBUG: No special hardware detected. Setting hwdec to auto.";
            my_set_property(pHandle, "hwdec", "auto");
        }

#if defined (__mips__)
        if (!CompositingManager::get().hascard()) {
            qInfo() << "修改音视频同步模式";
            my_set_property(pHandle, "video-sync", "desync");
        }
        my_set_property(pHandle, "vo", "vdpau,gpu,x11");
        my_set_property(pHandle, "ao", "alsa");
        m_sInitVo = "vdpau,gpu,x11";
#elif defined(_loongarch) || defined(__loongarch__) || defined(__loongarch64)
        if (!CompositingManager::get().hascard()) {
            qInfo() << "修改音视频同步模式";
            my_set_property(pHandle, "video-sync", "desync");
        }
        // 检测特殊机型，使用配置的 VO 渲染
        if (CompositingManager::get().shouldUseSpecialVo()) {
            QString voName = CompositingManager::get().getSpecialVoName();
            my_set_property(pHandle, "vo", voName.toUtf8().constData());
            m_sInitVo = voName;
        } else if (!utils::isJjwGPUPresent() && !mtfi.exists()) {
            if(CompositingManager::get().property("directRendering").toBool()) {
                qDebug() << "DEBUG: Loongarch: Direct rendering enabled. Setting vo to gpu,x11.";
                my_set_property(pHandle, "vo", "gpu,x11");
                m_sInitVo = "gpu,x11";
            } else {
                qDebug() << "DEBUG: Loongarch: Direct rendering disabled. Setting vo to x11.";
                my_set_property(pHandle, "vo", "x11");
                m_sInitVo = "x11";
            }
        } else {
            qDebug() << "DEBUG: Loongarch: Specific hardware detected, skipping direct rendering check.";
        }
#elif defined (__sw_64__)
        qDebug() << "DEBUG: SW_64 defined. Modifying video output.";
        //Synchronously modify the video output of the SW platform vdpau(powered by zhangfl)
        my_set_property(pHandle, "vo", "gpu,x11");
        m_sInitVo = "gpu,x11";
#elif defined (__aarch64__)
        // 检测特殊机型，使用配置的 VO 渲染
        if (CompositingManager::get().shouldUseSpecialVo()) {
            QString voName = CompositingManager::get().getSpecialVoName();
            my_set_property(pHandle, "vo", voName.toUtf8().constData());
            m_sInitVo = voName;
        } else if (!utils::isJjwGPUPresent()) { //2.1.1景嘉微
            qDebug() << "DEBUG: AARCH64: No Jingjiawei GPU detected. Setting vo to x11,gpu,xv.";
            my_set_property(pHandle, "vo", "gpu,xv,x11");
            m_sInitVo = "gpu,xv,x11";
        }
#else
        //去除9200显卡适配
        QFileInfo sjmfi("/dev/jmgpu");
        bool jmflag = false;
        if (sjmfi.exists()) {
            QDir jmdir(QLibraryInfo::location(QLibraryInfo::LibrariesPath) +QDir::separator() +"mwv207");
            if(jmdir.exists())
            {
                jmflag=true;
            }
        }
        //TODO(xxxxpengfei)：暂未处理intel集显情况
        if (CompositingManager::get().isZXIntgraphics() && !jmflag) {
            qDebug() << "DEBUG: ZXIntgraphics detected and no Jingjiawei driver. Checking apt policy.";
            QProcess process;
            process.start("apt", QStringList{"policy", "cx4-linux-graphics-driver-dri"});
            process.waitForFinished();
            process.waitForReadyRead();

            QString comStr = process.readAllStandardOutput();
            // Extract the version number from the second line of apt policy output
            QStringList outputLines = comStr.split('\n');
            comStr = (outputLines.size() >= 2) ? outputLines.at(1) : QString();
            comStr = comStr.right(3).left(2);
            int version = comStr.toInt();
            qDebug() << "DEBUG: apt policy output version:" << version;
            if (version >= 21) { // bug: 285669
                my_set_property(pHandle, "hwdec", "vaapi");
                my_set_property(pHandle, "vo", "gpu");
                m_sInitVo = "gpu";
            } else if (version >= 10) {
                my_set_property(pHandle, "hwdec", "vaapi");
                my_set_property(pHandle, "vo", "vaapi");
                m_sInitVo = "vaapi";
            } else {
                qDebug() << "DEBUG: Version < 10. Setting vo to gpu.";
                my_set_property(pHandle, "vo", "gpu");
                m_sInitVo = "gpu";
            }
        }
#endif
        if (utils::check_wayland_env()) {
            qInfo() << "V25 set ao auto";
            my_set_property(pHandle, "ao", "sdl");
        }

        if (QFile::exists("/sys/bus/pci/drivers/ljmcore")) {
            qDebug() << "DEBUG: Ljmcore driver detected. Setting vo to vaapi and hwdec to vaapi.";
            my_set_property(pHandle, "vo", "vaapi");
            my_set_property(pHandle, "hwdec", "vaapi");
            m_sInitVo = "vaapi";
        }

        if (QFile::exists("/usr/local/ctyun/clink/Mirror/Registry/Default") && !QFile::exists("/dev/mtgpu.0")) {
            qDebug() << "DEBUG: Ctyun clink registry detected. Setting hwdec to no, vo to x11, video-sync to desync, and profile to sw-fast.";
            my_set_property(pHandle, "hwdec", "no");
            my_set_property(pHandle, "vo", "x11");
            my_set_property(pHandle, "video-sync", "desync");
            my_set_property(pHandle, "profile", "sw-fast");
            m_sInitVo = "x11";
        }

        QDir innodir("/sys/bus/platform/drivers/inno-codec");
        if ( innodir.exists()) {
            qDebug() << "DEBUG: Inno-codec driver detected. Setting vo to gpu,x11.";
            my_set_property(pHandle, "vo", "gpu,x11");
            m_sInitVo = "gpu,x11";
        }

        if (CompositingManager::get().isSpecialControls()) {
            my_set_property(pHandle, "hwdec", "vaapi");
            my_set_property(pHandle, "vo", "vaapi");
            m_sInitVo = "vaapi";
        }

        // gpuinfo VO: if matched, use gpuinfo's recommendation (AUTO mode only)
        if (m_gpuInfoVo) {
            const char* vo = m_gpuInfoVo();
            if (vo && vo[0] != '\0') {
                qInfo() << "gpuinfo recommended vo:" << vo;
                my_set_property(pHandle, "vo", vo);
                m_sInitVo = vo;
            }
        }
    } else if (DecodeMode::HARDWARE == m_decodeMode) { //3.设置硬解
        qDebug() << "DEBUG: Decode mode set to HARDWARE. Checking specific hardware.";
        QFileInfo X100GPU("/dev/x100gpu");
        QFileInfo X100VPU("/dev/vxd0");
        //2.1.1景嘉微
        if (utils::isJjwGPUPresent()) {
            qDebug() << "DEBUG: Jingjiawei GPU detected. Checking driver existence.";
            configureJjwGPU(pHandle, true);
        } else if (X100GPU.exists() && X100VPU.exists()) {
            qDebug() << "DEBUG: X100 GPU and VPU detected. Setting hwdec to ftomx-copy and vo to gpu.";
            my_set_property(m_handle, "hwdec", "ftomx-copy");
            my_set_property(m_handle, "vo", "gpu");
        } else if (utils::check_wayland_env() && isSpecialHWHardware()) {
            my_set_property(pHandle, "hwdec", "omx-copy");
        } else {
            qDebug() << "DEBUG: No special GPU detected. Setting hwdec to auto.";
            my_set_property(pHandle, "hwdec", "auto");
        }

#if defined (__sw_64__)
        qDebug() << "DEBUG: SW_64 defined. Modifying video output.";
        //Synchronously modify the video output of the SW platform vdpau(powered by zhangfl)
        my_set_property(pHandle, "vo", "gpu,x11");
        m_sInitVo = "gpu,x11";
#elif defined(_loongarch) || defined(__loongarch__) || defined(__loongarch64)
        if (!CompositingManager::get().hascard()) {
            qInfo() << "修改音视频同步模式";
            my_set_property(pHandle, "video-sync", "desync");
        }
        if (!utils::isJjwGPUPresent()) {
            if(CompositingManager::get().property("directRendering").toBool()) {
                qDebug() << "DEBUG: Loongarch: Direct rendering enabled. Setting vo to gpu,x11.";
                my_set_property(pHandle, "vo", "gpu,x11");
                m_sInitVo = "gpu,x11";
            } else {
                qDebug() << "DEBUG: Loongarch: Direct rendering disabled. Setting vo to x11.";
                my_set_property(pHandle, "vo", "x11");
                m_sInitVo = "x11";
            }
        } else {
            qDebug() << "DEBUG: Loongarch: Specific hardware detected, skipping direct rendering check.";
        }
#endif
        if (QFile::exists("/usr/local/ctyun/clink/Mirror/Registry/Default") && !QFile::exists("/dev/mtgpu.0")) {
            qDebug() << "DEBUG: Ctyun clink registry detected. Setting hwdec to no and vo to x11.";
            my_set_property(pHandle, "hwdec", "no");
            my_set_property(pHandle, "vo", "x11");
            my_set_property(pHandle, "video-sync", "desync");
            my_set_property(pHandle, "profile", "sw-fast");
            m_sInitVo = "x11";
        }

        QDir innodir("/sys/bus/platform/drivers/inno-codec");
        if ( innodir.exists()) {
            qDebug() << "DEBUG: Inno-codec driver detected. Setting vo to gpu,x11.";
            my_set_property(pHandle, "vo", "gpu,x11");
            m_sInitVo = "gpu,x11";
        }
        if (QFile::exists("/sys/bus/pci/drivers/ljmcore")) {
            qDebug() << "DEBUG: Ljmcore driver detected. Setting vo to vaapi and hwdec to vaapi.";
            my_set_property(pHandle, "vo", "vaapi");
            my_set_property(pHandle, "hwdec", "vaapi");
            m_sInitVo = "vaapi";
        }

        if (CompositingManager::get().isSpecialControls()) {
            qDebug() << "DEBUG: Special controls detected. Setting hwdec to vaapi and vo to vaapi.";
            my_set_property(pHandle, "hwdec", "vaapi");
            my_set_property(pHandle, "vo", "vaapi");
            m_sInitVo = "vaapi";
        }
    }

    if (composited) {
#ifdef __mips__
        m_setOptionString(pHandle, "vo", "opengl-cb");
        m_setOptionString(pHandle, "hwdec-preload", "auto");
        m_setOptionString(pHandle, "opengl-hwdec-interop", "auto");
        m_setOptionString(pHandle, "hwdec", "auto");
        qInfo() << "-------- __mips__hwdec____________";
        m_sInitVo = "opengl-cb";
#else
        my_set_property(pHandle, "vo", "libmpv");
        my_set_property(pHandle, "vd-lavc-dr", "no");
        my_set_property(pHandle, "gpu-sw", "on");
        m_sInitVo = "libmpv";
        qDebug() << "DEBUG: Not MIPS, composited. Setting vo to libmpv, vd-lavc-dr to no, gpu-sw to on.";
#endif
    } else {
        my_set_property(pHandle, "wid", m_pParentWidget->winId());
        qDebug() << "DEBUG: Not composited. Setting wid to parent widget's winId.";
    }


    if (QFile::exists("/usr/local/ctyun/clink/Mirror/Registry/Default")) {
        my_set_property(pHandle, "update-on-pause", "yes");
        qDebug() << "DEBUG: Ctyun clink registry detected. Setting update-on-pause to yes.";
    }

    qInfo() << __func__ << "vo:" << my_get_property(pHandle, "vo").toString();
    qInfo() << __func__  << "hwdec:" << my_get_property(pHandle, "hwdec").toString();

    QString strMovie = QObject::tr("Movie");
    //设置音量名称
    my_set_property(pHandle, "audio-client-name", strMovie);
    qDebug() << "DEBUG: Audio client name set to:" << strMovie;
    //my_set_property(pHandle, "keepaspect-window", "no");
    //设置视频固定帧率，暂时无效
    //my_set_property(pHandle, "correct-pts", false);
    //my_set_property(pHandle, "fps", 30);
    my_set_property(pHandle, "panscan", 0);
    my_set_property(pHandle, "volume-max", 200.0);
    my_set_property(pHandle, "input-cursor", "no");
    my_set_property(pHandle, "cursor-autohide", "no");
    my_set_property(pHandle, "sub-auto", "fuzzy");
    my_set_property(pHandle, "sub-visibility", "true");
    my_set_property(pHandle, "sub-pos", 100);
    my_set_property(pHandle, "sub-margin-y", 36);
    my_set_property(pHandle, "sub-border-size", 0);
    my_set_property(pHandle, "screenshot-template", "deepin-movie-shot%n");
    my_set_property(pHandle, "screenshot-directory", "/tmp");
    my_set_property(pHandle, "vd-queue-enable","no");
    my_set_property(pHandle, "stop-screensaver", "no"); // 屏幕保护逻辑影院自己控制，不由mpv控制
    qDebug() << "DEBUG: Basic MPV properties set.";

#ifndef _LIBDMR_
    if (Settings::get().isSet(Settings::ResumeFromLast)) {
        my_set_property(pHandle, "save-position-on-quit", true);
        qDebug() << "DEBUG: Resume from last position enabled.";
    } else {
        qDebug() << "DEBUG: Resume from last position disabled.";
    }
#else
    qDebug() << "DEBUG: _LIBDMR_ defined, skipping resume from last position setting.";
#endif

    //only to get notification without data
    m_observeProperty(pHandle, 0, "time-pos", MPV_FORMAT_INT64); //playback-time ?
    m_observeProperty(pHandle, 0, "pause", MPV_FORMAT_FLAG);
    m_observeProperty(pHandle, 0, "mute", MPV_FORMAT_NONE);
    m_observeProperty(pHandle, 0, "volume", MPV_FORMAT_NONE); //ao-volume ?
    m_observeProperty(pHandle, 0, "sid", MPV_FORMAT_NONE);
    m_observeProperty(pHandle, 0, "aid", MPV_FORMAT_NODE);
    m_observeProperty(pHandle, 0, "dwidth", MPV_FORMAT_NODE);
    m_observeProperty(pHandle, 0, "dheight", MPV_FORMAT_NODE);
    qDebug() << "DEBUG: MPV properties observed (time-pos, pause, mute, volume, sid, aid, dwidth, dheight).";

    // because of vpu, we need to implement playlist w/o mpv
    //m_observeProperty(pHandle, 0, "playlist-pos", MPV_FORMAT_NONE);
    //m_observeProperty(pHandle, 0, "playlist-count", MPV_FORMAT_NONE);
    m_observeProperty(pHandle, 0, "core-idle", MPV_FORMAT_NODE);
    m_observeProperty(pHandle, 0, "paused-for-cache", MPV_FORMAT_FLAG);
    m_observeProperty(pHandle, 0, "idle-active", MPV_FORMAT_FLAG);
    qDebug() << "DEBUG: MPV properties observed (core-idle, paused-for-cache, idle-active).";

    m_setWakeupCallback(pHandle, mpv_callback, this);
    connect(this, &MpvProxy::has_mpv_events, this, &MpvProxy::handle_mpv_events,
            Qt::DirectConnection);
    qDebug() << "DEBUG: MPV wakeup callback set and has_mpv_events connected.";
    if (m_initialize(pHandle) < 0) {
        qCritical() << "CRITICAL: MPV initialization failed.";
        std::runtime_error("mpv init failed");
    }
    qDebug() << "DEBUG: MPV initialization successful. Loading profile.";

    //load profile
    auto ol = CompositingManager::get().getBestProfile();
    qDebug() << "DEBUG: Loading best profile. Profile size:" << ol.size();
    auto p = ol.begin();
    while (p != ol.end()) {
        if (!p->first.startsWith("#")) {
            qDebug() << "DEBUG: Applying profile property:" << p->first << "=" << p->second;
#if !defined (__mips__ ) && !defined(__aarch64__) && !defined(__sw_64__)
#ifdef MWV206_0
            //景嘉微显卡目前只支持vo=xv，等日后升级代码需要酌情修改。
            if (!utils::isJjwGPUPresent()) {
                my_set_property(pHandle, p->first.toUtf8().constData(), p->second.toUtf8().constData());
                qInfo() << "apply" << p->first << "=" << p->second;
            }
#else
            my_set_property(pHandle, p->first.toUtf8().constData(), p->second.toUtf8().constData());
            qInfo() << "apply" << p->first << "=" << p->second;
#endif
#else
            qDebug() << "DEBUG: Skipping profile application for specific architectures.";
#endif
        } else {
            qInfo() << "ignore(commented out)" << p->first << "=" << p->second;
        }
        ++p;
    }
    qDebug() << "DEBUG: Finished applying best profile.";

#ifndef USE_TEST
    // Wayland-only: pulse 禁止挂起。单测跑在 X11/Xvfb 下，check_wayland_env() 恒为
    // false，此块永不执行；按 cold-block 约定用 #ifndef USE_TEST 排除出测试构建。
    if(utils::check_wayland_env()) {
        my_set_property(pHandle, "pulse-allow-suspended", "yes");
    }
#endif // USE_TEST
    //设置hwdec和vo配置
    CompositingManager::get().getMpvConfig(m_pConfig);
    qDebug() << "DEBUG: MPV config retrieved for hwdec and vo settings.";
#ifndef _LIBDMR_
    if (Settings::get().settings()->getOption(QString("base.decode.select")).toInt() == DecodeMode::CUSTOM) {
        qDebug() << "DEBUG: Custom decode settings enabled.";
        int decodeIndex = Settings::get().settings()->getOption(QString("base.decode.Decodemode")).toInt();
        auto decodeModeOpt = Settings::get().settings()->option("base.decode.Decodemode");
        QString decodeMode = decodeModeOpt.data()->data("items").toStringList()[decodeIndex];
        decodeMode = decodeMode.isEmpty() ? "auto" : decodeMode;
        m_pConfig->insert("hwdec", decodeMode);
        qDebug() << "DEBUG: hwdec set to:" << decodeMode;
        if (decodeMode == "vaapi-copy") {
            my_set_property(pHandle, "vd-queue-enable","yes");
        }

        if (!CompositingManager::get().composited()) {
            qDebug() << "DEBUG: Not composited, setting vo from custom decode settings.";
            int voIndex = Settings::get().settings()->getOption(QString("base.decode.Videoout")).toInt();
            auto voOpt = Settings::get().settings()->option("base.decode.Videoout");
            QString voMode = voOpt.data()->data("items").toStringList()[voIndex];
            voMode = voMode.isEmpty() ? "auto" : voMode;
            m_pConfig->insert("vo", voMode);
            qDebug() << "DEBUG: vo set to:" << voMode;
        } else {
            qDebug() << "DEBUG: Composited, skipping vo setting from custom decode settings.";
        }
    } else {
        qDebug() << "DEBUG: Custom decode settings disabled.";
    }
#else
    qDebug() << "DEBUG: _LIBDMR_ defined, skipping custom decode settings.";
#endif
    QMap<QString, QString>::iterator iter = m_pConfig->begin();
    qInfo() << __func__ << "First set mpv propertys!!";
    while (iter != m_pConfig->end()) {
        my_set_property(pHandle, iter.key(), iter.value());
        qDebug() << "DEBUG: Setting mpv property from config:" << iter.key() << "=\"" << iter.value() << "\";";
        iter++;
    }
    qDebug() << "DEBUG: Finished setting mpv properties from config.";

    // Initialize property cache to avoid synchronous API calls during event handling
    initPropertyCache(pHandle);

    // Set fast profile globally for better playback performance
    my_set_property_async(pHandle, "profile", "fast", 0);
    qInfo() << "Set profile to fast for optimized playback";

    qDebug() << "DEBUG: Exiting MpvProxy::mpv_init() with handle:" << pHandle;
    return pHandle;
}

void MpvProxy::initPropertyCache(mpv_handle *pHandle)
{
    qDebug() << "Initializing property cache with mpv_observe_property";

    // Register observers for properties that are accessed during event handling
    // When these properties change, mpv will send MPV_EVENT_PROPERTY_CHANGE events
    // Note: time-pos is already observed in mpv_init() with MPV_FORMAT_INT64
    m_observeProperty(pHandle, 0, "duration", MPV_FORMAT_INT64);
    m_observeProperty(pHandle, 0, "volume", MPV_FORMAT_INT64);
    m_observeProperty(pHandle, 0, "mute", MPV_FORMAT_FLAG);
    m_observeProperty(pHandle, 0, "aid", MPV_FORMAT_INT64);
    m_observeProperty(pHandle, 0, "sid", MPV_FORMAT_INT64);
    m_observeProperty(pHandle, 0, "dwidth", MPV_FORMAT_INT64);
    m_observeProperty(pHandle, 0, "dheight", MPV_FORMAT_INT64);
    m_observeProperty(pHandle, 0, "video-out-params/rotate", MPV_FORMAT_INT64);

    qDebug() << "Property cache initialization completed";
}

void MpvProxy::updatePropertyCache(const QString &name, const QVariant &value)
{
    if (name == "duration") {
        m_cachedDuration = value.toLongLong();
        qDebug() << "Cache updated: duration =" << m_cachedDuration;
    } else if (name == "time-pos") {
        m_cachedElapsed = value.toLongLong();
    } else if (name == "volume") {
        m_cachedVolume = value.toInt();
    } else if (name == "mute") {
        m_cachedMute = value.toBool();
    } else if (name == "aid") {
        m_cachedAid = value.toInt();
    } else if (name == "sid") {
        m_cachedSid = value.toInt();
    } else if (name == "dwidth") {
        m_cachedVideoSize.setWidth(value.toInt());
    } else if (name == "dheight") {
        m_cachedVideoSize.setHeight(value.toInt());
    } else if (name == "video-out-params/rotate") {
        int rotate = value.toInt();
        if (rotate == 90 || rotate == 270) {
            m_cachedVideoSize.transpose();
        }
    } else if (name == "pause") {
        m_cachedPause = value.toBool();
    } else if (name == "idle-active") {
        m_cachedIdleActive = value.toBool();
    } else if (name == "paused-for-cache") {
        m_cachedPausedForCache = value.toBool();
    }
}

void MpvProxy::setState(PlayState state)
{
    qInfo() << "Setting play state to:" << static_cast<int>(state);
    bool bRawFormat = false;

    if (0 < dynamic_cast<PlayerEngine *>(m_pParentWidget)->getplaylist()->size()) {
        PlayItemInfo currentInfo = dynamic_cast<PlayerEngine *>(m_pParentWidget)->getplaylist()->currentInfo();
        bRawFormat = currentInfo.mi.isRawFormat();
    }

    if (_state != state) {
        _state = state;
        if (m_pMpvGLwidget) {
            m_pMpvGLwidget->setPlaying(state != PlayState::Stopped);
        }
        // Delay signal emission to avoid deadlock during mpv event handling
        QTimer::singleShot(0, this, [this]() {
            emit stateChanged();
        });
        qInfo() << "Play state changed to:" << static_cast<int>(state);
    }

    if (m_pMpvGLwidget) {
        m_pMpvGLwidget->setRawFormatFlag(bRawFormat);
    }
}

void MpvProxy::pollingEndOfPlayback()
{
    if (_state != Backend::Stopped) {
        m_bPolling = true;
        blockSignals(true);
        stop();

        // Add timeout protection to avoid deadlock
        int nTimeout = 0;

        while (_state != Backend::Stopped && nTimeout < POLLING_END_TIMEOUT) {
            mpv_event *pEvent = m_waitEvent(m_handle, 0.005);
            nTimeout++;

            if (pEvent->event_id == MPV_EVENT_NONE)
                continue;

            if (pEvent->event_id == MPV_EVENT_END_FILE) {
                blockSignals(false);
                setState(Backend::Stopped);
                break;
            }
        }

        if (nTimeout >= POLLING_END_TIMEOUT) {
            qWarning() << "pollingEndOfPlayback timeout, forcing stop";
            blockSignals(false);
            setState(Backend::Stopped);
        }

        m_bPolling = false;
    }
}

const PlayingMovieInfo &MpvProxy::playingMovieInfo()
{
    return m_movieInfo;
}

/**
 * @return 返回当前设备是否为特殊的HW设备类型,用于进行软/硬解码支持的判断
 */
bool isSpecialHWHardware()
{
    enum HWDevice { Unknown, IsHWDev, NotHWDev };
    static HWDevice s_DevType = Unknown;

#ifdef DTKCORE_CLASS_DConfigFile
    DTK_CORE_NAMESPACE::DConfig *dconfig = DTK_CORE_NAMESPACE::DConfig::create("org.deepin.movie","org.deepin.movie.specialhwdec");
    if(dconfig && dconfig->isValid() && dconfig->keyList().contains("IsSpecialHWDec")){
        if (dconfig->value("IsSpecialHWDec").toBool()) {
            delete dconfig;
            return true;
        }
    }
    delete dconfig;
#endif

    if (!utils::check_wayland_env())
        return false;

    if (Unknown == s_DevType) {
        s_DevType = NotHWDev;

        QProcess process;
        process.start("dmidecode", {"-s", "system-product-name"});
        process.waitForFinished(100);
        QString info = process.readAllStandardOutput();
        if (info.isEmpty()) {
            return false;
        }

        QStringList specialDev {"KLVV", "KLVU", "PGUV", "PGUW", "L540", "W585", "L420"};
        for (const QString &dev : specialDev) {
            if (info.contains(dev)) {
                s_DevType = IsHWDev;
                break;
            }
        }

        if (NotHWDev == s_DevType) {
            // dmidecode | grep -i “String 4”中的值来区分主板类型,PWC30表示PanguW（也就是W525）
            QStringList sList = dmr::utils::runPipeProcess("dmidecode -t 11", "String 4");
            foreach(info, sList) {
                if (info.contains("PWC30") || info.contains("PGUX")) {
                    s_DevType = IsHWDev;
                    break;
                }
            }
        }

        qInfo() << QString("Detect HW device, current type is: %1").arg((IsHWDev == s_DevType) ? "true" : "false");
    }

    return bool(s_DevType == IsHWDev);
}

bool MpvProxy::isSupportHardWareDecode(const QString sDecodeName, const int &nVideoWidth, const int &nVideoHeight)
{
    // FIXME: gpuinfo crash on treeland, so force soft decode on treeland
#ifndef USE_TEST
    // Wayland-only: 强制软解。测试环境为 X11，此块恒不进入；排除出测试构建。
    if (utils::check_wayland_env()) {
        qInfo() << "Wayland environment detected, forcing soft decode";
        return false;
    }
#endif // USE_TEST

    if (isSpecialHWHardware()) {
        qInfo() << "Wayland environment detected, special HW device, hardware decode";
        return true;
    }

    bool isHardWare = true;//未安装探测工具默认支持硬解
    decoder_profile decoderValue = decoder_profile::UN_KNOW; //初始化支持解码值
    decoderValue = (decoder_profile)getDecodeProbeValue(sDecodeName); //根据视频格式获取解码值
    if(decoderValue != decoder_profile::UN_KNOW ) {//开始探测是否支持硬解码
        VDP_Decoder_t *probeDecode = new VDP_Decoder_t;
        if(m_gpuInfo) {
            int nSupport =  ((gpu_decoderInfo)m_gpuInfo)(decoderValue, probeDecode);
            isHardWare = (nSupport > 0 && probeDecode->max_width >= nVideoWidth
                    &&  probeDecode->max_height >= nVideoHeight);//nSupport大于0表示支持，硬解码支持的最大宽高必须大于或等于视频的宽高
        }
        delete probeDecode;
    }
    return isHardWare;
}

int MpvProxy::getDecodeProbeValue(const QString sDecodeName)
{
    QStringList sNameList;
    sNameList << "MPEG1" << "MPEG2" << "MPEG4" << "H264" << "VC1" << "DIVX4" << "DIVX5" << "HEVC";
    int nCount = sNameList.count();
    for(int i = 0; i < nCount; i++ ){//匹配硬解支持的视频格式
        QString sValue = sNameList.at(i);
        if(sDecodeName.toUpper().contains(sValue)) {
            return (int)decoder_profile(decoder_profile::UN_KNOW + 1 + i);
        }
    }
    return (int)decoder_profile::UN_KNOW;
}

void MpvProxy::configureJjwGPU(mpv_handle *pHandle, bool setInitVo)
{
    QDir sdir(QLibraryInfo::location(QLibraryInfo::LibrariesPath) + QDir::separator() + "mwv206"); //判断是否安装核外驱动
    QDir jmdir(QLibraryInfo::location(QLibraryInfo::LibrariesPath) + QDir::separator() + "mwv207");
    QString jjwPath = utils::getJjwGPUPath();
    QString vo = m_sInitVo;

    if (sdir.exists() && jjwPath == "/dev/mwv206_0") {
        my_set_property(pHandle, "hwdec", "vdpau");
        my_set_property(pHandle, "vo", "vdpau");
        vo = "vdpau";
    } else if ((jjwPath == "/dev/jmgpu" && jmdir.exists()) || jjwPath == "mwv207d") {
        my_set_property(pHandle, "hwdec", "vaapi");
        my_set_property(pHandle, "vo", "vaapi");
        vo = "vaapi";
    } else {
        my_set_property(pHandle, "hwdec", "auto");
        my_set_property(pHandle, "vo", "vdpau,xv,x11");
        vo = "vdpau,xv,x11";
    }

    if (setInitVo)
        m_sInitVo = vo;
}

void MpvProxy::handle_mpv_events()
{
#ifndef USE_TEST
    // Wayland+test-mode: 跳过 mpv 事件处理。测试环境 check_wayland_env() 为 false，
    // 此块恒不进入；排除出测试构建。
    if (utils::check_wayland_env() && CompositingManager::get().isTestFlag()) {
        qInfo() << "Skipping MPV event handling in test mode";
        return;
    }
#endif // USE_TEST
    while (1) {
        mpv_event *pEvent = m_waitEvent(m_handle, 0.0005);
        if (pEvent->event_id == MPV_EVENT_NONE)
            break;

        switch (pEvent->event_id) {
        case MPV_EVENT_LOG_MESSAGE:
            processLogMessage(reinterpret_cast<mpv_event_log_message *>(pEvent->data));
            break;

        case MPV_EVENT_PROPERTY_CHANGE:
            processPropertyChange(reinterpret_cast<mpv_event_property *>(pEvent->data));
            break;

        case MPV_EVENT_COMMAND_REPLY:
            if (pEvent->error < 0) {
                qWarning() << "Command error:" << pEvent->error;
            }

            if (pEvent->reply_userdata == AsyncReplyTag::SEEK) {
                m_bPendingSeek = false;
                qInfo() << "Seek operation completed";
            }
            break;

        case MPV_EVENT_PLAYBACK_RESTART:
            // caused by seek or just playing
            break;

#if MPV_CLIENT_API_VERSION < MPV_MAKE_VERSION(2,0)
        case MPV_EVENT_TRACKS_CHANGED:
            qInfo() << m_eventName(pEvent->event_id);
            // Delay to avoid synchronous API calls during event handling
            QTimer::singleShot(50, this, [this]() {
                updatePlayingMovieInfo();
                emit tracksChanged();
            });
            break;
#endif

        case MPV_EVENT_FILE_LOADED: {
            qInfo() << m_eventName(pEvent->event_id);

            // Note: hwdec-interop, video-codec, video-format logging removed to avoid synchronous API calls
#if MPV_CLIENT_API_VERSION > MPV_MAKE_VERSION(2,0)
            // Delay to avoid synchronous API calls during event handling
            QTimer::singleShot(50, this, [this]() {
                updatePlayingMovieInfo();
                emit tracksChanged();
            });
#endif
//            if (!m_bIsJingJia) {
//#ifdef __mips__
//                qInfo() << "MPV_EVENT_FILE_LOADED __mips__";
//                QString sCodec = my_get_property(m_handle, "video-codec").toString();
//                auto name = my_get_property(m_handle, "filename").toString();
//                if (sCodec.toLower().contains("wmv3") || sCodec.toLower().contains("wmv2") || sCodec.toLower().contains("mpeg2video") ||
//                        name.toLower().contains("wmv")) {
//                    qInfo() << "my_set_property hwdec no";
//                    my_set_property(m_handle, "hwdec", "no");
//                }
//#endif
//#ifdef __aarch64__
//                qInfo() << "MPV_EVENT_FILE_LOADED aarch64";
//                QString sCodec = my_get_property(m_handle, "video-codec").toString();
//                if (sCodec.toLower().contains("wmv3") || sCodec.toLower().contains("wmv2") || sCodec.toLower().contains("mpeg2video")) {
//                    qInfo() << "my_set_property hwdec auto";
//                    if (CompositingManager::get().isOnlySoftDecode()) {
//                        my_set_property(m_handle, "hwdec", "off");
//                    } else {
//                        my_set_property(m_handle, "hwdec", "auto");
//                    }
//                }
//#endif
//            }
            //设置播放参数 - use async to avoid deadlock
            QMap<QString, QString>::iterator iter = m_pConfig->begin();
            qInfo() << __func__ << "Set mpv propertys (async)!!";
            while (iter != m_pConfig->end()) {
                my_set_property_async(m_handle, iter.key(), iter.value(), 0);
                iter++;
            }

            setState(PlayState::Playing); //might paused immediately
            // Delay signal emission to avoid synchronous API calls during event handling
            QTimer::singleShot(0, this, [this]() {
                emit fileLoaded();
            });
            // Note: rotation metadata logging removed to avoid synchronous API calls
            m_bLoadMedia = false;
#ifndef USE_TEST
            // Wayland-only: 切回默认音频 sink。测试环境恒不进入；排除出测试构建。
            if(utils::check_wayland_env()) {
                dmr::utils::switchToDefaultSink();
            }
#endif // USE_TEST
            break;
        }
        case MPV_EVENT_VIDEO_RECONFIG: {
            // Use QTimer to delay signal emission to avoid deadlock
            QTimer::singleShot(0, this, [this]() {
                QSize size = videoSize();
                if (!size.isEmpty())
                    emit videoSizeChanged();
            });
            break;
        }

        case MPV_EVENT_END_FILE: {
#ifndef _LIBDMR_
            MovieConfiguration::get().updateUrl(this->_file,
                                                ConfigKnownKey::StartPos, 0);
#endif
            mpv_event_end_file *ev_ef = reinterpret_cast<mpv_event_end_file *>(pEvent->data);
            qInfo() << m_eventName(pEvent->event_id) <<
                    "reason " << ev_ef->reason;

            setState(PlayState::Stopped);
//            m_bLoadMedia = false;
            break;
        }

        case MPV_EVENT_IDLE:
            qInfo() << m_eventName(pEvent->event_id);
            setState(PlayState::Stopped);
            // Delay signal emission to avoid synchronous API calls during event handling
            QTimer::singleShot(0, this, [this]() {
                emit elapsedChanged();
            });
            break;

        default:
            qInfo() << "Unhandled MPV event:" << m_eventName(pEvent->event_id);
            break;
        }
    }
}

void MpvProxy::processLogMessage(mpv_event_log_message *pEvent)
{
    switch (pEvent->log_level) {
    case MPV_LOG_LEVEL_WARN:
        qWarning() << QString("%1: %2").arg(pEvent->prefix).arg(pEvent->text);
        emit mpvWarningLogsChanged(QString(pEvent->prefix), QString(pEvent->text));
        break;

    case MPV_LOG_LEVEL_ERROR:
    case MPV_LOG_LEVEL_FATAL: {
        QString strError = pEvent->text;
        if (strError.contains("Failed setup for format vdpau")) {
            m_bLastIsSpecificFormat = true;
        }
        qCritical() << QString("%1: %2").arg(pEvent->prefix).arg(strError);
        emit mpvErrorLogsChanged(QString(pEvent->prefix), strError);
    }
    break;

    case MPV_LOG_LEVEL_INFO:
        qInfo() << QString("%1: %2").arg(pEvent->prefix).arg(pEvent->text);
        break;

    default:
        qInfo() << QString("%1: %2").arg(pEvent->prefix).arg(pEvent->text);
        break;
    }
}

void MpvProxy::processPropertyChange(mpv_event_property *pEvent)
{
    QString sName = QString::fromUtf8(pEvent->name);
    if (sName != "time-pos") qInfo() << sName;

    // Update property cache first to avoid synchronous API calls later
    if (pEvent->data) {
        QVariant value;
        if (pEvent->format == MPV_FORMAT_INT64) {
            value = QVariant::fromValue<qint64>(*static_cast<qint64 *>(pEvent->data));
        } else if (pEvent->format == MPV_FORMAT_DOUBLE) {
            value = QVariant(*static_cast<double *>(pEvent->data));
        } else if (pEvent->format == MPV_FORMAT_FLAG) {
            value = QVariant(*static_cast<int *>(pEvent->data) != 0);
        } else if (pEvent->format == MPV_FORMAT_STRING) {
            value = QVariant(QString::fromUtf8(*static_cast<char **>(pEvent->data)));
        }
        updatePropertyCache(sName, value);
    }

    // 使用 QPointer 检查对象是否还存在
    QPointer<MpvProxy> self(this);
    QTimer::singleShot(0, [this, sName, self]() {
        if (self.isNull()) {
            qWarning() << "MpvProxy obj is destroyed";
            return; // 对象已被销毁
        }

        processPropertyChange(sName);
    });
}

void MpvProxy::processPropertyChange(const QString &name)
{
    if (name == "time-pos") {
        emit elapsedChanged();
    } else if (name == "volume") {
        emit volumeChanged();
    } else if (name == "dwidth" || name == "dheight") {
        // Use QTimer to delay signal emission to avoid deadlock
        QTimer::singleShot(0, this, [this]() {
            QSize size = videoSize();
            if (!size.isEmpty())
                emit videoSizeChanged();
            qInfo() << "update videoSize " << size;
        });
    } else if (name == "aid") {
        emit aidChanged();
    } else if (name == "sid") {
        emit sidChanged();
    } else if (name == "mute") {
        emit muteChanged();
    } else if (name == "sub-visibility") {
        //_hideSub = my_get_property(m_handle, "sub-visibility")
    } else if (name == "pause") {
        // Use cached values to avoid synchronous API calls
        QTimer::singleShot(0, this, [this]() {
            if (m_cachedPause) {
                if (!m_cachedIdleActive)
                    setState(PlayState::Paused);
                else
                    my_set_property_async(m_handle, "pause", false, 0);
            } else {
                if (state() != PlayState::Stopped) {
                    setState(PlayState::Playing);
                }
            }
        });
    } else if (name == "core-idle") {
    } else if (name == "paused-for-cache") {
        // Use cached value to avoid synchronous API calls
        QTimer::singleShot(0, this, [this]() {
            qInfo() << "paused-for-cache" << m_cachedPausedForCache;
            emit urlpause(m_cachedPausedForCache);
        });
    }
}

bool MpvProxy::loadSubtitle(const QFileInfo &fileInfo)
{
    //movie could be in an inner state that marked as Stopped when loadfile executes
    //if (state() == PlayState::Stopped) { return true; }
    if (!fileInfo.exists())
        return false;

    QList<QVariant> args = { "sub-add", fileInfo.absoluteFilePath(), "select" };
    qInfo() << args;
    my_command_async(m_handle, args, 0);

    // Delay update to allow mpv to process the sub-add command and avoid deadlock
    QTimer::singleShot(100, this, [this]() {
        updatePlayingMovieInfo();
    });

    // by settings this flag, we can match the corresponding sid change and save it
    // in the movie database
    return true;
}

bool MpvProxy::isSubVisible()
{
    return my_get_property(m_handle, "sub-visibility").toBool();
}

void MpvProxy::setSubDelay(double dSecs)
{
    my_set_property(m_handle, "sub-delay", dSecs);
#ifndef _LIBDMR_
    MovieConfiguration::get().updateUrl(_file, ConfigKnownKey::SubDelay, subDelay());
#endif
}

double MpvProxy::subDelay() const
{
    return my_get_property(m_handle, "sub-delay").toDouble();
}

QString MpvProxy::subCodepage()
{
    auto cp = my_get_property(m_handle, "sub-codepage").toString();
    if (cp.startsWith("+")) {
        cp.remove(0, 1);
    }

    return cp;
}

void MpvProxy::addSubSearchPath(const QString &sPath)
{
    my_set_property(m_handle, "sub-paths", sPath);
    my_set_property(m_handle, "sub-file-paths", sPath);
}

void MpvProxy::setSubCodepage(const QString &sCodePage)
{
    QString strTmp = sCodePage;
    if (!sCodePage.startsWith("+") && sCodePage != "auto")
        strTmp.prepend('+');

    my_set_property(m_handle, "sub-codepage", strTmp);
    my_command(m_handle, {"sub-reload"});
#ifndef _LIBDMR_
    if (_file.isValid())
        MovieConfiguration::get().updateUrl(_file, ConfigKnownKey::SubCodepage, subCodepage());
#endif
}

void MpvProxy::updateSubStyle(const QString &sFont, int nSize)
{
    my_set_property(m_handle, "sub-font", sFont);
    my_set_property(m_handle, "sub-font-size", nSize);
    my_set_property(m_handle, "sub-color", "#FFFFFF");
    my_set_property(m_handle, "sub-border-size", 1);
    my_set_property(m_handle, "sub-border-color", "0.0/0.0/0.0/0.50");
    my_set_property(m_handle, "sub-shadow-offset", 1);
    my_set_property(m_handle, "sub-shadow-color", "0.0/0.0/0.0/0.50");
}

void MpvProxy::showEvent(QShowEvent *pEvent)
{
    if (!m_bConnectStateChange) {
        m_bConnectStateChange = true;
    }
    Backend::showEvent(pEvent);
}

void MpvProxy::resizeEvent(QResizeEvent *pEvent)
{
    if (state() == PlayState::Stopped) {
        return;
    }
    Backend::resizeEvent(pEvent);
}

void MpvProxy::savePlaybackPosition()
{
    if (state() == PlayState::Stopped) {
        return;
    }

#ifndef _LIBDMR_
    MovieConfiguration::get().updateUrl(this->_file, ConfigKnownKey::SubId, sid());
    if (duration() - elapsed() >= 5) {
        MovieConfiguration::get().updateUrl(this->_file, ConfigKnownKey::StartPos, elapsed());
    } else {
        MovieConfiguration::get().updateUrl(this->_file, ConfigKnownKey::StartPos, elapsed() - 1);
    }
#endif
}

void MpvProxy::setPlaySpeed(double dTimes)
{
    my_set_property_async(m_handle, "speed", dTimes, AsyncReplyTag::SPEED);
}

void MpvProxy::selectSubtitle(int nId)
{
    if (nId > m_movieInfo.subs.size()) {
        nId = m_movieInfo.subs.size() == 0 ? -1 : m_movieInfo.subs[0]["id"].toInt();
    }

    my_set_property_async(m_handle, "sid", nId, 0);
    m_cachedSid = nId;  // Update cache immediately
#ifndef _LIBDMR_
    MovieConfiguration::get().updateUrl(_file, ConfigKnownKey::SubId, sid());
#endif
}

void MpvProxy::toggleSubtitle()
{
    if (state() == PlayState::Stopped) {
        return;
    }

    my_set_property_async(m_handle, "sub-visibility", !isSubVisible(), 0);
}

int MpvProxy::aid() const
{
    // Return cached value to avoid synchronous API calls during event handling
    return m_cachedAid;
}

int MpvProxy::sid() const
{
    // Return cached value to avoid synchronous API calls during event handling
    return m_cachedSid;
}

void MpvProxy::selectTrack(int nId)
{
    if (nId >= m_movieInfo.audios.size()) return;
    QVariant aid  = m_movieInfo.audios[nId]["id"];
    my_set_property(m_handle, "aid", aid);
}

void MpvProxy::changeSoundMode(SoundMode soundMode)
{
    QList<QVariant> listArgs;

    switch (soundMode) {
    case SoundMode::Stereo:
        listArgs << "af" << "set" << "stereotools=muter=false";
        break;
    case SoundMode::Left:
        listArgs << "af" << "set" << "stereotools=muter=true";
        break;
    case SoundMode::Right:
        listArgs << "af" << "set" << "stereotools=mutel=true";
        break;
    }

    my_command(m_handle, listArgs);
}

void MpvProxy::volumeUp()
{
    if (volume() >= 200)
        return;

    changeVolume(volume() + 10);
}

void MpvProxy::changeVolume(int nVol)
{
    my_set_property(m_handle, "volume", volumeCorrection(nVol));
}

void MpvProxy::volumeDown()
{
    if (volume() <= 0)
        return;

    changeVolume(volume() - 10);
}

int MpvProxy::volume() const
{
    // Use cached value to avoid synchronous API calls during event handling
    int nActualVol = m_cachedVolume;
    int nDispalyVol = static_cast<int>((nActualVol - 40) / 60.0 * 100.0);
    return nDispalyVol > 100 ? nActualVol : nDispalyVol;
}

int MpvProxy::videoRotation() const
{
    int nRotate = my_get_property(m_handle, "video-rotate").toInt();
    return (nRotate + 360) % 360;
}

void MpvProxy::setVideoRotation(int nDegree)
{
    my_set_property(m_handle, "video-rotate", nDegree);
}

void MpvProxy::setVideoAspect(double dValue)
{
#if MPV_CLIENT_API_VERSION >= MPV_MAKE_VERSION(2, 2)
    QString aspectProperty = "video-aspect-override";
#else
    QString aspectProperty = "video-aspect";
#endif
    my_set_property(m_handle, aspectProperty, dValue);
}

double MpvProxy::videoAspect() const
{
#if MPV_CLIENT_API_VERSION >= MPV_MAKE_VERSION(2, 2)
    QString aspectProperty = "video-aspect-override";
#else
    QString aspectProperty = "video-aspect";
#endif  
    return my_get_property(m_handle, aspectProperty).toDouble();
}

bool MpvProxy::muted() const
{
    // Return cached value to avoid synchronous API calls during event handling
    return m_cachedMute;
}

void MpvProxy::toggleMute()
{
    QList<QVariant> listArgs = { "cycle", "mute" };
    qInfo() << listArgs;
    my_command(m_handle, listArgs);
}

void MpvProxy::setMute(bool bMute)
{
    my_set_property(m_handle, "mute", bMute);
}

void MpvProxy::slotStateChanged()
{
    m_pMpvGLwidget->setPlaying(state() != Backend::PlayState::Stopped);
    m_pMpvGLwidget->update();
}

void MpvProxy::refreshDecode()
{
    QList<QString> canHwTypes;
    auto playlist = dynamic_cast<PlayerEngine *>(m_pParentWidget)->getplaylist();
    if (!playlist || playlist->size() <= 0) return;

    // Check if there's a valid current item and file
    PlayItemInfo currentInfo = playlist->currentInfo();
    if (!currentInfo.valid || _file.isEmpty()) {
        qInfo() << "No valid current item, skipping refreshDecode";
        return;
    }

    malloc_trim(0);
    //bool bIsCanHwDec = HwdecProbe::get().isFileCanHwdec(_file.url(), canHwTypes);
    qInfo() << "DecodeMode:" << m_decodeMode << "(AUTO:0, HARDWARE:1, SOFTWARE:2, CUSTOM:3)";
    if (DecodeMode::SOFTWARE == m_decodeMode) { //1.设置软解
        my_set_property_async(m_handle, "hwdec", "no", 0);
        // In composited mode we must keep using libmpv (embedded rendering).
        // Forcing vo=x11 here will spawn a separate window and "detach" the playback surface.
        if (CompositingManager::get().composited()) {
            my_set_property_async(m_handle, "vo", "libmpv", 0);
            m_sInitVo = "libmpv";
        } else if (!utils::check_wayland_env()) {
            my_set_property_async(m_handle, "vo", "x11", 0);
            m_sInitVo = "x11";
        }
    } else if (DecodeMode::AUTO == m_decodeMode) {//2.设置自动
        //2.1 特殊格式
        bool isSoftCodec = false;
        auto codec = currentInfo.mi.videoCodec();
        auto name = _file.fileName();
        qInfo() << "Codec:" << codec << "Name:" << name;
            isSoftCodec = codec.toLower().contains("mpeg2video") || codec.toLower().contains("wmv") || name.toLower().contains("wmv");
            if (isSoftCodec) {
                qWarning() << "Using SoftCodec because of codec OR name";
            }
            //去除9200显卡适配
            bool jmflag =false;
            if (utils::isJjwGPUPresent()) {
                QDir jmdir(QLibraryInfo::location(QLibraryInfo::LibrariesPath) +QDir::separator() +"mwv207");
                if(jmdir.exists())
                {
                    jmflag=true;
                }
                isSoftCodec = codec.toLower().contains("mpeg4") ? true : isSoftCodec;
            }
            QFileInfo X100GPU("/dev/x100gpu");
            bool x100flag =false;
            if (X100GPU.exists()) {
                x100flag = true;
            }
#if !defined(_loongarch) && !defined(__loongarch__) && !defined(__loongarch64)
            //探测硬解码
            if(!isSoftCodec && !CompositingManager::get().isZXIntgraphics() && !jmflag && !x100flag) {
                isSoftCodec = !isSupportHardWareDecode(codec, currentInfo.mi.width, currentInfo.mi.height);
                if (isSoftCodec) {
                    qWarning() << "Using SoftCodec because of check SupportHardWareDecode";
                }
            }
            if (CompositingManager::get().isZXIntgraphics() && !jmflag) {
                isSoftCodec = codec.contains("vp8") && (currentInfo.mi.width > 1920 || currentInfo.mi.height > 1080);
                if (isSoftCodec) {
                    qWarning() << "Using SoftCodec because of codec OR size";
                }
            }
#endif
            if(utils::check_wayland_env()){
                PlaylistModel *playMode = dynamic_cast<PlayerEngine *>(m_pParentWidget)->getplaylist();
                QVariant varPixfmt = playMode->property(currentInfo.mi.filePath.toUtf8());
                if(varPixfmt.isValid() && varPixfmt.toInt() == AV_PIX_FMT_YUV444P) {
                    isSoftCodec = true;
                    qWarning() << "Using SoftCodec because of format";
                }
                auto codec = currentInfo.mi.videoCodec();
                if (    codec.toLower().contains("mpeg") ||
                        codec.toLower().contains("h264")  ||
                        codec.toLower().contains("hevc")  ||
                        codec.toLower().contains("vp")) {
                    my_set_property_async(m_handle, "hwdec-codecs", codec.toLower(), 0);
                    isSoftCodec = false;
                }
            }
        if (isSoftCodec) {
            qInfo() << "my_set_property_async hwdec no";
            my_set_property_async(m_handle, "hwdec", "no", 0);
        } else { //2.2 非特殊格式
            //2.2.1 特殊硬件
            QFileInfo X100GPU("/dev/x100gpu");
            QFileInfo X100VPU("/dev/vxd0");
            if (utils::isJjwGPUPresent()) {
                PlayItemInfo currentInfo = dynamic_cast<PlayerEngine *>(m_pParentWidget)->getplaylist()->currentInfo();
                auto codec = currentInfo.mi.videoCodec();
                if (codec.toLower().contains("mpeg2") || codec.toLower().contains("mpeg4")) {
                    qWarning() << "Using SoftCodec because of codec";
                    my_set_property_async(m_handle, "hwdec", "no", 0);
                } else if (utils::isJjwGPUPresent()) {
                    configureJjwGPU(m_handle);
                }
#ifdef _LIBDMR_
    my_set_property_async(m_handle, "vo", "libmpv,opengl-cb", 0);
#endif
            } else if (X100GPU.exists() && X100VPU.exists()) {
                my_set_property_async(m_handle, "hwdec", "ftomx-copy", 0);
                my_set_property_async(m_handle, "vo", "gpu", 0);
            } else if (CompositingManager::get().isOnlySoftDecode()) { //2.2.1.2 鲲鹏920 || 曙光+英伟达 || 浪潮
                qWarning() << "Using SoftCodec because of OnlySoftDecode";
                my_set_property_async(m_handle, "hwdec", "no", 0);
            } else if (CompositingManager::get().isSpecialControls()) {
                my_set_property_async(m_handle, "hwdec", "vaapi", 0);
            } else if (utils::check_wayland_env() && isSpecialHWHardware()) {
                my_set_property_async(m_handle, "hwdec", "omx-copy", 0);
            } else { //2.2.2 非特殊硬件 + 非特殊格式
                 my_set_property_async(m_handle, "hwdec","auto", 0);
                //bIsCanHwDec ? my_set_property_async(m_handle, "hwdec", canHwTypes.join(','), 0) : my_set_property_async(m_handle, "hwdec", "no", 0);
#if defined (__sw_64__)
        //Synchronously modify the video output of the SW platform vdpau(powered by zhangfl)
        my_set_property_async(m_handle, "hwdec", "vdpau", 0);
#endif
            }
        }

        if (QFile::exists("/sys/bus/pci/drivers/ljmcore")) {
            my_set_property_async(m_handle, "hwdec", "vaapi", 0);
        }

        if (QFile::exists("/usr/local/ctyun/clink/Mirror/Registry/Default") && !QFile::exists("/dev/mtgpu.0")) {
            my_set_property_async(m_handle, "hwdec", "no", 0);
            my_set_property_async(m_handle, "vo", "x11", 0);
            my_set_property_async(m_handle, "video-sync", "desync", 0);
            my_set_property_async(m_handle, "profile", "sw-fast", 0);
            m_sInitVo = "x11";
        }

        // 设置芯瞳显卡硬解
        if(utils::isSietiumGPUPresent()) {
            my_set_property_async(m_handle, "hwdec", "vaapi", 0);
            my_set_property_async(m_handle, "vo", "gpu", 0);
        }

        if (!CompositingManager::get().composited()) {
            if (CompositingManager::get().isSpecialControls()) {
                my_set_property_async(m_handle, "hwdec","vaapi", 0);
                my_set_property_async(m_handle, "vo","vaapi", 0);
            }
        }
    } else if (DecodeMode::HARDWARE == m_decodeMode) { //3.设置硬解
#ifndef _LIBDMR_

#if defined (__aarch64__)
        // 鲲鹏920 || 曙光+英伟达 || 浪潮
        if (CompositingManager::get().isOnlySoftDecode()) {
            qWarning() << "Using SoftCodec because of OnlySoftDecode";
            my_set_property_async(m_handle, "hwdec", "no", 0);
        } else if (!CompositingManager::get().hascard()) {
            // 即使检测不到显卡（如AIGLX error），也尝试让mpv自己判断硬解
            // 因为硬解不依赖AIGLX，可能仍然可用
            qWarning() << "hascard is false, but try auto hwdec";
            my_set_property_async(m_handle, "hwdec", "auto", 0);
        } else if (CompositingManager::get().isSpecialControls()) {
            my_set_property_async(m_handle, "hwdec", "vaapi", 0);
        } else {
            my_set_property_async(m_handle, "hwdec","auto", 0);
        }
#else
        if(CompositingManager::get().isOnlySoftDecode()) {
            qWarning() << "Using SoftCodec because of OnlySoftDecode";
            my_set_property_async(m_handle, "hwdec","no", 0);
        } else {
            my_set_property_async(m_handle, "hwdec","auto", 0);
        }
#endif

#else
        if (CompositingManager::get().isOnlySoftDecode()) { // 鲲鹏920 || 曙光+英伟达 || 浪潮
            qWarning() << "Using SoftCodec because of OnlySoftDecode";
            my_set_property_async(m_handle, "hwdec", "no", 0);
        } else {
             my_set_property_async(m_handle, "hwdec","auto", 0);
            //bIsCanHwDec ? my_set_property_async(m_handle, "hwdec", canHwTypes.join(','), 0) : my_set_property_async(m_handle, "hwdec", "no", 0);
        }
#endif
        QFileInfo X100GPU("/dev/x100gpu");
        QFileInfo X100VPU("/dev/vxd0");
        if (utils::isJjwGPUPresent()) {
            configureJjwGPU(m_handle);
#ifdef _LIBDMR_
    my_set_property_async(m_handle, "vo", "libmpv,opengl-cb", 0);
#endif
        } else if (X100GPU.exists() && X100VPU.exists()) {
            qDebug() << "DEBUG: X100 GPU/VPU detected (harddec mode). Setting hwdec to ftomx-copy, vo to gpu.";
            my_set_property_async(m_handle, "hwdec", "ftomx-copy", 0);
            my_set_property_async(m_handle, "vo", "gpu", 0);
        } else if (utils::check_wayland_env() && isSpecialHWHardware()) {
            my_set_property_async(m_handle, "hwdec", "omx-copy", 0);
        }

        if (QFile::exists("/sys/bus/pci/drivers/ljmcore")) {
            my_set_property_async(m_handle, "hwdec", "vaapi", 0);
        }

        if (QFile::exists("/usr/local/ctyun/clink/Mirror/Registry/Default") && !QFile::exists("/dev/mtgpu.0")) {
            my_set_property_async(m_handle, "hwdec", "no", 0);
            my_set_property_async(m_handle, "vo", "x11", 0);
            my_set_property_async(m_handle, "video-sync", "desync", 0);
            my_set_property_async(m_handle, "profile", "sw-fast", 0);
            m_sInitVo = "x11";
        }

        // 设置芯瞳显卡硬解
        if(utils::isSietiumGPUPresent()) {
            my_set_property_async(m_handle, "hwdec", "vaapi", 0);
            my_set_property_async(m_handle, "vo", "gpu", 0);
        }

        PlaylistModel *playMode = dynamic_cast<PlayerEngine *>(m_pParentWidget)->getplaylist();
        PlayItemInfo currentInfo = playMode->currentInfo();
#ifndef USE_TEST
        // Wayland-only: YUV444P 强制软解。测试环境恒不进入；排除出测试构建。
        if(utils::check_wayland_env()){
            QVariant varPixfmt = playMode->property(currentInfo.mi.filePath.toUtf8());
            if(varPixfmt.isValid() && varPixfmt.toInt() == AV_PIX_FMT_YUV444P) {
                qWarning() << "Using SoftCodec because of format";
                my_set_property_async(m_handle, "hwdec","no", 0);
            }
        }
#endif // USE_TEST
        auto codec = currentInfo.mi.videoCodec();
        my_set_property_async(m_handle, "hwdec-codecs", codec.toLower(), 0);

#ifndef USE_TEST
        // Wayland-only: pulse 禁止挂起（异步）。测试环境恒不进入；排除出测试构建。
        if(utils::check_wayland_env()) {
            my_set_property_async(m_handle, "pulse-allow-suspended", "yes", 0);
        }
#endif // USE_TEST
        if (CompositingManager::get().enablePower()) {
            QPair<QString, QString> config= CompositingManager::get().getEnablePowerConfig();
            my_set_property_async(m_handle, config.first, config.second, 0);
            qInfo() << __func__ << "enable power config: " << config;
        }
        //play.conf
        CompositingManager::get().getMpvConfig(m_pConfig);
        QMap<QString, QString>::iterator iter = m_pConfig->begin();
        while (iter != m_pConfig->end()) {
            if (iter.key().contains(QString("hwdec"))) {
                my_set_property_async(m_handle, iter.key(), iter.value(), 0);
                break;
            }
            iter++;
        }
    }
#ifndef _LIBDMR_
    else if (Settings::get().settings()->getOption(QString("base.decode.select")).toInt() == DecodeMode::CUSTOM) {
        int decodeIndex = Settings::get().settings()->getOption(QString("base.decode.Decodemode")).toInt();
        auto decodeModeOpt = Settings::get().settings()->option("base.decode.Decodemode");
        QString decodeMode = decodeModeOpt.data()->data("items").toStringList()[decodeIndex];
        decodeMode = decodeMode.isEmpty() ? "auto" : decodeMode;
        m_pConfig->insert("hwdec", decodeMode);

        if (!CompositingManager::get().composited()) {
            int voIndex = Settings::get().settings()->getOption(QString("base.decode.Videoout")).toInt();
            auto voOpt = Settings::get().settings()->option("base.decode.Videoout");
            QString voMode = voOpt.data()->data("items").toStringList()[voIndex];
            voMode = voMode.isEmpty() ? "auto" : voMode;
            m_pConfig->insert("vo", voMode);
        }
    }
#endif
}

void MpvProxy::initMember()
{
    m_nBurstStart = 0;

    m_pMpvGLwidget = nullptr;
    m_pParentWidget = nullptr;

    m_bInBurstShotting = false;
    m_posBeforeBurst = false;
    m_bPendingSeek = false;
    m_bPolling = false;
    m_bConnectStateChange = false;
    m_bLoadMedia = false;
    m_bPauseOnStart = false;
    m_bIsJingJia = false;
    m_bInited = false;
    m_bHwaccelAuto = false;
    m_bLastIsSpecificFormat = false;

    m_sInitVo = "gpu,xv,x11";//初始化vo数据
    m_listBurstPoints.clear();
    m_mapWaitSet.clear();
    m_vecWaitCommand.clear();

    m_waitEvent = nullptr;
    m_setOptionString = nullptr;
    m_setProperty = nullptr;
    m_setPropertyAsync = nullptr;
    m_commandNode = nullptr;
    m_commandNodeAsync = nullptr;
    m_getProperty = nullptr;
    m_observeProperty = nullptr;
    m_eventName = nullptr;
    m_creat = nullptr;
    m_requestLogMessage = nullptr;
    m_setWakeupCallback = nullptr;
    m_initialize = nullptr;
    m_freeNodecontents = nullptr;
    m_pConfig = nullptr;
    m_gpuInfo = nullptr;
    m_gpuInfoVo = nullptr;
}

void MpvProxy::play()
{
    qInfo() << "Starting playback";
    
    if(m_bLoadMedia) {
        qInfo() << "Media already loading, scheduling retry in 5 seconds";
        QTimer::singleShot(5000, [=](){ //超时5s恢复状态，视频加载成功后也会重置状态，正常播放状态下不会进入此函数
            qDebug() << "Media loading timeout reached, resetting loading state";
            m_bLoadMedia = false;
        });
        qDebug() << "Exiting MpvProxy::play() - media already loading";
        return;
    }
    
    bool bRawFormat = false;
    QList<QVariant> listArgs = { "loadfile" };
    QStringList listOpts = { };
    PlayerEngine* pEngine = nullptr;
    bool bAudio = false;
    m_bLoadMedia = true;
    qDebug() << "Set loading flag to prevent concurrent loading";

    if (!m_bInited) {
        qInfo() << "MPV not initialized, performing first initialization";
        firstInit();
        qDebug() << "MPV initialization completed";
    }

    pEngine = dynamic_cast<PlayerEngine *>(m_pParentWidget);
    if (pEngine && pEngine->getplaylist()->size() > 0) {
        bRawFormat = pEngine->getplaylist()->currentInfo().mi.isRawFormat();
        bAudio = pEngine->currFileIsAudio();
        qInfo() << "Current file info - Raw format:" << bRawFormat << "Audio only:" << bAudio;
    } else {
        qDebug() << "No playlist items or player engine not available";
    }

    // Use async property setting to avoid deadlock during short video playback
    if (bAudio) {
        qInfo() << "Setting video output to null for audio-only file (async)";
        my_set_property_async(m_handle, "vo", "null", 0);
    } else {
        qInfo() << "Setting video output to:" << m_sInitVo << "(async)";
        my_set_property_async(m_handle, "vo", m_sInitVo, 0);
    }

    if (_file.isLocalFile()) {
        qInfo() << "Loading local file:" << QFileInfo(_file.toLocalFile()).absoluteFilePath();
        listArgs << QFileInfo(_file.toLocalFile()).absoluteFilePath();
    } else {
        qInfo() << "Loading remote file:" << _file.url();
        listArgs << _file.url();
    }
#ifndef _LIBDMR_
    QMap<QString, QVariant> cfg = MovieConfiguration::get().queryByUrl(_file);
    QString key = MovieConfiguration::knownKey2String(ConfigKnownKey::StartPos);
    if (Settings::get().isSet(Settings::ResumeFromLast) && cfg.contains(key) && !bRawFormat) {   // 裸流没有时长，seek会崩溃
        listOpts << QString("start=%1").arg(cfg[key].toInt());   //如果视频长度小于1s这段代码会导致视频无法播放
    }

    key = MovieConfiguration::knownKey2String(ConfigKnownKey::SubCodepage);
    if (cfg.contains(key)) {
        listOpts << QString("sub-codepage=%1").arg(cfg[key].toString());
    }

    key = MovieConfiguration::knownKey2String(ConfigKnownKey::SubDelay);
    if (cfg.contains(key)) {
        listOpts << QString("sub-delay=%1").arg(cfg[key].toDouble());
    }

    if (!_dvdDevice.isEmpty()) {
        listOpts << QString("dvd-device=%1").arg(_dvdDevice);
    }
#endif

    //刷新解码模式
    refreshDecode();

    // Jingjiawei GPU special handling - use async to avoid deadlock
    if (utils::getJjwGPUPath() == "/dev/mwv206_0") {
        QDir sdir(QLibraryInfo::location(QLibraryInfo::LibrariesPath) +QDir::separator() +"mwv206");
        QString sCodec = pEngine->playlist().currentInfo().mi.videoCodec();
        if(sdir.exists() && sCodec.contains("avs2", Qt::CaseInsensitive)) {
            qWarning() << "Using SoftCodec because of codec (async)";
            my_set_property_async(m_handle, "hwdec", "no", 0);
            my_set_property_async(m_handle, "vo", "gpu,x11,xv", 0);
        }
    }

    if (listOpts.size()) {
        listArgs << "replace";
        if (MPV_CLIENT_API_VERSION >= MPV_MAKE_VERSION(2,3)) {
            listArgs << "-1";
        }
        listArgs << listOpts.join(',');
    }

    qInfo()<<"" << listArgs << listOpts;

    //设置播放参数
    QMap<QString, QString>::iterator iter = m_pConfig->begin();
    qInfo() << __func__ << "Set mpv propertys (async)!!";
    while (iter != m_pConfig->end()) {
        qInfo() << __func__ << iter.key() << iter.value();
        my_set_property_async(m_handle, iter.key(), iter.value(), 0);
        iter++;
    }

    qInfo() << "Executing play command with args:" << listArgs << "and options:" << listOpts;
    my_command_async(m_handle, listArgs, 0);
    my_set_property_async(m_handle, "pause", m_bPauseOnStart, 0);
    qInfo() << "Play command executed successfully";

#ifndef _LIBDMR_
    // by giving a period of time, movie will be loaded and auto-loaded subs are
    // all ready, then load extra subs from db
    // this keeps order of subs
    QTimer::singleShot(200, [this]() {
        auto mcfg = MovieConfiguration::get().queryByUrl(_file);
        auto ext_subs = MovieConfiguration::get().getListByUrl(_file, ConfigKnownKey::ExternalSubs);
        for (const auto &sub : ext_subs) {
            if (!QFile::exists(sub)) {
                MovieConfiguration::get().removeFromListUrl(_file, ConfigKnownKey::ExternalSubs, sub);
            } else {
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
                loadSubtitle(sub);
#else
                loadSubtitle(QFileInfo(sub));
#endif
            }
        }

        auto key_s = MovieConfiguration::knownKey2String(ConfigKnownKey::SubId);
        if (mcfg.contains(key_s)) {
            selectSubtitle(mcfg[key_s].toInt());
        }
    });
#endif
}


void MpvProxy::pauseResume()
{
    qDebug() << "Entering MpvProxy::pauseResume()";

    if (_state == PlayState::Stopped) {
        qInfo() << "Cannot pause/resume - player is stopped";
        return;
    }

    qInfo() << "Toggling pause state - current state:" << paused();
    my_set_property(m_handle, "pause", !paused());
    qDebug() << "Exiting MpvProxy::pauseResume()";
}

void MpvProxy::stop()
{
    qDebug() << "Entering MpvProxy::stop()";
    qInfo() << "Stopping playback";

    // Check if mpv handle is valid before sending stop command
    if (!m_handle) {
        qWarning() << "MpvProxy::stop() called with null handle";
        return;
    }

    QList<QVariant> args = { "stop" };
    qInfo() << args;
    my_command_async(m_handle, args, 0);

    qDebug() << "Exiting MpvProxy::stop()";
}

QImage MpvProxy::takeScreenshot()
{
    return takeOneScreenshot();
}

void MpvProxy::burstScreenshot()
{
    qDebug() << "Entering MpvProxy::burstScreenshot()";

    if (m_bInBurstShotting) {
        qWarning() << "already in burst screenshotting mode";
        return;
    }

    if (state() == PlayState::Stopped) {
        qDebug() << "Exiting MpvProxy::burstScreenshot() - player stopped";
        return;
    }

    //my_command(m_handle, QList<QVariant> {"revert-seek", "mark"});
    m_posBeforeBurst = my_get_property(m_handle, "time-pos");
    qDebug() << "Saved position before burst:" << m_posBeforeBurst.toDouble();

    int nDuration = static_cast<int>(duration() / 15);
    qDebug() << "Calculating burst points with duration segment:" << nDuration;

    std::random_device rd;
    std::mt19937 g(rd());
    std::uniform_int_distribution<int> uniform_dist(0, nDuration);
    m_listBurstPoints.clear();
    for (int i = 0; i < 15; i++) {
        m_listBurstPoints.append(nDuration * i + uniform_dist(g));
    }
    m_nBurstStart = 0;

    if (duration() < 35) {
        qWarning() << "Video too short for burst screenshot (duration:" << duration() << ")";
        emit notifyScreenshot(QImage(), 0);
        stopBurstScreenshot();
        qDebug() << "Exiting MpvProxy::burstScreenshot() - video too short";
        return;
    }
    qInfo() << "burst span " << m_nBurstStart;

    if (!paused()) {
        qDebug() << "Pausing playback for burst screenshot";
        pauseResume();
    }

    m_bInBurstShotting = true;
    QTimer::singleShot(0, this, &MpvProxy::stepBurstScreenshot);
    qDebug() << "Exiting MpvProxy::burstScreenshot() - scheduled first screenshot";
}

qint64 MpvProxy::nextBurstShootPoint()
{
    auto next = m_listBurstPoints[static_cast<int>(m_nBurstStart++)];
    if (next >= duration()) {
        next = duration() - 5;
    }

    return next;
}

int MpvProxy::volumeCorrection(int displayVol)
{
    int realVol = 0;
    if (displayVol > 100)
        return displayVol;
    realVol = static_cast<int>((displayVol / 100.0) * 60.0 + 40);
    return (realVol == 40 ? 0 : realVol);
}

QVariant MpvProxy::my_get_property(mpv_handle *pHandle, const QString &sName) const
{
    mpv_node node;
    if (!m_getProperty) return QVariant();
    int err = m_getProperty(pHandle, sName.toUtf8().data(), MPV_FORMAT_NODE, &node);
    if (err < 0)
        return QVariant::fromValue(ErrorReturn(err));
    auto variant = node_to_variant(&node);
    m_freeNodecontents(&node);
    return variant;
}

int MpvProxy::my_set_property(mpv_handle *pHandle, const QString &sName, const QVariant &v)
{
    QVariant sValue = v;
#ifndef _LIBDMR_
#ifdef __x86_64__
    bool composited = CompositingManager::get().composited();
    //设置mpv硬解码时，检测是否支持硬解，不支持则设置为软解
    if(sName.compare("hwdec") == 0 && v.toString().compare("auto") == 0 && !utils::check_wayland_env() && composited)
    {
        if(!CompositingManager::isCanHwdec())
        {
            sValue = "no";
        }
    }
#endif
#else
    if(sName.compare("hwdec") == 0) {
        if( property("dmrhwdec-switch").isValid() && property("dmrhwdec-switch").toBool()) {
            sValue = v;
        } else {
            sValue = "no";
        }
    }
#endif

    node_builder node(sValue);

    if (!m_bInited) {
        m_mapWaitSet.insert(sName, sValue);
        return 0;
    }

    if (!m_setProperty) return 0;
    int res = m_setProperty(pHandle, sName.toUtf8().data(), MPV_FORMAT_NODE, node.node());
    return res;
}

bool MpvProxy::my_command_async(mpv_handle *pHandle, const QVariant &args, uint64_t tag)
{
    node_builder node(args);
    int nErr = m_commandNodeAsync(pHandle, tag, node.node());
    return nErr == 0;
}

int MpvProxy::my_set_property_async(mpv_handle *pHandle, const QString &sName, const QVariant &value, uint64_t tag)
{
    node_builder node(value);
    return m_setPropertyAsync(pHandle, tag, sName.toUtf8().data(), MPV_FORMAT_NODE, node.node());
}

QVariant MpvProxy::my_get_property_variant(mpv_handle *pHandle, const QString &sName)
{
    mpv_node node;
    if (m_getProperty(pHandle, sName.toUtf8().data(), MPV_FORMAT_NODE, &node) < 0)
        return QVariant();
    my_node_autofree f(&node);
    return node_to_variant(&node);
}

QVariant MpvProxy::my_command(mpv_handle *pHandle, const QVariant &args)
{
    qDebug() << "Entering MpvProxy::my_command()";
    if (!m_bInited) {
        m_vecWaitCommand.append(args);
        qDebug() << "m_vecWaitCommand" << m_vecWaitCommand;
        return QVariant();
    }

    node_builder node(args);
    mpv_node res;
    int nErr = m_commandNode(pHandle, node.node(), &res);
    if (nErr < 0) {
        qDebug() << "error" << nErr;
        return QVariant::fromValue(ErrorReturn(nErr));
    }
    auto variant = node_to_variant(&res);
    m_freeNodecontents(&res);
    qDebug() << "Exiting MpvProxy::my_command()";
    return variant;
}

QImage MpvProxy::takeOneScreenshot()
{
    qDebug() << "Entering MpvProxy::takeOneScreenshot()";
    bool bNeedRotate = false;
    QString strVO = getProperty("current-vo").toString();  // the image by screenshot wont rotate when vo=vdpau

    if(strVO.compare("vdpau", Qt::CaseInsensitive) == 0) {
        qDebug() << "strVO is vdpau";
        bNeedRotate = true;
    }

    if (state() == PlayState::Stopped) {
        qDebug() << "player is stopped, exiting";
        return QImage();
    }

    QList<QVariant> args = {"screenshot-raw"};
    node_builder node(args);
    mpv_node res;
    int nErr = m_commandNode(m_handle, node.node(), &res);
    if (nErr < 0) {
        qWarning() << "screenshot raw failed";
        return QImage();
    }

    Q_ASSERT(res.format == MPV_FORMAT_NODE_MAP);

    int w = 0, h = 0, stride = 0;

    mpv_node_list *pNodeList = res.u.list;
    uchar *pData = nullptr;

    for (int n = 0; n < pNodeList->num; n++) {
        auto key = QString::fromUtf8(pNodeList->keys[n]);
        if (key == "w") {
            w = static_cast<int>(pNodeList->values[n].u.int64);
            qDebug() << "w" << w;
        } else if (key == "h") {
            h = static_cast<int>(pNodeList->values[n].u.int64);
            qDebug() << "h" << h;
        } else if (key == "stride") {
            stride = static_cast<int>(pNodeList->values[n].u.int64);
            qDebug() << "stride" << stride;
        } else if (key == "format") {
            auto format = QString::fromUtf8(pNodeList->values[n].u.string);
            qInfo() << "format" << format;
        } else if (key == "data") {
            pData = static_cast<uchar *>(pNodeList->values[n].u.ba->data);
            qDebug() << "pData" << pData;
        }
    }

    if (pData) {
        qDebug() << "pData is not null";
        //alpha should be ignored
        auto img = QImage(static_cast<const uchar *>(pData), w, h, stride, QImage::Format_RGB32);
        img.bits();
        int rotationdegree = videoRotation();
        if (rotationdegree && (CompositingManager::get().composited() || bNeedRotate)) {
            qDebug() << "rotationdegree" << rotationdegree;
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
            QMatrix matrix;
            matrix.rotate(rotationdegree);
            img = QPixmap::fromImage(img).transformed(matrix, Qt::SmoothTransformation).toImage();
#else
            QTransform transform;
            transform.rotate(rotationdegree);
            img = QPixmap::fromImage(img).transformed(transform, Qt::SmoothTransformation).toImage();
#endif
        }
        m_freeNodecontents(&res);
        qDebug() << "Exiting MpvProxy::takeOneScreenshot()";
        return img;
    }

    m_freeNodecontents(&res);

    qDebug() << "failed! Exiting MpvProxy::takeOneScreenshot()";
    return QImage();
}

void MpvProxy::stepBurstScreenshot()
{
    qDebug() << "Entering MpvProxy::stepBurstScreenshot()";

    if (!m_bInBurstShotting) {
        qDebug() << "Burst screenshot mode not active, exiting";
        return;
    }

    auto pos = nextBurstShootPoint();
    qDebug() << "Seeking to position" << pos << "for burst screenshot";
    my_command(m_handle, QList<QVariant> {"seek", pos, "absolute"});

//    int tries = 10;
    qDebug() << "Waiting for seek to complete";
    while (true) {
        mpv_event *pEvent = m_waitEvent(m_handle, 0.005);
        if (pEvent->event_id == MPV_EVENT_NONE)
            continue;

        if (pEvent->event_id == MPV_EVENT_PLAYBACK_RESTART) {
            qInfo() << "seek finished" << elapsed();
            break;
        }

        if (pEvent->event_id == MPV_EVENT_END_FILE) {
            qInfo() << "seek finished (end of file)" << elapsed();
            break;
        }
    }

    qDebug() << "Taking screenshot at position" << elapsed();
    QImage img = takeOneScreenshot();
    if (img.isNull()) {
        qWarning() << "Failed to take screenshot at position" << elapsed();
        emit notifyScreenshot(img, elapsed());
        stopBurstScreenshot();
        qDebug() << "Exiting MpvProxy::stepBurstScreenshot() - screenshot failed";
        return;
    }

    emit notifyScreenshot(img, elapsed());
    QTimer::singleShot(0, this, &MpvProxy::stepBurstScreenshot);
    qDebug() << "Exiting MpvProxy::stepBurstScreenshot()";
}

void MpvProxy::stopBurstScreenshot()
{
    qDebug() << "Entering MpvProxy::stopBurstScreenshot()";

    m_bInBurstShotting = false;
    qDebug() << "Burst screenshot mode deactivated";

    //my_command(m_handle, QList<QVariant> {"revert-seek", "mark"});
    qDebug() << "Restoring position to" << m_posBeforeBurst.toDouble();
    my_set_property(m_handle, "time-pos", m_posBeforeBurst);

    qDebug() << "Exiting MpvProxy::stopBurstScreenshot()";
}

void MpvProxy::seekForward(int nSecs)
{
    qDebug() << "Entering MpvProxy::seekForward() - seconds:" << nSecs;

    if (state() == PlayState::Stopped) {
        qDebug() << "Cannot seek forward - player is stopped";
        return;
    }

    if (m_bPendingSeek) {
        qDebug() << "Cannot seek forward - another seek operation is pending";
        return;
    }

    QList<QVariant> listArgs = { "seek", QVariant(nSecs), "relative+exact" };
    qInfo() << listArgs;
    my_command_async(m_handle, listArgs, AsyncReplyTag::SEEK);
    m_bPendingSeek = true;

    qDebug() << "Exiting MpvProxy::seekForward() - seek operation started";
}

void MpvProxy::seekBackward(int nSecs)
{
    qDebug() << "Entering MpvProxy::seekBackward() - seconds:" << nSecs;

    if (state() == PlayState::Stopped) {
        qDebug() << "Cannot seek backward - player is stopped";
        return;
    }

    if (m_bPendingSeek) {
        qDebug() << "Cannot seek backward - another seek operation is pending";
        return;
    }

    if (nSecs > 0) {
        qDebug() << "Adjusting positive seek value to negative";
        nSecs = -nSecs;
    }

    QList<QVariant> listArgs = { "seek", QVariant(nSecs), "relative+exact" };
    qInfo() << listArgs;
    my_command_async(m_handle, listArgs, AsyncReplyTag::SEEK);
    m_bPendingSeek = true;

    qDebug() << "Exiting MpvProxy::seekBackward() - seek operation started";
}

void MpvProxy::seekAbsolute(int nPos)
{
    qDebug() << "Entering MpvProxy::seekAbsolute() - position:" << nPos;

    if (state() == PlayState::Stopped) {
        qDebug() << "Cannot seek to absolute position - player is stopped";
        return;
    }

    if (m_bPendingSeek) {
        qDebug() << "Cannot seek to absolute position - another seek operation is pending";
        return;
    }

    QList<QVariant> listArgs = { "seek", QVariant(nPos), "absolute" };
    qInfo() << listArgs;
    //command(m_handle, args);
    m_bPendingSeek = true;
    my_command_async(m_handle, listArgs, AsyncReplyTag::SEEK);

    qDebug() << "Exiting MpvProxy::seekAbsolute() - seek operation started";
}

QSize MpvProxy::videoSize() const
{
    if (state() == PlayState::Stopped) {
        return QSize(-1, -1);
    }

    // Return cached value to avoid synchronous API calls during event handling
    return m_cachedVideoSize;
}

qint64 MpvProxy::duration() const
{
    bool bRawFormat = false;

    if (0 < dynamic_cast<PlayerEngine *>(m_pParentWidget)->getplaylist()->size()) {
        PlayItemInfo currentInfo = dynamic_cast<PlayerEngine *>(m_pParentWidget)->getplaylist()->currentInfo();
        bRawFormat = currentInfo.mi.isRawFormat();
    }

    if (bRawFormat) {     // 因为格式众多时长输出不同，这里做统一处理不显示时长
        qDebug() << "Raw format detected, returning duration 0";
        return 0;
    } else {
        // Return cached value to avoid synchronous API calls during event handling
        qDebug() << "Returning cached duration" << m_cachedDuration;
        return m_cachedDuration;
    }
}


qint64 MpvProxy::elapsed() const
{
    qDebug() << "Entering MpvProxy::elapsed()";
    if (state() == PlayState::Stopped) {
        qDebug() << "Player is stopped, returning 0";
        return 0;
    }

    // Return cached value to avoid synchronous API calls during event handling
    qDebug() << "Returning cached elapsed time" << m_cachedElapsed;
    return m_cachedElapsed;
}

void MpvProxy::updatePlayingMovieInfo()
{
    qDebug() << "Entering MpvProxy::updatePlayingMovieInfo()";

    m_movieInfo.subs.clear();
    m_movieInfo.audios.clear();
    qDebug() << "Cleared existing subtitle and audio track information";

    QList<QVariant> listInfo = my_get_property(m_handle, "track-list").toList();
    qDebug() << "Retrieved" << listInfo.size() << "tracks from MPV";

    auto p = listInfo.begin();
    while (p != listInfo.end()) {
        const auto &t = p->toMap();
        if (t["type"] == "audio") {
            qDebug() << "Processing audio track with ID:" << t["id"].toInt();
            AudioInfo audioInfo;
            audioInfo["type"] = t["type"];
            audioInfo["id"] = t["id"];
            audioInfo["lang"] = t["lang"];
            audioInfo["external"] = t["external"];
            audioInfo["external-filename"] = t["external-filename"];
            audioInfo["selected"] = t["selected"];
            audioInfo["title"] = t["title"];

            if (t["title"].toString().size() == 0) {
                qDebug() << "Audio track has no title, determining appropriate title";
                if (t["lang"].isValid() && t["lang"].toString().size() && t["lang"].toString() != "und") {
                    qDebug() << "Using language code as title";
                    audioInfo["title"] = t["lang"];
                } else if (!t["external"].toBool()) {
                    qDebug() << "Using [internal] as title";
                    audioInfo["title"] = "[internal]";
                }
            }


            m_movieInfo.audios.append(audioInfo);
        } else if (t["type"] == "sub") {
            qDebug() << "Processing subtitle track with ID:" << t["id"].toInt();
            SubtitleInfo titleInfo;
            titleInfo["type"] = t["type"];
            titleInfo["id"] = t["id"];
            titleInfo["lang"] = t["lang"];
            titleInfo["external"] = t["external"];
            titleInfo["external-filename"] = t["external-filename"];
            titleInfo["selected"] = t["selected"];
            titleInfo["title"] = t["title"];
            if (t["title"].toString().size() == 0) {
                qDebug() << "Subtitle track has no title, determining appropriate title";
                if (t["lang"].isValid() && t["lang"].toString().size() && t["lang"].toString() != "und") {
                    qDebug() << "Using language code as subtitle title";
                    titleInfo["title"] = t["lang"];
                } else if (!t["external"].toBool()) {
                    qDebug() << "Using [internal] as subtitle title";
                    titleInfo["title"] = tr("Internal");
                }
            }
            m_movieInfo.subs.append(titleInfo);
        }
        ++p;
    }

    qInfo() << m_movieInfo.subs;
    qInfo() << m_movieInfo.audios;
}

void MpvProxy::nextFrame()
{
    if (state() == PlayState::Stopped) {
        qDebug() << "Cannot step frame - player is stopped";
        return;
    }

    QList<QVariant> listArgs = { "frame-step"};
    my_command(m_handle, listArgs);
}

void MpvProxy::previousFrame()
{
    if (state() == PlayState::Stopped) {
        qDebug() << "Cannot step frame backward - player is stopped";
        return;
    }

    QList<QVariant> listArgs = { "frame-back-step"};
    my_command(m_handle, listArgs);
}

void MpvProxy::changehwaccelMode(hwaccelMode hwaccelMode)
{
    qDebug() << "Entering MpvProxy::changehwaccelMode()";
    switch (hwaccelMode) {
    case hwaccelAuto:
        qDebug() << "Setting hwaccel to auto";
        m_bHwaccelAuto = true;
        break;
    case hwaccelOpen:
        qDebug() << "Setting hwaccel to open";
        m_bHwaccelAuto = false;
        my_set_property(m_handle, "hwdec", "auto");
        break;
    case hwaccelClose:
        qDebug() << "Setting hwaccel to off";
        m_bHwaccelAuto = false;
        my_set_property(m_handle, "hwdec", "off");
        break;
    }
    qDebug() << "Exiting MpvProxy::changehwaccelMode()";
}

void MpvProxy::makeCurrent()
{
    qDebug() << "Entering MpvProxy::makeCurrent()";
    if (m_pMpvGLwidget) {
        m_pMpvGLwidget->makeCurrent();
    }
}

QVariant MpvProxy::getProperty(const QString &sName)
{
    qDebug() << "Entering MpvProxy::getProperty()";
    return my_get_property(m_handle, sName.toUtf8().data());
}

void MpvProxy::setProperty(const QString &sName, const QVariant &val)
{
    qDebug() << "Entering MpvProxy::setProperty()";
    if (sName == "pause-on-start") {
        qDebug() << "Setting pause-on-start to" << val.toBool();
        m_bPauseOnStart = val.toBool();
    } else if (sName == "video-zoom") {
        qDebug() << "Setting video-zoom to" << val.toDouble();
        my_set_property(m_handle, sName, val.toDouble());
    }  else if (sName == "color") {
        qDebug() << "Setting color to" << val.toString();
        QObject::setProperty("color", val);
    } else if (sName == "dmrhwdec-switch") {
        qDebug() << "Setting dmrhwdec-switch to" << val.toBool();
        QObject::setProperty("dmrhwdec-switch", val);
    } else {
        qDebug() << "Setting" << sName << "to" << val.toString();
        my_set_property(m_handle, sName.toUtf8().data(), val);
        if (sName == "vo") {
            qDebug() << "Setting vo to" << val.toString();
            m_sInitVo = val.toString();
        }
    }
    qDebug() << "Exiting MpvProxy::setProperty()";
}

} // end of namespace dmr
