# SPDX-License-Identifier: LGPL-3.0-only
cmake_minimum_required(VERSION 3.24)
project(CueViseQtAlphaPatch LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_AUTOMOC ON)
# Native PowerShell paths can contain backslashes. Qt's generated source
# processing must receive CMake paths, otherwise e.g. \Users becomes an escape.
file(TO_CMAKE_PATH "${QT_SOURCE_DIR}" QT_SOURCE_DIR)
file(TO_CMAKE_PATH "${FFMPEG_DIR}" FFMPEG_DIR)
foreach(component IN ITEMS avcodec avformat avutil swresample swscale)
    string(TOUPPER "${component}" upper)
    set(${upper}_INCLUDE_DIR "${FFMPEG_DIR}/include" CACHE PATH "Pinned FFmpeg headers" FORCE)
    set(${upper}_LIBRARY "${FFMPEG_DIR}/lib/lib${component}.dll.a" CACHE FILEPATH "Pinned FFmpeg import" FORCE)
endforeach()
find_package(Qt6 6.12.0 EXACT REQUIRED COMPONENTS Core Gui Network Multimedia FFmpegMediaPluginImplPrivate)
set(plugin_source "${QT_SOURCE_DIR}/src/plugins/multimedia/ffmpeg")
file(READ "${plugin_source}/qffmpegvideobuffer.cpp" buffer_source)
set(original "if (descriptor->flags & AV_PIX_FMT_FLAG_RGB)")
set(patched "if (descriptor->flags & (AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_ALPHA))")
string(FIND "${buffer_source}" "${original}" match)
if(match LESS 0)
    message(FATAL_ERROR "Unexpected Qt source: alpha patch cannot be applied")
endif()
string(REPLACE "${original}" "${patched}" buffer_source "${buffer_source}")
set(patched_file "${CMAKE_CURRENT_BINARY_DIR}/qffmpegvideobuffer.cpp")
if(EXISTS "${patched_file}")
    file(READ "${patched_file}" existing_source)
endif()
if(NOT existing_source STREQUAL buffer_source)
    file(WRITE "${patched_file}" "${buffer_source}")
endif()
# Own object resolves all QFFmpegVideoBuffer symbols before the unmodified
# installed static implementation archive; its original object is not loaded.
add_library(CueViseQtAlphaPlugin MODULE "${plugin_source}/qffmpegplugin.cpp" "${CMAKE_CURRENT_BINARY_DIR}/qffmpegvideobuffer.cpp")
file(READ "${plugin_source}/qffmpeghwaccel_d3d11.cpp" bridge_source)
foreach(required IN ITEMS "m_srcMutex->AcquireSync(m_srcKey, INFINITE)" "m_destMutex->AcquireSync(m_destKey, INFINITE)" "avDeviceCtx->lock(avDeviceCtx->lock_ctx);")
    string(FIND "${bridge_source}" "${required}" match)
    if(match LESS 0)
        message(FATAL_ERROR "Unexpected Qt D3D11 source: ${required}")
    endif()
endforeach()
string(REPLACE "#include \"qffmpeghwaccel_d3d11_p.h\"" "#include \"qffmpeghwaccel_d3d11_p.h\"\n#include \"d3d-trace.h\"" bridge_source "${bridge_source}")
string(REPLACE "QT_BEGIN_NAMESPACE" "#include \"d3d-copy-pool.h\"\nQT_BEGIN_NAMESPACE" bridge_source "${bridge_source}")
set(pool_entry "AVFrameUPtr copyFromHwPoolD3D11(AVFrameUPtr src)\n{")
string(FIND "${bridge_source}" "${pool_entry}" pool_entry_at)
if(pool_entry_at LESS 0)
    message(FATAL_ERROR "Unexpected Qt decoder-copy entry point")
endif()
string(REPLACE "${pool_entry}" "${pool_entry}\n    if (CueViseCopyPool::enabled()) return CueViseCopyPool::copy(std::move(src));" bridge_source "${bridge_source}")
string(REPLACE "m_srcMutex->AcquireSync(m_srcKey, INFINITE)" "CueViseD3DTrace::acquire(m_srcMutex.Get(), m_srcKey, \"source-key\")" bridge_source "${bridge_source}")
string(REPLACE "m_destMutex->AcquireSync(m_destKey, INFINITE)" "CueViseD3DTrace::acquire(m_destMutex.Get(), m_destKey, \"destination-key\")" bridge_source "${bridge_source}")
string(REPLACE "avDeviceCtx->lock(avDeviceCtx->lock_ctx);" "{ CueViseD3DTrace::Scope trace(\"decoder-context-lock\"); avDeviceCtx->lock(avDeviceCtx->lock_ctx); }" bridge_source "${bridge_source}")
string(REPLACE "    ctx->Flush();" "    { CueViseD3DTrace::Scope trace(\"decoder-flush\"); ctx->Flush(); }" bridge_source "${bridge_source}")
set(bridge_file "${CMAKE_CURRENT_BINARY_DIR}/qffmpeghwaccel_d3d11.cpp")
set(existing_bridge "")
if(EXISTS "${bridge_file}")
    file(READ "${bridge_file}" existing_bridge)
endif()
if(NOT existing_bridge STREQUAL bridge_source)
    file(WRITE "${bridge_file}" "${bridge_source}")
endif()
target_sources(CueViseQtAlphaPlugin PRIVATE "${bridge_file}")

# Position notifications are UI polling, not the audio/video scheduling clock.
# A coarse 50-ms timer avoids repeated synchronous WinMM cancellation on the
# GUI thread when paused decoders are primed/reused. Keep media clocks intact.
file(READ "${plugin_source}/qffmpegmediaplayer.cpp" player_source)
set(position_timer_original "m_positionUpdateTimer.setTimerType(Qt::PreciseTimer);")
string(FIND "${player_source}" "${position_timer_original}" position_timer_at)
if(position_timer_at LESS 0)
    message(FATAL_ERROR "Unexpected Qt UI position timer source")
endif()
string(REPLACE "${position_timer_original}" "m_positionUpdateTimer.setTimerType(qEnvironmentVariableIntValue(\"CUEVISE_PRECISE_POSITION_TIMER\") == 1 ? Qt::PreciseTimer : Qt::CoarseTimer);" player_source "${player_source}")
set(player_file "${CMAKE_CURRENT_BINARY_DIR}/qffmpegmediaplayer.cpp")
set(existing_player "")
if(EXISTS "${player_file}")
    file(READ "${player_file}" existing_player)
endif()
if(NOT existing_player STREQUAL player_source)
    file(WRITE "${player_file}" "${player_source}")
endif()
target_sources(CueViseQtAlphaPlugin PRIVATE "${player_file}")
target_include_directories(CueViseQtAlphaPlugin PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")
target_include_directories(CueViseQtAlphaPlugin PRIVATE "${plugin_source}" "${Qt6_DIR}/../../../include/QtFFmpegMediaPluginImpl/6.12.0/QtFFmpegMediaPluginImpl/private")
target_link_libraries(CueViseQtAlphaPlugin PRIVATE Qt6::FFmpegMediaPluginImplPrivate Qt6::GuiPrivate Qt6::Network d3d11 dxgi dxguid d3d12)
set_target_properties(CueViseQtAlphaPlugin PROPERTIES PREFIX "" OUTPUT_NAME ffmpegmediaplugin)
