cmake_minimum_required(VERSION 3.20)
project(maixsense_d640_sdk VERSION 0.0.3 LANGUAGES C CXX)
set(MSD_ABI_VERSION 1)

include(GNUInstallDirs)
include(CTest)
include(CMakePackageConfigHelpers)
find_package(Threads REQUIRED)

option(MSD_BUILD_SHARED "Build the shared SDK library" ON)
option(MSD_BUILD_EXAMPLES "Build SDK examples" ON)
option(MSD_BUILD_WASM "Build the processing-only WebAssembly module" OFF)
option(MSD_BUILD_DESKTOP_ALGORITHMS "Build the OpenCV image algorithm module" ON)
option(MSD_BUILD_POINT_CLOUD_TOOLS
    "Auto-detect and build available Open3D/PCL point-cloud integrations" ON)
option(MSD_REQUIRE_POINT_CLOUD_TOOLS
    "Require both Open3D and PCL point-cloud integrations" OFF)

if(MSD_REQUIRE_POINT_CLOUD_TOOLS AND NOT MSD_BUILD_POINT_CLOUD_TOOLS)
    message(FATAL_ERROR
        "MSD_REQUIRE_POINT_CLOUD_TOOLS=ON requires MSD_BUILD_POINT_CLOUD_TOOLS=ON")
endif()
if(MSD_REQUIRE_POINT_CLOUD_TOOLS AND EMSCRIPTEN)
    message(FATAL_ERROR
        "MSD_REQUIRE_POINT_CLOUD_TOOLS=ON is unavailable for the processing-only Emscripten build")
endif()

set(MSD_SOURCES
        src/sdk.cpp
        src/error.cpp
        src/processing.cpp
        src/calibration.cpp
        src/pipeline.cpp
)
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
    list(APPEND MSD_SOURCES src/linux_backend.cpp)
elseif(WIN32)
    list(APPEND MSD_SOURCES src/windows_backend.cpp src/windows_file_service.cpp src/file_service.cpp)
elseif(APPLE)
    enable_language(OBJCXX)
    list(APPEND MSD_SOURCES src/file_service.cpp src/macos_backend.mm src/macos_file_service.mm src/network_backend.cpp src/macos_usb_capture.cpp src/macos_usb_control.cpp)
    set_source_files_properties(src/macos_backend.mm src/macos_file_service.mm PROPERTIES COMPILE_FLAGS "-fobjc-arc")
else()
    list(APPEND MSD_SOURCES src/unsupported_backend.cpp)
endif()

if(APPLE)
    find_package(PkgConfig REQUIRED)
    pkg_check_modules(MSD_USB REQUIRED libusb-1.0)
    find_file(MSD_USB_STATIC libusb-1.0.a PATHS ${MSD_USB_LIBRARY_DIRS} REQUIRED)
    add_executable(msd-macos-usb-helper src/macos_usb_helper.cpp)
    target_include_directories(msd-macos-usb-helper PRIVATE include src)
    target_include_directories(msd-macos-usb-helper SYSTEM PRIVATE ${MSD_USB_INCLUDE_DIRS})
    target_compile_features(msd-macos-usb-helper PRIVATE cxx_std_17)
    target_compile_options(msd-macos-usb-helper PRIVATE -Wall -Wextra -Wpedantic -Werror)
    install(TARGETS msd-macos-usb-helper RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
    target_link_libraries(msd-macos-usb-helper PRIVATE ${MSD_USB_STATIC}
        "-framework IOKit" "-framework CoreFoundation" "-framework Security")
endif()

if(MSD_BUILD_WASM)
    if(NOT EMSCRIPTEN)
        message(FATAL_ERROR "MSD_BUILD_WASM requires the Emscripten toolchain")
    endif()
    find_package(Python3 REQUIRED COMPONENTS Interpreter)
    set(MSD_WASM_BASENAME
            "maixsense_d640_processing-${PROJECT_VERSION}-abi${MSD_ABI_VERSION}")
    add_executable(msd-processing-wasm src/error.cpp src/processing.cpp)
    target_include_directories(msd-processing-wasm PRIVATE include src)
    target_compile_features(msd-processing-wasm PRIVATE cxx_std_17)
    target_compile_definitions(msd-processing-wasm PRIVATE MSD_STATIC MSD_NO_EXCEPTIONS)
    target_compile_options(msd-processing-wasm PRIVATE
        -Oz -flto -fno-exceptions -fno-rtti -Wall -Wextra -Wpedantic -Werror)
    target_link_options(msd-processing-wasm PRIVATE
        -Oz -flto -fno-exceptions -fno-rtti
        "SHELL:-s STANDALONE_WASM=1"
        "SHELL:-s ALLOW_MEMORY_GROWTH=0"
        "SHELL:-s FILESYSTEM=0"
        "SHELL:-s ERROR_ON_UNDEFINED_SYMBOLS=1"
        "SHELL:-s EXPORTED_FUNCTIONS=['_malloc','_free','_msd_get_abi_version','_msd_get_version_string','_msd_get_last_error','_msd_colorize_depth16','_msd_colorized_rgba8_required_size','_msd_colorize_quantized8','_msd_threshold_depth16','_msd_spatial_filter_depth16','_msd_hole_fill_depth16']"
        "SHELL:--no-entry")
    set_target_properties(msd-processing-wasm PROPERTIES
        OUTPUT_NAME "${MSD_WASM_BASENAME}" SUFFIX ".wasm")
    add_custom_command(TARGET msd-processing-wasm POST_BUILD
        COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/scripts/filter_wasm_exports.py
            --wasm $<TARGET_FILE:msd-processing-wasm>
        COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/scripts/generate_wasm_manifest.py
            --wasm $<TARGET_FILE:msd-processing-wasm>
            --sdk-version ${PROJECT_VERSION}
            --abi-version ${MSD_ABI_VERSION}
        VERBATIM)
endif()

if(MSD_BUILD_SHARED)
    add_library(maixsense_d640 SHARED ${MSD_SOURCES})
else()
    add_library(maixsense_d640 STATIC ${MSD_SOURCES})
    target_compile_definitions(maixsense_d640 PUBLIC MSD_STATIC)
endif()
add_library(MaixStereoDepth::maixsense_d640 ALIAS maixsense_d640)

if(MSD_BUILD_DESKTOP_ALGORITHMS AND NOT EMSCRIPTEN)
    find_package(OpenCV REQUIRED COMPONENTS core imgcodecs imgproc highgui)
    add_library(maixsense_d640_opencv src/opencv.cpp)
    add_library(MaixStereoDepth::opencv ALIAS maixsense_d640_opencv)
    target_compile_features(maixsense_d640_opencv PUBLIC cxx_std_17)
    target_include_directories(maixsense_d640_opencv PUBLIC
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
        $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
        ${OpenCV_INCLUDE_DIRS})
    target_link_libraries(maixsense_d640_opencv
        PUBLIC MaixStereoDepth::maixsense_d640 ${OpenCV_LIBS})
    set_target_properties(maixsense_d640_opencv PROPERTIES EXPORT_NAME opencv
        POSITION_INDEPENDENT_CODE ON)
endif()

if(MSD_BUILD_POINT_CLOUD_TOOLS AND NOT EMSCRIPTEN)
    find_package(Open3D QUIET)
    find_package(PCL QUIET COMPONENTS common io)

    # Open3D and PCL pull Eigen3 and fmt. When one of those resolves inside an
    # activated Conda environment, its imported target puts the Conda lib
    # directory on the tools' RUNPATH; at runtime that shadows the system
    # libstdc++, a system Open3D built against a newer libstdc++ then refuses to
    # load, and the tool cannot start at all. Warn here because the symptom only
    # appears much later, as a loader error or a failing test.
    foreach(msd_conda_check Eigen3_DIR fmt_DIR Open3D_DIR PCL_DIR OpenCV_DIR)
        if(DEFINED ${msd_conda_check} AND "${${msd_conda_check}}" MATCHES "[Cc]onda")
            message(WARNING
                "${msd_conda_check} resolved inside a Conda environment (${${msd_conda_check}}). "
                "That directory can land on the built tools' RUNPATH and stop them from starting; "
                "reconfigure with -DCMAKE_IGNORE_PREFIX_PATH=<conda prefix> to use the system packages.")
        endif()
    endforeach()
    if(MSD_REQUIRE_POINT_CLOUD_TOOLS AND (NOT Open3D_FOUND OR NOT PCL_FOUND))
        set(MSD_MISSING_POINT_CLOUD_TOOLS "")
        if(NOT Open3D_FOUND)
            list(APPEND MSD_MISSING_POINT_CLOUD_TOOLS "Open3D")
        endif()
        if(NOT PCL_FOUND)
            list(APPEND MSD_MISSING_POINT_CLOUD_TOOLS "PCL (common, io)")
        endif()
        string(JOIN ", " MSD_MISSING_POINT_CLOUD_TOOLS_TEXT ${MSD_MISSING_POINT_CLOUD_TOOLS})
        message(FATAL_ERROR
            "MSD_REQUIRE_POINT_CLOUD_TOOLS=ON requires: ${MSD_MISSING_POINT_CLOUD_TOOLS_TEXT}")
    endif()
    if(Open3D_FOUND)
        add_library(maixsense_d640_open3d INTERFACE)
        add_library(MaixStereoDepth::open3d ALIAS maixsense_d640_open3d)
        target_include_directories(maixsense_d640_open3d INTERFACE
            $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
            $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>)
        target_link_libraries(maixsense_d640_open3d INTERFACE
            MaixStereoDepth::maixsense_d640 Open3D::Open3D)
        set_target_properties(maixsense_d640_open3d PROPERTIES EXPORT_NAME open3d)
    endif()
    if(PCL_FOUND)
        add_library(maixsense_d640_pcl INTERFACE)
        add_library(MaixStereoDepth::pcl ALIAS maixsense_d640_pcl)
        target_include_directories(maixsense_d640_pcl INTERFACE
            $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
            $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
            ${PCL_INCLUDE_DIRS})
        target_link_libraries(maixsense_d640_pcl INTERFACE
            MaixStereoDepth::maixsense_d640 ${PCL_LIBRARIES})
        set_target_properties(maixsense_d640_pcl PROPERTIES EXPORT_NAME pcl)
        if(MSD_BUILD_EXAMPLES)
            add_executable(msd-pcl-point-cloud examples/pcl_point_cloud.cpp)
            target_link_libraries(msd-pcl-point-cloud PRIVATE MaixStereoDepth::pcl)
        endif()
    endif()
    if(NOT Open3D_FOUND AND NOT PCL_FOUND)
        message(STATUS
            "Point-cloud integrations not found; msd-point-cloud keeps dependency-free PLY output. "
            "Install Open3D for --view or PCL for msd-pcl-point-cloud.")
    endif()
endif()

target_compile_features(maixsense_d640 PUBLIC cxx_std_17)
target_include_directories(maixsense_d640
    PUBLIC
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
        $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
    PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src
)
target_compile_definitions(maixsense_d640 PRIVATE MSD_BUILDING_LIBRARY)
# Optional: decrypting the device's tar.gz calibration archive. Without zlib the
# fetch API still exists and reports UNSUPPORTED, so platforms that do not ship
# zlib keep building and only lose the one-call calibration fetch.
if(NOT EMSCRIPTEN)
    find_package(ZLIB QUIET)
endif()
if(ZLIB_FOUND)
    set(MSD_ZLIB_ENABLED TRUE)
    target_link_libraries(maixsense_d640 PRIVATE ZLIB::ZLIB)
    target_compile_definitions(maixsense_d640 PRIVATE MSD_HAVE_ZLIB=1)
else()
    set(MSD_ZLIB_ENABLED FALSE)
endif()
if(NOT WIN32)
    # Rust's windows-gnu target already links libpthread statically; adding the
    # mingw import library here duplicates every pthread symbol.
    target_link_libraries(maixsense_d640 PRIVATE Threads::Threads)
endif()
if(WIN32)
    target_link_libraries(maixsense_d640 PRIVATE
        mfplat mfreadwrite mfuuid ole32 propsys winusb setupapi)
elseif(APPLE)
    target_include_directories(maixsense_d640 SYSTEM PRIVATE ${MSD_USB_INCLUDE_DIRS})
    # Keep the private static USB dependency out of the shared SDK's exports.
    target_link_options(maixsense_d640 PRIVATE "LINKER:-exported_symbol,_msd_*")
    target_link_libraries(maixsense_d640 PRIVATE ${MSD_USB_STATIC}
        "-framework Security")
    target_link_libraries(maixsense_d640 PRIVATE
        "-framework AVFoundation" "-framework CoreMedia" "-framework CoreVideo"
        "-framework Foundation" "-framework CoreFoundation" "-framework CoreGraphics"
        "-framework ImageIO" "-framework IOKit" "-framework IOUSBHost")
endif()
if(MSVC)
    target_compile_options(maixsense_d640 PRIVATE /W4 /permissive-)
else()
    target_compile_options(maixsense_d640 PRIVATE -Wall -Wextra -Wpedantic -Werror)
endif()
set_target_properties(maixsense_d640 PROPERTIES
    VERSION ${PROJECT_VERSION}
    SOVERSION 0
    POSITION_INDEPENDENT_CODE ON
    CXX_VISIBILITY_PRESET hidden
    VISIBILITY_INLINES_HIDDEN YES
)

if(MSD_BUILD_EXAMPLES)
    if(APPLE)
        find_package(PkgConfig QUIET)
        if(PkgConfig_FOUND)
            pkg_check_modules(MSD_USB QUIET IMPORTED_TARGET libusb-1.0)
            if(TARGET PkgConfig::MSD_USB)
                add_executable(msd-macos-uvc-transport-probe examples/macos_uvc_transport_probe.cpp)
                target_compile_features(msd-macos-uvc-transport-probe PRIVATE cxx_std_17)
                target_compile_options(msd-macos-uvc-transport-probe PRIVATE -Wall -Wextra -Wpedantic -Werror)
                target_link_libraries(msd-macos-uvc-transport-probe PRIVATE PkgConfig::MSD_USB)
            endif()
        endif()
        add_executable(msd-macos-uvc-probe examples/macos_uvc_probe.mm)
        target_compile_options(msd-macos-uvc-probe PRIVATE -fobjc-arc -Wall -Wextra -Wpedantic -Werror)
        target_link_libraries(msd-macos-uvc-probe PRIVATE
            "-framework AVFoundation" "-framework CoreMedia" "-framework Foundation")
    endif()
    add_executable(msd-enumerate examples/enumerate.c)
    target_link_libraries(msd-enumerate PRIVATE MaixStereoDepth::maixsense_d640)
    add_executable(msd-capture examples/capture.cpp)
    target_link_libraries(msd-capture PRIVATE MaixStereoDepth::maixsense_d640)
    add_executable(msd-device-monitor examples/device_monitor.cpp)
    target_link_libraries(msd-device-monitor PRIVATE MaixStereoDepth::maixsense_d640)
    add_executable(msd-exposure examples/exposure_control.c)
    target_link_libraries(msd-exposure PRIVATE MaixStereoDepth::maixsense_d640)
    add_executable(msd-upload examples/upload.c)
    target_link_libraries(msd-upload PRIVATE MaixStereoDepth::maixsense_d640)
    add_executable(msd-latency examples/latency.c)
    target_link_libraries(msd-latency PRIVATE MaixStereoDepth::maixsense_d640)
    if(UNIX)
        target_link_libraries(msd-latency PRIVATE m)
    endif()
    add_executable(msd-depth-snapshot examples/depth_snapshot.cpp)
    target_link_libraries(msd-depth-snapshot PRIVATE MaixStereoDepth::maixsense_d640)
    add_executable(msd-depth-colorize examples/depth_colorize.cpp)
    target_link_libraries(msd-depth-colorize PRIVATE MaixStereoDepth::maixsense_d640)
    add_executable(msd-point-cloud examples/point_cloud.cpp)
    target_link_libraries(msd-point-cloud PRIVATE MaixStereoDepth::maixsense_d640)
    if(TARGET maixsense_d640_open3d)
        target_link_libraries(msd-point-cloud PRIVATE MaixStereoDepth::open3d)
        target_compile_definitions(msd-point-cloud PRIVATE MSD_HAVE_OPEN3D_VIEWER=1)
    endif()
    if(TARGET maixsense_d640_opencv)
        add_executable(msd-opencv-viewer examples/opencv_viewer.cpp)
        target_link_libraries(msd-opencv-viewer PRIVATE MaixStereoDepth::opencv)
    endif()
endif()

# The installed command-line tools must run directly from an SDK prefix rather
# than depending on a developer's LD_LIBRARY_PATH.  Keep this relative so a
# staged tree remains relocatable when its prefix is moved as a whole.
if(MSD_BUILD_EXAMPLES AND UNIX AND NOT APPLE)
    set(MSD_CLI_INSTALL_RPATH "$ORIGIN/../${CMAKE_INSTALL_LIBDIR}")
    set(MSD_CLI_TARGETS
        msd-enumerate
        msd-capture
        msd-device-monitor
        msd-exposure
        msd-upload
        msd-latency
        msd-depth-snapshot
        msd-depth-colorize
        msd-point-cloud)
    if(TARGET msd-opencv-viewer)
        list(APPEND MSD_CLI_TARGETS msd-opencv-viewer)
    endif()
    if(TARGET msd-pcl-point-cloud)
        list(APPEND MSD_CLI_TARGETS msd-pcl-point-cloud)
    endif()
    foreach(msd_cli_target IN LISTS MSD_CLI_TARGETS)
        set_target_properties(${msd_cli_target} PROPERTIES
            INSTALL_RPATH "${MSD_CLI_INSTALL_RPATH}")
    endforeach()
endif()

if(BUILD_TESTING)
    if(NOT EMSCRIPTEN)
        add_executable(msd-macos-uvc-payload-tests tests/macos_uvc_payload_tests.cpp)
        target_include_directories(msd-macos-uvc-payload-tests PRIVATE src)
        target_compile_features(msd-macos-uvc-payload-tests PRIVATE cxx_std_17)
        if(MSVC)
            target_compile_options(msd-macos-uvc-payload-tests PRIVATE /W4 /WX /UNDEBUG)
        else()
            target_compile_options(msd-macos-uvc-payload-tests PRIVATE -Wall -Wextra -Wpedantic -Werror -UNDEBUG)
        endif()
        add_test(NAME macos-uvc-payload COMMAND msd-macos-uvc-payload-tests)
        add_executable(msd-macos-capture-policy-tests tests/macos_capture_policy_tests.cpp)
        target_include_directories(msd-macos-capture-policy-tests PRIVATE src)
        target_compile_features(msd-macos-capture-policy-tests PRIVATE cxx_std_17)
        if(MSVC)
            target_compile_options(msd-macos-capture-policy-tests PRIVATE /W4 /WX /UNDEBUG)
        else()
            target_compile_options(msd-macos-capture-policy-tests PRIVATE -Wall -Wextra -Wpedantic -Werror -UNDEBUG)
        endif()
        add_test(NAME macos-capture-policy COMMAND msd-macos-capture-policy-tests)
        add_executable(msd-file-service-recovery-tests tests/file_service_recovery_tests.cpp)
        target_include_directories(msd-file-service-recovery-tests PRIVATE src)
        target_compile_features(msd-file-service-recovery-tests PRIVATE cxx_std_17)
        if(MSVC)
            target_compile_options(msd-file-service-recovery-tests PRIVATE /W4 /WX /UNDEBUG)
        else()
            target_compile_options(msd-file-service-recovery-tests PRIVATE -Wall -Wextra -Wpedantic -Werror -UNDEBUG)
        endif()
        add_test(NAME msd-file-service-recovery COMMAND msd-file-service-recovery-tests)
        add_executable(msd-file-service-tests
            tests/file_service_protocol_tests.cpp
            src/file_service.cpp
            src/error.cpp)
        target_include_directories(msd-file-service-tests PRIVATE include src)
        target_compile_features(msd-file-service-tests PRIVATE cxx_std_17)
        add_test(NAME file-service-protocol COMMAND msd-file-service-tests)

        add_executable(msd-ncm-candidates-tests tests/ncm_candidates_tests.cpp)
        target_include_directories(msd-ncm-candidates-tests PRIVATE src include)
        target_compile_features(msd-ncm-candidates-tests PRIVATE cxx_std_17)
        if(MSVC)
            target_compile_options(msd-ncm-candidates-tests PRIVATE /UNDEBUG)
        else()
            target_compile_options(msd-ncm-candidates-tests PRIVATE
                -UNDEBUG -Wall -Wextra -Wpedantic -Werror)
        endif()
        add_test(NAME ncm-candidates COMMAND msd-ncm-candidates-tests)

        add_executable(msd-processing-tests tests/processing_tests.cpp)
        target_link_libraries(msd-processing-tests PRIVATE MaixStereoDepth::maixsense_d640)
        target_compile_definitions(msd-processing-tests PRIVATE
            MSD_COLORMAP_GOLDEN_PATH="${CMAKE_CURRENT_SOURCE_DIR}/tests/data/reference_colormaps.rgb"
            MSD_CALIBRATION_TEST_PATH="${CMAKE_CURRENT_SOURCE_DIR}/tests/data/stereo_calib_minimal.ini")
        add_test(NAME processing COMMAND msd-processing-tests)
        add_executable(msd-abi-tests tests/abi_tests.c)
        target_link_libraries(msd-abi-tests PRIVATE MaixStereoDepth::maixsense_d640)
        if(MSVC)
            target_compile_options(msd-processing-tests PRIVATE /UNDEBUG)
            target_compile_options(msd-abi-tests PRIVATE /UNDEBUG)
        else()
            # Both native test programs use assert as their executable check
            # primitive. Keep those checks enabled in Release builds as well.
            target_compile_options(msd-processing-tests PRIVATE -UNDEBUG)
            target_compile_options(msd-abi-tests PRIVATE -UNDEBUG)
        endif()
        add_test(NAME abi COMMAND msd-abi-tests)
        add_executable(msd-pipeline-tests tests/pipeline_tests.cpp)
        target_include_directories(msd-pipeline-tests PRIVATE src)
        target_link_libraries(msd-pipeline-tests PRIVATE MaixStereoDepth::maixsense_d640)
        if(MSVC)
            target_compile_options(msd-pipeline-tests PRIVATE /UNDEBUG)
        else()
            target_compile_options(msd-pipeline-tests PRIVATE -UNDEBUG -Wall -Wextra -Wpedantic -Werror)
        endif()
        add_test(NAME pipeline COMMAND msd-pipeline-tests)
        add_executable(msd-point-cloud-profile-selection-tests
            tests/point_cloud_profile_selection_tests.cpp)
        target_link_libraries(msd-point-cloud-profile-selection-tests
            PRIVATE MaixStereoDepth::maixsense_d640)
        if(MSVC)
            target_compile_options(msd-point-cloud-profile-selection-tests PRIVATE /UNDEBUG)
        else()
            target_compile_options(msd-point-cloud-profile-selection-tests PRIVATE
                -UNDEBUG -Wall -Wextra -Wpedantic -Werror)
        endif()
        add_test(NAME point-cloud-profile-selection
            COMMAND msd-point-cloud-profile-selection-tests)
        add_executable(msd-capture-completion-tests tests/capture_completion_tests.cpp)
        target_compile_features(msd-capture-completion-tests PRIVATE cxx_std_17)
        if(MSVC)
            target_compile_options(msd-capture-completion-tests PRIVATE /UNDEBUG)
        else()
            target_compile_options(msd-capture-completion-tests PRIVATE
                -UNDEBUG -Wall -Wextra -Wpedantic -Werror)
        endif()
        add_test(NAME capture-completion COMMAND msd-capture-completion-tests)
        add_executable(msd-payload-metadata-tests tests/payload_metadata_tests.cpp)
        target_include_directories(msd-payload-metadata-tests PRIVATE src)
        target_compile_features(msd-payload-metadata-tests PRIVATE cxx_std_17)
        if(MSVC)
            target_compile_options(msd-payload-metadata-tests PRIVATE /UNDEBUG)
        else()
            target_compile_options(msd-payload-metadata-tests PRIVATE
                -UNDEBUG -Wall -Wextra -Wpedantic -Werror)
        endif()
        add_test(NAME payload-metadata COMMAND msd-payload-metadata-tests)
        if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
            add_executable(msd-uvc-metadata-tests tests/uvc_metadata_tests.cpp)
            target_include_directories(msd-uvc-metadata-tests PRIVATE src)
            target_compile_features(msd-uvc-metadata-tests PRIVATE cxx_std_17)
            if(MSVC)
                target_compile_options(msd-uvc-metadata-tests PRIVATE /UNDEBUG)
            else()
                target_compile_options(msd-uvc-metadata-tests PRIVATE
                    -UNDEBUG -Wall -Wextra -Wpedantic -Werror)
            endif()
            add_test(NAME uvc-metadata COMMAND msd-uvc-metadata-tests)
        endif()
        if(MSD_BUILD_EXAMPLES)
            add_test(NAME point-cloud-cli-help COMMAND msd-point-cloud --help)
            add_test(NAME point-cloud-cli-invalid
                COMMAND ${CMAKE_COMMAND}
                    -DMSD_POINT_CLOUD_EXECUTABLE=$<TARGET_FILE:msd-point-cloud>
                    -P ${CMAKE_CURRENT_SOURCE_DIR}/tests/assert_point_cloud_cli_invalid.cmake)
            add_test(NAME depth-cli-arguments
                COMMAND ${CMAKE_COMMAND}
                    -DMSD_DEPTH_SNAPSHOT_EXECUTABLE=$<TARGET_FILE:msd-depth-snapshot>
                    -DMSD_DEPTH_COLORIZE_EXECUTABLE=$<TARGET_FILE:msd-depth-colorize>
                    -DMSD_CLI_SCRATCH_DIR=${CMAKE_CURRENT_BINARY_DIR}/depth-cli-scratch
                    -P ${CMAKE_CURRENT_SOURCE_DIR}/tests/assert_depth_cli_arguments.cmake)
        endif()
    endif()
    if(MSD_BUILD_WASM)
        find_program(MSD_NODE_EXECUTABLE NAMES node nodejs REQUIRED)
        add_test(NAME wasm-colormap-golden
            COMMAND ${MSD_NODE_EXECUTABLE}
                ${CMAKE_CURRENT_SOURCE_DIR}/tests/wasm_colormap_golden.mjs
                $<TARGET_FILE:msd-processing-wasm>
                ${CMAKE_CURRENT_SOURCE_DIR}/tests/data/reference_colormaps.rgb)
    endif()
endif()

install(TARGETS maixsense_d640 EXPORT MaixStereoDepthTargets
    RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
    ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
)
if(MSD_BUILD_EXAMPLES)
    set(MSD_CLI_INSTALL_TARGETS
        msd-enumerate
        msd-capture
        msd-device-monitor
        msd-exposure
        msd-upload
        msd-latency
        msd-depth-snapshot
        msd-depth-colorize
        msd-point-cloud)
    if(TARGET msd-opencv-viewer)
        list(APPEND MSD_CLI_INSTALL_TARGETS msd-opencv-viewer)
    endif()
    if(TARGET msd-pcl-point-cloud)
        list(APPEND MSD_CLI_INSTALL_TARGETS msd-pcl-point-cloud)
    endif()
    install(TARGETS ${MSD_CLI_INSTALL_TARGETS}
        RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
endif()
if(TARGET maixsense_d640_opencv)
    install(TARGETS maixsense_d640_opencv EXPORT MaixStereoDepthOpenCVTargets
        RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
        LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
        ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
    install(EXPORT MaixStereoDepthOpenCVTargets
        FILE MaixStereoDepthOpenCVTargets.cmake NAMESPACE MaixStereoDepth::
        DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/MaixStereoDepth)
endif()
if(TARGET maixsense_d640_open3d)
    install(TARGETS maixsense_d640_open3d EXPORT MaixStereoDepthOpen3DTargets)
    install(EXPORT MaixStereoDepthOpen3DTargets
        FILE MaixStereoDepthOpen3DTargets.cmake NAMESPACE MaixStereoDepth::
        DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/MaixStereoDepth)
endif()
if(TARGET maixsense_d640_pcl)
    install(TARGETS maixsense_d640_pcl EXPORT MaixStereoDepthPCLTargets)
    install(EXPORT MaixStereoDepthPCLTargets
        FILE MaixStereoDepthPCLTargets.cmake NAMESPACE MaixStereoDepth::
        DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/MaixStereoDepth)
endif()
install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(FILES
    docs/DEVELOPMENT.zh-CN.md
    docs/ORBBEC_COMPARISON.zh-CN.md
    examples/README.zh-CN.md
    third_party/COLORMAPS.md
    third_party/MATPLOTLIB_LICENSE.txt
    DESTINATION ${CMAKE_INSTALL_DATADIR}/doc/${PROJECT_NAME})
install(FILES packaging/99-maixsense-d640.rules
    DESTINATION ${CMAKE_INSTALL_DATADIR}/${PROJECT_NAME}/udev)
install(EXPORT MaixStereoDepthTargets
    FILE MaixStereoDepthTargets.cmake
    NAMESPACE MaixStereoDepth::
    DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/MaixStereoDepth
)
configure_package_config_file(cmake/MaixStereoDepthConfig.cmake.in
    ${CMAKE_CURRENT_BINARY_DIR}/MaixStereoDepthConfig.cmake
    INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/MaixStereoDepth)
write_basic_package_version_file(
    ${CMAKE_CURRENT_BINARY_DIR}/MaixStereoDepthConfigVersion.cmake
    VERSION ${PROJECT_VERSION} COMPATIBILITY SameMajorVersion)
install(FILES
    ${CMAKE_CURRENT_BINARY_DIR}/MaixStereoDepthConfig.cmake
    ${CMAKE_CURRENT_BINARY_DIR}/MaixStereoDepthConfigVersion.cmake
    DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/MaixStereoDepth)

if(BUILD_TESTING AND CMAKE_SYSTEM_NAME STREQUAL "Linux")
    add_executable(msd-stream-liveness-tests tests/stream_liveness_tests.cpp)
    target_compile_features(msd-stream-liveness-tests PRIVATE cxx_std_17)
    target_compile_options(msd-stream-liveness-tests PRIVATE -UNDEBUG)
    target_include_directories(msd-stream-liveness-tests PRIVATE src)
    add_test(NAME stream-liveness COMMAND msd-stream-liveness-tests)
endif()
