Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.
C++
feat(2.0.0): commit the P1-P5 work and the 2026-09-30 field-issue fixes
Veyra Goal Agent4fbc2b024614
diff --git a/CMakeLists.txt b/CMakeLists.txtindex c0090118..ae97972b 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -135,6 +135,7 @@ add_library(veyra_ngx STATICsrc/ngx/AdaMfgUnlock.cppsrc/ngx/AmpereMfgUnlock.cppsrc/ngx/NvapiArchSpoof.cpp+ src/ngx/DlssgTransfusion.cpp)set_source_files_properties(src/ngx/compat/hde/hde64.c PROPERTIES LANGUAGE CXX)veyra_apply_warnings(veyra_ngx)@@ -249,6 +250,7 @@ endif()# YUV→RGB shader is shared between the media pipeline and the harness.veyra_add_compute_shader(veyra_shader_yuv_to_rgb YuvToLinearRgb)veyra_add_compute_shader(veyra_shader_rgb_to_linear RgbToLinear)+veyra_add_compute_shader(veyra_shader_color_grade ColorGradePass)veyra_add_compute_shader(veyra_shader_yuy2_to_linear Yuy2ToLinear)veyra_add_compute_shader(veyra_shader_packed_capture PackedCaptureToLinear)add_dependencies(veyra_shader_rgb_to_linear veyra_shader_yuy2_to_linear)@@ -264,6 +266,8 @@ veyra_add_compute_shader(veyra_shader_nvof_densify NvofDensify)veyra_add_compute_shader(veyra_shader_nr_downsample NrDownsample)veyra_add_compute_shader(veyra_shader_nr_residual NrResidualComposite)veyra_add_compute_shader(veyra_shader_nr_temporal NrTemporal)+# Stage-5 output stabiliser (anti-flicker, default off).+veyra_add_compute_shader(veyra_shader_nr_hold NrHold)veyra_add_compute_shader(veyra_shader_flow_adapt FlowAdapt)veyra_add_compute_shader(veyra_shader_rgb_nv12 RgbToNv12)@@ -328,6 +332,7 @@ target_link_libraries(veyra_guidance_tests PRIVATE veyra_guidance)add_library(veyra_pipeline STATICsrc/pipeline/ResetCoordinator.cppsrc/pipeline/ColorGradeTables.cpp+ src/pipeline/ColorGradeInstance.cppsrc/pipeline/NrInstance.cpp)veyra_apply_warnings(veyra_pipeline)@@ -339,6 +344,7 @@ target_compile_definitions(veyra_pipeline PUBLICVEYRA_SHADER_DIR="${CMAKE_BINARY_DIR}/shaders")target_include_directories(veyra_pipeline PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)target_link_libraries(veyra_pipeline PUBLIC veyra_base veyra_gfx d3d12 dxgi dxguid d3dcompiler)+add_dependencies(veyra_pipeline veyra_shader_color_grade)add_executable(veyra_pipeline_teststests/unit/PipelineContractTests.cpp@@ -420,7 +426,7 @@ endif()# EnhanceGraph (the real GPU chain) needs the NGX + NVOF backends; wire it# into veyra_pipeline only when both exist so bare contract builds still work.if(TARGET veyra_ngx AND TARGET veyra_nvof AND VEYRA_FFMPEG_ROOT)- target_sources(veyra_pipeline PRIVATE src/pipeline/EnhanceGraph.cpp src/pipeline/NrTemporalPass.cpp src/core/SceneCadenceAnalyzer.cpp)+ target_sources(veyra_pipeline PRIVATE src/pipeline/EnhanceGraph.cpp src/pipeline/NrTemporalPass.cpp src/pipeline/NrHoldPass.cpp src/core/SceneCadenceAnalyzer.cpp)target_include_directories(veyra_pipeline PRIVATE ${FFMPEG_INCLUDE_DIRS})target_link_libraries(veyra_pipeline PRIVATE veyra_ngx veyra_nvof ${FFMPEG_LIBRARIES})add_dependencies(veyra_pipeline@@ -499,7 +505,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform# veyra_sources: product input sources (Playbook R3/R7). MediaFileSource# composes veyra_media; no second decode implementation exists.- add_dependencies(veyra_pipeline veyra_shader_nr_downsample veyra_shader_nr_residual veyra_shader_nr_temporal veyra_shader_flow_adapt)+ add_dependencies(veyra_pipeline veyra_shader_nr_downsample veyra_shader_nr_residual veyra_shader_nr_temporal veyra_shader_nr_hold veyra_shader_flow_adapt)add_library(veyra_sources STATICsrc/source/NativeCaptureSink.cppsrc/source/MediaFileSource.cpp@@ -593,6 +599,9 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_compile_definitions(veyra_decode_profile_probe PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN UNICODE _UNICODE)target_link_libraries(veyra_decode_profile_probe PRIVATE d3d12 dxgi dxguid)add_executable(veyra_fsr_probe tools/fsr_probe/main.cpp)+ add_executable(veyra_fsr_dispatch_tests tests/integration/FsrFgDispatchTests.cpp)+ target_compile_features(veyra_fsr_dispatch_tests PRIVATE cxx_std_20)+ target_link_libraries(veyra_fsr_dispatch_tests PRIVATE veyra_gfx d3d12 dxgi dxguid)target_compile_features(veyra_fsr_probe PRIVATE cxx_std_20)target_compile_options(veyra_fsr_probe PRIVATE /utf-8 /WX-)target_compile_definitions(veyra_fsr_probe PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN UNICODE _UNICODE)@@ -697,6 +706,10 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_compile_features(veyra_fg_sustained_tests PRIVATE cxx_std_20)target_link_libraries(veyra_fg_sustained_tests PRIVATE veyra_engine)add_executable(veyra_fg_presentation_tests tests/integration/FgPresentationTests.cpp)+ add_executable(veyra_fsr_switch_tests tests/integration/FsrFgSwitchTests.cpp)+ target_compile_features(veyra_fsr_switch_tests PRIVATE cxx_std_20)+ target_include_directories(veyra_fsr_switch_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})+ target_link_libraries(veyra_fsr_switch_tests PRIVATE veyra_engine)target_compile_features(veyra_fg_presentation_tests PRIVATE cxx_std_20)target_compile_definitions(veyra_fg_presentation_tests PRIVATE VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")target_link_libraries(veyra_fg_presentation_tests PRIVATE veyra_engine)@@ -746,12 +759,16 @@ endif()# never depend on Qt being installed.if(VEYRA_BUILD_QML_UI AND Qt6_FOUND)add_library(veyra_qml_bridge STATIC src/ui/QmlPlayerBridge.cpp src/ui/ThumbnailProvider.cpp- include/veyra/ui/QmlPlayerBridge.h include/veyra/ui/ThumbnailProvider.h)+ include/veyra/ui/QmlPlayerBridge.h include/veyra/ui/ThumbnailProvider.h+ # P4-c: the existing subtitle renderer, reused as-is (no second renderer).+ apps/veyra/ui/SubtitleOverlay.cpp)+ set_source_files_properties(apps/veyra/ui/SubtitleOverlay.cpp PROPERTIES COMPILE_OPTIONS /utf-8)# AUTOMOC: QmlPlayerBridge declares Q_OBJECT, so its meta-object has to be# generated. Without this the library links but every signal is unresolved.set_target_properties(veyra_qml_bridge PROPERTIES AUTOMOC ON)target_compile_features(veyra_qml_bridge PRIVATE cxx_std_20)- target_include_directories(veyra_qml_bridge PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/src ${FFMPEG_INCLUDE_DIRS})+ target_include_directories(veyra_qml_bridge PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/src ${FFMPEG_INCLUDE_DIRS}+ ${CMAKE_CURRENT_SOURCE_DIR}/apps/veyra/ui)# Widgets is needed only for QFileDialog: the native file picker is the one# piece of the old shell worth keeping, and its own dialog is what users# expect from a desktop app. No QWidget UI is created.@@ -768,12 +785,17 @@ if(VEYRA_BUILD_QML_UI AND Qt6_FOUND)# around, which is not what a player should look like. Diagnostics still reach# the log file through the logger.add_executable(veyra_qml_ui WIN32 apps/veyra-qml/main.cpp src/ui/QmlDataDirectory.cpp)- add_custom_command(TARGET veyra_qml_ui POST_BUILD- COMMAND ${CMAKE_COMMAND} -E copy_directory- ${CMAKE_CURRENT_SOURCE_DIR}/qml $<TARGET_FILE_DIR:veyra_qml_ui>/qml)+ # The QML copy is its own always-run step rather than a POST_BUILD of the link:+ # its two long E:/项目 paths on the link statement pushed that command past+ # CMake's response-file threshold, and link.exe reads response files in the+ # ANSI code page (the UTF-8 Qt library paths then fail to open).+ add_custom_target(veyra_qml_files ALL+ COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/qml ${CMAKE_CURRENT_BINARY_DIR}/qml+ COMMENT "Copying QML")+ add_dependencies(veyra_qml_ui veyra_qml_files)target_compile_features(veyra_qml_ui PRIVATE cxx_std_20)# Qt6::CorePrivate only for QUnifiedTimer's slow mode behind --slow-animations.- target_link_libraries(veyra_qml_ui PRIVATE veyra_qml_bridge veyra_engine Qt6::CorePrivate)+ target_link_libraries(veyra_qml_ui PRIVATE veyra_qml_bridge veyra_engine Qt6::CorePrivate dbghelp ole32)add_executable(veyra_qml_data_tests tests/unit/QmlDataDirectoryTests.cpp src/ui/QmlDataDirectory.cpp)target_compile_features(veyra_qml_data_tests PRIVATE cxx_std_20)@@ -823,6 +845,20 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionTtarget_link_libraries(veyra_motion_validation_tests PRIVATE veyra_pipeline)add_executable(veyra_repair_shader_tests tests/integration/RepairShaderTests.cpp)add_executable(veyra_nr_temporal_gpu_tests tests/integration/NrTemporalGpuTests.cpp)+ # Stage-4 defect-audit assertions: GPU-free checks on the architecture-spoof+ # scope and the Ampere re-label policy (see docs/NR_FG_OPTIMIZATION_PLAN_2026-09-29.md).+ # Stage-6 anti-flicker tier assertions (GPU-free: enum narrowing, flat/list+ # agreement, validation, chain-node carry).+ add_executable(veyra_nr_antiflicker_tests tests/integration/NrAntiFlickerTests.cpp)+ target_compile_features(veyra_nr_antiflicker_tests PRIVATE cxx_std_20)+ target_link_libraries(veyra_nr_antiflicker_tests PRIVATE veyra_engine)+ # Stage-5 output-stabiliser acceptance (anti-flicker, default off).+ add_executable(veyra_nr_hold_gpu_tests tests/integration/NrHoldGpuTests.cpp)+ target_compile_features(veyra_nr_hold_gpu_tests PRIVATE cxx_std_20)+ target_link_libraries(veyra_nr_hold_gpu_tests PRIVATE veyra_pipeline)+ add_executable(veyra_nr_runtime_assertion_tests tests/integration/NrRuntimeAssertionTests.cpp)+ target_compile_features(veyra_nr_runtime_assertion_tests PRIVATE cxx_std_20)+ target_link_libraries(veyra_nr_runtime_assertion_tests PRIVATE veyra_pipeline)add_executable(veyra_nr_video_quality_probe tests/integration/NrVideoQualityProbe.cpp)target_compile_features(veyra_nr_video_quality_probe PRIVATE cxx_std_20)target_link_libraries(veyra_nr_video_quality_probe PRIVATE veyra_engine)@@ -879,7 +915,7 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionTtarget_link_libraries(veyra_color_grade_tests PRIVATE veyra_pipeline)# GPU contract for the v4 colour chain: identity when off/neutral, exposure,# curve, saturation and hue, all through a real graph and its ingest pass.- add_executable(veyra_color_grade_gpu_tests tests/integration/ColorGradeGpuTests.cpp)+ add_executable(veyra_color_grade_gpu_tests tests/integration/ColorGradeGpuTests.cpp src/engine/EffectChain.cpp)target_compile_features(veyra_color_grade_gpu_tests PRIVATE cxx_std_20)target_compile_options(veyra_color_grade_gpu_tests PRIVATE /utf-8 /WX-)target_compile_definitions(veyra_color_grade_gpu_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)@@ -986,6 +1022,17 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionTfind_package(SDL3 3.4.14 EXACT CONFIG REQUIRED)target_sources(veyra PRIVATE apps/veyra/ui/RemotePlayPanel.cpp src/remoteplay/ControllerInput.cpp)target_link_libraries(veyra PRIVATE SDL3::SDL3)+ # P4-e: the QML front end forwards the PC controller to the PS5 the same way.+ # Only the SDL library file and headers: SDL3::SDL3's own system-library list+ # pushed the veyra_qml_ui link line over CMake's response-file threshold, and+ # link.exe reads response files in the ANSI code page, which breaks the UTF-8+ # Qt paths under E:/项目. Those system libraries come from #pragma comment in+ # QmlPlayerBridge.cpp instead.+ if(TARGET veyra_qml_bridge)+ target_sources(veyra_qml_bridge PRIVATE src/remoteplay/ControllerInput.cpp)+ target_link_libraries(veyra_qml_bridge PUBLIC $<TARGET_LINKER_FILE:SDL3::SDL3-static>)+ target_link_libraries(veyra_qml_bridge PRIVATE SDL3::Headers)+ endif()add_executable(veyra_remoteplay_boundary_tests tests/remoteplay/ProductBoundaryTests.cpp src/remoteplay/ControllerInput.cpp)target_compile_features(veyra_remoteplay_boundary_tests PRIVATE cxx_std_20)target_link_libraries(veyra_remoteplay_boundary_tests PRIVATE veyra_sources SDL3::SDL3)@@ -1098,3 +1145,10 @@ if(TARGET veyra_qml_ui)OBJECT_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/assets/veyra.ico;${CMAKE_CURRENT_SOURCE_DIR}/apps/veyra/resource.h")endif()target_link_options(veyra PRIVATE "/MANIFESTINPUT:${CMAKE_CURRENT_SOURCE_DIR}/apps/veyra/veyra.manifest")+# P4-c: the QML front end hosts the same layered child subtitle window.+if(TARGET veyra_qml_ui)+ # Copied next to the link step and named relatively: a short link line keeps+ # link.exe off the (ANSI-decoded) response file.+ configure_file(apps/veyra/veyra.manifest ${CMAKE_CURRENT_BINARY_DIR}/veyra-qml.manifest COPYONLY)+ target_link_options(veyra_qml_ui PRIVATE "/MANIFESTINPUT:veyra-qml.manifest")+endif()diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex b2d790a7..b667278e 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -2,6 +2,18 @@NVIDIA SDKs and runtimes are excluded from source control. The publisher-authorized experimental Release package contains only selected runtime DLLs and applicable notices, as documented in `docs/RUNTIME_COMPONENTS_0.0.2.md`. This is not vendor endorsement or a general redistribution grant. ReShade/RenoDX add-ons are not loaded or distributed by the product.+## AVerMedia capture HDR-to-SDR control++The AVerMedia hardware HDR-to-SDR property request in+`src/source/CaptureCardSource.cpp` is adapted from `source/device-vendor.cpp`+(`SetTonemapperAvermedia`) in [obsproject/libdshowcapture](https://github.com/obsproject/libdshowcapture/tree/c13d4b7b0c66979396ba0a9060c9aafc15bb7b22),+fixed commit `c13d4b7b0c66979396ba0a9060c9aafc15bb7b22`, Copyright (C) 2023+Lain Bailey, LGPL-2.1-or-later (see `licenses/capture/LIBDSHOWCAPTURE_LGPL.txt`). Veyra restricts+the protocol to the selected AVerMedia filter, logs Set/Get results, and applies+the wide/narrow format policy at each connection before SetFormat. Unsupported+properties remain an explicit warning. This does not prove the GC573 15 FPS+cause or provide unsupported Elgato 4K X HID control.+## Elgato MK.2 capture controlMIT adaptations in `src/source/ElgatoHdrControl.cpp` and its header:@@ -44,6 +56,16 @@ Source: https://github.com/Coldwood1026/OptiScaler , commit `70676c5f037c8c26f1eThe provider DLL on disk is never modified, re-signed or renamed; only the mapped image of the process is patched, and every patched byte is restored when the XeFG/XeLL contexts are destroyed. Because Veyra itself is GPLv3, the ported GPL-3.0 code is compatible; the upstream authorship above is attributed here. Locked provider identity: `libxess_fg.dll` 1.3.1.78, 22,957,432 bytes, SHA-256 `EC5E0C65E075570C6EDE72618BB666D0BE0C2E10B2EA9762C0FE8CB8E375AB27`, PE TimeDateStamp `0x69CB0F4D`, SizeOfImage `0x015ED000`.+2026-09-30 changes: `src/gfx/XessMfgUnlock.cpp` now stores the actual byte+string before forming the mismatch diagnostic, avoiding iterators into two+different temporaries; `src/gfx/XessPresenter.cpp` logs the unlock result detail.+The five patch locations and transaction remain unchanged. They were compared+with the renamed upstream [OptiScalerDp4aUnlock](https://github.com/Coldwood1026/OptiScalerDp4aUnlock),+commit `9eea95bba9fda7121f214d2eba358423be598d7e` (GPL-3.0).+The QML selector exposes experimental 3X/4X only for an audited provider and+uses the running SDK capacity when available. This is not official Intel+support for non-Intel multi-frame generation or proof for every AMD adapter.+XeSS pacing adaptation (2026-09-19): `include/veyra/gfx/XessPacing.h` and `src/gfx/XessPacing.cpp` also adapt the above pinned OptiScaler `XeFGPacing.h` NoteFrame/PaceFrame/WaitUntil logic: a bounded 15-period median, generated-frame deadlines, and the provider-owned tail limiter condition. Veyra retains its audited call-site hooks, adds synchronized statistics and complete hooked-present-return gap measurements, and does not port upstream timestamp hooks. Provider scheduling remains preferred; wall-clock pacing is used only when its scheduler is unavailable. No on-disk runtime changes.XeSS read-only timing diagnostics (2026-09-21): the timestamp callback ABI and@@ -76,6 +98,31 @@ Product D3D12 regression coverage is in`tests/integration/NrTemporalGpuTests.cpp`. The switch is default-off until affected RTX hardware and motion-scenequality tests reject ghosting and flicker regressions.+## DLSS NR default runtime: community Lecram 310.8.3 (2026-09-29)++The default NR slot (`runtime/experimental/nvngx_dlssnr.dll`) holds a community-modified build of+NVIDIA's `nvngx_dlssnr.dll`, file version 310.8.3.0, SHA-256+`F95FEB54137EA11979F9B4EC4F00AFD84B5C98A5624D3388FBF6A87714A39FCC`, 165840496 bytes, obtained by the user+from https://github.com/RankFTW/rhi-repo/releases/tag/dlssnr-310.8.Lecram (archive SHA-256+`ddb64e5545ba3f217c32555d2eb8fdfe76b9510d2256f13e8a5ecb1a9650ca54`). Compared with NVIDIA 310.8.0.0 it differs+in the `.data` section that holds the GPU kernels (and 25 bytes of `.text`); the model weights are unchanged.+Its Authenticode status is HashMismatch: NVIDIA's certificate over modified content, so it is not an+NVIDIA-signed original and is not endorsed by NVIDIA. Veyra loads it unmodified by absolute path; it is+never committed to source control. On an RTX 5070 its NR output was byte-identical to 310.8.0.0 on matched+frames and about 2% cheaper. NVIDIA's rights in the runtime and the model are unaffected by Veyra's license.++## DLSS NR RTX30 runtime: community SF-v2 310.8.2 (2026-09-29)++The RTX30 NR slot (`runtime/experimental/nr-ampere/nvngx_dlssnr.dll`) holds ShortFuse's community-modified+build of NVIDIA's `nvngx_dlssnr.dll`, version string 310.8.SF.0 (numeric 310.8.2.0), SHA-256+`6EB209E764F39872625DEBD6ABAF45E2BB6322F6F270F781F70C059AE30B3927`, 165830144 bytes, unsigned, obtained by the user+from https://github.com/RankFTW/rhi-repo/releases/tag/dlssnr-310.8.SF-v2 (archive SHA-256+`1da35941894994eb087e017577829e492454e9bae3a6a9397027069ceb74955c`). It changes the kernel and model-weight+sections to provide an FP16 route for RTX 20/30. On an RTX 5070 its NR output was byte-identical to NVIDIA's 310.8.0.0 on matched+frames; the RTX 20/30 route has not been measured locally. Veyra+loads it unmodified by absolute path and does not rewrite the reported GPU architecture for this build. It is+never committed to source control and is not endorsed by NVIDIA.+## AMD FidelityFX Optical FlowFidelityFX SDK 1.1.4, upstream commit `c6efa6bf7f2027b3ec94f28578bb5965eabb9e55`, https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK . The optical-flow and DX12 backend libraries are statically linked. Copyright (C) 2024 Advanced Micro Devices, Inc.; MIT license, reproduced in the package's `licenses/AMD_FIDELITYFX_LICENSE.txt`. This is optical flow, not AMD NR or AMD super resolution.@@ -183,8 +230,8 @@ Remote Play also depends on **OpenSSL, Opus, json-c, libevent, miniupnpc, curl,## AMD FidelityFX SDK 2.3.0 (experimental FSR frame generation and FSR upscaling)-The player's AMD FSR backends (frame generation in the present sink and-upscaling in the enhancement graph) are written against the public FidelityFX+The player's AMD FSR backends (independent frame generation and upscaling in+the enhancement graph) are written against the public FidelityFXAPI documented and shipped in the AMD FidelityFX SDK 2.3.0 (MIT licensed). TheSDK itself is **not** vendored into this source repository: it stays in thegitignored `third_party_local/amd/FidelityFX-SDK-2.3.0` tree, and the signed@@ -194,21 +241,128 @@ Integration code (`src/gfx/FsrFgPresenter.cpp`, `src/gfx/FsrSrBackend.cpp`) is aindependent implementation of the documented API sequence and was writtenagainst these references:+- Fixed SDK source: [GPUOpen-LibrariesAndSDKs/FidelityFX-SDK](https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK/tree/60f4ea81909200d8542eca14dccb2628b763a9a3),+ commit `60f4ea81909200d8542eca14dccb2628b763a9a3` (SDK 2.3.0).+- `Kits/FidelityFX/framegeneration/include/ffx_framegeneration.h` and+ `Kits/FidelityFX/framegeneration/fsr3/internal/ffx_provider_fsr3framegeneration.cpp`+- `Kits/FidelityFX/docs/techniques/frame-interpolation-ml.md`- `Kits/FidelityFX/docs/techniques/frame-interpolation-swap-chain.md`- `Kits/FidelityFX/docs/techniques/frame-interpolation-api.md`- `Kits/FidelityFX/upscalers/include/ffx_upscale.h` and the FSR3 upscalershader contract (`ffx_fsr3upscaler_reproject.h` for the motion convention)- `Samples/Upscalers/FidelityFX_FSR/dx12/fsrapirendermodule.cpp`-Relevant negative finding, recorded so it is not re-litigated: a FidelityFX+Historical negative finding: a FidelityFXframe-generation swapchain context keeps the real DXGI swapchain alive after-`ffxDestroyContext` (measured locally), so the player retains the proxy-swapchain for the window's lifetime. The FidelityFX upscale dispatch also does+`ffxDestroyContext` (measured locally). The 2026-09-30 repair removes this proxy+path from the player. `include/veyra/gfx/FsrFgPresenter.h` and+`src/gfx/FsrFgPresenter.cpp` use the documented+`FFX_FRAMEGENERATION_FLAG_NO_SWAPCHAIN_CONTEXT_NOTIFY` flag and the+Configure → PrepareV2 → Generate sequence, with caller-owned command lists and+output textures. `EnhanceGraph`, `VideoPresenter` and `PresentSink` share the+existing bounded batch, GPU fences and native presentation path; no dummy+display or second hidden video window is created. The adapter selects a+provider version explicitly and verifies the version returned by the created+context. FSR 3.1 and FSR 4 ML are separate requests, with no implicit version+fallback. Modules retain one process reference per absolute path, while each+effect context is destroyed after its GPU consumers finish.++Version selection and API ordering were also compared with OptiScaler commit+`45a2001303ddff632e279f77aef85ceede5832cb`,+`FSRFG_Dx12.cpp` (GPL-3.0); no source code from that file was+copied. AMD algorithm source, SDK files and runtime binaries are not added to+the Veyra source repository. Changes and actual hardware evidence are in+[FSR / XeSS repair execution](docs/FG_FSR_XESS_EXECUTION_2026-09-30.md).++The FidelityFX upscale dispatch also doesnot complete under D3D12 GPU-based validation (the standalone probe stallsbefore its dispatch), so that validation mode is skipped for the FSR SRconfiguration with an explicit log line. See[AMD FSR frame generation integration record](docs/FSR_FRAMEGEN_INTEGRATION_2026-09-16.md).+## DLSS-G 310.9.1 provider patches: DLSSG-Transfusion (2026-09-30)++SilyNoMeta/DLSSG-Transfusion, tag `v1.4.5.3-rtx20-30-40`, commit+`b56bd2deed114507ad2c88f986d90ed50ffb4639` (MIT; fork of+TonyJoaca/DLSSG-Transfusion, MIT, Copyright (c) 2026 Michael Robles), ported+into `include/veyra/ngx/DlssgTransfusion.h`, `src/ngx/DlssgTransfusion.cpp` and+`src/ngx/transfusion/` (which keeps the upstream MIT text in+`src/ngx/transfusion/LICENSE.txt`).++Ported pieces, with upstream file names:++- `patcher.cpp`: `SafeScanDlssgArchSites` / `PatchDlssgArchGates` (Blackwell+ `cmp r32, 0x1b0` gates lowered to the architecture actually present),+ `SafeFindUniqueImmediate` / `PatchDlssgMinimumArchitecture` (the unique Ada+ immediate `0x190` inside `NVSDK_NGX_GetGPUArchitecture` and the three+ `*_GetFeatureRequirements` exports), and `kNgxPatch` — the provider+ count/index validator branch (`84 d2 0f 84 03 01 00 00 be 05 00 00 00`) whose+ jz is removed, gate discovery by `PatchUniqueExecutablePattern`.+- `midpoint_fix.cpp`: `PatchProvider`. With Blackwell kernels enabled it+ rebuilds the `Kernel_EstimateIntermMvecsScatter` and+ `Kernel_BlendCandidatesFused` fatbins from their sm_120 PTX (uncompressed,+ relabelled for the target SM, so the driver JITs them instead of loading+ NVIDIA's SASS), redirects the descriptor slots that point at them, and+ retargets every remaining kernel container in place+ (`RetargetContainers`, same-length `.target` rewrite inside the LZ4 literal+ run, other images parked at arch 122). With Blackwell kernels disabled it+ applies the Ada temporal midpoint fix instead (`BuildTemporalFatbin`: the+ temporal parameter is injected and the 104 compiled-in `0f3F000000` midpoint+ multiplies become the kernel's own temporal parameter).+- `cu_module_hook.h`: interception of `NvAPI_D3D12_CreateCuModule` (id+ `0xAD1A677D`) so image kernels can be replaced before the driver compiles them.+- `network_optimizer.h`: the DL1/DL2 launch substitution (kernel ids, grids,+ blocks and fusions of the dlssg_for_sm86 0.3.5 backend, whose output is+ bit-identical to NVIDIA's; NVIDIA's weights and parameters are passed+ unchanged), plus `image_kernels.h` (Blend `st.global.v2.u32` store merge and+ the exact `Kernel_OutputPull` / `Kernel_OutputPushFine` replacements, matched+ by an FNV-1a fingerprint of NVIDIA's 310.9.1 sm_120 PTX with the `.target`+ line excluded) and `quality_fix.h` + `quality_explained_warp.h` (the+ valid-warp anti-tearing/anti-ghosting protection: Transfusion's V4 policy or,+ by default in Veyra, dlssg_for_sm86's `explained-warp` tuning).++Veyra adaptations: the module is compiled into `veyra_ngx` and applies its edits+through a recorded-write helper, so every patched byte is restored on release+with read-back verification (`memProtectionUncertain` is raised when+restoration cannot be proved); NvAPI is reached by redirecting only the+provider's own `GetProcAddress` import slot, so no Detours, trampoline or+global hook is installed; the optimized kernels are separate runtime files+under `runtime/experimental/dlssg-kernels/` (gitignored authoring copy in+`third_party_local/nvidia/dlssg-transfusion-kernels-1.4.5.3/`, extracted+read-only from the upstream release DLL), never linked in, and a missing file+set only disables the optimization; Turing, Vulkan, Streamline, the UI-assist+capture and the scatter/input-motion experiments are **not** ported.++### Optimized kernel files (`runtime/experimental/dlssg-kernels`)++29 PTX files extracted, read-only, from the upstream release binary+`DLSSG-Transfusion.dll` (release `v1.4.5.3-rtx20-30-40`, SHA256+`3C0621BE577E56D03945ACCA48C2DFC5935A8A5759C432044E4E561B16DBBAD8`): 27 RCDATA+resources 4000–4062 (the DL1/DL2 sm_86 network kernels) and the two embedded+image kernels. Upstream's `docs/PUBLIC-SOURCE.md` and `docs/OPTIMIZED-KERNELS.md`+state their provenance: they come from the `dlssg_for_sm86` 0.3.5 backend,+which publishes no source and no license for them, and they derive from+NVIDIA's DLSS-G network kernels; SilyNoMeta publishes them only as compiled+resources and explicitly disclaims the right to license them. **No license is+granted for these files by either author.** The 2026-09-30 user decision+accepts that risk and ships them the same way as the other experimental runtime+binaries: as separate runtime files, listed by name, size and SHA-256 in the+package manifest and in `release-runtime-manifest.json`, never committed to+source control. Each file is verified by FNV-1a fingerprint and per-launch+shape checks before use; the provider fingerprint guard (the+`Kernel_OutputPull` 310.9.1 match) is what enables the substitution at all, so+a different provider build leaves the kernels unused. Removing the folder+disables the optimization without affecting playback.++Machine evidence (RTX 5070, 2026-09-30): the patched provider applies and rolls+back cleanly, the harness reports `exact=true` and `networkReady=true`, the FG+truth harness (translation, direction, scene cut) passes with the patches+installed, and the product smoke path reports 2400+ generated frames with+`failed=false`. RTX 40 and RTX 30 hardware behaviour is unverified; the valid+warp and the optimized kernels only change output when both are active+together, which is recorded as an open question in+`docs/NR_FG_OPTIMIZATION_PLAN_2026-09-29.md`.+## RTX 40 series DLSS multi-frame unlock (ported)Two upstream projects are ported into `include/veyra/ngx/AdaMfgUnlock.h` /diff --git a/apps/veyra-qml/main.cpp b/apps/veyra-qml/main.cppindex d33b9adf..bd3396f2 100644--- a/apps/veyra-qml/main.cpp+++ b/apps/veyra-qml/main.cpp@@ -23,8 +23,15 @@#include <QRect>#include <QtCore/private/qabstractanimation_p.h>#include <QDebug>+#include <QAbstractNativeEventFilter>+#include <QFile>+#include <QJsonDocument>+#include <QJsonObject>#include <windows.h>+#include <shellapi.h>+#include <shobjidl.h>+#include <dbghelp.h>#include <cmath>#include <cstdlib>@@ -185,7 +192,10 @@ qreal sceneInsetFraction(QQuickWindow* window) {void collectCovers(QQuickItem* item, QList<Cover>& out) {if (!item->isVisible() || item->opacity() <= 0.0) return;- if (item->objectName() == QLatin1String("videoCover")) {+ // A cover is named "videoCover" or carries videoCover: true; the property lets a+ // dialog keep its own objectName for tests (an overridden name used to drop+ // the hole, leaving five dialogs behind the picture).+ if (item->objectName() == QLatin1String("videoCover") || item->property("videoCover").toBool()) {// Scale is folded into the scene rect; the corner radius scales with it.const QRectF r = item->mapRectToScene(QRectF(0, 0, item->width(), item->height()));const qreal s = item->width() > 0 ? r.width() / item->width() : 1.0;@@ -286,6 +296,47 @@ void syncVideoCovers(QQuickWindow* window, QQuickItem* host, qreal inset) {}} // namespace+namespace {+// Last-chance handler, as in the Win32 shell (apps/veyra/main.cpp): provider and+// driver faults are structured exceptions no C++ catch sees. The 2.0 beta had no+// handler, so a field crash left neither a reason nor the last buffered log lines.+std::wstring g_crashDumpDirectory;+LONG WINAPI crashFilter(EXCEPTION_POINTERS* info) {+ static LONG entered = 0;+ if (InterlockedIncrement(&entered) > 1) return EXCEPTION_CONTINUE_SEARCH;+ const auto code = info && info->ExceptionRecord ? info->ExceptionRecord->ExceptionCode : 0u;+ const auto address = info && info->ExceptionRecord+ ? reinterpret_cast<uintptr_t>(info->ExceptionRecord->ExceptionAddress) : uintptr_t(0);+ HMODULE module = nullptr;+ wchar_t moduleName[MAX_PATH]{};+ if (address && GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,+ reinterpret_cast<LPCWSTR>(address), &module) && module)+ GetModuleFileNameW(module, moduleName, MAX_PATH);+ veyra::log::error("crash", std::format("unhandled exception code=0x{:08X} address=0x{:X} module={} offset=0x{:X} thread={}",+ code, address, std::filesystem::path(moduleName).filename().string(),+ module ? address - reinterpret_cast<uintptr_t>(module) : uintptr_t(0), GetCurrentThreadId()));+ SYSTEMTIME st{};+ GetLocalTime(&st);+ wchar_t name[96]{};+ swprintf_s(name, L"veyra-crash-%04u%02u%02u-%02u%02u%02u-%lu.dmp", unsigned(st.wYear), unsigned(st.wMonth),+ unsigned(st.wDay), unsigned(st.wHour), unsigned(st.wMinute), unsigned(st.wSecond), GetCurrentProcessId());+ const std::wstring path = (std::filesystem::path(g_crashDumpDirectory) / name).wstring();+ HANDLE file = CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);+ if (file != INVALID_HANDLE_VALUE) {+ MINIDUMP_EXCEPTION_INFORMATION mei{GetCurrentThreadId(), info, FALSE};+ const BOOL ok = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), file,+ MiniDumpWithIndirectlyReferencedMemory, info ? &mei : nullptr, nullptr, nullptr);+ CloseHandle(file);+ veyra::log::error("crash", std::format("minidump written={} file={}", ok != FALSE,+ std::filesystem::path(name).string()));+ } else {+ veyra::log::error("crash", std::format("minidump open failed error={}", GetLastError()));+ }+ veyra::Logger::instance().flush();+ return EXCEPTION_CONTINUE_SEARCH;+}+} // namespace+int main(int argc, char** argv) {// ExportJobManager relaunches the owning executable with an inherited mapping.// Dispatch before Qt or the video HWND exists, as the Win32 shell does.@@ -312,8 +363,50 @@ int main(int argc, char** argv) {logPath = logPath.parent_path() / (L"veyra-qml-" + std::to_wstring(GetCurrentProcessId()) + L".log");(void)veyra::Logger::instance().openFile(logPath.wstring(), true);}+ g_crashDumpDirectory = logPath.parent_path().wstring();+ SetUnhandledExceptionFilter(crashFilter);+ // Interface scale (设置 → 界面缩放) has to be fixed before Qt starts, so the+ // preference file is read here, from the same data directory the bridge uses.+ // "Auto" leaves Qt following the Windows display scale.+ int uiScale = 0;+ {+ int count = 0;+ LPWSTR* args = CommandLineToArgvW(GetCommandLineW(), &count);+ std::filesystem::path dir = veyra::runtime::localDataDirectory() / L"user-data-2.0.0";+ for (int i = 1; args && i + 1 < count; ++i)+ if (std::wstring(args[i]) == L"--data-dir") dir = args[i + 1];+ if (args) LocalFree(args);+ QFile prefs(QString::fromStdWString((dir / L"qml-preferences.v1.json").wstring()));+ if (prefs.open(QIODevice::ReadOnly))+ uiScale = QJsonDocument::fromJson(prefs.readAll()).object().value(QStringLiteral("uiScale")).toInt();+ if (uiScale == 100 || uiScale == 125 || uiScale == 150) {+ qputenv("QT_ENABLE_HIGHDPI_SCALING", "0");+ qputenv("QT_SCALE_FACTOR", QByteArray::number(uiScale / 100.0));+ veyra::log::info("app", std::format("interface scale fixed at {}%", uiScale));+ } else {+ uiScale = 0;+ }+ }QApplication app(argc, argv);+ app.setProperty("veyraLogFile", QString::fromStdWString(logPath.wstring()));+ app.setProperty("veyraUiScale", uiScale);+ // Frameless windows have no menu, yet DefWindowProc turns a bare Alt tap into+ // SC_KEYMENU and enters modal menu tracking: the next mouse click is eaten and+ // input stalls for about two seconds. Qt has already handled the key itself+ // (Alt+Enter etc. are unaffected), so the system menu loop is refused.+ struct NoKeyMenuFilter final : QAbstractNativeEventFilter {+ bool nativeEventFilter(const QByteArray& type, void* message, qintptr* result) override {+ if (type != "windows_generic_MSG") return false;+ const auto* msg = static_cast<const MSG*>(message);+ if (msg->message != WM_SYSCOMMAND || (msg->wParam & 0xFFF0) != SC_KEYMENU) return false;+ veyra::log::info("ui-window", std::format("system key menu refused (lParam=0x{:X})", unsigned(msg->lParam)));+ if (result) *result = 0;+ return true;+ }+ };+ static NoKeyMenuFilter noKeyMenu;+ app.installNativeEventFilter(&noKeyMenu);app.setApplicationName(QStringLiteral("Veyra"));app.setOrganizationName(QStringLiteral("Veyra"));veyra::log::info("app", "Veyra QML session started");@@ -490,6 +583,24 @@ int main(int argc, char** argv) {}if (testSize.isValid()) window->resize(testSize);+ // Fullscreen must own the whole monitor. Without telling the shell, the taskbar+ // stayed above the fullscreen picture on some systems (field report with the+ // control pill showing behind it): the shell decides "fullscreen application"+ // from its own heuristics, and the owned control window defeats them.+ // ITaskbarList2::MarkFullscreenWindow states it explicitly.+ QObject::connect(window, &QWindow::visibilityChanged, &app, [window](QWindow::Visibility visibility) {+ const bool full = visibility == QWindow::FullScreen;+ ITaskbarList2* taskbar = nullptr;+ const HRESULT created = CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar));+ HRESULT marked = created;+ if (SUCCEEDED(created) && taskbar) {+ if (SUCCEEDED(taskbar->HrInit()))+ marked = taskbar->MarkFullscreenWindow(reinterpret_cast<HWND>(window->winId()), full ? TRUE : FALSE);+ taskbar->Release();+ }+ veyra::log::info("qml-window", std::format("taskbar fullscreen mark={} hr=0x{:X}", full, unsigned(marked)));+ });+// Closing the window must run the engine's own teardown, not just end the loop.// A test harness that hard-kills the process (Stop-Process -Force) loses every// log line still in the file sink's 64 KB buffer - including the ones a test is@@ -562,32 +673,9 @@ int main(int argc, char** argv) {if (syncVideoGeometry(window, host))syncVideoCovers(window, host, sceneInsetFraction(window));};- // V held shows the original picture on the professional page (AppShell: the- // OriginalHold key, engine.comparison(1, false) until release). A Shortcut only- // sees the press, so the window's key events are watched here. Auto-repeat is- // ignored, and a focused text field keeps its V.- struct HoldOriginalFilter : QObject {- QQuickWindow* window; ui::QmlPlayerBridge* bridge; bool held = false;- HoldOriginalFilter(QQuickWindow* w, ui::QmlPlayerBridge* b) : window(w), bridge(b) {}- bool eventFilter(QObject*, QEvent* e) override {- const auto t = e->type();- if (t == QEvent::FocusOut && held) { held = false; bridge->holdOriginal(false); return false; }- if (t != QEvent::KeyPress && t != QEvent::KeyRelease) return false;- auto* k = static_cast<QKeyEvent*>(e);- if (k->key() != Qt::Key_V || k->isAutoRepeat() || k->modifiers() != Qt::NoModifier) return false;- const bool press = t == QEvent::KeyPress;- if (press) {- if (window->property("page").toString() != QLatin1String("pro")) return false;- if (auto* f = window->activeFocusItem(); f && f->inherits("QQuickTextInput")) return false;- if (auto* f = window->activeFocusItem(); f && f->inherits("QQuickTextEdit")) return false;- }- if (press == held) return false;- held = press;- bridge->holdOriginal(press);- return true;- }- };- window->installEventFilter(new HoldOriginalFilter(window, &bridge));+ // Hold-to-compare (V by default) is the bridge's application event filter:+ // the key is rebindable (设置 → 快捷键) and can be switched off (显示 →+ // 按住 V 查看原画). A second hard-wired V filter here used to override both.QObject::connect(window, &QQuickWindow::afterAnimating, &app, follow);QObject::connect(&bridge, &ui::QmlPlayerBridge::snapshotChanged, &app, follow);// The first frame may come before the page layout settles; one pass after thediff --git a/apps/veyra/SettingsWindow.cpp b/apps/veyra/SettingsWindow.cppindex 3284a9c6..f5835fab 100644--- a/apps/veyra/SettingsWindow.cpp+++ b/apps/veyra/SettingsWindow.cpp@@ -951,7 +951,7 @@ void populate(engine::EnhancementSettings s){syncProtection(s.protection);check(200,enhancementEnabled&&s.nr?BST_CHECKED:BST_UNCHECKED);check(201,enhancementEnabled&&s.sr?BST_CHECKED:BST_UNCHECKED);- for(int j=0;j<3;++j){auto h=item(730+j);if(j==int(s.srTarget))SetPropW(h,L"veyra.selected",HANDLE(1));else RemovePropW(h,L"veyra.selected");InvalidateRect(h,nullptr,FALSE);}+ for(int j=0;j<6;++j){auto h=item(730+j);if(j==int(s.srTarget))SetPropW(h,L"veyra.selected",HANDLE(1));else RemovePropW(h,L"veyra.selected");InvalidateRect(h,nullptr,FALSE);}const int multiplierCount=multiplierChoiceCount(s.frameGenerationBackend);if(send(202,CB_GETCOUNT)!=multiplierCount){send(202,CB_RESETCONTENT);const wchar_t* choices[]={L"关闭补帧",L"2X · 一张中间帧",L"3X · 两张中间帧",L"4X · 三张中间帧",L"6X · 五张中间帧"};for(int i=0;i<multiplierCount;++i)send(202,CB_ADDSTRING,0,LPARAM(choices[i]));}send(207,CB_SETCURSEL,s.videoSrQuality,0);send(202,CB_SETCURSEL,multiplierChoiceIndex(s.multiplier),0);@@ -968,13 +968,14 @@ void populate(engine::EnhancementSettings s){}send(208,CB_SETCURSEL,int(s.frameGenerationBackend),0);send(203,CB_SETCURSEL,int(s.nrPolicy),0);send(508,CB_SETCURSEL,int(engine::exportBitrateIndex(s.exportBitrateMbps)),0);- send(218,CB_SETCURSEL,int(s.nrRuntime));+ send(218,CB_SETCURSEL,engine::currentNrRuntime(s.nrRuntime)==engine::NrRuntime::Ampere?1:0);check(219,s.captureCompatible?BST_CHECKED:BST_UNCHECKED);check(220,s.lowLatency?BST_CHECKED:BST_UNCHECKED);check(223,s.nrTemporal?BST_CHECKED:BST_UNCHECKED);check(230,enhancementEnabled&&s.videoHdr.enabled?BST_CHECKED:BST_UNCHECKED);const unsigned hdrValues[]={s.videoHdr.contrast,s.videoHdr.saturation,s.videoHdr.middleGray,s.videoHdr.peakNits};for(int i=0;i<4;++i){send(631+i,TBM_SETPOS,TRUE,hdrValues[i]);putText(1131+i,(std::to_wstring(hdrValues[i])+(i==3?L" nit":L"")).c_str());}send(204,CB_SETCURSEL,int(s.flow),0);send(205,CB_SETCURSEL,int(s.content),0);+ send(246,CB_SETCURSEL,int(s.hdrOutputMode));send(247,CB_SETCURSEL,engine::motionUsesFlow(s.nrMotion)?1:0);send(248,CB_SETCURSEL,engine::motionUsesFlow(s.srMotion)?1:0);send(249,CB_SETCURSEL,engine::motionUsesFlow(s.fgMotion,s.frameGenerationBackend)?1:0);send(209,CB_SETCURSEL,int(s.opticalFlowBackend),0);check(215,s.amdFlowHalfResolution?BST_CHECKED:BST_UNCHECKED);check(210,s.fgStrictAdmission?BST_CHECKED:BST_UNCHECKED);@@ -994,11 +995,11 @@ bool read(engine::EnhancementSettings& s,bool allPages=false){s=enhancementEnabls.multiplier=(multiplier>=0&&multiplier<int(engine::kFgMultiplierChoiceCount))?engine::kFgMultiplierChoices[multiplier]:1;s.frameGenerationBackend=static_cast<engine::FrameGenerationBackend>(generation);s.opticalFlowBackend=static_cast<engine::OpticalFlowBackend>(flowBackend);s.amdFlowHalfResolution=checked(215)==BST_CHECKED;s.flow=static_cast<engine::FlowQuality>(flowQuality);s.content=static_cast<engine::ContentRate>(content);{const int bitrate=send(508,CB_GETCURSEL,0,0);if(bitrate==CB_ERR||bitrate<0||bitrate>=int(engine::kExportBitrateChoiceCount)){message(L"导出码率控件未完成初始化;未保存设置");return false;}s.exportBitrateMbps=engine::kExportBitrateChoices[bitrate];}s.audioSync=static_cast<engine::AudioSyncMode>(send(216,CB_GETCURSEL));- s.nrRuntime=static_cast<engine::NrRuntime>(send(218,CB_GETCURSEL));+ s.nrRuntime=send(218,CB_GETCURSEL)==1?engine::NrRuntime::Ampere:engine::NrRuntime::Original;s.captureCompatible=checked(219)==BST_CHECKED;s.lowLatency=checked(220)==BST_CHECKED;s.nrTemporal=checked(223)==BST_CHECKED;wchar_t offset[32]{};GetWindowTextW(item(217),offset,32);wchar_t* offsetEnd=nullptr;const auto parsed=wcstol(offset,&offsetEnd,10);if(offsetEnd==offset||*offsetEnd||parsed<-250||parsed>250){message(L"声音偏移须为 -250 至 250 ms");return false;}s.audioOffsetMs=int(parsed);- for(int j=0;j<3;++j)if(GetPropW(item(730+j),L"veyra.selected")){s.srTarget=static_cast<pipeline::SrTarget>(j);break;}+ for(int j=0;j<6;++j)if(GetPropW(item(730+j),L"veyra.selected")){s.srTarget=static_cast<pipeline::SrTarget>(j);break;}if(engine::presentSinkFrameGeneration(s.frameGenerationBackend)){const int choices=multiplierChoiceCount(s.frameGenerationBackend);const size_t index=size_t(std::clamp(choices-1,1,int(engine::kFgMultiplierChoiceCount)-1));@@ -1026,7 +1027,11 @@ bool liveField(int id){case 107:s.residual.total=v;break;case 108:s.residual.darken=v;break;case 109:s.residual.brighten=v;break;case 110:s.residual.color=v;break;case 111:s.residual.luminance=v;break;default:return false;}}else switch(id){case 219:s.captureCompatible=checked(id)==BST_CHECKED;break;- case 218:s.nrRuntime=static_cast<engine::NrRuntime>(send(id,CB_GETCURSEL));break;+ case 246:s.hdrOutputMode=engine::HdrOutputMode(send(id,CB_GETCURSEL));break;+ case 247:s.nrMotion=engine::MotionSource(send(id,CB_GETCURSEL));break;+ case 248:s.srMotion=engine::MotionSource(send(id,CB_GETCURSEL));break;+ case 249:s.fgMotion=engine::MotionSource(send(id,CB_GETCURSEL));break;+ case 218:s.nrRuntime=send(id,CB_GETCURSEL)==1?engine::NrRuntime::Ampere:engine::NrRuntime::Original;break;case 203:s.nrPolicy=static_cast<pipeline::NrSizePolicy>(send(id,CB_GETCURSEL));break;case 204:s.flow=static_cast<engine::FlowQuality>(send(id,CB_GETCURSEL));break;case 205:s.content=static_cast<engine::ContentRate>(send(id,CB_GETCURSEL));break;@@ -1049,7 +1054,7 @@ bool liveField(int id){case 700:case 701:case 702:s.model.style=id-700;break;case 710:case 711:s.model.autoMask=id-710;break;case 720:case 721:s.model.uiCorrection=id-720;break;- case 730:case 731:case 732:s.srTarget=static_cast<pipeline::SrTarget>(id-730);break;+ case 730:case 731:case 732:case 733:case 734:case 735:s.srTarget=static_cast<pipeline::SrTarget>(id-730);break;default:return false;}if(!s.validate().empty()){message(L"数值超出范围;仍使用上次有效值");return false;}@@ -1164,8 +1169,9 @@ void layoutEnhancePage(int width){row(200,36);row(1117,24);row(218,36);row(203,36);row(220,36);row(223,36);row(201,36);const int third=(width-40)/3;- for(int i=0;i<3;++i)place(730+i,12+i*(third+8),y,third);- y+=44;row(207,36);+ const int order[6]={0,1,3,4,5,2};+ for(int i=0;i<6;++i)place(730+order[i],12+(i%3)*(third+8),y+(i/3)*44,third);+ y+=88;row(207,36);row(206,36);const int half=(width-32)/2;place(213,12,y,half);place(214,20+half,y,half);y+=44;@@ -1214,7 +1220,7 @@ void arrange(bool commitScroll){// The Smooth Motion explainer unfolds between the frame-generation rows and// the pacing rows, so everything below it moves down by the measured text// height. The control keeps its own y; only the rows after it shift.- const auto helpOffset=[&](const Item& entry){const auto id=GetDlgCtrlID(entry.h);return entry.page==1&&(id==1114||id==205||id==1110||id==240||id==241||id==242||id==243||id==244||id==1147||id==1150)?helpHeight:0;};+ const auto helpOffset=[&](const Item& entry){const auto id=GetDlgCtrlID(entry.h);return entry.page==1&&(id==1114||id==205||id==1110||id==240||id==241||id==242||id==243||id==244||id==1147||id==1150||(id>=246&&id<=249))?helpHeight:0;};for(auto& entry:items){if(GetDlgCtrlID(entry.h)==1120)entry.height=helpHeight;if(entry.page==page&&!entry.hidden&&(GetDlgCtrlID(entry.h)!=1120||smoothMotionHelpExpanded)){wchar_t cls[32]{};GetClassNameW(entry.h,cls,32);contentHeight=std::max(contentHeight,entry.y+helpOffset(entry)+(_wcsicmp(cls,L"COMBOBOX")==0?36:entry.height)+12);}}if(page==2)contentHeight=std::max(contentHeight,colorPageContentHeight);@@ -1490,16 +1496,17 @@ case WM_CREATE:{window=h;font=makeFont(h);items.clear();displayedBackendWarning.combo(207,0,100,{L"DLSS SR",L"RTX 视频超分 · 低",L"RTX 视频超分 · 中",L"RTX 视频超分 · 高",L"RTX 视频超分 · 最高",L"AMD FSR 超分 · 3.1.x(N卡可用)"});for(auto& entry:items)if(entry.page==0&&entry.y>=100)entry.y+=44;button(L"2K",730,0,12,100,80);button(L"4K",731,0,100,100,80);button(L"8K",732,0,188,100,80);+ button(L"5K",733,0,12,144,80);button(L"6K",734,0,100,144,80);button(L"7K",735,0,188,144,80);for(auto& entry:items)if(entry.page==0&&entry.y>=56)entry.y+=24;add(L"STATIC",L"NR 运行版本",1117,0,0,12,56,-1,24);- combo(218,0,84,{L"NVIDIA 原版 · RTX 50",L"社区兼容 · RTX 40/50 实验",L"RTX 30 兼容 · 实验"});- SetPropW(item(218),L"veyra.tip",HANDLE(L"社区版为修改运行时。RTX 30 档需单独组件,性能与兼容性待持卡验证;不解锁 DLSS 补帧。切换会重建管线,失败恢复原设置。"));+ combo(218,0,84,{L"RTX 50 · Lecram",L"RTX 20–50 · SF-v2"});+ SetPropW(item(218),L"veyra.tip",HANDLE(L"两版都是社区实验运行库,全链共享。SF-v2 的 20/30/40 实卡仍需验收;不解锁 DLSS 补帧。切换重建管线,失败恢复原设置。"));// Final layout in reading order; existing control IDs and bindings stay intact.for(auto& entry:items){const int id=GetDlgCtrlID(entry.h);if(id==203)entry.y=128;if(id==201)entry.y=176;- if(id>=730&&id<=732)entry.y=220;+ if(id>=730&&id<=735)entry.y=220;if(id==207)entry.y=264;// The capture/stream audio sync controls are created here but read as a// separate audio page.@@ -1514,6 +1521,10 @@ case WM_CREATE:{window=h;font=makeFont(h);items.clear();displayedBackendWarning.// Reflex) was removed: all three measured identical (2026-09-22).add(L"BUTTON",L"低延迟队列(减少排队;本机无法验收)",240,BS_AUTOCHECKBOX|WS_TABSTOP,1,12,550,-1,32);combo(242,1,590,{L"显示同步:允许撕裂",L"显示同步:垂直同步",L"显示同步:自动"});+ combo(246,1,872,{L"HDR 输出:HDR10(默认;补帧固定)",L"HDR 输出:scRGB 浮点"});+ combo(247,1,920,{L"NR 运动:零运动(抗闪烁仍需光流)",L"NR 运动:光流"});+ combo(248,1,968,{L"超分运动:零运动",L"超分运动:光流"});+ combo(249,1,1016,{L"补帧运动:零运动",L"补帧运动:光流"});combo(243,1,634,{L"输出上限:关闭",L"输出上限:跟随显示器",L"输出上限:自定义"});add(L"EDIT",L"60",244,ES_AUTOHSCROLL|ES_RIGHT|WS_TABSTOP,1,182,678,90,28);add(L"STATIC",L"FPS",1147,0,1,276,678,40,28);@@ -1655,6 +1666,7 @@ __declspec(noinline) LRESULT settingsCommand(HWND h,UINT msg,WPARAM wp,LPARAM lpif(setting.outputRate==engine::OutputRateMode::Custom){wchar_t fps[64]{};GetWindowTextW(item(244),fps,64);wchar_t* end=nullptr;const auto value=wcstod(fps,&end);if(end==fps||*end||!std::isfinite(value)||value<1||value>1000){message(L"自定义限帧须为 1–1000 FPS");return 0;}setting.customFps=value;}if(setting.valid()){controller->requestPresentation(setting);EnableWindow(item(244),setting.outputRate==engine::OutputRateMode::Custom);SendMessageW(GetParent(window),WM_APP+46,0,0);}return 0;}+ if(msg==WM_COMMAND&&LOWORD(wp)>=246&&LOWORD(wp)<=249&&HIWORD(wp)==CBN_SELCHANGE&&!populating){liveField(int(LOWORD(wp)));return 0;}if(msg==WM_COMMAND&&LOWORD(wp)==221&&HIWORD(wp)==BN_CLICKED){smoothMotionHelpExpanded=!smoothMotionHelpExpanded;putText(221,smoothMotionHelpExpanded?L"Smooth Motion · 收起说明 ▴":L"Smooth Motion · 开启方法 ▾");arrange();return 0;}if(msg==WM_COMMAND&&!populating&&(LOWORD(wp)==220||LOWORD(wp)==223)&&HIWORD(wp)==BN_CLICKED){liveField(LOWORD(wp));return 0;}if(msg==WM_COMMAND&&!populating&&LOWORD(wp)==230&&HIWORD(wp)==BN_CLICKED){SendMessageW(GetParent(window),WM_APP+44,230,checked(230));return 0;}@@ -1846,7 +1858,7 @@ __declspec(noinline) LRESULT settingsCommand(HWND h,UINT msg,WPARAM wp,LPARAM lp}if(msg==WM_COMMAND&&!populating&&((LOWORD(wp)==209&&HIWORD(wp)==CBN_SELCHANGE)||((LOWORD(wp)==215||LOWORD(wp)==210)&&HIWORD(wp)==BN_CLICKED))){liveField(LOWORD(wp));return 0;}switch(msg){-case WM_COMMAND:{const int id=LOWORD(wp);if(!populating&&((id>=202&&id<=205||id==207||id==208)&&HIWORD(wp)==CBN_SELCHANGE||(id>=700&&id<=732)&&HIWORD(wp)==BN_CLICKED)){liveField(id);return 0;}if((id==206||id==213||id==214)&&HIWORD(wp)==BN_CLICKED){const auto accepted=SendMessageW(GetParent(h),WM_APP+45,id,checked(206));message(accepted?(id==213?L"请在画面中左键拖动框选;Esc取消。":L"已请求更新NR剔除区。"):L"未能操作:请先打开画面,或清除已满的4个区域。");return 0;}if((id==200||id==201)&&HIWORD(wp)==BN_CLICKED){const bool accepted=SendMessageW(GetParent(h),WM_APP+44,id,checked(id))!=0;message(accepted?L"已请求开关;确认帧边界结果后生效。":L"总增强正在切换,请待当前事务完成。");return 0;}if(HIWORD(wp)==EN_SETFOCUS){for(auto& item:items)if(GetDlgCtrlID(item.h)==id&&item.page==page){RECT r{};GetClientRect(h,&r);int height=MulDiv(r.bottom,96,veyra::ui::layoutDpi(h))-128;if(item.y<scroll)scroll=item.y;if(item.y+item.height>scroll+height)scroll=item.y+item.height-height;arrange(true);break;}}if(!populating&&id>=100&&id<=111&&HIWORD(wp)==EN_CHANGE){liveField(id);return 0;}+case WM_COMMAND:{const int id=LOWORD(wp);if(!populating&&((id>=202&&id<=205||id==207||id==208)&&HIWORD(wp)==CBN_SELCHANGE||(id>=700&&id<=735)&&HIWORD(wp)==BN_CLICKED)){liveField(id);return 0;}if((id==206||id==213||id==214)&&HIWORD(wp)==BN_CLICKED){const auto accepted=SendMessageW(GetParent(h),WM_APP+45,id,checked(206));message(accepted?(id==213?L"请在画面中左键拖动框选;Esc取消。":L"已请求更新NR剔除区。"):L"未能操作:请先打开画面,或清除已满的4个区域。");return 0;}if((id==200||id==201)&&HIWORD(wp)==BN_CLICKED){const bool accepted=SendMessageW(GetParent(h),WM_APP+44,id,checked(id))!=0;message(accepted?L"已请求开关;确认帧边界结果后生效。":L"总增强正在切换,请待当前事务完成。");return 0;}if(HIWORD(wp)==EN_SETFOCUS){for(auto& item:items)if(GetDlgCtrlID(item.h)==id&&item.page==page){RECT r{};GetClientRect(h,&r);int height=MulDiv(r.bottom,96,veyra::ui::layoutDpi(h))-128;if(item.y<scroll)scroll=item.y;if(item.y+item.height>scroll+height)scroll=item.y+item.height-height;arrange(true);break;}}if(!populating&&id>=100&&id<=111&&HIWORD(wp)==EN_CHANGE){liveField(id);return 0;}if(!populating&&id>=100&&id<=111&&HIWORD(wp)==EN_KILLFOCUS){populate(enhancementEnabled?controller->snapshot().desired:configuredSettings);return 0;}engine::EnhancementSettings s;if(id==211){SetFocus(body);s={};if(submit(s)){editDrafts.clear();populate(s);}message(L"已还原内建默认。");}diff --git a/apps/veyra/TelemetryWindow.cpp b/apps/veyra/TelemetryWindow.cppindex 3fdd8a67..58032c25 100644--- a/apps/veyra/TelemetryWindow.cpp+++ b/apps/veyra/TelemetryWindow.cpp@@ -5,13 +5,14 @@#include <filesystem>#include "ui/Theme.h"#include <sstream>+#include <array>#include <iomanip>namespace veyra::ui {namespace {unsigned windowDpi=96;HWND window=nullptr;engine::EngineController* engine=nullptr;HFONT font=nullptr;std::wstring preview;std::wstring wide(const std::string& s){int n=MultiByteToWideChar(CP_UTF8,0,s.data(),int(s.size()),nullptr,0);std::wstring r(n,0);MultiByteToWideChar(CP_UTF8,0,s.data(),int(s.size()),r.data(),n);return r;}std::wstring value(std::optional<double> v){if(!v)return L"未能测量";std::wostringstream o;o<<std::fixed<<std::setprecision(3)<<*v;return o.str();}-void refresh(){auto s=engine->snapshot();const wchar_t* names[]={L"上传/颜色转换",L"超分 SR",L"光流 GPU队列区间(含同步)",L"NR",L"NR变化量合成",L"FG 子帧1",L"FG 子帧2",L"FG 子帧3",L"FG批次",L"最终blit"};std::wostringstream o;+void refresh(){auto s=engine->snapshot();static constexpr std::array<const wchar_t*,size_t(diagnostics::GpuStage::Count)> names={L"上传/颜色转换",L"超分 SR",L"光流 GPU队列区间(含同步)",L"NR",L"NR变化量合成",L"FG 子帧1",L"FG 子帧2",L"FG 子帧3",L"FG 子帧4",L"FG 子帧5",L"FG批次",L"最终blit",L"RTX Video HDR",L"NR节点1",L"NR节点2",L"NR节点3",L"NR节点4",L"调色节点1",L"调色节点2",L"调色节点3",L"调色节点4",L"调色节点5",L"调色节点6"};std::wostringstream o;o<<L"GPU时间戳(毫秒);未执行不记作0。样本帧 "<<s.metrics.identity.sourceFrameId<<L" / epoch "<<s.metrics.identity.epoch<<L" / 设置版本 "<<s.metrics.identity.settingsRevision<<L"\r\n";for(size_t i=0;i<s.metrics.gpu.size();++i){const auto& g=s.metrics.gpu[i];o<<names[i]<<L":"<<(g.state==diagnostics::SampleState::NotExecuted?L"未执行":g.state==diagnostics::SampleState::Pending?L"待GPU完成":value(g.milliseconds))<<L"\r\n";}o<<L"\r\nCPU与调度(毫秒,独立于GPU):取帧 "<<value(s.metrics.decodeCpuMs)<<L" / 图提交 "<<value(s.metrics.submitCpuMs)<<L" / GPU就绪等待 "<<value(s.metrics.gpuWaitCpuMs)<<L"\r\n截止时间等待 "<<value(s.metrics.deadlineWaitCpuMs)<<L" / Present调用 "<<value(s.metrics.presentCpuMs)<<L"\r\n源帧 "<<s.metrics.sourceFrames<<L" / 有效生成 "<<s.metrics.validGenerated<<L" / 实际提交 "<<s.metrics.submitted<<L" / 过期补帧 "<<s.metrics.expired<<L"\r\n当前批次容量 "<<s.metrics.queueWatermark<<L"(上限4);采集入口容量1;采集丢弃 "<<s.captureDropped<<L"\r\n实际提交频率(最近1秒观察):"<<value(s.submissionFps)<<L"fps;实际显示扫描率/光子延迟:未测\r\n";diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cppindex 9f5702e6..6f6a4a89 100644--- a/apps/veyra/ui/AppShell.cpp+++ b/apps/veyra/ui/AppShell.cpp@@ -280,7 +280,7 @@ void openFile(const std::wstring&);void layout();void updateComparison(){engine.comparison(holdOriginal?1:compareMode,holdOriginal?false:referenceBase,compareSplit);}void toggleFullscreenLock(){if(!full)return;fullLocked=!fullLocked;fullControls=!fullLocked;pointerTick=GetTickCount64();layout();SetFocus(mainWindow);SetCursor(fullLocked?nullptr:LoadCursorW(nullptr,IDC_ARROW));veyra::log::info("ui-fullscreen",std::format("locked={} shortcut=Ctrl+L; Esc/F11 exit remains available",fullLocked));}-void toggleFullscreen(){endTransition();fullLocked=false;full=!full;if(tooltips){SendMessageW(tooltips,TTM_POP,0,0);SendMessageW(tooltips,TTM_ACTIVATE,full?FALSE:TRUE,0);}DWORD corner=full?1:2;DwmSetWindowAttribute(mainWindow,33,&corner,sizeof(corner));fullControls=true;pointerTick=GetTickCount64();if(full){GetWindowPlacement(mainWindow,&windowPlacement);SetWindowLongPtrW(mainWindow,GWL_STYLE,WS_POPUP|WS_VISIBLE|WS_CLIPCHILDREN);MONITORINFO mi{sizeof(mi)};GetMonitorInfoW(MonitorFromWindow(mainWindow,MONITOR_DEFAULTTONEAREST),&mi);SetWindowPos(mainWindow,HWND_TOP,mi.rcMonitor.left,mi.rcMonitor.top,mi.rcMonitor.right-mi.rcMonitor.left,mi.rcMonitor.bottom-mi.rcMonitor.top,SWP_FRAMECHANGED);}else{SetWindowLongPtrW(mainWindow,GWL_STYLE,ShellStyle|WS_VISIBLE);MONITORINFO mi{sizeof(mi)};GetMonitorInfoW(MonitorFromRect(&windowPlacement.rcNormalPosition,MONITOR_DEFAULTTONEAREST),&mi);auto& r=windowPlacement.rcNormalPosition;if(r.right<mi.rcWork.left||r.left>mi.rcWork.right||r.bottom<mi.rcWork.top||r.top>mi.rcWork.bottom){OffsetRect(&r,mi.rcWork.left-r.left,mi.rcWork.top-r.top);}SetWindowPlacement(mainWindow,&windowPlacement);SetWindowPos(mainWindow,nullptr,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);}SetWindowTextW(GetDlgItem(mainWindow,Fullscreen),full?L"退出全屏":L"全屏 F11");SetCursor(LoadCursorW(nullptr,IDC_ARROW));layout();SetFocus(mainWindow);veyra::log::info("ui-fullscreen",std::format("enabled={} video-only viewport; transport auto-hides",full));}+void toggleFullscreen(){endTransition();fullLocked=false;full=!full;if(tooltips){SendMessageW(tooltips,TTM_POP,0,0);SendMessageW(tooltips,TTM_ACTIVATE,full?FALSE:TRUE,0);}DWORD corner=full?1:2;DwmSetWindowAttribute(mainWindow,33,&corner,sizeof(corner));fullControls=true;pointerTick=GetTickCount64();if(full){GetWindowPlacement(mainWindow,&windowPlacement);SetWindowLongPtrW(mainWindow,GWL_STYLE,WS_POPUP|WS_VISIBLE|WS_CLIPCHILDREN);MONITORINFO mi{sizeof(mi)};GetMonitorInfoW(MonitorFromWindow(mainWindow,MONITOR_DEFAULTTONEAREST),&mi);SetWindowPos(mainWindow,HWND_TOP,mi.rcMonitor.left,mi.rcMonitor.top,mi.rcMonitor.right-mi.rcMonitor.left,mi.rcMonitor.bottom-mi.rcMonitor.top,SWP_FRAMECHANGED);}else{SetWindowLongPtrW(mainWindow,GWL_STYLE,ShellStyle|WS_VISIBLE);MONITORINFO mi{sizeof(mi)};GetMonitorInfoW(MonitorFromRect(&windowPlacement.rcNormalPosition,MONITOR_DEFAULTTONEAREST),&mi);auto& r=windowPlacement.rcNormalPosition;if(r.right<mi.rcWork.left||r.left>mi.rcWork.right||r.bottom<mi.rcWork.top||r.top>mi.rcWork.bottom){OffsetRect(&r,mi.rcWork.left-r.left,mi.rcWork.top-r.top);}SetWindowPlacement(mainWindow,&windowPlacement);SetWindowPos(mainWindow,nullptr,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);}SetWindowTextW(GetDlgItem(mainWindow,Fullscreen),full?L"退出全屏":L"全屏 F11");SetCursor(LoadCursorW(nullptr,IDC_ARROW));layout();SetFocus(mainWindow);auto presentation=engine.snapshot().presentation;presentation.fullscreen=full;engine.requestPresentation(presentation);veyra::log::info("ui-fullscreen",std::format("enabled={} video-only viewport; transport auto-hides",full));}bool smokeProtection=false;int protectionStep=0;uint64_t protectionSession=0;bool protectionOverlayShown=false;bool protectionArmed=false,protectionDragging=false;POINT protectionStart{};std::pair<float,float> protectionSourceStart;HWND protectionOverlay=nullptr;void cancelProtection(){protectionArmed=protectionDragging=false;if(protectionOverlay)ShowWindow(protectionOverlay,SW_HIDE);if(video&&GetCapture()==video)ReleaseCapture();}@@ -632,7 +632,7 @@ for(auto [id,help]:std::initializer_list<std::pair<int,const wchar_t*>>{{OriginalHold,L"查看原始画面对照,松开回到增强效果。眼见为实。"},{Reference,L"选择对照底图。低延迟NR先行时,NR前底图为原图缩放,不是独立超分对照。"},{CompareToggle,L"切换画面对比,方便看清到底改了哪里。"},{Split,L"拖动对比边界,两边当面对质。"},{Seek,L"拖动跳转;松手后等待解码和增强预热。跳转中保持目标位置,不会故意弹回。"}})SetPropW(GetDlgItem(hwnd,id),L"veyra.tip",HANDLE(help));SetPropW(video,L"veyra.tip",HANDLE(L"专业模式:滚轮缩放 · 中键拖动画面 · 右键恢复适应窗口。缩放不影响增强或保存尺寸。"));tooltips=CreateWindowExW(WS_EX_TOPMOST,TOOLTIPS_CLASSW,nullptr,WS_POPUP|TTS_ALWAYSTIP|TTS_NOPREFIX,0,0,0,0,hwnd,nullptr,GetModuleHandleW(nullptr),nullptr);SetWindowTheme(tooltips,L"",L"");SendMessageW(tooltips,TTM_SETTIPBKCOLOR,RGB(28,31,33),0);SendMessageW(tooltips,TTM_SETTIPTEXTCOLOR,RGB(225,230,228),0);SendMessageW(tooltips,TTM_SETDELAYTIME,TTDT_INITIAL,550);SendMessageW(tooltips,TTM_SETDELAYTIME,TTDT_AUTOPOP,15000);SendMessageW(tooltips,TTM_SETMAXTIPWIDTH,0,360);EnumChildWindows(hwnd,[](HWND child,LPARAM context)->BOOL{auto tip=reinterpret_cast<HWND>(context);wchar_t cls[32]{};GetClassNameW(child,cls,32);if(child==video||_wcsicmp(cls,L"BUTTON")==0||_wcsicmp(cls,L"EDIT")==0||_wcsicmp(cls,L"COMBOBOX")==0||_wcsicmp(cls,TRACKBAR_CLASSW)==0){TOOLINFOW info{TTTOOLINFOW_V2_SIZE};info.uFlags=TTF_IDISHWND|TTF_SUBCLASS;info.hwnd=GetParent(child);info.uId=UINT_PTR(child);auto help=GetPropW(child,L"veyra.tip");info.lpszText=help?reinterpret_cast<wchar_t*>(help):LPSTR_TEXTCALLBACKW;if(!SendMessageW(tip,TTM_ADDTOOLW,0,LPARAM(&info)))veyra::log::error("ui-help","Tooltip registration failed");}return TRUE;},LPARAM(tooltips));-if(smokeSeconds>0)startTick=GetTickCount64();diagnosticPanel=veyra::ui::createTelemetryPanel(hwnd,engine);DragAcceptFiles(hwnd,TRUE);startShellTimer(hwnd,TelemetryTimer,100);layout();return 0;}+if(smokeSeconds>0&&smokeEmpty)startTick=GetTickCount64();diagnosticPanel=veyra::ui::createTelemetryPanel(hwnd,engine);DragAcceptFiles(hwnd,TRUE);startShellTimer(hwnd,TelemetryTimer,100);layout();return 0;}}return DefWindowProcW(hwnd,msg,wp,lp);}@@ -747,13 +747,19 @@ if(wp==ControllerTimer){const auto state=engine.snapshot();if(state.remotePlay&&if(wp==PreferenceSaveTimer){KillTimer(hwnd,PreferenceSaveTimer);if(!preferences.save(uiPreferences,nullptr))veyra::log::warn("preferences","Could not persist presentation settings");return 0;}if(wp==TransitionTimer){transition.sample(GetTickCount64());if(!transition.running){endTransition();veyra::log::info("ui-transition","completed; final layout and swapchain resize released");}layout();return 0;}if(full&&fullControls&&!menuOpen&&!veyra::ui::popupSelectorOpen()&&!GetCapture()&&GetTickCount64()-pointerTick>1600){POINT p{};GetCursorPos(&p);ScreenToClient(hwnd,&p);RECT r{};GetClientRect(hwnd,&r);if(p.y<r.bottom-veyra::ui::dip(hwnd,98)||p.x<0||p.x>=r.right||p.y>=r.bottom){fullControls=false;layout();if(GetForegroundWindow()==hwnd)SetCursor(nullptr);veyra::log::info("ui-fullscreen","controls hidden; video and subtitles only");}}-if(closing){if(engine.idle()&&!exportJob.poll().active()){KillTimer(hwnd,TelemetryTimer);DestroyWindow(hwnd);}return 0;}if(!autoInput.empty()){auto file=autoInput;autoInput.clear();openFile(file);startTick=GetTickCount64();if(openColourPageOnStart){openColourPageOnStart=false;if(uiState.mode==veyra::ui::Mode::Daily)switchMode();selectInspector(2);layout();}}if(smokeControls&&startTick){const auto elapsed=GetTickCount64()-startTick;+if(closing){if(engine.idle()&&!exportJob.poll().active()){KillTimer(hwnd,TelemetryTimer);DestroyWindow(hwnd);}return 0;}if(!autoInput.empty()){auto file=autoInput;autoInput.clear();openFile(file);if(openColourPageOnStart){openColourPageOnStart=false;if(uiState.mode==veyra::ui::Mode::Daily)switchMode();selectInspector(2);layout();}}auto s=engine.snapshot();+// Initialization can legitimately take longer than the short smoke window+// (CreateFeature is often the slowest first operation). Start the diagnostic+// clock only once the requested session is running, while preserving the+// explicit empty-input smoke mode and making failed opens terminate normally.+if(smokeSeconds>0&&!startTick&&!smokeEmpty&&(s.running||s.failed)){startTick=GetTickCount64();veyra::log::info("app",std::format("smoke timer started running={} failed={} image={} frames={}",s.running,s.failed,s.image,s.frames));}+if(smokeControls&&startTick){const auto elapsed=GetTickCount64()-startTick;if(smokeStep==0&&elapsed>2200){engine.pause(true);smokeStep=1;}if(smokeStep==1&&elapsed>2600){engine.seek(1.0);smokeStep=2;}if(smokeStep==2&&elapsed>3200){engine.pause(false);smokeStep=3;}if(smokeStep==3&&elapsed>4100&&!smokeSave.empty()){engine.saveFrame(smokeSave);smokeStep=4;}if(smokeStep==4&&elapsed>5200&&GetEnvironmentVariableW(L"VEYRA_TEST_LARGE_IMAGE_SAVE_THROW",nullptr,0)){const auto retained=engine.snapshot();if(!retained.failed&&retained.running&&retained.frames>0){engine.saveFrame(smokeSave);smokeStep=5;veyra::log::info("image-save-test","retry after injected allocation failure; result/session retained");}}-}auto s=engine.snapshot();playbackPower.update(!closing&&s.running&&!s.failed&&!s.image&&s.transport==veyra::engine::TransportState::Playing);pollSubtitleTracks();if(subtitleRequestAutoAlign&&subtitlePrimary>=0){subtitleRequestAutoAlign=false;startSubtitleAutoAlign();}pollSubtitleAutoAlign();+}playbackPower.update(!closing&&s.running&&!s.failed&&!s.image&&s.transport==veyra::engine::TransportState::Playing);pollSubtitleTracks();if(subtitleRequestAutoAlign&&subtitlePrimary>=0){subtitleRequestAutoAlign=false;startSubtitleAutoAlign();}pollSubtitleAutoAlign();if(screenFill&¤tFile.starts_with(L"screen:")&&s.running){RECT r{};GetClientRect(video,&r);auto extent=s.metrics.resolution.output;if(r.right>0&&r.bottom>0&&extent.width&&extent.height&&(screenFitClient.cx!=r.right||screenFitClient.cy!=r.bottom||screenFitImage.cx!=LONG(extent.width)||screenFitImage.cy!=LONG(extent.height))){diff --git a/apps/veyra/ui/LiveStatusPanel.h b/apps/veyra/ui/LiveStatusPanel.hindex 12e2d53e..20e17be6 100644--- a/apps/veyra/ui/LiveStatusPanel.h+++ b/apps/veyra/ui/LiveStatusPanel.h@@ -131,7 +131,7 @@ inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){:s.applied.frameGenerationBackend==engine::FrameGenerationBackend::Fsr?L"AMD FSR":L"DLSS";rows.emplace_back(L"补帧方式",s.applied.multiplier<=1?L"关闭":std::format(L"{} {}X",fgName,s.applied.multiplier));rows.emplace_back(L"NR内部尺寸",s.applied.nr?std::format(L"{} x {}",s.metrics.resolution.nr.width,s.metrics.resolution.nr.height):L"关闭");- rows.emplace_back(L"NR运行版本",s.nrActive?(s.applied.nrRuntime==engine::NrRuntime::Ampere?L"RTX 30兼容 · 实验":s.applied.nrRuntime==engine::NrRuntime::Community?L"社区兼容 · 实验":L"NVIDIA原版"):L"未运行");+ rows.emplace_back(L"NR运行版本",s.nrActive?(s.applied.nrRuntime==engine::NrRuntime::Ampere?L"RTX 30兼容 · SF-v2 实验":s.applied.nrRuntime==engine::NrRuntime::Community?L"社区兼容 · 实验":L"默认(Lecram 310.8.3)"):L"未运行");rows.emplace_back(L"显示模式",s.running?(s.applied.captureCompatible?L"直播兼容 · 实验":L"标准显示"):L"未运行");if(s.audioAvailable)rows.emplace_back(L"音频声道 · 输入 / 输出",std::format(L"{} / {}{}",s.capture?s.captureAudio.inputChannels:s.audioInputChannels,s.capture?s.captureAudio.outputChannels:s.audioOutputChannels,(s.capture?s.captureAudio.outputChannels<s.captureAudio.inputChannels:s.audioOutputChannels<s.audioInputChannels)?L" · 降混":L""));rows.emplace_back(L"音频同步",s.audioAvailable?(s.capture?(s.captureAudio.running?L"软件估算同步":L"等待视频锚点"):(s.audioEndpointRecovering?L"音频设备恢复中 · 时间线保持":s.audioRebuffering?L"重新同步 · 等待视频锚点":L"音频主时钟")):L"无音频");diff --git a/apps/veyra/ui/SettingHelp.h b/apps/veyra/ui/SettingHelp.hindex 614dbdff..a7e6dac8 100644--- a/apps/veyra/ui/SettingHelp.h+++ b/apps/veyra/ui/SettingHelp.h@@ -49,7 +49,7 @@ inline const wchar_t* settingHelp(int id){case 215:return L"把AMD光流输入宽高各减半,少算一些像素。速度可能更好,细小运动可能看不清。";case 216:return L"自动估算声音补偿,或改用手动偏移。目标是嘴和声音一起到,别让角色自带配音延迟。";case 217:return L"-250到250ms:正值让声音更晚,负值减少已有补偿,不能把未来声音变出来。";- case 218:return L"选择NR运行文件。原版面向RTX50;社区修改版尝试兼容RTX40/50。切换会重建链路,短暂停顿正常。";+ case 218:return L"选择NR运行文件。默认版为社区Lecram 310.8.3,面向RTX50,画面与NVIDIA原版一致且略省功耗;社区修改版尝试兼容RTX40/50;RTX 30兼容版为社区SF-v2(自带RTX 20/30的FP16路线,30系实际效果待持卡验证)。切换会重建链路,短暂停顿正常。";case 219:return L"切换直播兼容显示路径。给捕获软件搭个台阶,不是让所有捕获方式都突然开窍。";case 220:return L"默认先超分→NR(DLSS5)→补帧。打开后NR→超分→补帧,可能更快,也可能多些鬼影或边缘瑕疵。默认关闭,仅预览;需同时开启NR和超分。导出顺序不变。";case 500:return L"H.264兼容性广,HEVC通常更省空间。HDR视频须选HEVC,保存为Main10 / PQ;别把HDR硬塞进普通H.264。编码器按显卡自动选择:N卡用NVENC(零拷贝最快),A卡/I卡用系统硬件编码(驱动自带的H.264/HEVC编码器),HDR导出仍需N卡。";diff --git a/include/veyra/diagnostics/FrameMetrics.h b/include/veyra/diagnostics/FrameMetrics.hindex a2d2c375..d4eac1a4 100644--- a/include/veyra/diagnostics/FrameMetrics.h+++ b/include/veyra/diagnostics/FrameMetrics.h@@ -5,9 +5,18 @@#include "veyra/pipeline/FrameBatch.h"#include "veyra/pipeline/ResolutionPlan.h"namespace veyra::diagnostics {-enum class GpuStage { Color, Sr, Flow, Nr, Residual, Fg1, Fg2, Fg3, Fg4, Fg5, FgBatch, Blit, VideoHdr, Count };+// NrLayer*/ColorNode* are per-instance node spans nested inside the stage+// spans above; they are never merged into enhancementProcessingMs.+enum class GpuStage { Color, Sr, Flow, Nr, Residual, Fg1, Fg2, Fg3, Fg4, Fg5, FgBatch, Blit, VideoHdr,+ NrLayer0, NrLayer1, NrLayer2, NrLayer3,+ ColorNode0, ColorNode1, ColorNode2, ColorNode3, ColorNode4, ColorNode5, Count };static_assert(unsigned(GpuStage::Fg5)-unsigned(GpuStage::Fg1)==4);static_assert(unsigned(GpuStage::FgBatch)>unsigned(GpuStage::Fg5));+static_assert(unsigned(GpuStage::Count)<=32,"GpuTimer keeps one mask bit per stage");+inline constexpr unsigned kTimedNrLayers=4,kTimedColorNodes=6;+// NR layers are indexed among EXECUTING layers; Color by parameter ordinal.+constexpr GpuStage nrLayerStage(unsigned layer){return GpuStage(unsigned(GpuStage::NrLayer0)+layer);}+constexpr GpuStage colorNodeStage(unsigned parameter){return GpuStage(unsigned(GpuStage::ColorNode0)+parameter);}enum class SampleState { NotExecuted, Pending, Measured, Unavailable };enum class CpuStage { Decode, Submit, SlotWait, ReadyWait, DeadlineWait, Present, DecodedQueue, EnhancementDelayEstimate, Count };enum class PairTiming { ArrivalInterval, GeneratedFromA, GeneratedFromB, Count };diff --git a/include/veyra/engine/BackendRecovery.h b/include/veyra/engine/BackendRecovery.hindex b0d554a7..4b8267c1 100644--- a/include/veyra/engine/BackendRecovery.h+++ b/include/veyra/engine/BackendRecovery.h@@ -3,6 +3,15 @@namespace veyra::engine {enum class FailedBackend { None, Infrastructure, OpticalFlow, NgxCore, Nr, Sr, Fg, VideoHdr };+// NGX 310.9.1 definitions. A failure on 566.07 alone does not establish a+// universal minimum driver. Preserve the real result and suggest recovery.+constexpr const wchar_t* ngxFailureHint(uint64_t result) {+ switch(uint32_t(result)) {+ case 0xBAD00002:return L"平台或驱动初始化失败;请更新 NVIDIA 驱动或选择兼容运行库";+ case 0xBAD00001:return L"显卡、驱动或运行库不支持所选功能";+ default:return L"初始化失败;详细原因见诊断日志";+ }+}inline bool disableUnsupportedNvidiaEffects(EnhancementSettings& settings,bool nvidia){if(nvidia)return false;const auto before=settings;diff --git a/include/veyra/engine/DeadlineWait.h b/include/veyra/engine/DeadlineWait.hindex 113a858e..8a3633b3 100644--- a/include/veyra/engine/DeadlineWait.h+++ b/include/veyra/engine/DeadlineWait.h@@ -15,14 +15,23 @@ public:DeadlineWait& operator=(const DeadlineWait&)=delete;// Waits for the timer or, when supplied, an external event (capture// sample arrival). Returns true when the event fired first.- bool slice(double milliseconds=1,HANDLE wakeEvent=nullptr){+ // A second event (GPU fence completion) also ends the wait; only the first+ // event decides the return value.+ bool slice(double milliseconds=1,HANDLE wakeEvent=nullptr,HANDLE secondEvent=nullptr){if(!timer_){Sleep(1);return false;}LARGE_INTEGER due;due.QuadPart=-std::max<LONGLONG>(1,static_cast<LONGLONG>(std::clamp(milliseconds,0.05,2.0)*10000));if(!SetWaitableTimer(timer_,&due,0,nullptr,nullptr,FALSE)){log::error("scheduler","SetWaitableTimer error="+std::to_string(GetLastError()));return false;}- if(wakeEvent){- HANDLE handles[2]={wakeEvent,timer_};- const auto result=WaitForMultipleObjects(2,handles,FALSE,10);+ if(wakeEvent&&secondEvent){+ HANDLE handles[3]={wakeEvent,secondEvent,timer_};+ const auto result=WaitForMultipleObjects(3,handles,FALSE,10);if(result==WAIT_OBJECT_0)return true;+ if(result!=WAIT_OBJECT_0+1&&result!=WAIT_OBJECT_0+2)log::warn("scheduler","wait result="+std::to_string(result));+ return false;+ }+ if(wakeEvent||secondEvent){+ HANDLE handles[2]={wakeEvent?wakeEvent:secondEvent,timer_};+ const auto result=WaitForMultipleObjects(2,handles,FALSE,10);+ if(result==WAIT_OBJECT_0)return wakeEvent!=nullptr;if(result!=WAIT_OBJECT_0+1)log::warn("scheduler","wait result="+std::to_string(result));return false;}diff --git a/include/veyra/engine/EffectChain.h b/include/veyra/engine/EffectChain.hindex 8552e9cf..ab3e574a 100644--- a/include/veyra/engine/EffectChain.h+++ b/include/veyra/engine/EffectChain.h@@ -4,6 +4,8 @@#include "veyra/engine/VideoHdrSettings.h"#include <array>#include <cstdint>+#include <optional>+#include <memory>#include <string_view>namespace veyra::engine {@@ -18,8 +20,6 @@ namespace veyra::engine {// input, and toChain()/fromChain() convert between the two. Later engine work// (multi-NR, ordered executor, node mode) consumes the chain directly.inline constexpr uint32_t kMaxChainNodes = 16;-inline constexpr uint32_t kMaxNrInstances = 4;-inline constexpr uint32_t kMaxColorInstances = 6;enum class EffectType : uint8_t {Color = 0, // tone/LUT grade@@ -52,6 +52,10 @@ struct ChainNrParams {NrRuntime runtime = NrRuntime::Original;bool temporal = false; // motion-reprojected residual stabilizationbool lowLatencyPairing = false; // this layer may run before SR (preview only)+ // Anti-flicker tier, only meaningful when `temporal` is set. Flow is the+ // pre-tier behaviour, so an existing chain keeps doing exactly what it did.+ NrAntiFlicker antiFlicker = NrAntiFlicker::Flow;+ pipeline::NrSizePolicy sizePolicy = pipeline::NrSizePolicy::Realtime;bool operator==(const ChainNrParams&) const = default;};@@ -113,6 +117,124 @@ struct ChainValidation {// but the physics of the pipeline does not change with the UI.ChainValidation validateChain(const EffectChain& chain);+// Editor-only topology. Deliberately NOT a field of EffectChain: that structure+// crosses the export worker ABI. Node payloads stay in the existing chain; IDs+// and edges never become GPU resources. 0 is the input/source (and no edge),+// 1 is the output/sink; effect IDs start at 2 and are never recycled.+struct NodeGraphLayout {+ static constexpr uint32_t Input = 0, Output = 1;+ std::array<uint32_t, kMaxChainNodes> ids{}, next{};+ uint32_t inputNext = Output, nextId = 2;+ bool operator==(const NodeGraphLayout&) const = default;++ // Explicit migration from an already cleaned, valid legacy linear chain.+ ChainValidation initialize(const EffectChain&);+ int indexOf(const EffectChain&, uint32_t id) const;+ // Partial/disconnected documents are legal, but duplicate IDs, merges,+ // cycles, invalid endpoints and singleton/capacity violations are not.+ ChainValidation validate(const EffectChain&) const;+ // Only an input-to-output path can be submitted. Failure leaves `output`+ // unchanged so callers can keep the last accepted runtime chain.+ ChainValidation project(const EffectChain&, EffectChain& output) const;+ ChainValidation connect(const EffectChain&, uint32_t from, uint32_t to);+ ChainValidation disconnect(const EffectChain&, uint32_t from);+ ChainValidation duplicate(EffectChain&, uint32_t id, uint32_t& createdId);+ ChainValidation remove(EffectChain&, uint32_t id);+ ChainValidation insertAfter(const EffectChain&, uint32_t id, uint32_t after);+};+// Legacy node chains are ordered arrays, so removing a stage unambiguously+// bypasses it. List chains and all remaining payload/layout fields are retained.+uint32_t removeLegacyNodeProtection(EffectChain&, int* selectedNr = nullptr, int* selectedColour = nullptr);++// In-process topology envelope. Parameters remain in EnhancementSettings;+// editor coordinates and persistent/export-worker layouts are unchanged.+struct ChainRuntimeOrder {+ std::array<EffectType, kMaxChainNodes> types{};+ uint32_t nodeCount = 0;+ bool operator==(const ChainRuntimeOrder&) const = default;+};+std::optional<ChainRuntimeOrder> runtimeOrder(const EffectChain&);+ChainValidation restoreRuntimeOrder(const EnhancementSettings&, const ChainRuntimeOrder&, EffectChain&);++// CPU-side execution contract, not proof that a GPU executor supports it.+// Kept separate from EffectChain/EnhancementSettings so compiling a plan does+// not change their persistent or export-worker shared-memory representation.+struct ChainExecutionRequest {+ pipeline::Extent source{};+ pipeline::SrTarget srTarget = pipeline::SrTarget::Uhd4K;+ bool stillImage = false;+ bool exportJob = false;+};+struct ChainExecutionStep {+ EffectType type = EffectType::NrEnhance;+ uint32_t nodeIndex = 0; // source editor node, never a compacted index+ uint32_t parameterIndex = 0; // ordinal among ALL nodes of this type+ uint32_t resourceIndex = 0; // ordinal among executing nodes of this type+ pipeline::Extent input{}, processing{}, output{};+ bool operator==(const ChainExecutionStep&) const = default;+};+struct ChainExecutionPlan {+ std::array<ChainExecutionStep, kMaxChainNodes> steps{};+ uint32_t stepCount = 0;+ std::array<uint32_t, effectTypeCount> resourceCounts{};+ pipeline::Extent output{};+ bool operator==(const ChainExecutionPlan&) const = default;+};+// Node mode preserves inter-effect order; list mode uses the existing fixed+// default/NR-first schedules. Each NR size is relative to its actual input,+// not a global nrBeforeSr flag. Disabled nodes and identity SR need no step.+// Failure is atomic. Hardware admission and port connectivity are not inferred+// here: callers must establish those before allocating/executing this plan.+ChainValidation compileChainExecutionPlan(const EffectChain&, const ChainExecutionRequest&, ChainExecutionPlan&);++// Editor state is separate from presets and from source/audio/export settings.+// Only options belonging to the effect chain travel when the mode changes.+struct ChainGlobalSettings {+ pipeline::SrTarget srTarget = pipeline::SrTarget::Uhd4K;+ uint32_t videoSrQuality = 0;+ FrameGenerationBackend fgBackend = FrameGenerationBackend::Dlss;+ FlowQuality flow = FlowQuality::Balanced;+ OpticalFlowBackend opticalFlowBackend = OpticalFlowBackend::Nvidia;+ bool amdFlowHalfResolution = false;+ pipeline::NrSizePolicy nrPolicy = pipeline::NrSizePolicy::Realtime;+ HdrOutputMode hdrOutputMode=HdrOutputMode::Hdr10;+ MotionSource fgMotion=MotionSource::Automatic,srMotion=MotionSource::OpticalFlow,nrMotion=MotionSource::OpticalFlow;+ static ChainGlobalSettings capture(const EnhancementSettings&);+ void apply(EnhancementSettings&) const;+ bool operator==(const ChainGlobalSettings&) const = default;+};++struct NodeEditorDocument {+ EffectChain nodes{};+ NodeGraphLayout layout{};+ // Absent in legacy documents: inherit the enclosing runtime configuration.+ std::optional<ChainGlobalSettings> globals;+ bool operator==(const NodeEditorDocument&) const = default;+};++struct ChainConfiguration : ChainGlobalSettings {+ EffectChain chain{};+ // Runtime parameters remain accepted values; an incomplete editor may hold+ // a different immutable draft without changing the running graph.+ std::shared_ptr<const NodeEditorDocument> editor;+ int selectedNr = -1, selectedColour = -1;+ static ChainConfiguration capture(const EffectChain&, const EnhancementSettings&, int nr = -1, int colour = -1);+ void apply(EnhancementSettings&) const;+ bool valid() const;+ bool operator==(const ChainConfiguration&) const;+};++struct ChainSession {+ std::array<ChainConfiguration, 2> configurations{};+ std::array<bool, 2> initialized{true, false};+ ChainMode active = ChainMode::List;+ static ChainSession initial(const EnhancementSettings&);+ // Work on a copy until the caller has accepted the engine transaction.+ bool select(ChainMode);+ bool valid() const;+ bool operator==(const ChainSession&) const = default;+};+// Converts between the chain description and the settings struct the engine// consumes today. `fromChain` keeps every non-stage field of `base`, so a// round trip through the chain never loses capture/audio/export settings.diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.hindex 8b2a1bf5..4f5e1726 100644--- a/include/veyra/engine/EngineController.h+++ b/include/veyra/engine/EngineController.h@@ -7,6 +7,7 @@#include <condition_variable>#include <functional>#include "veyra/engine/EnhancementSettings.h"+#include "veyra/engine/EffectChain.h"#include "veyra/engine/PresentationSettings.h"#include "veyra/diagnostics/FrameMetrics.h"#include "veyra/engine/PreviewView.h"@@ -21,14 +22,17 @@ namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }namespace veyra::engine {class FrameFlowWindow;struct PlayerOptions { bool nr=false,sr=false,fg=false,realtime=true; uint32_t fgMultiplier=2; EnhancementSettings settings;+ std::optional<ChainRuntimeOrder> nodeOrder; // in-process only; not export shared memoryint audioStreamIndex=-1; // export selection; -1 selects the container defaultdouble exportStartSeconds=0.0; // export-only trim; first complete frame at/after this timedouble exportEndSeconds=0.0; // export-only trim; 0 means source endsink::ExportRateControl exportRateControl=sink::ExportRateControl::Cq;bool captureReplayForTest=false; // file-backed live scheduler test; never enabled by UIbool captureCpuUnpack=false; // N1 diagnostic: legacy per-pixel CPU unpack+ bool softwareDecode=false; // user setting: files skip D3D12VA and decode on the CPU+ bool hardwareDecodeOnly=false; // user setting "强制硬解": files fail instead of falling back to softwareEnhancementSettings snapshot()const{auto s=settings;s.nr=nr;s.sr=sr;s.multiplier=fg?fgMultiplier:1;s.nrPolicy=realtime?(settings.nrPolicy==pipeline::NrSizePolicy::Native?pipeline::NrSizePolicy::Realtime:settings.nrPolicy):pipeline::NrSizePolicy::Native;return s;}- static PlayerOptions from(EnhancementSettings s){PlayerOptions o;o.nr=s.nr;o.sr=s.sr;o.fg=s.multiplier>1;o.fgMultiplier=std::max(2u,s.multiplier);o.realtime=s.nrPolicy!=pipeline::NrSizePolicy::Native;o.settings=s;return o;}+ static PlayerOptions from(EnhancementSettings s,std::optional<ChainRuntimeOrder> order=std::nullopt){PlayerOptions o;o.nr=s.nr;o.sr=s.sr;o.fg=s.multiplier>1;o.fgMultiplier=std::max(2u,s.multiplier);o.realtime=s.nrPolicy!=pipeline::NrSizePolicy::Native;o.settings=s;o.nodeOrder=order;return o;}};enum class TransportState { Empty, Opening, Playing, Paused, Ended, Stopping, Failed };struct PlayerSnapshot {@@ -42,6 +46,7 @@ struct PlayerSnapshot {std::wstring status=L"请打开视频或图片";EnhancementSettings desired,applied;bool applying=false;bool nrActive=false,srActive=false,fgActive=false;+ bool videoHdrActive=false; // TrueHDR actually running this graph (needs an HDR display path)std::wstring backendWarning;std::wstring sourceNotice;std::wstring colorStatus;@@ -99,6 +104,7 @@ struct PlayerSnapshot {// AMD FSR frame-generation ceiling (generated frames per presented frame;// 1 = 2X). 0 = no FSR session has reported yet.int fsrMaxGeneratedFrames=0;+ std::string fsrProviderVersion;bool running=false,failed=false,image=false,capture=false,remotePlay=false;int remotePlayState=0; uint64_t remotePlaySkipped=0;bool remoteRecovering=false;unsigned remoteReconnectAttempts=0;std::wstring remoteRecoveryMessage;@@ -110,7 +116,7 @@ public:EngineController();~EngineController();bool idle()const;- bool requestSettings(EnhancementSettings);+ bool requestSettings(EnhancementSettings,std::optional<ChainRuntimeOrder> = std::nullopt,uint64_t* acceptedRevision=nullptr);void requestPresentation(PresentationSettings);void open(HWND video,const std::wstring& path,PlayerOptions options);#ifdef VEYRA_ENABLE_REMOTEPLAY@@ -122,7 +128,7 @@ public:void stop();void comparison(int mode,bool base,float split=.5f){comparisonMode_=mode;comparisonBase_=base;comparisonSplit_=std::clamp(split,0.0f,1.0f);}void pause(bool p);- void previewView(PreviewView view){if(!std::isfinite(view.zoom)||!std::isfinite(view.centerX)||!std::isfinite(view.centerY))return;std::lock_guard lock(mutex_);view.zoom=std::clamp(view.zoom,.05f,64.0f);previewView_=view;}+ void previewView(PreviewView view){if(!std::isfinite(view.zoom)||!std::isfinite(view.centerX)||!std::isfinite(view.centerY)||!std::isfinite(view.displayAspect)||view.displayAspect<0||view.mode<0||view.mode>6)return;std::lock_guard lock(mutex_);view.zoom=std::clamp(view.zoom,.05f,64.0f);if(view.displayAspect==0)view.displayAspect=previewView_.displayAspect;previewView_=view;}PreviewView previewView()const{std::lock_guard lock(mutex_);return previewView_;}void setVolume(float gain,bool mute);bool selectAudioTrack(uint64_t sessionId,int streamIndex);@@ -147,6 +153,7 @@ private:std::thread worker_;std::condition_variable wake_;std::function<void()> pending_;bool shutdown_=false,busy_=false;EnhancementSettings desired_;uint64_t nextRevision_=1;+ std::optional<ChainRuntimeOrder> desiredNodeOrder_; // protected by mutex_, paired with desired_std::atomic<bool> stop_{false},paused_{false},muted_{false};std::atomic<float> volume_{1};uint64_t sessionId_=0;std::atomic<double> seekSeconds_{-1};diff --git a/include/veyra/engine/EnhancementSettings.h b/include/veyra/engine/EnhancementSettings.hindex 7af67df1..8b64de2a 100644--- a/include/veyra/engine/EnhancementSettings.h+++ b/include/veyra/engine/EnhancementSettings.h@@ -9,11 +9,38 @@#include "veyra/source/CaptureBuffer.h"#include "veyra/engine/ColorSettings.h"namespace veyra::engine {-enum class FrameGenerationBackend { Dlss, XeSS, Fsr };+inline constexpr uint32_t kMaxColorInstances = 6;+inline constexpr uint32_t kMaxNrInstances = 4;+// Anti-flicker route for the NR temporal pass. The tiers come from Magpie's+// DLSSNRTemporal (GPL-3.0, commit 3841698): see shaders/NrTemporal.hlsl.+// Off - no temporal accumulation at all.+// Static - accumulate only where the source is not moving; motion is+// published immediately. The safest tier.+// Flow - motion-reprojected accumulation with a fixed 80 ms EMA. This is+// the behaviour the pass had before the tiers existed, so it+// stays the value a legacy `temporal=true` maps onto.+// FlowPlus - as Flow, plus a 60 ms attack / 180 ms release memory and an+// explicit rejection of a correction whose direction reverses.+// LowFrequency - as Flow, but the accumulated signal is a half-resolution+// residual; this frame's high frequency rides through untouched.+enum class NrAntiFlicker : uint8_t { Off, Static, Flow, FlowPlus, LowFrequency };+// Narrowing for the wire and preset formats, which store this as one integer.+inline bool validNrAntiFlicker(NrAntiFlicker v) {+ return v>=NrAntiFlicker::Off&&v<=NrAntiFlicker::LowFrequency;+}+// Preserve persisted values 0/1/2; the old Fsr value now explicitly selects+// the 3.1 provider. Fsr4 requires a real ML provider, never an auto fallback.+enum class FrameGenerationBackend { Dlss = 0, XeSS = 1, Fsr = 2, Fsr4 = 3 };+constexpr bool fsrFrameGeneration(FrameGenerationBackend backend) {+ return backend == FrameGenerationBackend::Fsr || backend == FrameGenerationBackend::Fsr4;+}+constexpr bool crossVendorFrameGeneration(FrameGenerationBackend backend) {+ return backend == FrameGenerationBackend::XeSS || fsrFrameGeneration(backend);+}// Frame generation that runs inside the present sink (external frame// interpolation swapchain) instead of the in-graph DLSSG backend.constexpr bool presentSinkFrameGeneration(FrameGenerationBackend backend) {- return backend==FrameGenerationBackend::XeSS||backend==FrameGenerationBackend::Fsr;+ return backend==FrameGenerationBackend::XeSS;}// Multipliers the UI offers. 5X is intentionally absent: the DLSS runtime// exposes 2/3/4/6 and MFG buyers pick from those; 1 = generation off.@@ -42,11 +69,16 @@ constexpr std::wstring_view captureAudioIngressName(CaptureAudioIngress mode) {return L"自动(优先 PCM,必要时位流解码)";}enum class NrRuntime { Original, Community, Ampere };+// Persisted value 1 selected the retired RTX40 DLL. Never load that DLL in+// current builds; preserve 0 (Lecram) and 2 (SF-v2) as explicit user choices.+constexpr NrRuntime currentNrRuntime(NrRuntime runtime) {+ return runtime == NrRuntime::Community ? NrRuntime::Ampere : runtime;+}constexpr std::string_view nrRuntimeName(NrRuntime runtime) {switch(runtime) {- case NrRuntime::Original:return "NVIDIA-original";- case NrRuntime::Community:return "community-RTX40-RTX50";- case NrRuntime::Ampere:return "community-RTX30-experimental";+ case NrRuntime::Original:return "community-Lecram-RTX50";+ case NrRuntime::Community:return "community-SF-v2-RTX20-RTX50-legacy40";+ case NrRuntime::Ampere:return "community-SF-v2-RTX20-RTX50";}return "unknown";}@@ -54,11 +86,17 @@ enum class FlowQuality { Performance, Balanced, Quality };enum class OpticalFlowBackend { Nvidia, AmdFidelityFx, GpuDis };enum class ContentRate { Transport, Auto, Fps30, Fps50, Fps60, Capture60To30 };enum class AudioSyncMode { Automatic, Manual, Off };+enum class HdrOutputMode { Hdr10, ScRgb };+enum class MotionSource { Zero, OpticalFlow, Automatic };+constexpr bool motionUsesFlow(MotionSource source,FrameGenerationBackend backend=FrameGenerationBackend::Dlss) {+ return source==MotionSource::OpticalFlow||(source==MotionSource::Automatic&&backend!=FrameGenerationBackend::XeSS);+}constexpr std::string_view frameGenerationBackendName(FrameGenerationBackend backend) {switch(backend) {case FrameGenerationBackend::Dlss: return "DLSS";case FrameGenerationBackend::XeSS: return "XeSS";case FrameGenerationBackend::Fsr: return "AMD-FSR";+ case FrameGenerationBackend::Fsr4: return "AMD-FSR4-ML";}return "unknown";}@@ -79,11 +117,33 @@ struct ResidualSettings {float total=1,darken=1,brighten=1,color=1,luminance=1;bool operator==(const ResidualSettings&) const = default;};+// Fixed storage: settings also cross the export worker's shared-memory POD.+// Runtime and NR/SR order are shared by active instances, not separate adapters.+struct NrLayerSettings {+ NrSettings model{};+ ResidualSettings residual{};+ NrRuntime runtime=NrRuntime::Original;+ bool temporal=false,lowLatencyPairing=false,enabled=false;+ // The tier only applies when `temporal` is set; `temporal=false` forces Off.+ // Kept as a separate field so an older preset that only knew the boolean+ // keeps meaning exactly what it meant (Flow).+ NrAntiFlicker antiFlicker=NrAntiFlicker::Flow;+ pipeline::NrSizePolicy sizePolicy=pipeline::NrSizePolicy::Realtime;+ bool operator==(const NrLayerSettings&) const = default;+};struct ProtectionRect {float left=0,top=0,right=0,bottom=0;+ // The ellipse inscribed in the rectangle instead of the rectangle itself.+ bool ellipse=false;bool empty()const{return left==right||top==bottom;}bool operator==(const ProtectionRect&)const=default;};+// Shader constants for one region (NrProtection.hlsli). An ellipse is sent with+// left and right swapped: the constant layout stays the same and a rectangle's+// constants stay byte-for-byte what they were.+inline std::array<float,4> protectionConstants(const ProtectionRect& q){+ return q.ellipse?std::array<float,4>{q.right,q.top,q.left,q.bottom}:std::array<float,4>{q.left,q.top,q.right,q.bottom};+}struct ProtectionSettings {bool enabled=false;float featherPixels=2;@@ -93,7 +153,10 @@ struct ProtectionSettings {// Upper bound is 64 px at the working extent; TiledImageProcessor keeps// its tile halo above this value so export tiles cannot clip the ramp.if(!std::isfinite(featherPixels)||featherPixels<0||featherPixels>64)return "invalid protection feather";- for(auto r:regions){for(float v:{r.left,r.top,r.right,r.bottom})if(!std::isfinite(v)||v<0||v>1)return "invalid protection rectangle";+ // An ellipse may extend past the frame: a tiled export maps it into+ // tile space without clipping, since clipping would change its shape.+ for(auto r:regions){const float low=r.ellipse?-64.0f:0.0f,high=r.ellipse?65.0f:1.0f;+ for(float v:{r.left,r.top,r.right,r.bottom})if(!std::isfinite(v)||v<low||v>high)return "invalid protection rectangle";if(r.left>r.right||r.top>r.bottom)return "inverted protection rectangle";}return {};}@@ -107,6 +170,34 @@ struct EnhancementSettings {bool lowLatency=false; // preview only: NR before SR, opt-inNrRuntime nrRuntime=NrRuntime::Original;bool nrTemporal=false; // optional motion-reprojected residual stabilization+ // Which anti-flicker tier the temporal pass runs, for the flat (non-list)+ // path. Ignored when nrTemporal is false.+ NrAntiFlicker nrAntiFlicker=NrAntiFlicker::Flow;+ // Zero keeps the original flat, single-layer API byte-for-byte in use.+ // Multi-layer lists retain disabled nodes; the flat fields mirror the first+ // enabled layer (or the first node when every layer is bypassed).+ std::array<NrLayerSettings,kMaxNrInstances> nrLayers{};+ uint32_t nrLayerCount=0;+ NrLayerSettings nrLayer(uint32_t index) const {+ if(nrLayerCount&&index<nrLayers.size())return nrLayers[index];+ return {model,residual,nrRuntime,nrTemporal,lowLatency,nr,nrAntiFlicker,nrPolicy};+ }+ uint32_t activeNrLayerCount() const {+ if(!nr)return 0;+ if(!nrLayerCount)return 1;+ uint32_t count=0;+ for(uint32_t i=0;i<nrLayerCount&&i<nrLayers.size();++i)if(nrLayers[i].enabled)++count;+ return count;+ }+ bool sameNrTopology(const EnhancementSettings& other) const {+ if(nrLayerCount!=other.nrLayerCount)return false;+ for(uint32_t i=0;i<nrLayerCount&&i<nrLayers.size();++i){+ const auto& a=nrLayers[i]; const auto& b=other.nrLayers[i];+ if(a.enabled!=b.enabled||a.temporal!=b.temporal||a.runtime!=b.runtime||+ a.lowLatencyPairing!=b.lowLatencyPairing||a.sizePolicy!=b.sizePolicy)return false;+ }+ return true;+ }// Frame-generation admission strictness.// false (default): a group is admitted when the whole group can still// reach its LAST deadline, which is what 1.4.0 did. More generated@@ -132,6 +223,10 @@ struct EnhancementSettings {// the next sample, so it is a live edit, not a graph rebuild.bool captureFlipVertical=false;bool forceSdrPreview=false; // display only; retain actual HDR source metadata+ HdrOutputMode hdrOutputMode=HdrOutputMode::Hdr10;+ MotionSource fgMotion=MotionSource::Automatic;+ MotionSource srMotion=MotionSource::OpticalFlow;+ MotionSource nrMotion=MotionSource::OpticalFlow;VideoHdrSettings videoHdr;bool useHdrPreview(bool hdrInput,bool hdrDisplayActive)const{return (hdrInput||videoHdr.enabled)&&hdrDisplayActive&&!forceSdrPreview;}pipeline::SrTarget srTarget=pipeline::SrTarget::Uhd4K;@@ -145,6 +240,18 @@ struct EnhancementSettings {// Lightroom-aligned colour grade. Live: the engine uploads it per frame, so// changing it never rebuilds the graph (see sameVideoConfiguration below).ColorSettings color;+ // Instance zero remains the legacy field, including for live Win32 edits.+ // Fixed capacity preserves the export shared-memory POD contract.+ std::array<ColorSettings,kMaxColorInstances-1> additionalColors{};+ uint32_t additionalColorCount=0;+ // Stage-5 output stabiliser (anti-flicker). Holds the previous output where+ // the source has not visibly changed. 0 is off, and off is the default: the+ // graph then skips the dispatch entirely, so a build with this feature+ // disabled is byte-identical to one without it. `nrHoldTolerance` is a+ // relative 3x3 box-luma delta; the default is the value the pass was+ // tuned against (see shaders/NrHold.hlsl).+ float nrHoldStrength=0.0f;+ float nrHoldTolerance=0.02f;pipeline::NrSizePolicy nrPolicy=pipeline::NrSizePolicy::Realtime;FlowQuality flow=FlowQuality::Balanced;OpticalFlowBackend opticalFlowBackend=OpticalFlowBackend::Nvidia;@@ -168,6 +275,14 @@ struct EnhancementSettings {// master switch changes the graph shape, so it stays in the comparison.video.color=other.color;video.color.enabled=color.enabled;+ video.color.lutName=color.lutName;+ video.color.lutInputSpace=color.lutInputSpace;+ video.additionalColors=other.additionalColors;+ for(size_t i=0;i<additionalColors.size();++i){+ video.additionalColors[i].enabled=additionalColors[i].enabled;+ video.additionalColors[i].lutName=additionalColors[i].lutName;+ video.additionalColors[i].lutInputSpace=additionalColors[i].lutInputSpace;+ }video.videoHdr=other.videoHdr;video.videoHdr.enabled=videoHdr.enabled;return video==other;@@ -181,6 +296,8 @@ struct EnhancementSettings {*this=restored;}std::string validate() const {+ if(hdrOutputMode<HdrOutputMode::Hdr10||hdrOutputMode>HdrOutputMode::ScRgb)return "invalid HDR output mode";+ for(auto source:{fgMotion,srMotion,nrMotion})if(source<MotionSource::Zero||source>MotionSource::Automatic)return "invalid motion source";if(!videoHdr.valid())return "invalid RTX Video HDR parameters";auto range=[](float v,float hi){return std::isfinite(v)&&v>=0&&v<=hi;};if(auto error=protection.validate();!error.empty())return error;@@ -189,18 +306,38 @@ struct EnhancementSettings {if(captureAudio<CaptureAudioIngress::Auto||captureAudio>CaptureAudioIngress::BitstreamPreferred)return "invalid capture audio ingress mode";if(captureBuffer<source::CaptureBufferMode::Auto||captureBuffer>source::CaptureBufferMode::DriverDefault)return "invalid capture buffer mode";if(audioSync<AudioSyncMode::Automatic||audioSync>AudioSyncMode::Off||audioOffsetMs<-250||audioOffsetMs>250)return "invalid audio sync setting";+ // Stage-5 output stabiliser: 0 is off, 1 is full hold; the tolerance is+ // a relative box-luma delta, so anything above 1 would hold every pixel.+ if(!range(nrHoldStrength,1))return "output stabiliser strength out of range";+ if(!range(nrHoldTolerance,1))return "output stabiliser tolerance out of range";if(!range(model.intensity,1)||!range(model.tone,1)||!range(model.structure,1))return "model parameter out of range";if(model.skin!=-1&&!range(model.skin,2))return "skin parameter out of range";if(model.style<0||model.style>2||model.autoMask<0||model.autoMask>1||model.uiCorrection<0||model.uiCorrection>1)return "invalid experimental parameter";for(float v:{residual.total,residual.darken,residual.brighten,residual.color,residual.luminance})if(!range(v,2))return "residual parameter out of range";- if(frameGenerationBackend<FrameGenerationBackend::Dlss||frameGenerationBackend>FrameGenerationBackend::Fsr)return "invalid frame generation backend";+ if(nrLayerCount>nrLayers.size())return "too many NR instances";+ for(uint32_t i=0;i<nrLayerCount;++i){+ const auto& n=nrLayers[i];+ if(!pipeline::validNrSizePolicy(n.sizePolicy))return "invalid NR layer size policy";+ if(!range(n.model.intensity,1)||!range(n.model.tone,1)||!range(n.model.structure,1)||+ (n.model.skin!=-1&&!range(n.model.skin,2)))return "NR layer model parameter out of range";+ if(n.model.style<0||n.model.style>2||n.model.autoMask<0||n.model.autoMask>1||+ n.model.uiCorrection<0||n.model.uiCorrection>1)return "invalid NR layer experimental parameter";+ for(float v:{n.residual.total,n.residual.darken,n.residual.brighten,n.residual.color,n.residual.luminance})+ if(!range(v,2))return "NR layer residual parameter out of range";+ if(n.runtime!=NrRuntime::Original&&n.runtime!=NrRuntime::Community&&n.runtime!=NrRuntime::Ampere)+ return "invalid NR layer runtime";+ if(n.enabled&&(n.runtime!=nrRuntime||n.lowLatencyPairing!=lowLatency))+ return "active NR layers must share runtime and NR/SR order";+ }+ if(nr&&nrLayerCount&&!activeNrLayerCount())return "enabled NR stack has no active layer";+ if(frameGenerationBackend<FrameGenerationBackend::Dlss||frameGenerationBackend>FrameGenerationBackend::Fsr4)return "invalid frame generation backend";// The XeSS provider reports its own generated-frame ceiling at session// start; the engine clamps/rejects above it, so validation only guards// the absolute API range here.if(frameGenerationBackend==FrameGenerationBackend::XeSS&&multiplier>4)return "XeSS frame generation supports up to 4X";// The AMD 3.1.x provider delivers one generated frame per present; the// probe measured the same count for 2/3/4 requested frames.- if(frameGenerationBackend==FrameGenerationBackend::Fsr&&multiplier>2)return "AMD FSR frame generation supports up to 2X";+ if(fsrFrameGeneration(frameGenerationBackend)&&multiplier>2)return "AMD FSR frame generation supports up to 2X";if(videoSrQuality>kVideoSrFsr)return "invalid video SR quality";if(!pipeline::validSrTarget(srTarget))return "invalid SR target";if(opticalFlowBackend!=OpticalFlowBackend::Nvidia&&opticalFlowBackend!=OpticalFlowBackend::AmdFidelityFx&&opticalFlowBackend!=OpticalFlowBackend::GpuDis)return "invalid optical flow backend";@@ -209,6 +346,9 @@ struct EnhancementSettings {// cannot ask a driver for a nonsense rate.if(exportBitrateMbps>300)return "export bitrate out of range";if(auto error=color.validate();!error.empty())return error;+ if(additionalColorCount>additionalColors.size())return "too many color instances";+ for(uint32_t i=0;i<additionalColorCount;++i)+ if(auto error=additionalColors[i].validate();!error.empty())return error;if(!pipeline::validNrSizePolicy(nrPolicy))return "invalid NR size policy";if(flow<FlowQuality::Performance||flow>FlowQuality::Quality||content<ContentRate::Transport||content>ContentRate::Capture60To30)return "invalid flow/content mode";return {};diff --git a/include/veyra/engine/ExportJobManager.h b/include/veyra/engine/ExportJobManager.hindex cf963d6d..8b218213 100644--- a/include/veyra/engine/ExportJobManager.h+++ b/include/veyra/engine/ExportJobManager.h@@ -13,6 +13,11 @@ struct ExportJobSnapshot {uint32_t workerPid=0;double etaSeconds=0;uint64_t queuePosition=0,queued=0;+ // Queue items that could not start (existing output, invalid range...) are+ // counted and the latest reason kept, then the queue moves on; they are+ // never skipped silently. Reset when a fresh export starts from idle.+ uint64_t queueFailures=0;+ std::wstring lastQueueFailure;bool active()const{return state>=ExportState::Preparing&&state<=ExportState::Finishing;}};// One isolated NGX context in a child process. Anonymous inherited mapping isdiff --git a/include/veyra/engine/GraphDescription.h b/include/veyra/engine/GraphDescription.hindex c5f24ddc..d0f8c2fc 100644--- a/include/veyra/engine/GraphDescription.h+++ b/include/veyra/engine/GraphDescription.h@@ -4,6 +4,28 @@#include "veyra/pipeline/ResolutionPlan.h"namespace veyra::engine {+// Shared by graph creation and drained live-parameter updates. Disabled list+// nodes stay in settings, but never allocate or evaluate an NR feature.+inline void describeNrLayers(const EnhancementSettings& settings,pipeline::EnhanceGraphDesc& desc){+ desc.nrRuntime=settings.nrRuntime;desc.nrTemporal=settings.nrTemporal;desc.nrAntiFlicker=settings.nrAntiFlicker;+ desc.model=settings.model;desc.residual=settings.residual;desc.protection=settings.protection;+ desc.nrHoldStrength=settings.nrHoldStrength;desc.nrHoldTolerance=settings.nrHoldTolerance;+ desc.nrLayersModel.clear();desc.nrLayersResidual.clear();+ desc.nrLayersTemporal.clear();desc.nrLayersProtection.clear();+ desc.nrLayersSizePolicy={settings.nrPolicy};+ if(!settings.nrLayerCount||!settings.nr)return;+ desc.nrLayersSizePolicy.clear();+ for(uint32_t i=0;i<settings.nrLayerCount&&i<kMaxNrInstances;++i){+ const auto& n=settings.nrLayers[i];+ if(!n.enabled)continue;+ desc.nrLayersModel.push_back(n.model);desc.nrLayersResidual.push_back(n.residual);+ desc.nrLayersTemporal.push_back(n.temporal);+ desc.nrLayersSizePolicy.push_back(n.sizePolicy);+ desc.nrLayersProtection.push_back(ProtectionSettings{});+ }+ // Protection is a single list stage after the complete NR stack.+ if(!desc.nrLayersProtection.empty())desc.nrLayersProtection.back()=settings.protection;+}// Stage selection for one graph build. Preview and export used to fill the// EnhanceGraphDesc in five separate places with slightly different formulas;// every build now goes through describeStages() so the rules live in one spot.@@ -14,6 +36,7 @@ struct StageRequest {bool stillImage=false; // image preview/processing: no NR-first orderbool exportJob=false; // offline export: native NR size, no present-sink FG, no NR-first orderbool nvidiaAdapter=true;+ const ChainRuntimeOrder* nodeOrder=nullptr; // paired with this settings transaction};// Fills the stage, size and parameter fields of `desc` from `settings`.@@ -21,8 +44,35 @@ struct StageRequest {// host hooks are left untouched: the caller owns those.inline pipeline::ResolutionPlan describeStages(const StageRequest& request,const EnhancementSettings& settings,pipeline::EnhanceGraphDesc& desc) {- const bool lowLatency=!request.exportJob&&settings.lowLatency&&request.nr;+ desc.fixedExecutionPlan.reset();desc.fixedExecutionPlanError.clear();+ desc.runtimeNodeOrder=request.nodeOrder!=nullptr;+ if(settings.nrLayerCount>settings.nrLayers.size()||settings.additionalColorCount>settings.additionalColors.size()){+ desc.fixedExecutionPlanError="too many runtime chain instances";return {};+ }+ auto chain=toChain(settings);+ bool lowLatency=!request.exportJob&&settings.lowLatency&&request.nr;+ if(request.nodeOrder){+ const auto restored=restoreRuntimeOrder(settings,*request.nodeOrder,chain);+ if(!restored.accepted){desc.fixedExecutionPlanError=restored.message;return {};}+ uint32_t nr=chain.nodeCount,sr=chain.nodeCount;+ for(uint32_t i=0;i<chain.nodeCount;++i){+ if(!chain.nodes[i].enabled)continue;+ if(chain.nodes[i].type==EffectType::NrEnhance&&nr==chain.nodeCount)nr=i;+ if(chain.nodes[i].type==EffectType::SuperResolution)sr=i;+ }+ lowLatency=request.nr&&nr<sr&&sr<chain.nodeCount;+ if(lowLatency&&(request.stillImage||request.exportJob)){+ desc.fixedExecutionPlanError="node NR-before-SR offline execution requires ordered dispatcher";return {};+ }+ }const auto policy=request.exportJob?pipeline::NrSizePolicy::Native:settings.nrPolicy;+ if(!pipeline::Extent{request.width,request.height}.valid()||!pipeline::validSrTarget(settings.srTarget)||+ !pipeline::validNrSizePolicy(policy)){+ // ResolutionPlan::make throws for these inputs. Report the same+ // invalid contract before any graph allocation, including on reuse.+ desc.fixedExecutionPlanError="invalid fixed-plan source extent, SR target or NR size policy";+ return {};+ }const auto plan=pipeline::ResolutionPlan::make({request.width,request.height},request.sr,policy,request.stillImage||request.exportJob,settings.revision,settings.srTarget,lowLatency);desc.sourceWidth=request.width;desc.sourceHeight=request.height;@@ -30,25 +80,63 @@ inline pipeline::ResolutionPlan describeStages(const StageRequest& request,constdesc.nrWidth=plan.nr.width;desc.nrHeight=plan.nr.height;desc.flowWidth=plan.flow.width;desc.flowHeight=plan.flow.height;desc.enableSr=plan.srApplied&&(request.nvidiaAdapter||settings.videoSrQuality==kVideoSrFsr);- desc.enableNr=request.nr&&request.nvidiaAdapter;+ desc.enableNr=request.nr&&request.nvidiaAdapter&&(!settings.nrLayerCount||settings.activeNrLayerCount()>0);desc.nrBeforeSr=!request.stillImage&&!request.exportJob&&lowLatency&&desc.enableNr&&desc.enableSr;desc.enableNvofStandalone=desc.enableNr;- desc.enableFg=request.fg&&(request.nvidiaAdapter||(!request.exportJob&&presentSinkFrameGeneration(settings.frameGenerationBackend)));+ const bool temporalMotion=settings.nrTemporal||std::any_of(settings.nrLayers.begin(),settings.nrLayers.begin()+settings.nrLayerCount,[](const auto& n){return n.enabled&&n.temporal;});+ desc.enableNvofStandalone=desc.enableNr&&(motionUsesFlow(settings.nrMotion)||temporalMotion);+ desc.enableFg=request.fg&&(request.nvidiaAdapter||(!request.exportJob&&crossVendorFrameGeneration(settings.frameGenerationBackend)));desc.fgMultiplier=request.fgMultiplier;desc.videoSrQuality=settings.videoSrQuality;- desc.nrRuntime=settings.nrRuntime;- desc.nrTemporal=settings.nrTemporal;+ describeNrLayers(settings,desc);desc.frameGenerationBackend=settings.frameGenerationBackend;- desc.model=settings.model;- desc.residual=settings.residual;- desc.protection=settings.protection;desc.color=settings.color;+ desc.additionalColors=settings.additionalColors;+ desc.additionalColorCount=settings.additionalColorCount;desc.videoHdr=settings.videoHdr;+ desc.hdrOutputMode=settings.hdrOutputMode;+ desc.fgMotion=settings.fgMotion;desc.srMotion=settings.srMotion;desc.nrMotion=settings.nrMotion;desc.settingsRevision=settings.revision;desc.flowQuality=settings.flow;desc.contentRate=settings.content;desc.opticalFlowBackend=settings.opticalFlowBackend;desc.amdFlowHalfResolution=settings.amdFlowHalfResolution;+ desc.nrLayersExtent.clear();+ for(uint32_t i=0;i<chain.nodeCount;++i){+ auto& node=chain.nodes[i];+ // Request flags are authoritative for the legacy flat API. Retain a+ // resolution step even when AI SR is unavailable: the existing graph+ // still performs its ordinary source-to-work resize in that slot.+ if(node.type==EffectType::SuperResolution)node.enabled=request.sr;+ if(node.type==EffectType::NrEnhance)+ node.enabled=desc.enableNr&&(!settings.nrLayerCount||node.enabled);+ if(node.type==EffectType::Protection)node.enabled=node.enabled&&desc.enableNr;+ if(node.type==EffectType::FrameGeneration)node.enabled=desc.enableFg;+ }+ ChainExecutionPlan execution;+ const auto validation=compileChainExecutionPlan(chain,{{request.width,request.height},settings.srTarget,+ request.stillImage,request.exportJob},execution);+ if(!validation.accepted){desc.fixedExecutionPlanError=validation.message;return plan;}+ if(request.nodeOrder){+ // Node order owns the first NR stage, even for an ordinary resize or+ // same-size SR bypass. Each NR resource keeps its own compiled input.+ uint32_t firstNr=execution.stepCount,firstSr=execution.stepCount;+ for(uint32_t i=0;i<execution.stepCount;++i){+ if(execution.steps[i].type==EffectType::NrEnhance&&firstNr==execution.stepCount)firstNr=i;+ if(execution.steps[i].type==EffectType::SuperResolution)firstSr=i;+ }+ desc.nrBeforeSr=desc.enableNr&&firstSr<execution.stepCount&&firstNr<firstSr;+ }+ for(uint32_t i=0;i<execution.stepCount;++i)+ if(execution.steps[i].type==EffectType::NrEnhance)desc.nrLayersExtent.push_back(execution.steps[i].processing);+ // Preserve disabled-stage diagnostic dimensions; these allocate no NR+ // feature. Active NR extents now come exclusively from the compiled plan.+ if(!desc.enableNr)for(const auto size:desc.nrLayersSizePolicy){+ desc.nrLayersExtent.push_back(pipeline::ResolutionPlan::make({request.width,request.height},request.sr,+ request.exportJob?pipeline::NrSizePolicy::Native:size,request.stillImage||request.exportJob,+ settings.revision,settings.srTarget,lowLatency).nr);+ }+ desc.fixedExecutionPlan=execution;return plan;}}diff --git a/include/veyra/engine/PresentationGeometry.h b/include/veyra/engine/PresentationGeometry.hindex 6d8e5d89..22a0955b 100644--- a/include/veyra/engine/PresentationGeometry.h+++ b/include/veyra/engine/PresentationGeometry.h@@ -10,13 +10,12 @@ namespace veyra::engine {inline RECT presentationRegion(unsigned imageWidth,unsigned imageHeight,unsigned clientWidth,unsigned clientHeight,unsigned bufferWidth,unsigned bufferHeight,PreviewView view){if(!imageWidth||!imageHeight||!clientWidth||!clientHeight||bufferWidth<2||bufferHeight<2)return {};- const float zoom=std::isfinite(view.zoom)&&view.zoom>0?view.zoom:1.0f;- const float fit=std::min(float(clientWidth)/imageWidth,float(clientHeight)/imageHeight)*zoom;+ const auto [rw,rh]=view.renderedSize(float(clientWidth),float(clientHeight),float(imageWidth),float(imageHeight));const float sx=float(bufferWidth)/clientWidth,sy=float(bufferHeight)/clientHeight;- const float left=(clientWidth*.5f-view.centerX*imageWidth*fit)*sx;- const float top=(clientHeight*.5f-view.centerY*imageHeight*fit)*sy;+ const float left=(clientWidth*.5f-view.centerX*rw)*sx;+ const float top=(clientHeight*.5f-view.centerY*rh)*sy;const auto edge=[](float value,unsigned bound){return LONG(std::clamp(value,0.0f,float(bound)))&~1L;};return {edge(left,bufferWidth),edge(top,bufferHeight),- edge(left+imageWidth*fit*sx+.5f,bufferWidth),edge(top+imageHeight*fit*sy+.5f,bufferHeight)};+ edge(left+rw*sx+.5f,bufferWidth),edge(top+rh*sy+.5f,bufferHeight)};}}diff --git a/include/veyra/engine/PresentationSettings.h b/include/veyra/engine/PresentationSettings.hindex da83e6bb..c46d1595 100644--- a/include/veyra/engine/PresentationSettings.h+++ b/include/veyra/engine/PresentationSettings.h@@ -16,12 +16,24 @@ struct PresentationSettings {// which cannot be measured on this machine - do not claim a figure for it.bool enabled=false;PacingMode mode=PacingMode::LowQueue; // deprecated, see above- DisplaySync display=DisplaySync::Tearing;+ DisplaySync display=DisplaySync::Automatic;OutputRateMode outputRate=OutputRateMode::Off;double customFps=60.0;+ bool fullscreen=false; // transient UI state, never persisted as a preferencebool operator==(const PresentationSettings&) const = default;bool valid()const{return unsigned(mode)<=2&&unsigned(display)<=2&&unsigned(outputRate)<=2&&std::isfinite(customFps)&&customFps>=1.0&&customFps<=1000.0;}};+// Automatic never waits for vertical sync and never requests tearing: a+// flip-model Present(0, 0) replaces the queued frame at the next refresh.+// Tearing is only requested when the user explicitly selects it, because a+// borderless fullscreen window is promoted to independent flip, where+// DXGI_PRESENT_ALLOW_TEARING really tears (windowed output is composed).+constexpr bool presentationVsync(const PresentationSettings& s) {+ return s.display==DisplaySync::Vsync;+}+constexpr bool presentationTearing(const PresentationSettings& s) {+ return s.display==DisplaySync::Tearing;+}// Media time remains the authority. Spacing adds at most one interval from// the current decision; stale generated frames are discarded by the caller.class PresentationCadence {diff --git a/include/veyra/engine/PresetLibrary.h b/include/veyra/engine/PresetLibrary.hindex 13f34106..c4dee859 100644--- a/include/veyra/engine/PresetLibrary.h+++ b/include/veyra/engine/PresetLibrary.h@@ -48,6 +48,12 @@ struct PresetEntry {PresetFrameGeneration fg{};AudioSyncMode audioSync = AudioSyncMode::Automatic;int32_t audioOffsetMs = 0;+ // Version 4 node presets retain the complete draft and last accepted chain.+ // Optional so legacy/list presets keep their original representation.+ std::optional<ChainConfiguration> nodeConfiguration;+ // v6: chain rendering choices also travel with list presets. No capture,+ // audio or export configuration is carried by this optional snapshot.+ std::optional<ChainGlobalSettings> globals;bool operator==(const PresetEntry&) const = default;};@@ -62,25 +68,63 @@ public:bool duplicate(size_t index);bool erase(size_t index);bool setDefault(size_t index);+ bool clearDefault();const std::optional<size_t> defaultIndex() const;// Applies the parts the preset carries onto `settings`, leaving everything// else (capture, export, resolution policy) untouched.static void apply(const PresetEntry& entry, EnhancementSettings& settings);+ // Editor variant: retain topology/layout unless Chain is selected. Colour+ // grades replace colour slots by ordinal (extras follow the last slot);+ // all unrelated nodes remain intact. Failure changes neither argument.+ static ChainValidation applyToChain(const PresetEntry& entry, EffectChain& chain,+ EnhancementSettings& settings);+ // Partial presets retain stable IDs, detached nodes and wires.+ static ChainValidation applyToEditor(const PresetEntry&, NodeEditorDocument&,+ EnhancementSettings& settings);// True when the preset can be applied to a settings struct of this kind.static bool matchesKind(const PresetEntry& entry, ChainMode kind) { return entry.kind == kind; }const std::vector<PresetEntry>& entries() const { return entries_; }const std::wstring& error() const { return error_; }bool corrupt() const { return corrupt_; }+ // The 2.0 interface ships no built-in presets (user decision 2026-09-29):+ // with this off, none are added and any built-in entries a file still+ // carries are dropped on load. Other callers keep the default.+ void setIncludeBuiltins(bool include) { includeBuiltins_ = include; }+ // One preset to / from a standalone file in the library's own format. An+ // import never replaces an existing name: it gets a numbered suffix.+ bool exportEntry(size_t index, const std::filesystem::path& target);+ bool importFile(const std::filesystem::path& source, std::wstring& nameOut);// Imports an existing single-purpose store (the old VEYRA_PRESETS files)// as chain-only or colour-only presets. Never overwrites an existing name.bool importLegacy(const std::vector<PresetEntry>& entries);private:- static bool parse(const std::string& data, std::vector<PresetEntry>& out, std::wstring& def, std::wstring& error);+ friend class ChainSessionStore;+ static bool parse(const std::string& data, std::vector<PresetEntry>& out, std::wstring& def, std::wstring& error,+ bool* migrated = nullptr, bool preserveLegacy = false);std::string serialize() const;+ static std::string encodeEntries(const std::vector<PresetEntry>& entries, const std::wstring& defaultName, int minimumVersion = 1);void addBuiltins();std::filesystem::path path_;std::vector<PresetEntry> entries_;std::wstring defaultName_, error_;bool corrupt_ = false;+ bool includeBuiltins_ = true;+};++// A private editor-session file, not entries in the user's preset library.+// Reuses the versioned chain codec; no second set of per-node serializers.+class ChainSessionStore {+public:+ explicit ChainSessionStore(std::filesystem::path path) : path_(std::move(path)) {}+ bool load(ChainSession& session); // missing: keep the caller's initial state+ bool save(const ChainSession& session);+ const std::wstring& error() const { return error_; }+private:+ friend class PresetLibrary;+ static std::string encode(const ChainSession&);+ static bool decode(const std::string&, ChainSession&, bool* migrated = nullptr);+ std::filesystem::path path_;+ std::wstring error_;+ bool corrupt_ = false;};}diff --git a/include/veyra/engine/PreviewView.h b/include/veyra/engine/PreviewView.hindex 5145d4ee..247b2c14 100644--- a/include/veyra/engine/PreviewView.h+++ b/include/veyra/engine/PreviewView.h@@ -5,24 +5,39 @@namespace veyra::engine {struct PreviewView {float zoom=1,centerX=.5f,centerY=.5f;+ // Preserve UI IDs 0=fit, 1=native pixels, 2=fill; append stretch/ratios.+ int mode=0;+ double displayAspect=0;bool operator==(const PreviewView&)const=default;+ double aspect(float iw,float ih)const{+ if(mode==4)return 16.0/9;if(mode==5)return 4.0/3;if(mode==6)return 21.0/9;+ return mode!=1&&std::isfinite(displayAspect)&&displayAspect>0?displayAspect:ih>0?double(iw)/ih:0;+ }+ std::pair<float,float> renderedSize(float cw,float ch,float iw,float ih)const{+ if(cw<=0||ch<=0||iw<=0||ih<=0)return {0,0};+ if(mode==1)return {iw*zoom,ih*zoom};+ if(mode==3)return {cw*zoom,ch*zoom};+ const float virtualW=float(aspect(iw,ih))*ih;+ const float scale=(mode==2?std::max(cw/virtualW,ch/ih):std::min(cw/virtualW,ch/ih))*zoom;+ return {virtualW*scale,ih*scale};+ }std::pair<float,float> sourcePoint(float x,float y,float cw,float ch,float iw,float ih)const{if(cw<=0||ch<=0||iw<=0||ih<=0)return {-1.0f,-1.0f};- const float fit=std::min(cw/iw,ch/ih)*zoom;- return {centerX+(x-cw*.5f)/(iw*fit),centerY+(y-ch*.5f)/(ih*fit)};+ const auto [rw,rh]=renderedSize(cw,ch,iw,ih);+ return {centerX+(x-cw*.5f)/rw,centerY+(y-ch*.5f)/rh};}void wheel(float steps,float x,float y,float clientW,float clientH,float imageW,float imageH){if(clientW<=0||clientH<=0||imageW<=0||imageH<=0||!std::isfinite(steps))return;- const float fit=std::min(clientW/imageW,clientH/imageH);+ const auto [rw,rh]=renderedSize(clientW,clientH,imageW,imageH);const float next=std::clamp(zoom*std::pow(1.2f,steps),.05f,64.0f);- centerX+=(x-clientW*.5f)/(imageW*fit)*(1/zoom-1/next);- centerY+=(y-clientH*.5f)/(imageH*fit)*(1/zoom-1/next);+ centerX+=(x-clientW*.5f)/rw*(1-zoom/next);+ centerY+=(y-clientH*.5f)/rh*(1-zoom/next);zoom=next;}void pan(float dx,float dy,float clientW,float clientH,float imageW,float imageH){if(clientW<=0||clientH<=0||imageW<=0||imageH<=0)return;- const float fit=std::min(clientW/imageW,clientH/imageH)*zoom;- centerX-=dx/(imageW*fit);centerY-=dy/(imageH*fit);+ const auto [rw,rh]=renderedSize(clientW,clientH,imageW,imageH);+ centerX-=dx/rw;centerY-=dy/rh;}};}diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.hindex ad38b94e..eb5b35b1 100644--- a/include/veyra/engine/VideoPresenter.h+++ b/include/veyra/engine/VideoPresenter.h@@ -21,7 +21,7 @@ public:bool open(gfx::D3D12DeviceContext&, HWND, pipeline::EnhanceGraph&, bool captureCompatible=false, bool mediaClockPaced=false);bool present(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,pipeline::EnhanceGraph&,unsigned slot,bool generated,bool referencesValid=true,int comparison=0,bool baseReference=false,float split=.5f,pipeline::FrameIdentity identity={},PreviewView view={},int64_t sourcePts100ns=-1);void close();- // Present-sink providers (XeSS/FSR) block inside Present while pacing+ // Present-sink providers (XeSS) block inside Present while pacing// their generated frames. A helper-thread Present was tried on// 2026-09-22 (X3): the provider then estimated its period from the// longer hand-off intervals and the source rate fell 51 -> 24/s at 44%@@ -33,7 +33,7 @@ public:bool presentationReady(){return sink_.presentationReady();}uint64_t beginReflex(){return reflex_.begin();}void reflexFrame(uint64_t id){reflexFrame_=id;}- // True while XeSS/FSR owns Present: the low-latency queue and the output+ // True while XeSS owns Present: the low-latency queue and the output// cap cannot reach provider-generated frames, so the UI greys them out.bool providerOwnedPresentation()const{return providerOwnedPresentation_;}@@ -53,13 +53,6 @@ public:uint64_t xessPresentedCount() const {return sink_.xess()?sink_.xess()->presentedCount():0;}bool xessActive() const {return sink_.xess()!=nullptr;}bool xessFailed() const {return xessFailed_;}- uint64_t fsrGeneratedCount() const {return sink_.fsr()?sink_.fsr()->generatedCount():0;}- uint64_t fsrPresentedCount() const {return sink_.fsr()?sink_.fsr()->presentedCount():0;}- bool fsrActive() const {return sink_.fsr()!=nullptr;}- bool fsrFailed() const {return fsrFailed_;}- // Provider-reported generated frames per real frame (1 = 2X); 0 when the- // AMD runtime is unavailable.- uint32_t fsrMaxGeneratedFrames() const {return sink_.fsr()?sink_.fsr()->maxGeneratedFrames():0;}// Sustained under-rate may suppress SDK-owned XeSS-FG generation over a// stable interval (xefgSwapChainSetEnabled); re-enabling goes through the// per-frame history reset, never a per-frame toggle.@@ -67,7 +60,7 @@ public:bool xessGenerationSuppressed() const {return xessGenerationSuppressed_;}diagnostics::GpuSample blitTiming(ID3D12Fence* f,uint64_t revision=0,uint64_t epoch=0){gpuTimer_.collect(presentationFence_?presentationFence_.Get():f);if((revision&&gpuTimer_.last().identity.settingsRevision!=revision)||(epoch&&gpuTimer_.last().identity.epoch!=epoch)){diagnostics::GpuSample pending;pending.state=diagnostics::SampleState::Pending;return pending;}return gpuTimer_.last().gpu[size_t(diagnostics::GpuStage::Blit)];}// Application-side frame-generation timing for present-sink backends- // (XeSS/FSR): the copies, barriers and provider prepare work recorded on+ // (XeSS): the copies, barriers and provider prepare work recorded on// our list. collect() is idempotent, so this is safe alongside blitTiming.diagnostics::GpuSample fgTiming(ID3D12Fence* f,uint64_t revision=0,uint64_t epoch=0){gpuTimer_.collect(f);if((revision&&gpuTimer_.last().identity.settingsRevision!=revision)||(epoch&&gpuTimer_.last().identity.epoch!=epoch)){diagnostics::GpuSample pending;pending.state=diagnostics::SampleState::Pending;return pending;}return gpuTimer_.last().gpu[size_t(diagnostics::GpuStage::FgBatch)];}std::vector<diagnostics::GpuFrameTiming> takeGpuTimings(ID3D12Fence* fence){gpuTimer_.collect(presentationFence_?presentationFence_.Get():fence);return gpuTimer_.takeCompleted();}@@ -106,10 +99,6 @@ private:struct XessWork {pipeline::FrameIdentity identity{};uint32_t id=0;};std::array<XessWork,4> xessWork_{};size_t xessWorkPosition_=0;- std::chrono::steady_clock::time_point lastFsrFrame_{};- pipeline::FrameIdentity lastFsrIdentity_{};- bool fsrWasEnabled_=false;- bool fsrFailed_=false;void refresh(ID3D12Device*);};}diff --git a/include/veyra/gfx/D3D12DeviceContext.h b/include/veyra/gfx/D3D12DeviceContext.hindex ae360ea7..aebfdff9 100644--- a/include/veyra/gfx/D3D12DeviceContext.h+++ b/include/veyra/gfx/D3D12DeviceContext.h@@ -6,6 +6,7 @@#include <cstdint>#include <string>+#include <string_view>#include "veyra/Result.h"@@ -74,6 +75,8 @@ public:// GetDeviceRemovedReason; returns true when the device is still alive.bool checkDeviceAlive(uint32_t& removedReason) const;+ // Bounded DRED snapshot on a failure path, never a normal per-frame readback.+ bool reportDeviceFailure(std::string_view operation, uint64_t requestedFence=0) const;// Exercises the full slot ring: acquire (wait+reset), empty command list// with timestamp begin/end markers, execute, signal, wait idle. Phase 0diff --git a/include/veyra/gfx/FsrFgPresenter.h b/include/veyra/gfx/FsrFgPresenter.hindex 979a2b8e..7c5d79e1 100644--- a/include/veyra/gfx/FsrFgPresenter.h+++ b/include/veyra/gfx/FsrFgPresenter.h@@ -1,79 +1,33 @@#pragma once--// AMD FidelityFX Super Resolution frame generation behind the Veyra present-// path. The provider creates (and owns) a proxy IDXGISwapChain4 for our HWND;-// the engine renders into that proxy and calls Present on it, and the provider-// inserts interpolated frames according to the per-frame dispatch we record.-//-// Evidence and limits (local RTX 5070, FSR SDK 2.3.0, provider 3.1.7/3.1.6):-// docs/FRAMEGEN_FSR_DOLBY_STATUS_2026-09-16.md and tools/fsr_probe. The 3.1.x-// provider delivers exactly one generated frame per presented frame, so the-// requested multiplier is capped at 2X for this provider.-#include <d3d12.h>#include <dxgi1_6.h>-#include <cstdint>#include <memory>namespace veyra::gfx {-+// AMD SDK frame interpolation into application-owned GPU textures. The+// historical class name is retained, but no HWND / swapchain / presentation+// worker is created. FrameBatch and VideoPresenter own timing/presentation.class FsrFgPresenter {public:FsrFgPresenter();~FsrFgPresenter();-FsrFgPresenter(const FsrFgPresenter&) = delete;FsrFgPresenter& operator=(const FsrFgPresenter&) = delete;-- // Creates the AMD proxy swapchain for the window. On success `swapchain`- // receives a BORROWED pointer: the provider owns one reference and releases- // it when this object destroys its context, so a caller that wants to keep- // the swapchain must take its own reference (QueryInterface/AddRef) and- // release it before the presenter is destroyed.- bool initialize(ID3D12Device* device, ID3D12CommandQueue* queue, IDXGIFactory2* factory, HWND window,- const DXGI_SWAP_CHAIN_DESC1& desc, uint32_t renderWidth, uint32_t renderHeight,- IDXGISwapChain4** swapchain, uint32_t fgMultiplier);-- // Records one frame of frame-generation work on the caller's command list:- // prepare dispatch (motion + depth), per-frame configure and the- // interpolation dispatch. `motion` is the guidance motion in working-extent- // pixels (previous = current + motion), `depth` is the guidance depth.- bool tag(ID3D12GraphicsCommandList* list, ID3D12Resource* backBuffer, ID3D12Resource* motion,- ID3D12Resource* depth, RECT region, bool enabled, bool reset, float elapsedMs);-- // Frame ids must advance by exactly one per presented frame, including the- // frames that carry no generation work.- void afterPresent();-- uint64_t generatedCount() const;- uint64_t presentedCount() const;- // Generated frames per real frame the provider delivers (1 = 2X) once a- // context exists; 0 while unavailable.+ bool initializeIndependent(ID3D12Device*, uint32_t width, uint32_t height,+ DXGI_FORMAT, bool requireMl);+ // All resources COMMON before/after; motion current->previous in display+ // pixels, depth R32F. The owner drains GPU/consumer work before shutdown.+ bool generate(ID3D12GraphicsCommandList*, ID3D12Resource* color,+ ID3D12Resource* motion, ID3D12Resource* depth, ID3D12Resource* output,+ bool reset, float elapsedMs);uint32_t maxGeneratedFrames() const;bool available() const;bool failed() const;const char* providerVersion() const;- // Borrowed proxy swapchain (valid while this object lives).- IDXGISwapChain4* swapchainHandle() const;- // Turns generation off while the proxy keeps presenting real frames. Used- // when the session stops using AMD frame generation but the swapchain has- // to stay: the provider retains the DXGI swapchain, so a second swapchain- // cannot be created for the same HWND in this process.- void disableGeneration();-- // Tears the provider contexts down and releases the proxy swapchain so a- // later session can create a new swapchain for the same window (the- // window's flip-model slot is only freed once every reference, including- // the provider's, is gone). Idempotent; the destructor reuses it.void shutdown();-- // Implementation state; public because the provider's presentation- // callback (a free function in the translation unit) must reach it.- struct Impl;-private:+ struct Impl;std::unique_ptr<Impl> p_;};--} // namespace veyra::gfx+}diff --git a/include/veyra/gfx/PresentSink.h b/include/veyra/gfx/PresentSink.hindex e040fb04..4b34c065 100644--- a/include/veyra/gfx/PresentSink.h+++ b/include/veyra/gfx/PresentSink.h@@ -17,7 +17,6 @@#include "veyra/Result.h"#include "veyra/gfx/XessPresenter.h"-#include "veyra/gfx/FsrFgPresenter.h"namespace veyra::gfx {@@ -43,14 +42,9 @@ public:uint32_t width = 1280;uint32_t height = 720;bool vsync = true;+ bool tearing = false; // request DXGI_PRESENT_ALLOW_TEARING (only without vsync)bool waitable = false;bool xess = false;- // AMD FSR frame generation: the provider creates the proxy swapchain.- bool fsr = false;- // Working (render) extent for the AMD provider's maxRenderSize; 0 keeps- // it equal to the swapchain extent.- uint32_t renderWidth = 0;- uint32_t renderHeight = 0;bool captureCompatible = false;bool hdr = false;bool hdr10 = false;@@ -108,7 +102,7 @@ public:};FrameStatisticsDelta sampleFrameStatistics();double displayRefreshHz()const{return displayRefreshHz_;}- bool configurePacing(bool enabled,bool vsync);+ bool configurePacing(bool enabled,bool vsync,bool tearing);bool presentationReady();bool pacingActive()const{return pacing_;}@@ -128,8 +122,6 @@ public:IDXGISwapChain3* swapChain() const { return swapChain_.Get(); }XessPresenter* xess() const { return xess_.get(); }bool xessFailed() const { return xessFailed_; }- FsrFgPresenter* fsr() const { return fsr_.get(); }- bool fsrFailed() const { return fsrFailed_; }void shutdown();@@ -156,13 +148,11 @@ private:UINT swapChainFlags_ = 0;bool pendingResize_ = false;bool xessFailed_ = false;- bool fsrFailed_ = false;ID3D12Device* device_ = nullptr;ID3D12CommandQueue* queue_ = nullptr;ComPtr<IDXGIFactory2> factory_;ComPtr<IDXGISwapChain3> swapChain_;std::unique_ptr<XessPresenter> xess_;- std::unique_ptr<FsrFgPresenter> fsr_;ComPtr<ID3D12Resource> backBuffers_[3];UINT backBufferIndex_ = 0;bool closed_ = false;diff --git a/include/veyra/ngx/DlssgTransfusion.h b/include/veyra/ngx/DlssgTransfusion.hnew file mode 100644index 00000000..fc730bcd--- /dev/null+++ b/include/veyra/ngx/DlssgTransfusion.h@@ -0,0 +1,110 @@+#pragma once++#include <windows.h>++#include <cstdint>+#include <string>++namespace veyra::ngx {++// Process-memory DLSS-G 310.9.1 provider patches for RTX 40 (Ada) and RTX 30+// (Ampere), replacing the audited-310.7 AdaMfgUnlock/AmpereMfgUnlock pair when+// the 310.9.1 provider is installed.+//+// Ported from SilyNoMeta/DLSSG-Transfusion (MIT), tag v1.4.5.3-rtx20-30-40,+// commit b56bd2deed114507ad2c88f986d90ed50ffb4639 (a fork of+// TonyJoaca/DLSSG-Transfusion, MIT):+// source/native/patcher.cpp PatchDlssgArchGates, PatchDlssgMinimumArchitecture,+// kNgxPatch (validator guard), PatchUniqueExecutablePattern+// source/native/midpoint_fix.cpp PatchProvider (Blackwell kernels, in-place retarget),+// PrepareModuleImage (exact image-kernel substitution)+// source/native/cu_module_hook.h NvAPI_D3D12_CreateCuModule interception+// source/native/network_optimizer.h DL1/DL2 launch substitution+// source/native/image_kernels.h, quality_fix.h, quality_explained_warp.h+// Veyra adaptations: every written byte is recorded and restored on release;+// NvAPI is intercepted through the provider's own GetProcAddress import slot+// (no Detours, no global hook); the optimized kernels are separate runtime+// files, not resources; Turing, Vulkan, Streamline, HUD assist and the+// quality experiments are not ported.+//+// Never applied on Blackwell: RTX 50 keeps NVIDIA's native path.+class DlssgTransfusion {+public:+ // NVIDIA DLSS SDK 310.9.1 lib/Windows_x86_64/rel/nvngx_dlssg.dll.+ static constexpr uint64_t kKnownModuleSize = 7460976ull;+ static constexpr const char* kKnownModuleSha256 =+ "FF6E90EB78B827927DFF5B4ECC6B1C870C2E9BCA29ED9F48C7D348CC9E170B82";+ static constexpr uint32_t kKnownTimeDateStamp = 0x6A986031u;+ static constexpr uint32_t kKnownSizeOfImage = 0x00737000u;+ static constexpr uint32_t kAdaArchId = 0x190u;+ static constexpr uint32_t kAmpereArchId = 0x170u;+ static constexpr size_t kExpectedArchGateSites = 2;+ static constexpr size_t kExpectedMinimumArchitectureExports = 4;++ enum class Target : uint8_t { Ada, Ampere };++ struct Options {+ // Transfusion defaults: Blackwell kernels, valid-warp protection with+ // the explained-warp policy, and bit-exact optimized kernels.+ bool blackwellKernels = true;+ bool qualityValidWarp = true;+ bool explainedWarp = true;+ bool optimizedKernels = true;+ // Directory holding k40xx.ptx, OutputPull.ptx and OutputPushFine.ptx.+ std::wstring kernelDirectory;+ };++ struct State {+ bool applied = false;+ bool identityVerified = false;+ Target target = Target::Ada;+ uint32_t targetSm = 0;+ size_t archGateSites = 0;+ size_t minimumArchitectureExports = 0;+ bool validatorPatched = false;+ bool blackwellKernels = false;+ size_t descriptorSlots = 0;+ size_t retargetedContainers = 0;+ bool nvapiHooked = false;+ size_t networkKernelsLoaded = 0;+ bool imageKernelsLoaded = false;+ size_t writes = 0;+ std::wstring detail;+ };++ struct Counters {+ uint32_t nvapiResolutions = 0;+ uint32_t modulesAccepted = 0;+ uint32_t modulesRejected = 0;+ uint32_t modulesRewritten = 0;+ bool exactProviderKernels = false;+ bool networkReady = false;+ bool networkFailed = false;+ uint64_t optimizedDl1Runs = 0;+ uint64_t optimizedDl2Runs = 0;+ };++ // True for the pinned 310.9.1 provider file (size + SHA-256).+ static bool moduleIsKnown(const std::wstring& path);+ static bool moduleIsKnown(uint64_t size, const std::string& sha256Upper);++ // Installs every patch into the mapped provider. Must run before NGX+ // initializes it (the NvAPI entry point and CUDA programs are resolved+ // then). Refuses, rolling back, unless each site matches its expectation.+ static State apply(HMODULE module, Target target, const Options& options);++ // Restores every patched byte and the import slot. Call after NGX shutdown.+ // Returns false when restoration cannot be proved.+ static bool release();++ static State snapshot();+ static Counters counters();+ static bool applied();++ // Options from the product defaults, overridable for A/B tests by+ // VEYRA_DLSSG_TF_{DISABLE_BLACKWELL,DISABLE_QUALITY,DISABLE_OPTIMIZED}=1+ // and VEYRA_DLSSG_TF_QUALITY_POLICY=transfusion.+ static Options defaultOptions(const std::wstring& kernelDirectory);+};++} // namespace veyra::ngxdiff --git a/include/veyra/ngx/FgCompatibilitySession.h b/include/veyra/ngx/FgCompatibilitySession.hindex 8813e74e..89731aef 100644--- a/include/veyra/ngx/FgCompatibilitySession.h+++ b/include/veyra/ngx/FgCompatibilitySession.h@@ -17,6 +17,8 @@ public:static bool processHealthy();bool open(ID3D12Device* device, uint32_t vendor, uint32_t deviceId, const std::wstring& directory);HMODULE provider() const;+ // True when the 310.9.1 provider was opened and patched by DlssgTransfusion.+ bool transfusionProfile() const;bool prepareDriver(const std::wstring& directory, const char* project, const char* engine);bool bindResources(std::span<ID3D12Resource* const> real, std::span<ID3D12Resource* const> generated);bool beginInitialization();diff --git a/include/veyra/ngx/NrArchitecturePolicy.h b/include/veyra/ngx/NrArchitecturePolicy.hindex b3951500..72ad86b9 100644--- a/include/veyra/ngx/NrArchitecturePolicy.h+++ b/include/veyra/ngx/NrArchitecturePolicy.h@@ -1,6 +1,13 @@#pragma once#include <cstdint>+#include <string_view>namespace veyra::ngx {+// Defaults for a fresh UI only. Explicit choices restored from a preset or+// session win. Unknown/professional adapters are not guessed from a PCI range.+constexpr bool preferSfNr(uint32_t vendorId, std::wstring_view description) {+ return vendorId == 0x10DE && (description.find(L"RTX 20") != description.npos ||+ description.find(L"RTX 30") != description.npos || description.find(L"RTX 40") != description.npos);+}// The experimental profile only changes a successful query for the exact// selected Ampere adapter. Other GPUs and driver failures retain their result.constexpr bool rewriteNrAmpereArchitecture(uint32_t& architecture, bool selected, int result) {@@ -8,4 +15,13 @@ constexpr bool rewriteNrAmpereArchitecture(uint32_t& architecture, bool selectedarchitecture=0x1B0u;return true;}+// The rewrite suits builds that put Ampere-runnable kernels in the Blackwell+// slot (NeuralScreen's 310.8.0.0). The ShortFuse "SF" family (310.8.2.x and the+// later Lecram 310.8.3.x) lifts the gate itself and picks an FP16 route from the+// real architecture, so reporting Blackwell there would select kernels Ampere+// cannot run. Versions come from the loaded DLL's VS_FIXEDFILEINFO.+constexpr bool nrRuntimeNeedsAmpereRewrite(uint32_t fileVersionMs, uint32_t fileVersionLs) {+ const uint32_t major=fileVersionMs>>16, minor=fileVersionMs&0xFFFFu, build=fileVersionLs>>16;+ return !(major==310u&&minor==8u&&build>=2u);+}}diff --git a/include/veyra/pipeline/CaptureUploadFrame.h b/include/veyra/pipeline/CaptureUploadFrame.hnew file mode 100644index 00000000..3c314346--- /dev/null+++ b/include/veyra/pipeline/CaptureUploadFrame.h@@ -0,0 +1,195 @@+#pragma once+// Capture frames that live in a D3D12 upload buffer (latency work 2026-09-30).+//+// A native capture frame used to be copied twice before the GPU saw it: driver+// sample -> owned AVFrame in the capture callback, then AVFrame -> upload heap+// in the graph. On the test machine each copy is memory-bandwidth bound (4K+// NV12: 1.3 ms + 0.9 ms of a 3.3 ms capture-to-present path with all effects+// off), and splitting it over threads gained nothing. Here the capture source's+// own frames ARE upload buffers, so the callback's copy is the only one and the+// graph records its CopyTextureRegion straight from the frame.+//+// Layouts: semiplanar NV12/P010/P016 (two planes in one buffer) and the packed+// single-plane formats the graph converts on the GPU (YUY2, UYVY, YVYU, BGR24,+// RGB555, RGB565). Planar I420/YV12 is interleaved into an NV12 frame by the+// callback (interleaveCaptureI420), which replaces the graph's swscale pass.+//+// Rules:+// - The frame keeps normal AVFrame semantics (data/linesize, ref-counted), so+// any consumer that does not know this header still works; it just reads+// write-combined memory, which is slow.+// - The graph stores the fence of the list that reads the buffer. While that+// fence is pending the callback must not write the buffer, so it fills the+// frame's CPU planes instead (direct=false) and the graph copies as before.+// - The 64x36 points the graph analyses are sampled in the callback from the+// driver sample (raw pixel bytes, same packing as the frame), never read+// back from the upload buffer.+#include <d3d12.h>+#include <wrl/client.h>+#include <cstdint>+#include <cstring>+#include <emmintrin.h>+#include <mutex>+extern "C" {+#include <libavutil/buffer.h>+#include <libavutil/frame.h>+#include <libavutil/mem.h>+}++namespace veyra::pipeline {++struct CaptureUploadFrame {+ static constexpr uint64_t kMagic = 0x5645595255504652ull;+ static constexpr unsigned kProxyWidth = 64, kProxyHeight = 36, kMaxPixelBytes = 4;+ uint64_t magic = kMagic;+ Microsoft::WRL::ComPtr<ID3D12Device> device;+ Microsoft::WRL::ComPtr<ID3D12Resource> resource;+ uint8_t* mapped = nullptr; // plane 0 at 0, semiplanar chroma at chromaOffset+ uint8_t* cpu = nullptr; // same layout; allocated on first fallback+ uint64_t chromaOffset = 0, bytes = 0;+ uint32_t pitch = 0, width = 0, height = 0;+ uint32_t planes = 1; // 2 = semiplanar+ uint32_t pixelBytes = 1; // bytes per pixel of plane 0 (NV12 1, P010/YUY2/RGB565 2, BGR24 3)+ bool direct = false; // pixels of the current frame are in the upload buffer+ bool proxyValid = false;+ // kProxyWidth x kProxyHeight pixels of plane 0, pixelBytes each, row pitch+ // proxyPitch(): a tiny frame with the same packing as the real one.+ uint8_t proxy[kProxyWidth * kProxyHeight * kMaxPixelBytes] = {};+ int proxyPitch() const { return int(kProxyWidth * pixelBytes); }+ uint64_t fallbacks = 0;++ // Last GPU list that reads the upload buffer (set by the graph).+ void gpuRead(ID3D12Fence* object, uint64_t value) { std::lock_guard lock(mutex_); fence_ = object; fenceValue_ = value; }+ bool gpuBusy() { std::lock_guard lock(mutex_); return fence_ && fence_->GetCompletedValue() < fenceValue_; }++ ~CaptureUploadFrame() { if (resource && mapped) resource->Unmap(0, nullptr); av_free(cpu); }++private:+ std::mutex mutex_;+ Microsoft::WRL::ComPtr<ID3D12Fence> fence_;+ uint64_t fenceValue_ = 0;+};++inline CaptureUploadFrame* captureUploadFrame(const AVFrame* frame) {+ if (!frame || !frame->opaque_ref || frame->opaque_ref->size != sizeof(CaptureUploadFrame)) return nullptr;+ auto* info = reinterpret_cast<CaptureUploadFrame*>(frame->opaque_ref->data);+ return info->magic == CaptureUploadFrame::kMagic ? info : nullptr;+}++// Bytes per plane-0 pixel for a format this header can back; 0 = unsupported.+inline uint32_t captureUploadPixelBytes(AVPixelFormat format) {+ switch (format) {+ case AV_PIX_FMT_NV12: return 1;+ case AV_PIX_FMT_P010: case AV_PIX_FMT_P016: return 2;+ case AV_PIX_FMT_YUYV422: case AV_PIX_FMT_UYVY422: case AV_PIX_FMT_YVYU422: return 2;+ case AV_PIX_FMT_RGB555LE: case AV_PIX_FMT_RGB565LE: return 2;+ case AV_PIX_FMT_BGR24: return 3;+ default: return 0;+ }+}++// Returns nullptr when the format is not supported or the buffer cannot be+// created; the caller then allocates an ordinary frame.+inline AVFrame* allocCaptureUploadFrame(ID3D12Device* device, AVPixelFormat format, unsigned width, unsigned height) {+ const uint32_t pixelBytes = captureUploadPixelBytes(format);+ if (!device || !width || !height || !pixelBytes) return nullptr;+ const bool semiplanar = format == AV_PIX_FMT_NV12 || format == AV_PIX_FMT_P010 || format == AV_PIX_FMT_P016;+ // Packed rows are uploaded as RGBA8 texels, so a row is a whole number of texels.+ const uint32_t rowBytes = (width * pixelBytes + 3u) & ~3u;+ const uint32_t pitch = (rowBytes + 255u) & ~255u; // D3D12_TEXTURE_DATA_PITCH_ALIGNMENT+ const uint64_t chromaOffset = semiplanar ? (uint64_t(pitch) * height + 511u) & ~uint64_t(511) : 0; // ..._PLACEMENT_ALIGNMENT+ const uint64_t bytes = semiplanar ? chromaOffset + uint64_t(pitch) * ((height + 1) / 2) : uint64_t(pitch) * height;+ D3D12_HEAP_PROPERTIES heap{}; heap.Type = D3D12_HEAP_TYPE_UPLOAD;+ D3D12_RESOURCE_DESC desc{}; desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; desc.Width = bytes; desc.Height = 1; desc.DepthOrArraySize = 1;+ desc.MipLevels = 1; desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;+ auto* info = new CaptureUploadFrame;+ void* mapped = nullptr; const D3D12_RANGE noRead{0, 0};+ if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&info->resource))) ||+ FAILED(info->resource->Map(0, &noRead, &mapped)) || !mapped) { delete info; return nullptr; }+ info->device = device; info->mapped = static_cast<uint8_t*>(mapped); info->chromaOffset = chromaOffset; info->bytes = bytes;+ info->pitch = pitch; info->width = width; info->height = height; info->planes = semiplanar ? 2u : 1u; info->pixelBytes = pixelBytes;+ // The packed texel upload reads up to 3 bytes past a BGR24 row: keep them defined.+ std::memset(info->mapped, 0, size_t(bytes));+ AVBufferRef* infoRef = av_buffer_create(reinterpret_cast<uint8_t*>(info), sizeof(CaptureUploadFrame),+ [](void*, uint8_t* data) { delete reinterpret_cast<CaptureUploadFrame*>(data); }, nullptr, 0);+ if (!infoRef) { delete info; return nullptr; }+ // The pixel buffer keeps the info (and so the mapped resource) alive.+ AVBufferRef* keep = av_buffer_ref(infoRef);+ AVBufferRef* pixels = keep ? av_buffer_create(info->mapped, size_t(bytes),+ [](void* opaque, uint8_t*) { auto* ref = static_cast<AVBufferRef*>(opaque); av_buffer_unref(&ref); }, keep, 0) : nullptr;+ AVFrame* frame = pixels ? av_frame_alloc() : nullptr;+ if (!frame) { if (pixels) av_buffer_unref(&pixels); else if (keep) av_buffer_unref(&keep); av_buffer_unref(&infoRef); return nullptr; }+ frame->format = format; frame->width = int(width); frame->height = int(height);+ frame->buf[0] = pixels; frame->opaque_ref = infoRef;+ frame->data[0] = info->mapped; frame->linesize[0] = int(pitch);+ if (semiplanar) { frame->data[1] = info->mapped + chromaOffset; frame->linesize[1] = int(pitch); }+ return frame;+}++// Capture callback, before it writes a frame: point the planes at the upload+// buffer, or at the CPU planes while the GPU still reads the buffer.+inline void selectCaptureUploadTarget(AVFrame& frame) {+ auto* info = captureUploadFrame(&frame);+ if (!info) return;+ uint8_t* base = info->mapped;+ info->direct = true; info->proxyValid = false;+ if (info->gpuBusy()) {+ if (!info->cpu) { info->cpu = static_cast<uint8_t*>(av_malloc(size_t(info->bytes))); if (info->cpu) std::memset(info->cpu, 0, size_t(info->bytes)); }+ if (info->cpu) { base = info->cpu; info->direct = false; ++info->fallbacks; }+ }+ frame.data[0] = base;+ if (info->planes == 2) frame.data[1] = base + info->chromaOffset;+}++// A writer that cannot supply the analysis pixels (generic swscale output)+// keeps the frame on its CPU planes; the graph then copies it as before.+inline void useCaptureUploadCpuPlanes(AVFrame& frame) {+ auto* info = captureUploadFrame(&frame);+ if (!info) return;+ if (!info->cpu) { info->cpu = static_cast<uint8_t*>(av_malloc(size_t(info->bytes))); if (info->cpu) std::memset(info->cpu, 0, size_t(info->bytes)); }+ if (!info->cpu) return;+ info->direct = false; info->proxyValid = false;+ frame.data[0] = info->cpu;+ if (info->planes == 2) frame.data[1] = info->cpu + info->chromaOffset;+}++// Capture callback, after the copy: the pixels the graph analyses, read from+// plane 0 of the driver sample. flip: destination row r came from source row+// height-1-r.+inline void sampleCaptureUploadProxy(AVFrame& frame, const uint8_t* source, size_t sourcePitch, bool flip) {+ auto* info = captureUploadFrame(&frame);+ if (!info || !source) return;+ const unsigned n = info->pixelBytes;+ uint8_t* out = info->proxy;+ for (unsigned y = 0; y < CaptureUploadFrame::kProxyHeight; ++y) {+ const unsigned row = y * info->height / CaptureUploadFrame::kProxyHeight;+ const uint8_t* line = source + size_t(flip ? info->height - 1 - row : row) * sourcePitch;+ for (unsigned x = 0; x < CaptureUploadFrame::kProxyWidth; ++x) {+ const uint8_t* pixel = line + size_t(x * info->width / CaptureUploadFrame::kProxyWidth) * n;+ for (unsigned k = 0; k < n; ++k) *out++ = pixel[k];+ }+ }+ info->proxyValid = true;+}++// Planar 4:2:0 (I420 / YV12) driver sample -> NV12 frame. u/v point at the+// first source row of each chroma plane; flip reverses the rows of every plane.+inline void interleaveCaptureI420(AVFrame& dst, const uint8_t* luma, size_t lumaPitch, const uint8_t* u, const uint8_t* v, size_t chromaPitch,+ unsigned width, unsigned height, bool flip) {+ for (unsigned row = 0; row < height; ++row)+ std::memcpy(dst.data[0] + ptrdiff_t(flip ? height - 1 - row : row) * dst.linesize[0], luma + size_t(row) * lumaPitch, width);+ const unsigned chromaRows = height / 2, chromaWidth = width / 2;+ for (unsigned row = 0; row < chromaRows; ++row) {+ uint8_t* out = dst.data[1] + ptrdiff_t(flip ? chromaRows - 1 - row : row) * dst.linesize[1];+ const uint8_t* a = u + size_t(row) * chromaPitch; const uint8_t* b = v + size_t(row) * chromaPitch;+ unsigned x = 0;+ for (; x + 16 <= chromaWidth; x += 16) {+ const __m128i uu = _mm_loadu_si128(reinterpret_cast<const __m128i*>(a + x)), vv = _mm_loadu_si128(reinterpret_cast<const __m128i*>(b + x));+ _mm_storeu_si128(reinterpret_cast<__m128i*>(out + 2 * x), _mm_unpacklo_epi8(uu, vv));+ _mm_storeu_si128(reinterpret_cast<__m128i*>(out + 2 * x + 16), _mm_unpackhi_epi8(uu, vv));+ }+ for (; x < chromaWidth; ++x) { out[2 * x] = a[x]; out[2 * x + 1] = b[x]; }+ }+}++} // namespace veyra::pipelinediff --git a/include/veyra/pipeline/ColorGradeInstance.h b/include/veyra/pipeline/ColorGradeInstance.hnew file mode 100644index 00000000..fb393d7f--- /dev/null+++ b/include/veyra/pipeline/ColorGradeInstance.h@@ -0,0 +1,32 @@+#pragma once+#include "veyra/pipeline/ColorGradeTables.h"+#include "veyra/pipeline/GpuPassUtils.h"++namespace veyra::pipeline {+// One non-ingress grade. All video pixels stay on the GPU. Upload buffers are+// indexed by the acquired command slot, so live table edits cannot overwrite+// data still referenced by an older submission. The owner drains before close.+class ColorGradeInstance {+public:+ bool initialize(ID3D12Device* device,uint32_t commandSlots);+ bool createPass(ID3D12Device* device);+ void refresh(const engine::ColorSettings& settings);+ bool setLut(ID3D12Device* device,const float* rgb,unsigned size);+ void createViews(ID3D12Device* device,DescriptorStager& stager,ID3D12Resource* input,ID3D12Resource* output);+ void stageLut(DescriptorStager& stager);+ bool dispatch(ID3D12GraphicsCommandList* list,StateTracker& tracker,uint32_t slot,+ uint32_t width,uint32_t height,bool hdrWorking);+ bool identity()const{return tables_.identity;}+private:+ ComputePass pass_;+ ColorGradeTables tables_;+ engine::ColorSettings settings_;+ std::array<ComPtr<ID3D12Resource>,3> textures_;+ std::vector<std::array<ComPtr<ID3D12Resource>,3>> uploads_;+ ComPtr<ID3D12Resource> lut_,lutUpload_;+ ID3D12Resource* input_=nullptr;+ ID3D12Resource* output_=nullptr;+ unsigned lutSize_=0,lutPitch_=0;+ bool dirty_=true,lutPending_=false,exposureOnly_=false;+};+}diff --git a/include/veyra/pipeline/ColorGradeTables.h b/include/veyra/pipeline/ColorGradeTables.hindex 02f2278b..d6e579fe 100644--- a/include/veyra/pipeline/ColorGradeTables.h+++ b/include/veyra/pipeline/ColorGradeTables.h@@ -29,6 +29,7 @@ struct ColorGradeTables {int lutInputSpace=0;bool blackWhite=false; // monochrome mixer instead of the HSL mixerbool identity=true; // master switch off or every parameter neutral+ bool exposureOnly=false; // only exposure is non-neutral; use exact linear gainstatic ColorGradeTables bake(const engine::ColorSettings& settings);// The exact piecewise-linear response the bake uses, exposed so the UI can// draw the same curve the shader will apply (no second implementation).@@ -50,6 +51,6 @@ inline void packColorGradeConstants(const ColorGradeTables& t,float* out){// in either case the shader must return the input untouched.// flags.w(z) = black & white mixer active. Its per-band weights live in the// hue table's alpha channel, so no extra texture or constant slot is needed.- out[16]=t.identity?0.0f:1.0f;out[17]=float(t.identity?0:t.lutInputSpace);out[18]=t.blackWhite?1.0f:0.0f;out[19]=0;+ out[16]=t.identity?0.0f:1.0f;out[17]=float(t.identity?0:t.lutInputSpace);out[18]=t.blackWhite?1.0f:0.0f;out[19]=t.exposureOnly?1.0f:0.0f;}} // namespace veyra::pipelinediff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.hindex dc8d89b6..63a1fea3 100644--- a/include/veyra/pipeline/EnhanceGraph.h+++ b/include/veyra/pipeline/EnhanceGraph.h@@ -1,8 +1,13 @@#pragma once+#include "veyra/engine/EffectChain.h"+#include <optional>#include "veyra/engine/BackendRecovery.h"#include "veyra/pipeline/ColorGradeTables.h"+#include "veyra/pipeline/ColorGradeInstance.h"#include "veyra/pipeline/NrInstance.h"+#include "veyra/pipeline/ResolutionPlan.h"#include "veyra/pipeline/NrTemporalPass.h"+#include "veyra/pipeline/NrHoldPass.h"// EnhanceGraph - the real unified processing graph (Playbook R3.2).// Chains, per real frame:@@ -45,6 +50,7 @@ namespace veyra::gfx {class D3D12DeviceContext;class CommandSlotRing;class FsrSrBackend;+class FsrFgPresenter;}namespace veyra::ngx {@@ -79,6 +85,7 @@ struct EnhanceGraphDesc {bool nrBeforeSr = false;engine::NrRuntime nrRuntime=engine::NrRuntime::Original;bool nrTemporal=false;+ engine::NrAntiFlicker nrAntiFlicker=engine::NrAntiFlicker::Flow;bool enableFg = true;bool validateMotion = true; // disable only in isolated legacy A/B diagnosticsbool enableNvofStandalone = false; // run NVOF+densify per frame without FG (quality core)@@ -87,7 +94,12 @@ struct EnhanceGraphDesc {bool hdrInput = false; // PQ/HLG YUV ingress; SDR tone mapping unless hdrOutput.unsigned captureBitDepth = 8; // SDR P010/P016 storage, independent of HDR transfer.bool wideYuvInput() const { return hdrInput || captureBitDepth > 8; }- bool hdrOutput = false; // HDR-preserving output: scRGB without FG; RGB10/PQ with FG.+ bool hdrOutput = false; // HDR-preserving output; HDR10 by default, FG requires HDR10.+ engine::HdrOutputMode hdrOutputMode=engine::HdrOutputMode::Hdr10;+ engine::MotionSource fgMotion=engine::MotionSource::Automatic,srMotion=engine::MotionSource::OpticalFlow,nrMotion=engine::MotionSource::OpticalFlow;+ bool fgUsesFlow()const{return engine::motionUsesFlow(fgMotion,frameGenerationBackend);}+ bool srUsesFlow()const{return engine::motionUsesFlow(srMotion);}+ bool nrUsesFlow()const{return engine::motionUsesFlow(nrMotion);}engine::VideoHdrSettings videoHdr;bool hdrWorking() const {return hdrInput&&hdrOutput;}bool convertVideoHdr() const {return videoHdr.enabled&&!hdrInput&&hdrOutput;}@@ -113,14 +125,248 @@ struct EnhanceGraphDesc {// path; extra entries stack further Feature-18 instances, each with its own// parameters and history. src/pipeline/NrInstance.h.std::vector<engine::NrSettings> nrLayersModel;+ std::vector<NrSizePolicy> nrLayersSizePolicy;+ std::vector<Extent> nrLayersExtent; // active instances; full output stays unchangedstd::vector<engine::ResidualSettings> nrLayersResidual;std::vector<bool> nrLayersTemporal;+ // Per-layer anti-flicker tier, parallel to nrLayersTemporal. Empty means the+ // flat nrAntiFlicker applies to every layer.+ std::vector<engine::NrAntiFlicker> nrLayersAntiFlicker;std::vector<engine::ProtectionSettings> nrLayersProtection;engine::ProtectionSettings protection;+ // Stage-5 output stabiliser (anti-flicker). 0 keeps the pass unallocated and+ // the dispatch skipped, so a default session is byte-identical to a build+ // without it. See shaders/NrHold.hlsl.+ float nrHoldStrength=0.0f;+ float nrHoldTolerance=0.02f;// Colour grade (plan v4). When color.enabled is false the stage does not// exist: no tables are allocated, no constants are packed and the ingest// shaders return their linear RGB untouched.engine::ColorSettings color;+ // Instance zero keeps the fused ingress path. Additional instances execute+ // in order on RGBA16F textures; never on a CPU copy of a video frame.+ std::array<engine::ColorSettings,engine::kMaxColorInstances-1> additionalColors{};+ uint32_t additionalColorCount=0;+ // Production builders compile once and use this plan for NR resource+ // sizes and node tail Color routing after the fixed base block. This is+ // NOT an arbitrary-order GPU dispatcher. Direct+ // diagnostic builders may omit it. Neither field crosses the worker ABI.+ std::optional<engine::ChainExecutionPlan> fixedExecutionPlan;+ bool runtimeNodeOrder=false;+ std::string fixedExecutionPlanError;+ // Supported non-ingress positions include the SR/NR boundaries and+ // contiguous NR layers. Other interleaving still fails admission.+ uint32_t nrBeforeSrLayerCount() const {+ if(!runtimeNodeOrder||!fixedExecutionPlan)return 0;+ uint32_t count=0;+ for(uint32_t i=0;i<fixedExecutionPlan->stepCount&&i<fixedExecutionPlan->steps.size();++i){+ const auto type=fixedExecutionPlan->steps[i].type;+ if(type==engine::EffectType::SuperResolution)return count;+ if(type==engine::EffectType::NrEnhance)++count;+ }+ return 0;+ }+ bool splitNrAcrossSr() const {+ const auto before=nrBeforeSrLayerCount();+ return before&&fixedExecutionPlan&&before<fixedExecutionPlan->resourceCounts[size_t(engine::EffectType::NrEnhance)];+ }+ // The source-size prefix has an unenhanced reference before SR. After+ // SR, workRgba already contains that prefix's NR and is not an original.+ bool protectionBeforeSr() const {+ if(!splitNrAcrossSr())return false;+ const auto& plan=*fixedExecutionPlan;+ for(uint32_t i=1;i<plan.stepCount&&i<plan.steps.size();++i){+ if(plan.steps[i].type==engine::EffectType::SuperResolution)return false;+ if(plan.steps[i].type!=engine::EffectType::Protection)continue;+ if(plan.steps[i-1].type!=engine::EffectType::NrEnhance)return false;+ for(uint32_t j=i+1;j<plan.stepCount&&j<plan.steps.size();++j){+ if(plan.steps[j].type==engine::EffectType::SuperResolution)return true;+ if(plan.steps[j].type!=engine::EffectType::Color)return false;+ }+ return false;+ }+ return false;+ }+ // Protection may restore the upstream NR stack before another same-size+ // NR consumes it. A split chain still has no all-NR original after SR.+ uint32_t interNrProtectionTarget() const {+ if(!runtimeNodeOrder||!fixedExecutionPlan)return engine::kMaxNrInstances;+ const auto& plan=*fixedExecutionPlan;bool afterSr=false;+ for(uint32_t i=0;i<plan.stepCount&&i<plan.steps.size();++i){+ if(plan.steps[i].type==engine::EffectType::SuperResolution)afterSr=true;+ if(plan.steps[i].type!=engine::EffectType::Protection)continue;+ if(!i||plan.steps[i-1].type!=engine::EffectType::NrEnhance||+ (afterSr&&splitNrAcrossSr()))return engine::kMaxNrInstances;+ for(uint32_t j=i+1;j<plan.stepCount&&j<plan.steps.size();++j){+ if(plan.steps[j].type==engine::EffectType::NrEnhance)return plan.steps[j].resourceIndex;+ if(plan.steps[j].type!=engine::EffectType::Color)break;+ }+ return engine::kMaxNrInstances;+ }+ return engine::kMaxNrInstances;+ }+ Extent nrFullExtent(size_t resource) const {+ if(runtimeNodeOrder&&fixedExecutionPlan){+ for(uint32_t i=0;i<fixedExecutionPlan->stepCount&&i<fixedExecutionPlan->steps.size();++i){+ const auto& step=fixedExecutionPlan->steps[i];+ if(step.type==engine::EffectType::NrEnhance&&step.resourceIndex==resource)return step.input;+ }+ }+ return nrBeforeSr?Extent{sourceWidth,sourceHeight}:Extent{workWidth,workHeight};+ }+ bool finalNrAfterSr() const { return !nrBeforeSr||splitNrAcrossSr(); }+ bool preSrColor(uint32_t parameter) const {+ if(!runtimeNodeOrder||!fixedExecutionPlan||!nrBeforeSr)return false;+ using engine::EffectType;+ const auto& plan=*fixedExecutionPlan;+ bool afterNr=false;+ for(uint32_t i=0;i<plan.stepCount&&i<plan.steps.size();++i){+ const auto& step=plan.steps[i];+ if(step.type==EffectType::SuperResolution)return false;+ if(step.type==EffectType::NrEnhance)afterNr=true;+ if(step.type!=EffectType::Color||step.parameterIndex!=parameter)continue;+ if(!afterNr)return false;+ for(uint32_t j=i+1;j<plan.stepCount&&j<plan.steps.size();++j){+ if(plan.steps[j].type==EffectType::SuperResolution)return true;+ if(plan.steps[j].type!=EffectType::Color)break;+ }+ return false;+ }+ return false;+ }+ bool preNrColor(uint32_t parameter) const {+ if(!runtimeNodeOrder||!fixedExecutionPlan||(nrBeforeSr&&!splitNrAcrossSr()))return false;+ using engine::EffectType;+ bool afterSr=false;+ for(uint32_t i=0;i<fixedExecutionPlan->stepCount&&i<fixedExecutionPlan->steps.size();++i){+ const auto& step=fixedExecutionPlan->steps[i];+ if(step.type==EffectType::NrEnhance&&afterSr)return false;+ if(step.type==EffectType::SuperResolution)afterSr=true;+ if(step.type!=EffectType::Color||step.parameterIndex!=parameter)continue;+ if(!afterSr)return false;+ for(uint32_t j=i+1;j<fixedExecutionPlan->stepCount&&j<fixedExecutionPlan->steps.size();++j)+ if(fixedExecutionPlan->steps[j].type==EffectType::NrEnhance)return true;+ return false;+ }+ return false;+ }+ // Compact NR resource ordinal consuming this grade. Only a contiguous+ // NR -> [Protection] -> Color(s) -> NR segment is admitted here.+ // Crossing SR needs a separate boundary, not a relaxed rank check.+ uint32_t interNrColorTarget(uint32_t parameter) const {+ if(!runtimeNodeOrder||!fixedExecutionPlan)return engine::kMaxNrInstances;+ using engine::EffectType;+ const auto& plan=*fixedExecutionPlan;+ bool afterNr=false;+ for(uint32_t i=0;i<plan.stepCount&&i<plan.steps.size();++i){+ const auto& step=plan.steps[i];+ if(step.type==EffectType::NrEnhance)afterNr=true;+ else if(step.type!=EffectType::Color&&+ !(step.type==EffectType::Protection&&interNrProtectionTarget()<engine::kMaxNrInstances))afterNr=false;+ if(step.type!=EffectType::Color||step.parameterIndex!=parameter)continue;+ if(!afterNr)return engine::kMaxNrInstances;+ for(uint32_t j=i+1;j<plan.stepCount&&j<plan.steps.size();++j){+ const auto& next=plan.steps[j];+ if(next.type==EffectType::NrEnhance)return next.resourceIndex;+ if(next.type!=EffectType::Color)break;+ }+ return engine::kMaxNrInstances;+ }+ return engine::kMaxNrInstances;+ }+ bool nodeColor(uint32_t parameter) const {+ return preNrColor(parameter)||preSrColor(parameter)||tailColor(parameter)||interNrColorTarget(parameter)<engine::kMaxNrInstances;+ }+ bool tailColor(uint32_t parameter) const {+ if(!runtimeNodeOrder||!fixedExecutionPlan)return false;+ using engine::EffectType;+ bool afterBase=false;+ for(uint32_t i=0;i<fixedExecutionPlan->stepCount&&i<fixedExecutionPlan->steps.size();++i){+ const auto& step=fixedExecutionPlan->steps[i];+ if(step.type==EffectType::SuperResolution||step.type==EffectType::NrEnhance||step.type==EffectType::Protection)afterBase=true;+ if(step.type!=EffectType::Color||step.parameterIndex!=parameter)continue;+ if(!afterBase)return false;+ for(uint32_t j=i+1;j<fixedExecutionPlan->stepCount&&j<fixedExecutionPlan->steps.size();++j){+ const auto type=fixedExecutionPlan->steps[j].type;+ if(type==EffectType::SuperResolution||type==EffectType::NrEnhance||type==EffectType::Protection)return false;+ }+ return true;+ }+ return false;+ }+ std::string_view validateFixedExecutionPlan() const {+ if(!fixedExecutionPlanError.empty())return fixedExecutionPlanError;+ if(!fixedExecutionPlan)return {};+ using engine::EffectType;+ const auto& plan=*fixedExecutionPlan;+ if(plan.stepCount>plan.steps.size()||plan.output!=Extent{workWidth,workHeight})+ return "fixed execution plan output/count mismatch";+ std::array<uint32_t,engine::effectTypeCount> counts{};+ Extent cursor{sourceWidth,sourceHeight}; int lastRank=-1;+ const bool split=splitNrAcrossSr();+ const bool interProtection=interNrProtectionTarget()<engine::kMaxNrInstances;+ if(interProtection&&(noFeatures||noNgx))return "inter-NR protection requires active NR resources";+ if(split&&(noFeatures||noNgx))return "split NR execution requires active NR resources";+ if(split&&protection.enabled&&!protectionBeforeSr()&&!interProtection)return "split NR protection requires a stage-local original reference";+ bool afterSr=false;+ for(uint32_t i=0;i<plan.stepCount;++i){+ const auto& step=plan.steps[i];const auto type=size_t(step.type);+ if(type>=counts.size())return "unknown fixed execution stage";+ int rank=int(type);+ if(nrBeforeSr){+ if(step.type==EffectType::NrEnhance)rank=1;+ if(step.type==EffectType::Protection)rank=2;+ if(step.type==EffectType::SuperResolution)rank=3;+ }+ if(runtimeNodeOrder){+ if(step.type==EffectType::Protection&&interProtection)rank=nrBeforeSr?1:2;+ if(step.type==EffectType::Color){+ if(step.parameterIndex>additionalColorCount||step.parameterIndex>=engine::kMaxColorInstances||+ !(step.parameterIndex?additionalColors[step.parameterIndex-1].enabled:color.enabled))+ return "node Color parameter index/enabled mismatch";+ if(tailColor(step.parameterIndex))rank=4;+ else if(preNrColor(step.parameterIndex))rank=2;+ else if(preSrColor(step.parameterIndex))rank=3;+ else if(interNrColorTarget(step.parameterIndex)<engine::kMaxNrInstances)rank=nrBeforeSr?1:2;+ }+ if(step.type==EffectType::VideoHdr)rank=5;+ if(step.type==EffectType::FrameGeneration)rank=6;+ }+ if(split){+ if(step.type==EffectType::Protection){+ if(!protectionBeforeSr()&&!interProtection)return "split NR protection requires a stage-local original reference";+ rank=interProtection?1:2;+ }+ if(step.type==EffectType::SuperResolution){rank=3;afterSr=true;}+ if(step.type==EffectType::NrEnhance)rank=afterSr?4:1;+ if(step.type==EffectType::Color){+ if(tailColor(step.parameterIndex))rank=6;+ else if(preNrColor(step.parameterIndex))rank=4;+ else if(preSrColor(step.parameterIndex))rank=2;+ else if(interNrColorTarget(step.parameterIndex)<engine::kMaxNrInstances)rank=afterSr?4:1;+ }+ if(step.type==EffectType::VideoHdr)rank=7;+ if(step.type==EffectType::FrameGeneration)rank=8;+ }+ if(rank<lastRank)return "ordered node execution is not supported by fixed dispatcher";+ lastRank=rank;+ if(step.input!=cursor||!step.processing.valid()||!step.output.valid()||+ step.resourceIndex!=counts[type]++)return "invalid fixed stage dimensions/resource index";+ if(step.type!=EffectType::SuperResolution&&step.output!=cursor)+ return "fixed non-SR stage changes output dimensions";+ if(step.type==EffectType::NrEnhance){+ const Extent full=split?nrFullExtent(step.resourceIndex):(nrBeforeSr?Extent{sourceWidth,sourceHeight}:Extent{workWidth,workHeight});+ if(!enableNr||step.input!=full||step.resourceIndex>=nrLayersExtent.size()||+ step.processing!=nrLayersExtent[step.resourceIndex]||step.parameterIndex>=engine::kMaxNrInstances)+ return "fixed NR plan/resource dimensions mismatch";+ }+ cursor=step.output;+ }+ const size_t expectedNr=enableNr?(nrLayersModel.empty()?1:nrLayersModel.size()):0;+ if(cursor!=plan.output||counts!=plan.resourceCounts||counts[size_t(EffectType::NrEnhance)]!=expectedNr)+ return "fixed execution plan resource count mismatch";+ return {};+ }std::wstring runtimeAbsPath; // absolute runtime_local/nvidia path// Optional stage instrumentation hook (GPU timing experiments).std::function<void(const char*)> stageMark;@@ -156,7 +402,7 @@ public:bool initialize(const EnhanceGraphDesc& desc);// Uploads a .cube payload (size^3 RGB triples, 0..1) into the optional 3D// LUT the ingest shader samples. Without a LUT the strength stays 0.- bool setColorLut(const float* rgb,unsigned size);+ bool setColorLut(const float* rgb,unsigned size,unsigned instance=0);bool createViews();struct FrameOutputs {@@ -235,6 +481,7 @@ public:uint64_t nvofFrameFailures = 0;uint64_t fgGeneratedFrames = 0;uint64_t fgSubmittedCandidates = 0, fgDisabledFrames = 0;+ uint64_t fgProviderDisabled = 0, fgDuplicateSuppressed = 0, fgBothDisabled = 0;uint64_t nrMotionFrames = 0, sceneCutCount = 0, resetCount = 0;};const Metrics& metrics() const { return metrics_; }@@ -262,14 +509,16 @@ public:bool fgEnabled() const { return fgEnabled_; }bool hdrOutput() const { return desc_.hdrOutput; }bool videoHdrActive() const {return desc_.convertVideoHdr();}- bool hdr10Output() const { return desc_.hdrOutput && desc_.enableFg; }+ bool hdr10Output() const { return desc_.hdrOutput && (desc_.enableFg||desc_.hdrOutputMode==engine::HdrOutputMode::Hdr10); }DXGI_FORMAT outputFormat() const { return hdr10Output()?DXGI_FORMAT_R10G10B10A2_UNORM:desc_.hdrOutput?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_R8G8B8A8_UNORM; }bool highQualityPresentation() const { return desc_.highQualityPresentation; }bool xessEnabled() const { return desc_.enableFg && !desc_.noFeatures && !desc_.stillImage && desc_.frameGenerationBackend==engine::FrameGenerationBackend::XeSS; }- bool fsrEnabled() const { return desc_.enableFg && !desc_.noFeatures && !desc_.stillImage && desc_.frameGenerationBackend==engine::FrameGenerationBackend::Fsr; }- // Frame generation implemented by the present sink (XeSS, FSR) instead of- // the in-graph DLSSG path; both consume the same guidance motion texture.- bool presentSinkFg() const { return xessEnabled() || fsrEnabled(); }+ bool fsrEnabled() const { return desc_.enableFg && !desc_.noFeatures && !desc_.stillImage && engine::fsrFrameGeneration(desc_.frameGenerationBackend); }+ bool fsrActive() const;+ const char* fsrProviderVersion() const;+ // XeSS generates in the present sink; FSR and DLSSG generate in the graph.+ // All backends consume the same guidance motion texture.+ bool presentSinkFg() const { return xessEnabled(); }// AMD FSR upscaling replaces the SR stage; it is a FidelityFX effect, not// an NGX feature, so it also works on non-NVIDIA adapters.bool fsrSrRequested() const { return desc_.enableSr && !desc_.stillImage && desc_.videoSrQuality==engine::kVideoSrFsr; }@@ -294,15 +543,30 @@ public:ID3D12Resource* diagnosticLinearInput() const { return srcRgba_.Get(); }// Offline diagnostics only. Borrowed after process; restore NON_PIXEL_SHADER_RESOURCE.ID3D12Resource* diagnosticNrBase() const { return desc_.nrBeforeSr?srcRgba_.Get():workRgba_.Get(); }- ID3D12Resource* diagnosticNrRaw() const { return desc_.nrTemporal&&!nrInstances_.empty()?nrInstances_.front()->temporal().raw():residualRgba_.Get(); }+ // Last layer's pre-temporal result; stack protection is applied afterwards.+ ID3D12Resource* diagnosticNrRaw() const { return !nrInstances_.empty()&&nrInstances_.back()->stabilised?nrInstances_.back()->temporal().raw():(!nrInstances_.empty()?nrInstances_.back()->fullTarget():residualRgba_.Get()); }ID3D12Resource* diagnosticNrFiltered() const { return residualRgba_.Get(); }+ ID3D12Resource* diagnosticPreSrProtection() const { return preSrProtectionRgba_.Get(); }+ ID3D12Resource* diagnosticInterNrProtection() const { return interNrProtectionRgba_.Get(); }+ ID3D12Resource* diagnosticVideoSrInput() const { return videoSrInput_.Get(); }+ ID3D12Resource* diagnosticVideoSrOutput() const { return videoSrOutput_.Get(); }+ ID3D12Resource* diagnosticNrLayerInput(size_t index) const { return index < nrInstances_.size() ? nrInstances_[index]->input() : nullptr; }+ ID3D12Resource* diagnosticNrLayerOutput(size_t index) const { return index < nrInstances_.size() ? nrInstances_[index]->fullTarget() : nullptr; }+ engine::NrLayerSettings diagnosticNrLayerSettings(size_t index) const {+ if(index>=nrInstances_.size())return {};+ const auto& n=*nrInstances_[index];+ const bool beforeSr=desc_.nrBeforeSr&&(!desc_.splitNrAcrossSr()||index<desc_.nrBeforeSrLayerCount());+ return {n.model,n.residualSettings,desc_.nrRuntime,n.temporalEnabled,beforeSr,n.enabled};+ }+ uint64_t diagnosticNrInputRevision(size_t index) const { return index<nrInstances_.size()?nrInstances_[index]->inputRevision:0; }+ D3D12_RESOURCE_STATES diagnosticResourceState(ID3D12Resource* resource) const { return tracker_.get(resource); }// Non-empty when the colour stage refused the referenced LUT (input space// does not match the content domain). The engine surfaces this in the// status panel so the refusal is visible, not only logged.const std::wstring& colorLutNotice() const { return colorLutNotice_; }// True when the colour stage exists in this graph (master switch on and not// neutral). The encoder uses it to dither its 8/10-bit conversion output.- bool colorGradeActive() const { return colorActive_; }+ bool colorGradeActive() const { return colorActive_||additionalColorActiveCount_!=0||tailColorActiveCount_!=0||preNrColorActiveCount_!=0||preSrColorActiveCount_!=0||interNrColorActiveCount_!=0; }// Effective dither step for the 8/10-bit output paths (0 = no dither).float outputDitherStep() const;// Isolated diagnostics only: existing constant guidance, borrowed lifetime.@@ -318,6 +582,8 @@ public:bool nvofSessionInitialized() const;uint64_t nvofNextOutValue() const;uint64_t nrCreateResult() const { return nrResult_; }+ uint64_t failedNgxResult() const;+ const std::wstring& driverRequirementNotice() const {return driverRequirementNotice_;}bool fgCapabilityAvailable() const { return fgCapsAvailable_; }int fgMultiFrameCountMax() const { return fgMultiFrameMax_; }// Scenario toggles (probe/UI): gates only; the feature handles stay alive.@@ -335,6 +601,7 @@ private:bool initNvof();bool initNgxFeatures();bool initFsrSr();+ bool initFsrFg();// RTX 40 series: opens the Blackwell-only multi-frame gate in the mapped// DLSS-G runtime. Never touched on any other architecture.void applyAdaMfgUnlock();@@ -366,6 +633,9 @@ private:ComPtr<ID3D12Resource> lumaTex_;ComPtr<ID3D12Resource> chromaTex_;ComPtr<ID3D12Resource> srcRgba_;+ // Preserve the ungraded decode at FP32 when the first enabled grade is an+ // independent instance; later passes still use the RGBA16F chain.+ ComPtr<ID3D12Resource> preGradeRgba_;ComPtr<ID3D12Resource> rgbTex_,upRgb_[2];uint8_t* mappedRgb_[2]={};size_t rgbPitch_=0;@@ -373,6 +643,8 @@ private:ComPtr<ID3D12Resource> videoSrInput_,videoSrOutput_;ComPtr<ID3D12Resource> videoHdrInput_,videoHdrOutput_;ComPtr<ID3D12Resource> residualRgba_,nrFlow_,baseFlow_;+ ComPtr<ID3D12Resource> preSrProtectionRgba_;+ ComPtr<ID3D12Resource> interNrProtectionRgba_;// NR layers. One entry means the single-layer product path; the probe in// tools/nr_probe verified several handles coexist on one snippet session.std::vector<std::unique_ptr<NrInstance>> nrInstances_;@@ -405,25 +677,64 @@ private:ComputePass yuvPass_, encPass_, decPass_, blitPass_, uploadPass_, densifyPass_;float toneMapPeakNits_=0; // latched per graph/source; never varies with frame brightnessComputePass rgbPass_,hdrVideoSrPass_;- ComputePass downsamplePass_,residualPass_,flowAdaptPass_;+ ComputePass downsamplePass_,residualPass_,stackProtectionPass_,flowAdaptPass_;+ // Stage-5 output stabiliser (anti-flicker). Constructed only when the+ // setting is non-zero; a default (0) session never allocates it and the+ // dispatch is skipped, so the disabled path is unchanged.+ std::unique_ptr<NrHoldPass> nrHoldPass_;+ // The texture the rest of the graph reads as "the NR result". Without the+ // stabiliser this is residualRgba_; with it, the stabilised copy the pass+ // produces. Set once per frame, read by the SR/FG/tail bindings below.+ ID3D12Resource* nrOutputView_=nullptr;+ bool createNrHoldPass();// --- colour grade (v4): CPU-baked tables read by the ingest shaders -----bool colorActive_=false;std::wstring colorLutNotice_;bool colorDirty_=true;ColorGradeTables colorTables_;ComPtr<ID3D12Resource> colorCurveTex_,colorHueTex_,colorLumTex_,colorLutTex_;- ComPtr<ID3D12Resource> upColorCurve_,upColorHue_,upColorLum_;- float* mappedColorCurve_=nullptr;- float* mappedColorHue_=nullptr;- float* mappedColorLum_=nullptr;+ // Only write the upload resources of the acquired (completed) command slot.+ std::vector<std::array<ComPtr<ID3D12Resource>,3>> colorTableUploads_;unsigned colorLutSize_=0;std::vector<float> colorLutUpload_;unsigned colorLutPending_=0;std::array<ComPtr<ID3D12Resource>,2> colorLutStaging_{};unsigned colorLutStagingSlot_=0;bool createColorResources();+ bool createAdditionalColorResources();+ bool createNodeColorResources();+ std::array<std::unique_ptr<ColorGradeInstance>,engine::kMaxColorInstances-1> additionalColorInstances_{};+ std::array<ComPtr<ID3D12Resource>,2> colorScratch_{};+ unsigned additionalColorActiveCount_=0;+ // Indexed by settings identity (including disabled slots), not compact+ // resource ordinal. Only enabled non-ingress nodes allocate resources.+ std::array<std::unique_ptr<ColorGradeInstance>,engine::kMaxColorInstances> nodeColorInstances_{};+ std::array<ComPtr<ID3D12Resource>,engine::kMaxColorInstances> nodeColorOutputs_{};+ unsigned tailColorActiveCount_=0,preNrColorActiveCount_=0,preSrColorActiveCount_=0,interNrColorActiveCount_=0;+ bool tailColorExecutionLogged_=false,preNrColorExecutionLogged_=false;+ bool preSrColorExecutionLogged_=false;+ bool interNrColorExecutionLogged_=false;+ ID3D12Resource* tailColorOutput_=nullptr; // borrowed from nodeColorOutputs_+ ID3D12Resource* preNrColorOutput_=nullptr;+ ID3D12Resource* preSrColorOutput_=nullptr;+ std::array<ID3D12Resource*,engine::kMaxNrInstances> interNrColorOutputs_{};+ ID3D12Resource* nrBaseInput() const { return desc_.nrBeforeSr?srcRgba_.Get():(preNrColorOutput_?preNrColorOutput_:workRgba_.Get()); }+ ID3D12Resource* preSrBaseInput() const {+ if(preSrProtectionRgba_)return preSrProtectionRgba_.Get();+ const auto before=desc_.nrBeforeSrLayerCount();+ return desc_.splitNrAcrossSr()&&before<=nrInstances_.size()?nrInstances_[before-1]->fullTarget():residualRgba_.Get();+ }+ ID3D12Resource* srStageInput() const {+ return preSrColorOutput_?preSrColorOutput_:(desc_.nrBeforeSr?preSrBaseInput():srcRgba_.Get());+ }+ ID3D12Resource* nrLayerBase(size_t layer) const {+ if(layer<interNrColorOutputs_.size()&&interNrColorOutputs_[layer])return interNrColorOutputs_[layer];+ if(interNrProtectionRgba_&&layer==desc_.interNrProtectionTarget())return interNrProtectionRgba_.Get();+ if(desc_.splitNrAcrossSr()&&layer==desc_.nrBeforeSrLayerCount())return preNrColorOutput_?preNrColorOutput_:workRgba_.Get();+ return layer?nrInstances_[layer-1]->fullTarget():nrBaseInput();+ }void refreshColorTables();- void uploadColorTables(ID3D12GraphicsCommandList* list);+ bool uploadColorTables(ID3D12GraphicsCommandList* list,uint32_t slot);DescriptorStager stager_;Microsoft::WRL::ComPtr<ID3D12Resource> sourceReferences_[2],baseReferences_[2];StateTracker tracker_;@@ -443,11 +754,14 @@ private:std::unique_ptr<ngx::VideoSrBackend> videoSrBackend_;std::unique_ptr<ngx::TrueHdrBackend> videoHdrBackend_;std::unique_ptr<ngx::DlssFgBackend> fgBackend_;+ std::unique_ptr<gfx::FsrFgPresenter> fsrFgBackend_;std::unique_ptr<gfx::FsrSrBackend> fsrSrBackend_;- ComPtr<ID3D12Resource> fsrSrDepth_, upFsrSrDepth_;+ ComPtr<ID3D12Resource> fsrSrDepth_, upFsrSrDepth_, fsrSrZeroMotion_, upFsrSrZeroMotion_;size_t fsrSrDepthPitch_=0;NVSDK_NGX_Parameter* ngxParams_ = nullptr;uint64_t nrResult_ = 0;+ uint64_t fgInitResult_ = 0;+ std::wstring driverRequirementNotice_;uint32_t nrSeh_ = 0;bool fgCapsAvailable_ = false;int fgMultiFrameMax_ = 0;diff --git a/include/veyra/pipeline/NrHoldPass.h b/include/veyra/pipeline/NrHoldPass.hnew file mode 100644index 00000000..0af02253--- /dev/null+++ b/include/veyra/pipeline/NrHoldPass.h@@ -0,0 +1,51 @@+#pragma once+#include "veyra/pipeline/GpuPassUtils.h"++namespace veyra::pipeline {+// Output stabiliser: holds the previous output where the source has not+// visibly changed (stage 5 of docs/NR_FG_OPTIMIZATION_PLAN_2026-09-29.md).+//+// It sits after the last NR layer and the residual composite, before SR/FG, so+// it can only smooth what NR emitted -- never a generated frame. It is disabled+// by default (strength 0), and at 0 the caller skips run() entirely, which+// keeps the disabled path byte-identical to a build without this pass.+//+// The pass owns its own textures and never writes into the graph's NR output:+// it reads that output, produces a stabilised result in its own ping-pong+// target, and the caller copies it back. That copy is the price of leaving+// every existing SR/FG/present binding untouched, and it is one full-extent+// blit behind the NR cost.+//+// No reprojection and no motion vectors: a wrong vector would drag the previous+// output into a region that did move, which is exactly the ghosting this pass+// exists to avoid. Regions that moved stop holding.+class NrHoldPass {+public:+ // `current` is the graph's NR result for this frame, `base` the image that+ // fed NR (possibly a different extent under the realtime NR policy, which+ // the shader rescales). Both are borrowed; the pass allocates its own+ // history at the NR extent.+ bool initialize(ID3D12Device* device, uint32_t width, uint32_t height,+ ID3D12Resource* current, ID3D12Resource* base);+ // `reset` (seek, scene cut, resize, source switch, pause/resume) publishes+ // the current value and holds nothing. `strength` 0 is refused: callers must+ // skip the call instead, so the disabled path records no dispatch at all.+ void run(ID3D12GraphicsCommandList* list, StateTracker& tracker, bool reset,+ float strength, float tolerance);+ // The stabilised result, valid until the next run(). The caller copies this+ // into whatever texture the rest of the graph already reads.+ ID3D12Resource* result() const { return output_[index_ ^ 1u].Get(); }+ bool active() const { return valid_; }+ void reset() { valid_ = false; }+ void close();++private:+ ComputePass pass_;+ ComPtr<ID3D12Resource> output_[2]; // ping-pong results+ ComPtr<ID3D12Resource> previousBase_[2]; // ping-pong source anchors+ ID3D12Resource* current_ = nullptr;+ ID3D12Resource* base_ = nullptr;+ unsigned width_ = 0, height_ = 0, baseWidth_ = 0, baseHeight_ = 0, index_ = 0;+ bool valid_ = false;+};+}diff --git a/include/veyra/pipeline/NrInstance.h b/include/veyra/pipeline/NrInstance.hindex 8c85b49f..6eb761b9 100644--- a/include/veyra/pipeline/NrInstance.h+++ b/include/veyra/pipeline/NrInstance.h@@ -36,7 +36,7 @@ public:bool create(ID3D12Device* device, uint32_t width, uint32_t height,uint32_t fullWidth, uint32_t fullHeight,ID3D12Resource* zeroMotion, ID3D12Resource* zeroDepth,- ID3D12Resource* borrowedInput = nullptr);+ ID3D12Resource* borrowedInput = nullptr, ID3D12Resource* borrowedMotion = nullptr);void close();bool created() const { return proxy_ != nullptr; }@@ -52,6 +52,7 @@ public:ID3D12Resource* finalRgba() const { return finalRgba_.Get(); }ID3D12Resource* residual() const { return residual_.Get(); }ID3D12Resource* zeroMotion() const { return zeroMotion_; }+ ID3D12Resource* motion() const { return motion_.Get(); }// The full-extent image this layer composites onto, and the full-extent// result it produces (except for the last layer, which the graph owns).ID3D12Resource* baseFull() const { return baseFull_; }@@ -92,6 +93,7 @@ public:private:ComPtr<ID3D12Resource> input_, proxy_, neural_, finalRgba_, residual_, outputFull_;+ ComPtr<ID3D12Resource> motion_; // same-size shared guidance or own adapted textureID3D12Resource* baseFull_ = nullptr;// Not owned: either this layer's `outputFull_` or the graph's residual// texture. Set when views are created.diff --git a/include/veyra/pipeline/NrTemporalPass.h b/include/veyra/pipeline/NrTemporalPass.hindex 434116ef..8aacc126 100644--- a/include/veyra/pipeline/NrTemporalPass.h+++ b/include/veyra/pipeline/NrTemporalPass.h@@ -6,9 +6,16 @@namespace veyra::pipeline {// Residual history stays on the graph's ordered GPU queue. Descriptor sets are// immutable; neither CPU waits nor descriptor rewrites occur per frame.+//+// The anti-flicker tier (engine::NrAntiFlicker) selects how the accumulation+// behaves; see shaders/NrTemporal.hlsl for what each route means. Route+// LowFrequency additionally runs a half-resolution reduce pass and rebuilds a+// low-frequency observation, which is why this pass owns the reduce shader and+// the pair of half-resolution textures.class NrTemporalPass {public:- bool initialize(ID3D12Device*,ID3D12Resource* base,ID3D12Resource* motion,ID3D12Resource* output);+ bool initialize(ID3D12Device*,ID3D12Resource* base,ID3D12Resource* motion,ID3D12Resource* output,+ engine::NrAntiFlicker tier=engine::NrAntiFlicker::Flow);ID3D12Resource* raw()const{return raw_.Get();}void run(ID3D12GraphicsCommandList*,StateTracker&,bool reset,bool haveMotion,double frameMs,float total,const engine::ProtectionSettings& protection);@@ -16,9 +23,16 @@ public:void close();private:ComputePass pass_;+ // Only allocated for the low-frequency tier. The reduce pass writes both+ // every frame and the main pass reads both back in the same frame, so they+ // are two distinct signals (residual and guide), not a ping-pong pair --+ // matching the upstream shader's u0/u1 outputs.+ ComputePass reducePass_;+ ComPtr<ID3D12Resource> lowResidual_,lowGuide_;ComPtr<ID3D12Resource> raw_,history_[2],guide_[2];ID3D12Resource* base_=nullptr;ID3D12Resource* motion_=nullptr;ID3D12Resource* output_=nullptr;- unsigned width_=0,height_=0,index_=0;+ unsigned width_=0,height_=0,lowWidth_=0,lowHeight_=0,index_=0;+ engine::NrAntiFlicker tier_=engine::NrAntiFlicker::Flow;bool valid_=false;};}diff --git a/include/veyra/pipeline/ResolutionPlan.h b/include/veyra/pipeline/ResolutionPlan.hindex 9e5dbd30..6e0dfdcb 100644--- a/include/veyra/pipeline/ResolutionPlan.h+++ b/include/veyra/pipeline/ResolutionPlan.h@@ -14,13 +14,17 @@ constexpr bool validNrSizePolicy(NrSizePolicy policy){return policy>=NrSizePolicconstexpr unsigned nrHeightLimit(NrSizePolicy policy){switch(policy){case NrSizePolicy::Realtime:return 1080;case NrSizePolicy::P480:return 480;case NrSizePolicy::P720:return 720;case NrSizePolicy::P900:return 900;case NrSizePolicy::P1440:return 1440;default:return 0;}}-enum class SrTarget : uint32_t { Qhd, Uhd4K, Uhd8K };-constexpr bool validSrTarget(SrTarget target) { return target<=SrTarget::Uhd8K; }+// Preserve the existing 0/1/2 preset IDs. New choices are appended.+enum class SrTarget : uint32_t { Qhd, Uhd4K, Uhd8K, Uhd5K, Uhd6K, Uhd7K };+constexpr bool validSrTarget(SrTarget target) { return target<=SrTarget::Uhd7K; }constexpr Extent srTargetExtent(SrTarget target) {switch(target) {case SrTarget::Qhd:return {2560,1440};case SrTarget::Uhd4K:return {3840,2160};case SrTarget::Uhd8K:return {7680,4320};+ case SrTarget::Uhd5K:return {5120,2880};+ case SrTarget::Uhd6K:return {6144,3456};+ case SrTarget::Uhd7K:return {7168,4032};}return {};}diff --git a/include/veyra/sink/WasapiAudioSink.h b/include/veyra/sink/WasapiAudioSink.hindex 157a3a0c..be59e0e7 100644--- a/include/veyra/sink/WasapiAudioSink.h+++ b/include/veyra/sink/WasapiAudioSink.h@@ -17,6 +17,7 @@#include <format>#include <mutex>#include <limits>+#include <string>#include <thread>#include <vector>@@ -40,6 +41,26 @@ constexpr double kAudioPrefillMs = 500.0;constexpr double kAudioHighWatermarkMs = 1000.0;constexpr uint32_t kAudioRate = 48000;+// --- output endpoint choice (P4-d) -------------------------------------------+// One process-wide choice shared by every renderer (file playback and capture+// monitoring). Empty id = follow the Windows default device, which is also what+// happens when the chosen device is missing; it is switched back to as soon as+// it reappears. Changing the choice rebuilds live endpoints through the existing+// recovery path (the same one a default-device change uses): the audio clock and+// PCM handling are untouched.+struct RenderEndpoint { std::wstring id, name; bool isDefault = false; };+std::vector<RenderEndpoint> enumerateRenderEndpoints();+void setPreferredRenderEndpoint(std::wstring id);+std::wstring preferredRenderEndpoint();+// Mix everything down to stereo before the endpoint (headphones on a 5.1/7.1+// device), instead of mapping channels to the device layout.+void setForceStereoDownmix(bool enabled);+bool forceStereoDownmix();+// What the most recently opened renderer actually uses.+struct ActiveRenderEndpoint { std::wstring id, name; bool fallback = false; unsigned channels = 0; bool downmix = false; bool valid = false; };+ActiveRenderEndpoint activeRenderEndpoint();+uint64_t renderEndpointGeneration();+class AudioRenderer; // forward: pipeline thread needs the rendererenum class AudioFadeResult { NotPlaying, Drained, Cancelled, TimedOut, Failed };@@ -195,7 +216,8 @@ public:uint64_t recoveryFades() const{return recoveryFades_.load();}uint64_t clockStalledGaps() const{return clockStalledGaps_.load();}uint64_t framesWritten() const;- HRESULT lastError()const{return lastError_.load();}+ // A changed endpoint choice reads as a lost device, so the owner rebuilds it.+ HRESULT lastError()const{if(running_&&endpointGeneration_.load()!=renderEndpointGeneration())return AUDCLNT_E_DEVICE_INVALIDATED;return lastError_.load();}double bufferedMs()const{return bufferedMs_.load();}double capacityMs()const{std::lock_guard lock(endpointMutex_);return 1000.0*bufferFrames_/sampleRate_;}@@ -221,6 +243,12 @@ private:void registerEndpointNotification();void unregisterEndpointNotification();IMMDevice* device_ = nullptr;+ // Set in start() before the notifier is registered, read by its callbacks.+ std::wstring deviceId_;+ std::wstring preferredId_;+ std::atomic<bool> followsDefault_{true};+ std::atomic<bool> onFallback_{false};+ std::atomic<uint64_t> endpointGeneration_{0};IAudioClient* client_ = nullptr;IAudioRenderClient* render_ = nullptr;IAudioClock* clock_ = nullptr;diff --git a/include/veyra/source/CaptureCompressedDecoder.h b/include/veyra/source/CaptureCompressedDecoder.hindex bba9a4dc..20397ded 100644--- a/include/veyra/source/CaptureCompressedDecoder.h+++ b/include/veyra/source/CaptureCompressedDecoder.h@@ -58,6 +58,9 @@ public:uint64_t framesDecoded() const;uint64_t decodeFailures() const;uint64_t hardwareFallbacks() const;+ // Running averages of the two halves of a software decode() call.+ double decodeMsAverage() const;+ double convertMsAverage() const;void close();private:diff --git a/include/veyra/source/IFrameSource.h b/include/veyra/source/IFrameSource.hindex da20e76e..5adc0417 100644--- a/include/veyra/source/IFrameSource.h+++ b/include/veyra/source/IFrameSource.h@@ -19,6 +19,9 @@ namespace pipeline = veyra::pipeline;struct SourceOpenDesc {std::wstring path;bool preferHardwareDecode = true; // hardware first, software fallback explicit+ // User setting "强制硬解": a file whose hardware decoder cannot open fails+ // with a clear error instead of falling back to software decode.+ bool requireHardwareDecode = false;void* d3d12Device = nullptr; // ID3D12Device* when hardware decode is wantedvoid* d3d12Queue = nullptr; // ID3D12CommandQueue*// Adapter the D3D12 device lives on. The D3D11VA path creates its owndiff --git a/include/veyra/source/MediaFileSource.h b/include/veyra/source/MediaFileSource.hindex b588c106..d76c0734 100644--- a/include/veyra/source/MediaFileSource.h+++ b/include/veyra/source/MediaFileSource.h@@ -54,6 +54,7 @@ private:int64_t lastPtsUs_ = INT64_MIN;std::wstring path_;bool preferHardwareDecode_ = false;+ bool requireHardwareDecode_ = false; // "强制硬解": never fall back to software};} // namespace veyra::sourcediff --git a/include/veyra/ui/PlayerUiFacade.h b/include/veyra/ui/PlayerUiFacade.hindex bf870496..983f9820 100644--- a/include/veyra/ui/PlayerUiFacade.h+++ b/include/veyra/ui/PlayerUiFacade.h@@ -42,7 +42,8 @@ public:// --- commands ----------------------------------------------------------// Applied to the engine's desired settings, keeping the facade's copy in// step so the UI can show the pending value before the engine confirms it.- bool applySettings(const veyra::engine::EnhancementSettings& settings);+ bool applySettings(const veyra::engine::EnhancementSettings& settings,+ std::optional<veyra::engine::ChainRuntimeOrder> order = std::nullopt);veyra::engine::EnhancementSettings pendingSettings() const { return pending_; }void setPending(veyra::engine::EnhancementSettings settings) { pending_ = std::move(settings); }// True while the engine has not yet applied what the UI asked for.@@ -104,6 +105,8 @@ public:// --- persistence -------------------------------------------------------bool loadPreferences();bool savePreferences();+ bool loadChainSession(veyra::engine::ChainSession&);+ bool saveChainSession(const veyra::engine::ChainSession&);const std::wstring& error() const { return error_; }private:@@ -111,8 +114,14 @@ private:veyra::engine::PresetLibrary presets_;bool presetsLoaded_ = false;std::filesystem::path dataDirectory_;+ veyra::engine::ChainSessionStore chainSessionStore_;veyra::engine::PlayerSnapshot last_{};veyra::engine::EnhancementSettings pending_{};+ uint64_t pendingFgRevision_=0;+ uint64_t pendingNrRevision_=0;+ veyra::engine::NrRuntime requestedNrRuntime_=veyra::engine::NrRuntime::Original;+ veyra::engine::FrameGenerationBackend requestedFgBackend_=veyra::engine::FrameGenerationBackend::Dlss;+ uint32_t requestedFgMultiplier_=1;uint64_t revision_ = 0;bool haveLast_ = false;std::vector<RecentEntry> recent_;diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.hindex ed814f7f..94a66571 100644--- a/include/veyra/ui/QmlPlayerBridge.h+++ b/include/veyra/ui/QmlPlayerBridge.h@@ -51,18 +51,27 @@ class QmlPlayerBridge : public QObject {Q_PROPERTY(double displayFps READ displayFps NOTIFY snapshotChanged)Q_PROPERTY(bool displayFpsKnown READ displayFpsKnown NOTIFY snapshotChanged)Q_PROPERTY(double queuedFrames READ queuedFrames NOTIFY snapshotChanged)+ Q_PROPERTY(bool queuedFramesKnown READ queuedFramesKnown NOTIFY snapshotChanged)Q_PROPERTY(int skippedFrames READ skippedFrames NOTIFY snapshotChanged)Q_PROPERTY(QString flowBackend READ flowBackend NOTIFY snapshotChanged)+ Q_PROPERTY(int opticalFlowChoice READ opticalFlowChoice NOTIFY settingsChanged)Q_PROPERTY(QVariantList stageTimings READ stageTimings NOTIFY snapshotChanged)+ Q_PROPERTY(QVariantMap nodeTimings READ nodeTimings NOTIFY snapshotChanged)+ Q_PROPERTY(QVariantMap nodeAnchors READ nodeAnchors NOTIFY nodeAnchorsChanged)Q_PROPERTY(double stageBudgetMs READ stageBudgetMs NOTIFY snapshotChanged)- // Total measured cost of the chain, or 0 when nothing has been measured.+ // Existing measured enhancement-interval P95, NOT full-chain latency.Q_PROPERTY(double chainTotalMs READ chainTotalMs NOTIFY snapshotChanged)+ Q_PROPERTY(bool chainTotalMsKnown READ chainTotalMsKnown NOTIFY snapshotChanged)Q_PROPERTY(double scheduleP95Ms READ scheduleP95Ms NOTIFY snapshotChanged)// --- frame generation settings ----------------------------------------Q_PROPERTY(QString fgBackendName READ fgBackendName WRITE setFgBackendName NOTIFY settingsChanged)+ Q_PROPERTY(QVariantList fgBackendChoices READ fgBackendChoices CONSTANT)+ Q_PROPERTY(QString fgProviderText READ fgProviderText NOTIFY fgChoicesChanged)Q_PROPERTY(int fgMaxMultiplier READ fgMaxMultiplier NOTIFY snapshotChanged)- Q_PROPERTY(QVariantList fgMultiplierChoices READ fgMultiplierChoices NOTIFY snapshotChanged)+ Q_PROPERTY(bool fgEnabled READ fgEnabled WRITE setFgEnabled NOTIFY chainChanged)+ Q_PROPERTY(QString submitFpsLabel READ submitFpsLabel NOTIFY snapshotChanged)+ Q_PROPERTY(QVariantList fgMultiplierChoices READ fgMultiplierChoices NOTIFY fgChoicesChanged)Q_PROPERTY(bool fgStrict READ fgStrict WRITE setFgStrict NOTIFY settingsChanged)Q_PROPERTY(bool fgLowQueue READ fgLowQueue WRITE setFgLowQueue NOTIFY settingsChanged)@@ -99,21 +108,73 @@ class QmlPlayerBridge : public QObject {Q_PROPERTY(QString captureDeviceLabel READ captureDeviceLabel NOTIFY captureChanged)Q_PROPERTY(bool captureForceSdr READ captureForceSdr WRITE setCaptureForceSdr NOTIFY settingsChanged)Q_PROPERTY(bool captureFlipVertical READ captureFlipVertical WRITE setCaptureFlipVertical NOTIFY settingsChanged)+ // P4-e: the full capture connection, as the 1.4.4 panel: device details and+ // formats come from asynchronous DirectShow queries (never on the UI thread),+ // the choice is remembered in capture-preferences.v1 for "continue".+ Q_PROPERTY(QVariantList captureFormats READ captureFormats NOTIFY captureChanged)+ Q_PROPERTY(QString captureFormatKey READ captureFormatKey WRITE setCaptureFormatKey NOTIFY captureChanged)+ Q_PROPERTY(QVariantList captureAudioInputs READ captureAudioInputs NOTIFY captureChanged)+ Q_PROPERTY(int captureAudioChoice READ captureAudioChoice WRITE setCaptureAudioChoice NOTIFY captureChanged)+ Q_PROPERTY(int captureColorSpace READ captureColorSpace WRITE setCaptureColorSpace NOTIFY captureChanged)+ Q_PROPERTY(int captureColorRange READ captureColorRange WRITE setCaptureColorRange NOTIFY captureChanged)+ Q_PROPERTY(double captureRequestedFps READ captureRequestedFps WRITE setCaptureRequestedFps NOTIFY captureChanged)+ Q_PROPERTY(int captureAudioIngress READ captureAudioIngress WRITE setCaptureAudioIngress NOTIFY settingsChanged)+ Q_PROPERTY(int captureBufferMode READ captureBufferMode WRITE setCaptureBufferMode NOTIFY settingsChanged)+ Q_PROPERTY(bool captureQueryBusy READ captureQueryBusy NOTIFY captureChanged)+ Q_PROPERTY(QString captureStatus READ captureStatus NOTIFY captureChanged)// --- screen-capture dialog ---------------------------------------------Q_PROPERTY(QVariantList screenTargets READ screenTargets NOTIFY captureChanged)Q_PROPERTY(QString screenTargetId READ screenTargetId WRITE setScreenTargetId NOTIFY captureChanged)Q_PROPERTY(QString screenTargetLabel READ screenTargetLabel NOTIFY captureChanged)- Q_INVOKABLE void refreshCaptureTargets();-- // Subtitles: SubtitleStyle is owned by the old Win32 shell, not by the engine,- // so there is nothing here for the bridge to read or write. The subtitle dialog- // says it is not wired rather than keeping a second copy of that state that- // would silently disagree with the renderer.+ // Screen capture options (ScreenCaptureOptions): kind 0 window / 1 monitor,+ // method 0 WGC / 1 DXGI (monitor only), fps cap index into {follow,30,60,120,144,240},+ // pointer, crop margins in source pixels, and "fill the window".+ Q_PROPERTY(QVariantMap screenOptions READ screenOptions NOTIFY captureChanged)++ // Subtitles (P4-c): the engine's SubtitleLoader reads the embedded tracks and+ // the same-name external file; the old shell's SubtitleOverlay draws them as a+ // layered child of the native video window, so the picture's window region+ // also clips the subtitles away from QML popups. Style lives in preferences.+ Q_PROPERTY(QVariantList subtitleTracks READ subtitleTracks NOTIFY subtitlesChanged)+ Q_PROPERTY(int subtitlePrimary READ subtitlePrimary WRITE setSubtitlePrimary NOTIFY subtitlesChanged)+ Q_PROPERTY(int subtitleSecondary READ subtitleSecondary WRITE setSubtitleSecondary NOTIFY subtitlesChanged)+ Q_PROPERTY(int subtitleOffsetMs READ subtitleOffsetMs WRITE setSubtitleOffsetMs NOTIFY subtitlesChanged)+ Q_PROPERTY(QString subtitleStatus READ subtitleStatus NOTIFY subtitlesChanged)+ Q_PROPERTY(bool subtitleAligning READ subtitleAligning NOTIFY subtitlesChanged)+ // The text the overlay is drawing now (joined lines), for tests and the a11y name.+ Q_PROPERTY(QString subtitleText READ subtitleText NOTIFY subtitleTextChanged)+ // Extra space the shell keeps free at the bottom (fullscreen controls).+ Q_PROPERTY(int subtitleBottomInset READ subtitleBottomInset WRITE setSubtitleBottomInset NOTIFY subtitlesChanged)// --- ps5 dialog --------------------------------------------------------Q_PROPERTY(QString remotePlayHost READ remotePlayHost WRITE setRemotePlayHost NOTIFY settingsChanged)Q_PROPERTY(QString remotePlayPin READ remotePlayPin WRITE setRemotePlayPin NOTIFY settingsChanged)+ // P4-e PS5 Remote Play, ported from the 1.4.4 panel: saved pairings (shared+ // %LOCALAPPDATA%\Veyra\remoteplay, encrypted), discovery, pairing, PSN login,+ // wake, stream profile, decode/sampling, view-only, login PIN, controller+ // forwarding and gyro calibration. `ps5` carries the form state.+ Q_PROPERTY(QVariantMap ps5 READ ps5 NOTIFY ps5Changed)+ Q_PROPERTY(QVariantList ps5Profiles READ ps5Profiles NOTIFY ps5Changed)++ // Shell preferences that are not enhancement settings: screenshot folder,+ // subtitle look, audio output. Stored in <data>/qml-preferences.v1.json and+ // validated key by key in setPreference(); anything unknown is refused.+ Q_PROPERTY(QVariantMap preferences READ preferences NOTIFY preferencesChanged)+ Q_PROPERTY(QString screenshotDirectory READ screenshotDirectory NOTIFY preferencesChanged)+ Q_PROPERTY(QString lastScreenshot READ lastScreenshot NOTIFY preferencesChanged)+ Q_PROPERTY(QString dataDirectory READ dataDirectory CONSTANT)+ // Rebindable shortcuts: action -> key sequence text (defaults merged in).+ Q_PROPERTY(QVariantMap shortcuts READ shortcuts NOTIFY preferencesChanged)+ // The interface scale chosen for the next start (0 = follow Windows).+ Q_PROPERTY(int uiScaleActive READ uiScaleActive CONSTANT)+ // Audio output (P4-d): the active WASAPI render endpoints by device id, the+ // stored choice (preferences.audioDevice, empty = system default) and what+ // the renderer actually opened, including a fallback to the default.+ Q_PROPERTY(QVariantList audioDevices READ audioDevices NOTIFY audioDevicesChanged)+ Q_PROPERTY(QString audioOutputStatus READ audioOutputStatus NOTIFY audioDevicesChanged)+ Q_PROPERTY(bool audioOutputFallback READ audioOutputFallback NOTIFY audioDevicesChanged)+ Q_PROPERTY(QString logFile READ logFile CONSTANT)Q_PROPERTY(QString appName READ appName CONSTANT)Q_PROPERTY(QString version READ version CONSTANT)@@ -143,6 +204,7 @@ class QmlPlayerBridge : public QObject {// The film's display aspect, so the window can snap to it in cinema mode// exactly as the prototype's fitAspect() does. 0 when nothing is open.Q_PROPERTY(double sourceAspect READ sourceAspect NOTIFY snapshotChanged)+ Q_PROPERTY(double previewAspect READ previewAspect NOTIFY compareChanged)// --- live performance --------------------------------------------------// Submit FPS only. There is deliberately no "display FPS": the user asked@@ -163,11 +225,16 @@ class QmlPlayerBridge : public QObject {// --- settings (what the UI shows) --------------------------------------Q_PROPERTY(bool nrEnabled READ nrEnabled WRITE setNrEnabled NOTIFY settingsChanged)+ Q_PROPERTY(int selectedNrLayer READ selectedNrLayer WRITE setSelectedNrLayer NOTIFY settingsChanged)+ Q_PROPERTY(QVariantList nrLayers READ nrLayers NOTIFY chainChanged)Q_PROPERTY(bool srEnabled READ srEnabled WRITE setSrEnabled NOTIFY settingsChanged)Q_PROPERTY(int fgMultiplier READ fgMultiplier WRITE setFgMultiplier NOTIFY settingsChanged)Q_PROPERTY(bool lowLatency READ lowLatency WRITE setLowLatency NOTIFY settingsChanged)Q_PROPERTY(bool nrTemporal READ nrTemporal WRITE setNrTemporal NOTIFY settingsChanged)+ Q_PROPERTY(double nrHoldStrength READ nrHoldStrength WRITE setNrHoldStrength NOTIFY settingsChanged)+ Q_PROPERTY(double nrHoldTolerance READ nrHoldTolerance WRITE setNrHoldTolerance NOTIFY settingsChanged)Q_PROPERTY(bool videoHdr READ videoHdr WRITE setVideoHdr NOTIFY settingsChanged)+ Q_PROPERTY(QVariantMap videoHdrParams READ videoHdrParams NOTIFY chainChanged)Q_PROPERTY(int nrStyle READ nrStyle WRITE setNrStyle NOTIFY settingsChanged)Q_PROPERTY(double nrIntensity READ nrIntensity WRITE setNrIntensity NOTIFY settingsChanged)Q_PROPERTY(double nrTone READ nrTone WRITE setNrTone NOTIFY settingsChanged)@@ -177,8 +244,77 @@ class QmlPlayerBridge : public QObject {Q_PROPERTY(bool nrUiCorrection READ nrUiCorrection WRITE setNrUiCorrection NOTIFY settingsChanged)Q_PROPERTY(int videoSrQuality READ videoSrQuality WRITE setVideoSrQuality NOTIFY settingsChanged)Q_PROPERTY(bool protectionEnabled READ protectionEnabled WRITE setProtectionEnabled NOTIFY settingsChanged)+ Q_PROPERTY(QVariantMap protectionState READ protectionState NOTIFY chainChanged)Q_PROPERTY(bool colorEnabled READ colorEnabled WRITE setColorEnabled NOTIFY settingsChanged)Q_PROPERTY(int audioOffsetMs READ audioOffsetMs WRITE setAudioOffsetMs NOTIFY settingsChanged)+ // 1.4.4 声音补偿: 0 自动(软件估算) / 1 手动 / 2 关闭; live sources only.+ Q_PROPERTY(int audioSyncMode READ audioSyncMode WRITE setAudioSyncMode NOTIFY settingsChanged)+ Q_PROPERTY(bool audioSyncLive READ audioSyncLive NOTIFY snapshotChanged)+ Q_PROPERTY(double audioCompensationMs READ audioCompensationMs NOTIFY snapshotChanged)+ // Performance orbs and the status light (1.4.4 live status dashboard).+ Q_PROPERTY(double gpuUtilization READ gpuUtilization NOTIFY perfChanged)+ Q_PROPERTY(bool gpuUtilizationKnown READ gpuUtilizationKnown NOTIFY perfChanged)+ Q_PROPERTY(QString runStatus READ runStatus NOTIFY perfChanged)+ Q_PROPERTY(QString runStatusLevel READ runStatusLevel NOTIFY perfChanged)+ Q_PROPERTY(QString runStatusDetail READ runStatusDetail NOTIFY perfChanged)+ // Achieved output rate / target (source x multiplier); -1 while unknown.+ Q_PROPERTY(double outputRateRatio READ outputRateRatio NOTIFY perfChanged)+ // Frame interval history (ms, newest last) for the frame-time line.+ Q_PROPERTY(QVariantList frameTimes READ frameTimes NOTIFY perfChanged)+ // 补帧 / 光流 (design gap A1-A5): motion estimation quality 0 性能 1 平衡 2 质量,+ // AMD half-resolution flow, content cadence (engine::ContentRate order).+ Q_PROPERTY(int flowQuality READ flowQuality WRITE setFlowQuality NOTIFY settingsChanged)+ Q_PROPERTY(bool amdFlowHalf READ amdFlowHalf WRITE setAmdFlowHalf NOTIFY settingsChanged)+ Q_PROPERTY(int contentRate READ contentRate WRITE setContentRate NOTIFY settingsChanged)+ Q_PROPERTY(int hdrOutputMode READ hdrOutputMode WRITE setHdrOutputMode NOTIFY settingsChanged)+ Q_PROPERTY(int fgMotionSource READ fgMotionSource WRITE setFgMotionSource NOTIFY settingsChanged)+ Q_PROPERTY(int srMotionSource READ srMotionSource WRITE setSrMotionSource NOTIFY settingsChanged)+ Q_PROPERTY(int nrMotionSource READ nrMotionSource WRITE setNrMotionSource NOTIFY settingsChanged)+ // Presentation: display sync 0 允许撕裂 1 垂直同步 2 自动; output cap 0 关闭+ // 1 跟随显示器 2 自定义 (+ fps). Owned by XeSS when presentationOwned.+ Q_PROPERTY(int displaySync READ displaySync WRITE setDisplaySync NOTIFY presentationChanged)+ Q_PROPERTY(int outputRateMode READ outputRateMode WRITE setOutputRateMode NOTIFY presentationChanged)+ Q_PROPERTY(double outputCustomFps READ outputCustomFps WRITE setOutputCustomFps NOTIFY presentationChanged)+ Q_PROPERTY(bool presentationOwned READ presentationOwned NOTIFY snapshotChanged)+ Q_PROPERTY(QString presentationStatus READ presentationStatus NOTIFY snapshotChanged)+ // 显示: compare 0 增强 1 原画 2 分屏; base false 输入原画 / true 增强前底图;+ // split 0..1 of the picture. Aspect 0 适应 1 原始 2 填充.+ Q_PROPERTY(int compareMode READ compareMode WRITE setCompareMode NOTIFY compareChanged)+ Q_PROPERTY(bool compareBase READ compareBase WRITE setCompareBase NOTIFY compareChanged)+ Q_PROPERTY(double compareSplit READ compareSplit NOTIFY compareChanged)+ Q_PROPERTY(int aspectMode READ aspectMode WRITE setAspectMode NOTIFY compareChanged)+ // Measured audio/video skew of a live source (ms); unknown otherwise.+ Q_PROPERTY(double audioSkewMs READ audioSkewMs NOTIFY snapshotChanged)+ Q_PROPERTY(bool audioSkewKnown READ audioSkewKnown NOTIFY snapshotChanged)+ // Export: an estimate of the output size ("" when there is nothing to base it on).+ Q_PROPERTY(QString exportSizeEstimate READ exportSizeEstimate NOTIFY exportChanged)+ // 继续上次: {kind: capture|ps5|screen, label, summary}; empty when none.+ Q_PROPERTY(QVariantMap lastSource READ lastSource NOTIFY preferencesChanged)+ // P5 (2026-09-29): what is playing, for the page headers.+ // sourceKind: "" | file | image | capture | ps5 | screen.+ Q_PROPERTY(QString sourceKind READ sourceKind NOTIFY snapshotChanged)+ Q_PROPERTY(QString sourceTitle READ sourceTitle NOTIFY snapshotChanged)+ // "1080p60 · YUY2 · SDR": reported values only.+ Q_PROPERTY(QString sourceFormatText READ sourceFormatText NOTIFY snapshotChanged)+ Q_PROPERTY(QString sourceRateText READ sourceRateText NOTIFY snapshotChanged)+ // 调色 undo / redo / copy / paste for the selected colour layer.+ Q_PROPERTY(bool colourCanUndo READ colourCanUndo NOTIFY settingsChanged)+ Q_PROPERTY(bool colourCanRedo READ colourCanRedo NOTIFY settingsChanged)+ Q_PROPERTY(bool colourCanPaste READ colourCanPaste NOTIFY settingsChanged)+ // Export queue rows: [{name, input, output, state, progress, note, current}].+ Q_PROPERTY(QVariantList exportItems READ exportItems NOTIFY exportChanged)+ // Capture dialog preview: the session's poster still (the engine's own+ // first-frame poster), as a data URL; "" when the session has none. Never a+ // periodic readback: that would stall the live capture path.+ Q_PROPERTY(QString capturePreviewUrl READ capturePreviewUrl NOTIFY snapshotChanged)+ Q_PROPERTY(QString captureSignalText READ captureSignalText NOTIFY snapshotChanged)+ Q_PROPERTY(QString captureSignalLevel READ captureSignalLevel NOTIFY snapshotChanged)+ // A live source (PS5 / capture) that is still opening: what the picture area+ // says meanwhile ("" once it plays or when nothing is opening).+ Q_PROPERTY(QString liveOpeningText READ liveOpeningText NOTIFY snapshotChanged)+ // Protection regions as the engine holds them: [{left,top,right,bottom,ellipse}].+ Q_PROPERTY(QVariantList protectionRegions READ protectionRegions NOTIFY chainChanged)+ Q_PROPERTY(QString protectionDrawShape READ protectionDrawShape NOTIFY protectionDrawChanged)Q_PROPERTY(double volume READ volume WRITE setVolume NOTIFY snapshotChanged)Q_PROPERTY(bool muted READ muted WRITE setMuted NOTIFY snapshotChanged)Q_PROPERTY(double playbackSpeed READ playbackSpeed NOTIFY snapshotChanged)@@ -191,7 +327,8 @@ class QmlPlayerBridge : public QObject {// objects with positions. Both edit one chain, so switching modes never// loses work.Q_PROPERTY(QVariantList chain READ chain NOTIFY chainChanged)- Q_PROPERTY(QVariantList effectCatalog READ effectCatalog CONSTANT)+ Q_PROPERTY(QVariantList nodeConnections READ nodeConnections NOTIFY chainChanged)+ Q_PROPERTY(QVariantList effectCatalog READ effectCatalog NOTIFY chainChanged)Q_PROPERTY(QString chainError READ chainError NOTIFY chainChanged)Q_PROPERTY(bool chainValid READ chainValid NOTIFY chainChanged)Q_PROPERTY(int nodeMode READ nodeMode WRITE setNodeMode NOTIFY chainChanged)@@ -226,6 +363,16 @@ class QmlPlayerBridge : public QObject {Q_PROPERTY(int exportRateControl READ exportRateControl WRITE setExportRateControl NOTIFY exportChanged)Q_PROPERTY(double exportEtaSeconds READ exportEtaSeconds NOTIFY exportChanged)Q_PROPERTY(int exportQueueCount READ exportQueueCount NOTIFY exportChanged)+ // Queue items that could not start, and why the latest one failed.+ Q_PROPERTY(int exportQueueFailures READ exportQueueFailures NOTIFY exportChanged)+ Q_PROPERTY(QString exportQueueFailure READ exportQueueFailure NOTIFY exportChanged)+ // Image export (P4-b): each image goes through the real player chain (open,+ // first processed frame, the engine's own frame save), one after another.+ Q_PROPERTY(bool imageBatchActive READ imageBatchActive NOTIFY imageBatchChanged)+ Q_PROPERTY(int imageBatchDone READ imageBatchDone NOTIFY imageBatchChanged)+ Q_PROPERTY(int imageBatchTotal READ imageBatchTotal NOTIFY imageBatchChanged)+ Q_PROPERTY(int imageBatchFailures READ imageBatchFailures NOTIFY imageBatchChanged)+ Q_PROPERTY(QString imageBatchStatus READ imageBatchStatus NOTIFY imageBatchChanged)// The preset the export will use. The design requires export to select a// preset (list or node) rather than assembling effects separately.Q_PROPERTY(QString exportPresetName READ exportPresetName NOTIFY exportChanged)@@ -255,6 +402,13 @@ class QmlPlayerBridge : public QObject {// The same catalogue grouped by section, so the page can nest its collapsible// sub-panels without re-grouping in QML.Q_PROPERTY(QVariantList colourGroups READ colourGroups NOTIFY chainChanged)+ Q_PROPERTY(int selectedColourLayer READ selectedColourLayer WRITE setSelectedColourLayer NOTIFY settingsChanged)+ Q_PROPERTY(QVariantMap colourState READ colourState NOTIFY settingsChanged)+ // Imported .cube files (ColorLutStore, the folder the engine resolves) and+ // the saved colour looks (ColorLookStore): a colour preset is one Color+ // node's settings, separate from the whole-chain presets.+ Q_PROPERTY(QVariantList lutLibrary READ lutLibrary NOTIFY colourLibraryChanged)+ Q_PROPERTY(QVariantList colourLooks READ colourLooks NOTIFY colourLibraryChanged)public:// `engine` must outlive the bridge. `dataDirectory` holds ui-session.v1 and@@ -267,16 +421,29 @@ public:double displayFps() const;bool displayFpsKnown() const;double queuedFrames() const;+ bool queuedFramesKnown() const;int skippedFrames() const;QString flowBackend() const;+ int opticalFlowChoice() const;+ Q_INVOKABLE bool setOpticalFlowChoice(int backend);QVariantList stageTimings() const;+ QVariantMap nodeTimings() const;+ QVariantMap nodeAnchors() const;+ Q_INVOKABLE bool setNodeAnchor(const QString& key, double x, double y);+ Q_INVOKABLE QVariantMap colourStateAt(int index) const;double stageBudgetMs() const;double chainTotalMs() const;+ bool chainTotalMsKnown() const;double scheduleP95Ms() const;QString fgBackendName() const;+ QVariantList fgBackendChoices() const;+ QString fgProviderText() const;void setFgBackendName(const QString& value);int fgMaxMultiplier() const;+ bool fgEnabled() const;+ void setFgEnabled(bool enabled);+ QString submitFpsLabel() const;QVariantList fgMultiplierChoices() const;bool fgStrict() const;void setFgStrict(bool value);@@ -311,17 +478,99 @@ public:void setCaptureForceSdr(bool value);bool captureFlipVertical() const;void setCaptureFlipVertical(bool value);+ QVariantList captureFormats() const;+ QString captureFormatKey() const;+ void setCaptureFormatKey(const QString& key);+ QVariantList captureAudioInputs() const;+ int captureAudioChoice() const;+ void setCaptureAudioChoice(int choice);+ int captureColorSpace() const;+ void setCaptureColorSpace(int value);+ int captureColorRange() const;+ void setCaptureColorRange(int value);+ double captureRequestedFps() const;+ void setCaptureRequestedFps(double value);+ int captureAudioIngress() const;+ void setCaptureAudioIngress(int value);+ int captureBufferMode() const;+ void setCaptureBufferMode(int value);+ bool captureQueryBusy() const;+ QString captureStatus() const;+ QVariantMap screenOptions() const;+ // Declared here, in the public section: a Q_INVOKABLE above `public:` is+ // private to QML ("is not a function").+ Q_INVOKABLE void refreshCaptureTargets();+ Q_INVOKABLE void refreshCaptureDevices();+ Q_INVOKABLE bool startCaptureSession();+ Q_INVOKABLE bool setScreenOption(const QString& key, const QVariant& value);+ Q_INVOKABLE bool startScreenCapture();QVariantList screenTargets() const;QString screenTargetId() const;void setScreenTargetId(const QString& value);QString screenTargetLabel() const;+ QVariantList subtitleTracks() const;+ int subtitlePrimary() const;+ void setSubtitlePrimary(int index);+ int subtitleSecondary() const;+ void setSubtitleSecondary(int index);+ int subtitleOffsetMs() const;+ void setSubtitleOffsetMs(int ms);+ QString subtitleStatus() const;+ bool subtitleAligning() const;+ QString subtitleText() const;+ int subtitleBottomInset() const;+ void setSubtitleBottomInset(int value);+ Q_INVOKABLE void loadSubtitleDialog();+ Q_INVOKABLE bool loadSubtitleFile(const QString& path);+ Q_INVOKABLE void nudgeSubtitle(int deltaMs);+ Q_INVOKABLE void cycleSubtitle(bool secondary);+ Q_INVOKABLE void toggleSubtitles();+ Q_INVOKABLE void autoAlignSubtitle();++ QVariantMap ps5() const;+ QVariantList ps5Profiles() const;+ Q_INVOKABLE void ps5Load();+ Q_INVOKABLE bool ps5Set(const QString& key, const QVariant& value);+ Q_INVOKABLE void ps5SelectProfile(const QString& id);+ Q_INVOKABLE void ps5Scan();+ Q_INVOKABLE void ps5Pair(const QString& pin);+ Q_INVOKABLE bool ps5Connect();+ Q_INVOKABLE void ps5Wake();+ Q_INVOKABLE void ps5Forget();+ Q_INVOKABLE void ps5PsnLogin();+ Q_INVOKABLE void ps5PsnComplete();+ Q_INVOKABLE void ps5PsnForget();+ Q_INVOKABLE void ps5SendLoginPin(const QString& pin);+ Q_INVOKABLE void ps5Cancel();+ Q_INVOKABLE void ps5Calibrate();QString remotePlayHost() const;void setRemotePlayHost(const QString& value);QString remotePlayPin() const;void setRemotePlayPin(const QString& value);+ QVariantMap preferences() const;+ Q_INVOKABLE void rememberWindowSize(int width, int height);+ Q_INVOKABLE bool setPreference(const QString& key, const QVariant& value);+ QString screenshotDirectory() const;+ QString lastScreenshot() const;+ QString dataDirectory() const;+ QString logFile() const;+ Q_INVOKABLE void chooseScreenshotDirectory();+ QVariantMap shortcuts() const;+ Q_INVOKABLE bool setShortcut(const QString& action, const QString& sequence);+ Q_INVOKABLE void resetShortcuts();+ int uiScaleActive() const;+ Q_INVOKABLE void openFeedbackPage();+ Q_INVOKABLE void openReleasesPage();+ QVariantList audioDevices() const;+ QString audioOutputStatus() const;+ bool audioOutputFallback() const;+ Q_INVOKABLE void refreshAudioDevices();+ Q_INVOKABLE void openScreenshotDirectory();+ Q_INVOKABLE void openLogFolder();+ Q_INVOKABLE void openDataFolder();QString appName() const;QString version() const;@@ -350,6 +599,7 @@ public:double sourceFps() const;int sourceRotation() const;double sourceAspect() const;+ double previewAspect() const;double submitFps() const;bool submitFpsKnown() const;@@ -372,6 +622,8 @@ public:double playbackSpeed() const;bool nrEnabled() const;+ int selectedNrLayer() const;+ void setSelectedNrLayer(int index);void setNrEnabled(bool value);bool srEnabled() const;void setSrEnabled(bool value);@@ -381,8 +633,16 @@ public:void setLowLatency(bool value);bool nrTemporal() const;void setNrTemporal(bool value);+ // Stage-5 output stabiliser (anti-flicker). Global rather than per-node:+ // it runs once, after the whole NR stack and the residual composite.+ double nrHoldStrength() const;+ void setNrHoldStrength(double value);+ double nrHoldTolerance() const;+ void setNrHoldTolerance(double value);bool videoHdr() const;void setVideoHdr(bool value);+ QVariantMap videoHdrParams() const;+ Q_INVOKABLE bool setVideoHdrParameter(const QString& key, double value);int nrStyle() const;void setNrStyle(int value);double nrIntensity() const;@@ -401,12 +661,99 @@ public:void setVideoSrQuality(int value);bool protectionEnabled() const;void setProtectionEnabled(bool value);+ QVariantMap protectionState() const;+ Q_INVOKABLE bool setProtectionRegion(double left, double top, double right, double bottom, double feather);bool colorEnabled() const;void setColorEnabled(bool value);int audioOffsetMs() const;void setAudioOffsetMs(int value);+ int audioSyncMode() const;+ void setAudioSyncMode(int value);+ bool audioSyncLive() const;+ double audioCompensationMs() const;+ double gpuUtilization() const;+ bool gpuUtilizationKnown() const;+ QString runStatus() const;+ QString runStatusLevel() const;+ QString runStatusDetail() const;+ double outputRateRatio() const;+ QVariantList frameTimes() const;+ int flowQuality() const;+ int hdrOutputMode() const;+ void setHdrOutputMode(int value);+ int fgMotionSource() const;+ void setFgMotionSource(int value);+ int srMotionSource() const;+ void setSrMotionSource(int value);+ int nrMotionSource() const;+ void setNrMotionSource(int value);+ void setFlowQuality(int value);+ bool amdFlowHalf() const;+ void setAmdFlowHalf(bool value);+ int contentRate() const;+ void setContentRate(int value);+ int displaySync() const;+ void setDisplaySync(int value);+ Q_INVOKABLE void setPresentationFullscreen(bool value);+ int outputRateMode() const;+ void setOutputRateMode(int value);+ double outputCustomFps() const;+ void setOutputCustomFps(double value);+ bool presentationOwned() const;+ QString presentationStatus() const;+ int compareMode() const;+ void setCompareMode(int value);+ bool compareBase() const;+ void setCompareBase(bool value);+ double compareSplit() const;+ int aspectMode() const;+ void setAspectMode(int value);+ double audioSkewMs() const;+ bool audioSkewKnown() const;+ QString exportSizeEstimate() const;+ QVariantMap lastSource() const;+ QString sourceKind() const;+ QString sourceTitle() const;+ QString sourceFormatText() const;+ QString sourceRateText() const;+ bool colourCanUndo() const;+ bool colourCanRedo() const;+ bool colourCanPaste() const;+ Q_INVOKABLE bool colourUndo();+ Q_INVOKABLE bool colourRedo();+ Q_INVOKABLE void colourCopy();+ Q_INVOKABLE bool colourPaste();+ QVariantList exportItems() const;+ Q_INVOKABLE void clearFinishedExportItems();+ Q_INVOKABLE QString fileThumbnailId(const QString& path, double seconds) const;+ QString capturePreviewUrl() const;+ QString captureSignalText() const;+ QString captureSignalLevel() const;+ QString liveOpeningText() const;+ Q_INVOKABLE void importPresetDialog();+ Q_INVOKABLE bool importPreset(const QString& path);+ Q_INVOKABLE void exportPresetDialog(int index);+ Q_INVOKABLE bool exportPreset(int index, const QString& path);+ // Split position from a pointer on the picture host (fractions of the host).+ Q_INVOKABLE void setCompareSplitAt(double hostFractionX);+ Q_INVOKABLE void resumeLastSource();+ // List mode: an NR layer's model and residual back to their defaults.+ Q_INVOKABLE bool resetNrLayer(int index);+ QVariantList protectionRegions() const;+ QString protectionDrawShape() const;+ // Drawing on the picture: arm with "rect"/"ellipse" ("" cancels), then+ // report the drag in picture-host pixels; commit adds the region.+ Q_INVOKABLE bool beginProtectionDraw(const QString& shape);+ Q_INVOKABLE void updateProtectionDraw(double x0, double y0, double x1, double y1);+ Q_INVOKABLE bool commitProtectionDraw(double x0, double y0, double x1, double y1);+ Q_INVOKABLE bool removeProtectionRegion(int index);+ Q_INVOKABLE bool clearProtectionRegions();+ Q_INVOKABLE bool setProtectionFeather(double pixels);QVariantList chain() const;+ QVariantList nodeConnections() const;+ QVariantList nrLayers() const;+ Q_INVOKABLE bool setNrLayerParameter(int index, const QString& key, double value);QVariantList effectCatalog() const;QString chainError() const;bool chainValid() const;@@ -439,6 +786,18 @@ public:void setExportRateControl(int value);double exportEtaSeconds() const;int exportQueueCount() const;+ int exportQueueFailures() const;+ bool imageBatchActive() const;+ int imageBatchDone() const;+ int imageBatchTotal() const;+ int imageBatchFailures() const;+ QString imageBatchStatus() const;+ // The processed frame on screen, saved as PNG/JPEG (JXR for HDR output).+ Q_INVOKABLE void saveFrameDialog();+ Q_INVOKABLE void exportImagesDialog();+ Q_INVOKABLE bool startImageBatch(const QStringList& files, const QString& folder);+ Q_INVOKABLE void cancelImageBatch();+ QString exportQueueFailure() const;QString exportPresetName() const;int exportSrTargetIndex() const;void setExportSrTargetIndex(int index);@@ -454,9 +813,29 @@ public:int defaultPresetIndex() const;QVariantList colourParameters() const;QVariantList colourGroups() const;+ int selectedColourLayer() const;+ void setSelectedColourLayer(int index);+ QVariantMap colourState() const;Q_INVOKABLE double colourParameter(const QString& name) const;Q_INVOKABLE bool setColourParameter(const QString& name, double value);Q_INVOKABLE bool resetColourParameter(const QString& name);+ Q_INVOKABLE bool setColourCurve(int channel, const QVariantList& points);+ Q_INVOKABLE bool setColourWheel(int zone, double hue, double saturation, double luminance);+ Q_INVOKABLE bool setColourOption(const QString& name, int value);+ Q_INVOKABLE bool resetColourGroup(int group);+ QVariantList lutLibrary() const;+ QVariantList colourLooks() const;+ Q_INVOKABLE void importLutDialog();+ Q_INVOKABLE bool importLut(const QString& path);+ // Empty name clears the LUT from the selected Color node.+ Q_INVOKABLE bool setColourLut(const QString& name);+ Q_INVOKABLE bool saveColourLook(const QString& name, bool replace);+ Q_INVOKABLE bool applyColourLook(int index);+ Q_INVOKABLE bool deleteColourLook(int index);+ Q_INVOKABLE void importColourLookDialog();+ Q_INVOKABLE bool importColourLook(const QString& path);+ Q_INVOKABLE void exportColourLookDialog(int index);+ Q_INVOKABLE bool exportColourLook(int index, const QString& path);// The native HWND the engine presents into. The UI creates it as a child// window of the QML window and hands it over; the bridge never draws QML@@ -480,6 +859,8 @@ public:Q_INVOKABLE void resumeCaptureSession();Q_INVOKABLE void openPs5Dialog();Q_INVOKABLE void openScreenCaptureDialog();+ Q_INVOKABLE void openAudioDialog();+ Q_INVOKABLE void openSubtitleDialog();Q_INVOKABLE void togglePlayPause();Q_INVOKABLE void stopPlayback();Q_INVOKABLE void seekTo(double seconds);@@ -513,6 +894,13 @@ public:// was asked (frame generation is pinned last, RTX Video HDR immediately// before it) and reports why when it is not.Q_INVOKABLE int addEffect(const QString& type);+ Q_INVOKABLE int duplicateNrLayer(int index);+ Q_INVOKABLE int nodeIndexForId(uint id) const;+ Q_INVOKABLE int duplicateNode(uint id);+ Q_INVOKABLE bool resetNode(uint id);+ Q_INVOKABLE bool connectNodes(uint from, uint to);+ Q_INVOKABLE bool disconnectNode(uint from);+ Q_INVOKABLE bool insertNodeAfter(uint id, uint after);Q_INVOKABLE bool removeEffect(int index);Q_INVOKABLE bool moveEffect(int from, int to);Q_INVOKABLE bool setEffectEnabled(int index, bool enabled);@@ -541,12 +929,25 @@ public:Q_INVOKABLE void copyDiagnostics();signals:+ void nodeAnchorsChanged();+ void ps5Changed();+ void imageBatchChanged();+ void audioDevicesChanged();+ void subtitlesChanged();+ void subtitleTextChanged();+ void preferencesChanged();+ void colourLibraryChanged();// Emitted only when the underlying snapshot actually changed, so QML// bindings do not re-evaluate 60 times a second for nothing.void snapshotChanged();+ void perfChanged();+ void protectionDrawChanged();+ void presentationChanged();+ void compareChanged();void thumbnailGenerationChanged();void thumbnailSourceChanged(const QString& path);void settingsChanged();+ void fgChoicesChanged();void chainChanged();void recentFilesChanged();void presetsChanged();@@ -564,8 +965,34 @@ private:// engine has been asked to apply. Every settings property reads this, so// they can never disagree with each other.engine::EnhancementSettings settings() const;+ void startGpuSampler();+ void updateRunStatus();+ void applyPresentation();+ void applyAspect(bool force);+ // Live sources started from the start page: switch to 极简 first, show the+ // connecting note, and start the engine once the page and window have settled.+ void openAfterCinema(const QString& pending, std::function<void()> open);+ void rememberSource(const QString& kind, const QString& label);+ // Edits the list chain's protection node; rolls back when refused.+ bool editProtection(const std::function<bool(engine::ChainNode&)>& edit);+ engine::ColorSettings selectedColourSettings() const;+ bool commitColour(const engine::ColorSettings& colour);// Reads the export job's snapshot and emits exportChanged.void pollExport();+ // Pushes a stored preference to whatever consumes it (subtitle overlay,+ // audio endpoint). Called after load and after every accepted change.+ void applyPreference(const QString& key);+ // Hold-to-compare key (press/release), handled for the whole application.+ bool eventFilter(QObject* watched, QEvent* event) override;+ void rememberPosition(bool flush);+ void refreshSubtitles(const std::wstring& media);+ void tickSubtitles();+ void tickImageBatch();+ void tickCapture();+ void tickPs5();+ void queryCapture(int kind, std::wstring device);+ // Opens a device/stream URI (capture, screen) the way openPath opens a file.+ void openSourceUri(const std::wstring& uri, const std::wstring& label);struct Impl;std::unique_ptr<Impl> impl_;diff --git a/include/veyra/ui/ThumbnailProvider.h b/include/veyra/ui/ThumbnailProvider.hindex 384c1444..43115c3d 100644--- a/include/veyra/ui/ThumbnailProvider.h+++ b/include/veyra/ui/ThumbnailProvider.h@@ -3,6 +3,7 @@#include <QQuickImageProvider>#include <QString>+#include <cstdint>#include <mutex>namespace veyra::ui {@@ -16,6 +17,8 @@ public:QImage requestImage(const QString& id, QSize* size, const QSize& requestedSize) override;private:+ static QImage frameAt(const QString& path, int64_t milliseconds);+ static QImage coverArt(const QString& path);std::mutex mutex_;QString source_;};diff --git a/licenses/capture/LIBDSHOWCAPTURE_LGPL.txt b/licenses/capture/LIBDSHOWCAPTURE_LGPL.txtnew file mode 100644index 00000000..4362b491--- /dev/null+++ b/licenses/capture/LIBDSHOWCAPTURE_LGPL.txt@@ -0,0 +1,502 @@+ GNU LESSER GENERAL PUBLIC LICENSE+ Version 2.1, February 1999++ Copyright (C) 1991, 1999 Free Software Foundation, Inc.+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++[This is the first released version of the Lesser GPL. It also counts+ as the successor of the GNU Library Public License, version 2, hence+ the version number 2.1.]++ Preamble++ The licenses for most software are designed to take away your+freedom to share and change it. By contrast, the GNU General Public+Licenses are intended to guarantee your freedom to share and change+free software--to make sure the software is free for all its users.++ This license, the Lesser General Public License, applies to some+specially designated software packages--typically libraries--of the+Free Software Foundation and other authors who decide to use it. You+can use it too, but we suggest you first think carefully about whether+this license or the ordinary General Public License is the better+strategy to use in any particular case, based on the explanations below.++ When we speak of free software, we are referring to freedom of use,+not price. Our General Public Licenses are designed to make sure that+you have the freedom to distribute copies of free software (and charge+for this service if you wish); that you receive source code or can get+it if you want it; that you can change the software and use pieces of+it in new free programs; and that you are informed that you can do+these things.++ To protect your rights, we need to make restrictions that forbid+distributors to deny you these rights or to ask you to surrender these+rights. These restrictions translate to certain responsibilities for+you if you distribute copies of the library or if you modify it.++ For example, if you distribute copies of the library, whether gratis+or for a fee, you must give the recipients all the rights that we gave+you. You must make sure that they, too, receive or can get the source+code. If you link other code with the library, you must provide+complete object files to the recipients, so that they can relink them+with the library after making changes to the library and recompiling+it. And you must show them these terms so they know their rights.++ We protect your rights with a two-step method: (1) we copyright the+library, and (2) we offer you this license, which gives you legal+permission to copy, distribute and/or modify the library.++ To protect each distributor, we want to make it very clear that+there is no warranty for the free library. Also, if the library is+modified by someone else and passed on, the recipients should know+that what they have is not the original version, so that the original+author's reputation will not be affected by problems that might be+introduced by others.++ Finally, software patents pose a constant threat to the existence of+any free program. We wish to make sure that a company cannot+effectively restrict the users of a free program by obtaining a+restrictive license from a patent holder. Therefore, we insist that+any patent license obtained for a version of the library must be+consistent with the full freedom of use specified in this license.++ Most GNU software, including some libraries, is covered by the+ordinary GNU General Public License. This license, the GNU Lesser+General Public License, applies to certain designated libraries, and+is quite different from the ordinary General Public License. We use+this license for certain libraries in order to permit linking those+libraries into non-free programs.++ When a program is linked with a library, whether statically or using+a shared library, the combination of the two is legally speaking a+combined work, a derivative of the original library. The ordinary+General Public License therefore permits such linking only if the+entire combination fits its criteria of freedom. The Lesser General+Public License permits more lax criteria for linking other code with+the library.++ We call this license the "Lesser" General Public License because it+does Less to protect the user's freedom than the ordinary General+Public License. It also provides other free software developers Less+of an advantage over competing non-free programs. These disadvantages+are the reason we use the ordinary General Public License for many+libraries. However, the Lesser license provides advantages in certain+special circumstances.++ For example, on rare occasions, there may be a special need to+encourage the widest possible use of a certain library, so that it becomes+a de-facto standard. To achieve this, non-free programs must be+allowed to use the library. A more frequent case is that a free+library does the same job as widely used non-free libraries. In this+case, there is little to gain by limiting the free library to free+software only, so we use the Lesser General Public License.++ In other cases, permission to use a particular library in non-free+programs enables a greater number of people to use a large body of+free software. For example, permission to use the GNU C Library in+non-free programs enables many more people to use the whole GNU+operating system, as well as its variant, the GNU/Linux operating+system.++ Although the Lesser General Public License is Less protective of the+users' freedom, it does ensure that the user of a program that is+linked with the Library has the freedom and the wherewithal to run+that program using a modified version of the Library.++ The precise terms and conditions for copying, distribution and+modification follow. Pay close attention to the difference between a+"work based on the library" and a "work that uses the library". The+former contains code derived from the library, whereas the latter must+be combined with the library in order to run.++ GNU LESSER GENERAL PUBLIC LICENSE+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++ 0. This License Agreement applies to any software library or other+program which contains a notice placed by the copyright holder or+other authorized party saying it may be distributed under the terms of+this Lesser General Public License (also called "this License").+Each licensee is addressed as "you".++ A "library" means a collection of software functions and/or data+prepared so as to be conveniently linked with application programs+(which use some of those functions and data) to form executables.++ The "Library", below, refers to any such software library or work+which has been distributed under these terms. A "work based on the+Library" means either the Library or any derivative work under+copyright law: that is to say, a work containing the Library or a+portion of it, either verbatim or with modifications and/or translated+straightforwardly into another language. (Hereinafter, translation is+included without limitation in the term "modification".)++ "Source code" for a work means the preferred form of the work for+making modifications to it. For a library, complete source code means+all the source code for all modules it contains, plus any associated+interface definition files, plus the scripts used to control compilation+and installation of the library.++ Activities other than copying, distribution and modification are not+covered by this License; they are outside its scope. The act of+running a program using the Library is not restricted, and output from+such a program is covered only if its contents constitute a work based+on the Library (independent of the use of the Library in a tool for+writing it). Whether that is true depends on what the Library does+and what the program that uses the Library does.++ 1. You may copy and distribute verbatim copies of the Library's+complete source code as you receive it, in any medium, provided that+you conspicuously and appropriately publish on each copy an+appropriate copyright notice and disclaimer of warranty; keep intact+all the notices that refer to this License and to the absence of any+warranty; and distribute a copy of this License along with the+Library.++ You may charge a fee for the physical act of transferring a copy,+and you may at your option offer warranty protection in exchange for a+fee.++ 2. You may modify your copy or copies of the Library or any portion+of it, thus forming a work based on the Library, and copy and+distribute such modifications or work under the terms of Section 1+above, provided that you also meet all of these conditions:++ a) The modified work must itself be a software library.++ b) You must cause the files modified to carry prominent notices+ stating that you changed the files and the date of any change.++ c) You must cause the whole of the work to be licensed at no+ charge to all third parties under the terms of this License.++ d) If a facility in the modified Library refers to a function or a+ table of data to be supplied by an application program that uses+ the facility, other than as an argument passed when the facility+ is invoked, then you must make a good faith effort to ensure that,+ in the event an application does not supply such function or+ table, the facility still operates, and performs whatever part of+ its purpose remains meaningful.++ (For example, a function in a library to compute square roots has+ a purpose that is entirely well-defined independent of the+ application. Therefore, Subsection 2d requires that any+ application-supplied function or table used by this function must+ be optional: if the application does not supply it, the square+ root function must still compute square roots.)++These requirements apply to the modified work as a whole. If+identifiable sections of that work are not derived from the Library,+and can be reasonably considered independent and separate works in+themselves, then this License, and its terms, do not apply to those+sections when you distribute them as separate works. But when you+distribute the same sections as part of a whole which is a work based+on the Library, the distribution of the whole must be on the terms of+this License, whose permissions for other licensees extend to the+entire whole, and thus to each and every part regardless of who wrote+it.++Thus, it is not the intent of this section to claim rights or contest+your rights to work written entirely by you; rather, the intent is to+exercise the right to control the distribution of derivative or+collective works based on the Library.++In addition, mere aggregation of another work not based on the Library+with the Library (or with a work based on the Library) on a volume of+a storage or distribution medium does not bring the other work under+the scope of this License.++ 3. You may opt to apply the terms of the ordinary GNU General Public+License instead of this License to a given copy of the Library. To do+this, you must alter all the notices that refer to this License, so+that they refer to the ordinary GNU General Public License, version 2,+instead of to this License. (If a newer version than version 2 of the+ordinary GNU General Public License has appeared, then you can specify+that version instead if you wish.) Do not make any other change in+these notices.++ Once this change is made in a given copy, it is irreversible for+that copy, so the ordinary GNU General Public License applies to all+subsequent copies and derivative works made from that copy.++ This option is useful when you wish to copy part of the code of+the Library into a program that is not a library.++ 4. You may copy and distribute the Library (or a portion or+derivative of it, under Section 2) in object code or executable form+under the terms of Sections 1 and 2 above provided that you accompany+it with the complete corresponding machine-readable source code, which+must be distributed under the terms of Sections 1 and 2 above on a+medium customarily used for software interchange.++ If distribution of object code is made by offering access to copy+from a designated place, then offering equivalent access to copy the+source code from the same place satisfies the requirement to+distribute the source code, even though third parties are not+compelled to copy the source along with the object code.++ 5. A program that contains no derivative of any portion of the+Library, but is designed to work with the Library by being compiled or+linked with it, is called a "work that uses the Library". Such a+work, in isolation, is not a derivative work of the Library, and+therefore falls outside the scope of this License.++ However, linking a "work that uses the Library" with the Library+creates an executable that is a derivative of the Library (because it+contains portions of the Library), rather than a "work that uses the+library". The executable is therefore covered by this License.+Section 6 states terms for distribution of such executables.++ When a "work that uses the Library" uses material from a header file+that is part of the Library, the object code for the work may be a+derivative work of the Library even though the source code is not.+Whether this is true is especially significant if the work can be+linked without the Library, or if the work is itself a library. The+threshold for this to be true is not precisely defined by law.++ If such an object file uses only numerical parameters, data+structure layouts and accessors, and small macros and small inline+functions (ten lines or less in length), then the use of the object+file is unrestricted, regardless of whether it is legally a derivative+work. (Executables containing this object code plus portions of the+Library will still fall under Section 6.)++ Otherwise, if the work is a derivative of the Library, you may+distribute the object code for the work under the terms of Section 6.+Any executables containing that work also fall under Section 6,+whether or not they are linked directly with the Library itself.++ 6. As an exception to the Sections above, you may also combine or+link a "work that uses the Library" with the Library to produce a+work containing portions of the Library, and distribute that work+under terms of your choice, provided that the terms permit+modification of the work for the customer's own use and reverse+engineering for debugging such modifications.++ You must give prominent notice with each copy of the work that the+Library is used in it and that the Library and its use are covered by+this License. You must supply a copy of this License. If the work+during execution displays copyright notices, you must include the+copyright notice for the Library among them, as well as a reference+directing the user to the copy of this License. Also, you must do one+of these things:++ a) Accompany the work with the complete corresponding+ machine-readable source code for the Library including whatever+ changes were used in the work (which must be distributed under+ Sections 1 and 2 above); and, if the work is an executable linked+ with the Library, with the complete machine-readable "work that+ uses the Library", as object code and/or source code, so that the+ user can modify the Library and then relink to produce a modified+ executable containing the modified Library. (It is understood+ that the user who changes the contents of definitions files in the+ Library will not necessarily be able to recompile the application+ to use the modified definitions.)++ b) Use a suitable shared library mechanism for linking with the+ Library. A suitable mechanism is one that (1) uses at run time a+ copy of the library already present on the user's computer system,+ rather than copying library functions into the executable, and (2)+ will operate properly with a modified version of the library, if+ the user installs one, as long as the modified version is+ interface-compatible with the version that the work was made with.++ c) Accompany the work with a written offer, valid for at+ least three years, to give the same user the materials+ specified in Subsection 6a, above, for a charge no more+ than the cost of performing this distribution.++ d) If distribution of the work is made by offering access to copy+ from a designated place, offer equivalent access to copy the above+ specified materials from the same place.++ e) Verify that the user has already received a copy of these+ materials or that you have already sent this user a copy.++ For an executable, the required form of the "work that uses the+Library" must include any data and utility programs needed for+reproducing the executable from it. However, as a special exception,+the materials to be distributed need not include anything that is+normally distributed (in either source or binary form) with the major+components (compiler, kernel, and so on) of the operating system on+which the executable runs, unless that component itself accompanies+the executable.++ It may happen that this requirement contradicts the license+restrictions of other proprietary libraries that do not normally+accompany the operating system. Such a contradiction means you cannot+use both them and the Library together in an executable that you+distribute.++ 7. You may place library facilities that are a work based on the+Library side-by-side in a single library together with other library+facilities not covered by this License, and distribute such a combined+library, provided that the separate distribution of the work based on+the Library and of the other library facilities is otherwise+permitted, and provided that you do these two things:++ a) Accompany the combined library with a copy of the same work+ based on the Library, uncombined with any other library+ facilities. This must be distributed under the terms of the+ Sections above.++ b) Give prominent notice with the combined library of the fact+ that part of it is a work based on the Library, and explaining+ where to find the accompanying uncombined form of the same work.++ 8. You may not copy, modify, sublicense, link with, or distribute+the Library except as expressly provided under this License. Any+attempt otherwise to copy, modify, sublicense, link with, or+distribute the Library is void, and will automatically terminate your+rights under this License. However, parties who have received copies,+or rights, from you under this License will not have their licenses+terminated so long as such parties remain in full compliance.++ 9. You are not required to accept this License, since you have not+signed it. However, nothing else grants you permission to modify or+distribute the Library or its derivative works. These actions are+prohibited by law if you do not accept this License. Therefore, by+modifying or distributing the Library (or any work based on the+Library), you indicate your acceptance of this License to do so, and+all its terms and conditions for copying, distributing or modifying+the Library or works based on it.++ 10. Each time you redistribute the Library (or any work based on the+Library), the recipient automatically receives a license from the+original licensor to copy, distribute, link with or modify the Library+subject to these terms and conditions. You may not impose any further+restrictions on the recipients' exercise of the rights granted herein.+You are not responsible for enforcing compliance by third parties with+this License.++ 11. If, as a consequence of a court judgment or allegation of patent+infringement or for any other reason (not limited to patent issues),+conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot+distribute so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you+may not distribute the Library at all. For example, if a patent+license would not permit royalty-free redistribution of the Library by+all those who receive copies directly or indirectly through you, then+the only way you could satisfy both it and this License would be to+refrain entirely from distribution of the Library.++If any portion of this section is held invalid or unenforceable under any+particular circumstance, the balance of the section is intended to apply,+and the section as a whole is intended to apply in other circumstances.++It is not the purpose of this section to induce you to infringe any+patents or other property right claims or to contest validity of any+such claims; this section has the sole purpose of protecting the+integrity of the free software distribution system which is+implemented by public license practices. Many people have made+generous contributions to the wide range of software distributed+through that system in reliance on consistent application of that+system; it is up to the author/donor to decide if he or she is willing+to distribute software through any other system and a licensee cannot+impose that choice.++This section is intended to make thoroughly clear what is believed to+be a consequence of the rest of this License.++ 12. If the distribution and/or use of the Library is restricted in+certain countries either by patents or by copyrighted interfaces, the+original copyright holder who places the Library under this License may add+an explicit geographical distribution limitation excluding those countries,+so that distribution is permitted only in or among countries not thus+excluded. In such case, this License incorporates the limitation as if+written in the body of this License.++ 13. The Free Software Foundation may publish revised and/or new+versions of the Lesser General Public License from time to time.+Such new versions will be similar in spirit to the present version,+but may differ in detail to address new problems or concerns.++Each version is given a distinguishing version number. If the Library+specifies a version number of this License which applies to it and+"any later version", you have the option of following the terms and+conditions either of that version or of any later version published by+the Free Software Foundation. If the Library does not specify a+license version number, you may choose any version ever published by+the Free Software Foundation.++ 14. If you wish to incorporate parts of the Library into other free+programs whose distribution conditions are incompatible with these,+write to the author to ask for permission. For software which is+copyrighted by the Free Software Foundation, write to the Free+Software Foundation; we sometimes make exceptions for this. Our+decision will be guided by the two goals of preserving the free status+of all derivatives of our free software and of promoting the sharing+and reuse of software generally.++ NO WARRANTY++ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH+DAMAGES.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Libraries++ If you develop a new library, and you want it to be of the greatest+possible use to the public, we recommend making it free software that+everyone can redistribute and change. You can do so by permitting+redistribution under these terms (or, alternatively, under the terms of the+ordinary General Public License).++ To apply these terms, attach the following notices to the library. It is+safest to attach them to the start of each source file to most effectively+convey the exclusion of warranty; and each file should have at least the+"copyright" line and a pointer to where the full notice is found.++ <one line to give the library's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This library is free software; you can redistribute it and/or+ modify it under the terms of the GNU Lesser General Public+ License as published by the Free Software Foundation; either+ version 2.1 of the License, or (at your option) any later version.++ This library is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU+ Lesser General Public License for more details.++ You should have received a copy of the GNU Lesser General Public+ License along with this library; if not, write to the Free Software+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA++Also add information on how to contact you by electronic and paper mail.++You should also get your employer (if you work as a programmer) or your+school, if any, to sign a "copyright disclaimer" for the library, if+necessary. Here is a sample; alter the names:++ Yoyodyne, Inc., hereby disclaims all copyright interest in the+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.++ <signature of Ty Coon>, 1 April 1990+ Ty Coon, President of Vice++That's all there is to it!diff --git a/qml/Veyra/ChainList.qml b/qml/Veyra/ChainList.qmlindex 8c8d10f8..c02fdb61 100644--- a/qml/Veyra/ChainList.qml+++ b/qml/Veyra/ChainList.qml@@ -16,6 +16,7 @@ ColumnLayout {}property int selected: -1+ onSelectedChanged: veyra.selectedNrLayer = selectedRepeater {model: veyra.chaindiff --git a/qml/Veyra/ChainNodeCard.qml b/qml/Veyra/ChainNodeCard.qmlindex e1c75318..a9d4e8db 100644--- a/qml/Veyra/ChainNodeCard.qml+++ b/qml/Veyra/ChainNodeCard.qml@@ -46,7 +46,7 @@ Rectangle {Behavior on x { NumberAnimation { duration: Theme.d(Theme.durNormal); easing.bezierCurve: Theme.spring } }}HoverHandler { cursorShape: Qt.PointingHandCursor }- TapHandler { onTapped: card.toggleRequested(!card.node.enabled) }+ TapHandler { gesturePolicy: TapHandler.WithinBounds; onTapped: card.toggleRequested(!card.node.enabled) }}ColumnLayout {@@ -82,7 +82,7 @@ Rectangle {color: removeHover.hovered ? Theme.err : Theme.t3size: 14HoverHandler { id: removeHover; cursorShape: Qt.PointingHandCursor }- TapHandler { onTapped: card.removeRequested() }+ TapHandler { gesturePolicy: TapHandler.WithinBounds; onTapped: card.removeRequested() }}}HoverHandler { id: cardHover }diff --git a/qml/Veyra/CineBar.qml b/qml/Veyra/CineBar.qmlindex 412a13f7..d43ff87a 100644--- a/qml/Veyra/CineBar.qml+++ b/qml/Veyra/CineBar.qml@@ -8,10 +8,13 @@import QtQuickimport QtQuick.Controlsimport QtQuick.Layouts+import QtQuick.EffectsRectangle {id: barsignal requestPage(string page)+ // Opens one of the main window's dialogs (字幕设置 / 音频设置).+ signal requestDialog(string key)signal requestFullscreen()signal requestLock()// Set on the fullscreen bar: shows the lock button.@@ -32,20 +35,41 @@ Rectangle {RowLayout {anchors.fill: parent- anchors.leftMargin: 14- anchors.rightMargin: 18+ anchors.leftMargin: 16+ anchors.rightMargin: 16spacing: 18// --- left: artwork + title (230px) ---------------------------RowLayout {- Layout.preferredWidth: 230+ Layout.preferredWidth: 230; Layout.minimumWidth: 230; Layout.maximumWidth: 230Layout.fillHeight: truespacing: 10+ // The file's own cover art when it carries one (MP4 covr, MKV image+ // attachment); otherwise the plate stays black - never a stand-in.Rectangle {+ id: coverPlateimplicitWidth: 46; implicitHeight: 46; radius: 12color: Theme.videoBlackborder.width: 1border.color: Theme.stroke+ clip: true+ Image {+ id: coverArt+ objectName: "cine-cover"+ anchors.fill: parent+ anchors.margins: 1+ visible: status === Image.Ready+ fillMode: Image.PreserveAspectCrop+ asynchronous: true+ cache: false+ source: veyra.hasSource && !veyra.isCapture ? "image://veyra-thumb/cover/" + veyra.thumbnailGeneration : ""+ layer.enabled: visible+ layer.effect: MultiEffect {+ maskEnabled: true+ maskSource: coverMask+ }+ }+ Rectangle { id: coverMask; anchors.fill: coverArt; radius: 11; visible: false; layer.enabled: true }}ColumnLayout {Layout.fillWidth: true@@ -105,7 +129,9 @@ Rectangle {scale: cTap.pressed ? 0.86 : 1.0Behavior on scale { NumberAnimation { duration: Theme.d(400); easing.bezierCurve: Theme.spring } }HoverHandler { id: cHover; cursorShape: Qt.PointingHandCursor }- TapHandler { id: cTap; onTapped: cbtn.tapped() }+ ToolTip.visible: cHover.hovered && cbtn.tip.length > 0+ ToolTip.text: cbtn.tip+ TapHandler { id: cTap; gesturePolicy: TapHandler.WithinBounds; onTapped: cbtn.tapped() }}CBtn { glyph: "cc"; onTapped: ccMenu.openAt(this, "up") }@@ -129,7 +155,7 @@ Rectangle {scale: playTap.pressed ? 0.88 : (playHover.hovered ? 1.06 : 1.0)Behavior on scale { NumberAnimation { duration: Theme.d(450); easing.bezierCurve: Theme.spring } }HoverHandler { id: playHover; cursorShape: Qt.PointingHandCursor }- TapHandler { id: playTap; onTapped: veyra.togglePlayPause() }+ TapHandler { id: playTap; gesturePolicy: TapHandler.WithinBounds; onTapped: veyra.togglePlayPause() }}CBtn { glyph: "fwd10"; onTapped: veyra.seekBy(10) }@@ -163,6 +189,11 @@ Rectangle {function fractionAt(x) {return seekArea.width > 0 ? Math.max(0, Math.min(1, x / seekArea.width)) : 0}+ Timer {+ id: scrubSeek+ interval: 120+ onTriggered: if (seekArea.scrubbing) veyra.seekTo(seekArea.scrubFrac * veyra.duration)+ }Timer {id: thumbnailDelayinterval: 120@@ -266,11 +297,16 @@ Rectangle {seekArea.scrubbing = true}onPositionChanged: mouse => {- if (seekArea.scrubbing) seekArea.scrubFrac = seekArea.fractionAt(mouse.x)+ if (seekArea.scrubbing) {+ seekArea.scrubFrac = seekArea.fractionAt(mouse.x)+ // Scrubbing seeks as it goes, 120 ms apart.+ if (!scrubSeek.running) scrubSeek.start()+ }thumbnailDelay.restart()}onReleased: mouse => {const target = seekArea.fractionAt(mouse.x) * veyra.duration+ scrubSeek.stop()seekArea.scrubbing = falseveyra.logUi("ui-seek", "targetSeconds=" + target.toFixed(3))veyra.seekTo(target)@@ -289,7 +325,7 @@ Rectangle {// --- right: preset, volume, fullscreen (230px) ---------------RowLayout {- Layout.preferredWidth: 230+ Layout.preferredWidth: 230; Layout.minimumWidth: 230; Layout.maximumWidth: 230Layout.alignment: Qt.AlignVCenter | Qt.AlignRightspacing: 6@@ -352,23 +388,24 @@ Rectangle {}}- // 字幕 (design: app.menu(anchor, '字幕', [...])): the design lists embedded- // tracks plus a settings dialog. The engine has no subtitle stream at all -- // no track list, no renderer - so every entry here is the design's own text- // with nothing behind it. Shown disabled rather than silently doing nothing.+ // 字幕 (design: app.menu(anchor, '字幕', [...])): the file's own tracks+ // (embedded and same-name external) from the subtitle loader, the primary+ // one checked, then loading a file and the settings dialog.VMenu {id: ccMenuaboveLimit: bar.menuBottomLimittitle: "字幕"- items: [- { label: "关闭", disabled: true },- { label: "简体中文 · 内嵌 ASS", disabled: true },- { label: "English · 内嵌 SRT", disabled: true },- { label: "加载外部字幕…", icon: "import", disabled: true },- { sep: true },- { label: "字幕设置…", note: "字体、字号、描边、位置、延时(尚未接入)", icon: "type", disabled: true }- ]- onPicked: veyra.logUi("ui-cine", "subtitle menu picked index=" + i + " (no subtitle stream in the engine)")+ items: [{ label: "关闭", checked: veyra.subtitlePrimary < 0, track: -1 }]+ .concat(veyra.subtitleTracks.map(t => ({ label: t.label, note: t.note, track: t.index,+ disabled: !t.usable, checked: t.index === veyra.subtitlePrimary })))+ .concat([{ label: "加载外部字幕…", icon: "import", act: "load" },+ { sep: true },+ { label: "字幕设置…", note: "字体、字号、描边、位置、延时", icon: "type", act: "dlg" }])+ onPicked: (i, o) => {+ if (o.act === "load") veyra.loadSubtitleDialog()+ else if (o.act === "dlg") bar.requestDialog("subtitle")+ else if (o.track !== undefined) veyra.subtitlePrimary = o.track+ }}// 音轨: this one is real - the bridge exposes the file's audio streams and the@@ -387,7 +424,7 @@ Rectangle {{ label: "音频设置…", note: "输出设备、音画同步、偏移", icon: "music", act: "dlg" }]): [{ label: "片源没有音轨或尚未打开", disabled: true }]onPicked: (i, o) => {- if (o.act === "dlg") return bar.requestPage("set")+ if (o.act === "dlg") return bar.requestDialog("audio")if (o.index !== undefined) veyra.selectedAudioTrack = o.index}}diff --git a/qml/Veyra/ColourCurve.qml b/qml/Veyra/ColourCurve.qmlnew file mode 100644index 00000000..58562888--- /dev/null+++ b/qml/Veyra/ColourCurve.qml@@ -0,0 +1,190 @@+import QtQuick+import QtQuick.Layouts++// Point curve editor. The engine's samples (ColorGradeTables::curveValue) draw+// the settled curve; while a point is dragged the editor draws its own draft+// with the same monotone Hermite spline, so the line follows the pointer+// instead of waiting for the engine round trip, and edits go out every 40 ms.+ColumnLayout {+ id: root+ property int channel: 0+ property var curves: [[{x:0,y:0},{x:1,y:1}],[{x:0,y:0},{x:1,y:1}],[{x:0,y:0},{x:1,y:1}],[{x:0,y:0},{x:1,y:1}]]+ property var samples: []+ readonly property var modelPoints: curves[channel] || []+ // The draft owns the points during a drag; otherwise the model does.+ property var draft: null+ readonly property var points: draft || modelPoints+ readonly property color channelColor: ["#E7E7EA","#FF5A5A","#4CD964","#4F8BFF"][channel]+ readonly property int maxPoints: 8+ signal edited(int channel, var points)+ spacing: 8+ onPointsChanged: graph.requestPaint()+ onSamplesChanged: graph.requestPaint()+ onChannelChanged: { draft = null; graph.requestPaint() }++ // ColorGradeTables.cpp curveTangents + pointCurve, ported for the live draft.+ function curveAt(pts, x) {+ const n = pts.length+ if (n < 2) return x+ if (x <= pts[0].x) return pts[0].y+ if (x >= pts[n - 1].x) return pts[n - 1].y+ const sec = [], m = []+ for (let i = 0; i < n - 1; ++i) sec.push((pts[i + 1].y - pts[i].y) / Math.max(1e-6, pts[i + 1].x - pts[i].x))+ m[0] = sec[0]+ for (let i = 1; i < n - 1; ++i) m[i] = sec[i - 1] * sec[i] <= 0 ? 0 : (sec[i - 1] + sec[i]) / 2+ m[n - 1] = sec[n - 2]+ for (let i = 0; i < n - 1; ++i) {+ if (sec[i] === 0) { m[i] = 0; m[i + 1] = 0; continue }+ const a = m[i] / sec[i], b = m[i + 1] / sec[i], mag = Math.sqrt(a * a + b * b)+ if (mag > 3) { const k = 3 / mag; m[i] = k * a * sec[i]; m[i + 1] = k * b * sec[i] }+ }+ for (let i = 0; i < n - 1; ++i) {+ const p = pts[i], q = pts[i + 1]+ if (x <= q.x) {+ const dx = Math.max(1e-6, q.x - p.x), t = Math.max(0, Math.min(1, (x - p.x) / dx))+ const t2 = t * t, t3 = t2 * t+ return (2 * t3 - 3 * t2 + 1) * p.y + (t3 - 2 * t2 + t) * dx * m[i] + (-2 * t3 + 3 * t2) * q.y + (t3 - t2) * dx * m[i + 1]+ }+ }+ return pts[n - 1].y+ }+ function clamp01(v) { return Math.max(0, Math.min(1, v)) }++ VSeg {+ objectName: "colour-curve-channels"+ Layout.fillWidth: true+ options: [{id:"0",label:"RGB"},{id:"1",label:"红"},{id:"2",label:"绿"},{id:"3",label:"蓝"}]+ current: String(root.channel)+ onPicked: id => root.channel = Number(id)+ }+ Rectangle {+ Layout.fillWidth: true+ Layout.preferredHeight: Math.min(width, 240)+ color: "#17191E"; radius: 8; border.color: Theme.stroke+ Canvas {+ id: graph+ objectName: "colour-curve-canvas"+ anchors.fill: parent; anchors.margins: 12+ property int hover: -1+ property int active: -1+ onWidthChanged: requestPaint()+ onHeightChanged: requestPaint()+ onHoverChanged: requestPaint()+ onActiveChanged: requestPaint()+ onPaint: {+ const c = getContext("2d"); c.reset()+ c.strokeStyle = "#30343C"; c.lineWidth = 1+ for (let i = 0; i <= 4; ++i) {+ c.beginPath(); c.moveTo(width * i / 4, 0); c.lineTo(width * i / 4, height); c.stroke()+ c.beginPath(); c.moveTo(0, height * i / 4); c.lineTo(width, height * i / 4); c.stroke()+ }+ c.strokeStyle = "#545966"; c.beginPath(); c.moveTo(0, height); c.lineTo(width, 0); c.stroke()+ c.strokeStyle = root.channelColor; c.lineWidth = 2; c.beginPath()+ const values = root.draft ? null : root.samples[root.channel]+ if (values && values.length > 1) {+ for (let i = 0; i < values.length; ++i) {+ const x = width * i / (values.length - 1), y = height * (1 - values[i])+ if (i === 0) c.moveTo(x, y); else c.lineTo(x, y)+ }+ } else {+ const steps = Math.max(32, Math.round(width / 3))+ for (let i = 0; i <= steps; ++i) {+ const x = i / steps, y = root.clamp01(root.curveAt(root.points, x))+ if (i === 0) c.moveTo(x * width, (1 - y) * height); else c.lineTo(x * width, (1 - y) * height)+ }+ }+ c.stroke()+ for (let i = 0; i < root.points.length; ++i) {+ const p = root.points[i], big = i === active || i === hover+ c.beginPath(); c.arc(p.x * width, (1 - p.y) * height, big ? 7 : 5.5, 0, Math.PI * 2)+ c.fillStyle = i === active ? root.channelColor : "#17191E"; c.fill()+ c.lineWidth = 2; c.strokeStyle = root.channelColor; c.stroke()+ }+ }+ // Coalesce drag edits: the engine gets the latest draft every 40 ms and+ // once more on release.+ Timer {+ id: sendTimer+ interval: 40+ onTriggered: if (root.draft) root.edited(root.channel, root.draft.map(p => ({ x: p.x, y: p.y })))+ }+ MouseArea {+ anchors.fill: parent+ anchors.margins: -8 // points on the border stay easy to grab+ acceptedButtons: Qt.LeftButton | Qt.RightButton+ hoverEnabled: true+ preventStealing: true+ cursorShape: graph.hover >= 0 || graph.active >= 0 ? Qt.SizeAllCursor : Qt.CrossCursor+ readonly property real w: graph.width+ readonly property real h: graph.height+ function local(mouse) { return Qt.point(mouse.x - 8, mouse.y - 8) }+ function closest(x, y) {+ let found = -1, dist = 16 * 16+ for (let i = 0; i < root.points.length; ++i) {+ const p = root.points[i], d = Math.pow(p.x * w - x, 2) + Math.pow((1 - p.y) * h - y, 2)+ if (d < dist) { found = i; dist = d }+ }+ return found+ }+ function moveTo(x, y) {+ const i = graph.active+ if (i < 0 || !root.draft || i >= root.draft.length) return+ const next = root.draft.map(p => ({ x: p.x, y: p.y }))+ const last = next.length - 1+ // The end points stay on the edges and only move vertically.+ const px = i === 0 ? 0 : i === last ? 1+ : Math.max(next[i - 1].x + 0.01, Math.min(next[i + 1].x - 0.01, x / w))+ next[i] = { x: px, y: root.clamp01(1 - y / h) }+ root.draft = next+ if (!sendTimer.running) sendTimer.start()+ }+ function removeAt(i) {+ if (i <= 0 || i >= root.points.length - 1) return+ const next = root.points.map(p => ({ x: p.x, y: p.y })); next.splice(i, 1)+ draftRelease.stop(); sendTimer.stop(); root.draft = null+ root.edited(root.channel, next)+ }+ onPositionChanged: mouse => {+ const p = local(mouse)+ if (pressed && graph.active >= 0 && (pressedButtons & Qt.LeftButton)) moveTo(p.x, p.y)+ else graph.hover = closest(p.x, p.y)+ }+ onExited: graph.hover = -1+ onPressed: mouse => {+ const p = local(mouse)+ let i = closest(p.x, p.y)+ if (mouse.button === Qt.RightButton) { removeAt(i); return }+ root.draft = root.modelPoints.map(q => ({ x: q.x, y: q.y }))+ if (i < 0) {+ // A single click on the graph adds a point ON the curve at+ // that x (so nothing jumps), then drags it straight away.+ const x = root.clamp01(p.x / w)+ if (root.draft.length >= root.maxPoints || root.draft.some(q => Math.abs(q.x - x) < 0.01)) {+ root.draft = null; return+ }+ root.draft.push({ x: x, y: root.clamp01(root.curveAt(root.draft, x)) })+ root.draft.sort((a, b) => a.x - b.x)+ root.draft = root.draft.slice()+ i = root.draft.findIndex(q => q.x === x)+ }+ graph.active = i+ moveTo(p.x, p.y)+ }+ function finish() {+ sendTimer.stop()+ if (root.draft) root.edited(root.channel, root.draft.map(p => ({ x: p.x, y: p.y })))+ graph.active = -1+ // Keep drawing the draft until the engine's samples arrive.+ draftRelease.restart()+ }+ onReleased: finish()+ onCanceled: finish()+ }+ Timer { id: draftRelease; interval: 250; onTriggered: if (graph.active < 0) root.draft = null }+ }+ }+ RowLayout {+ Text { Layout.fillWidth: true; text: "单击曲线加点并拖动 · 右键删点 · 最多 8 点"; color: Theme.t3; font.pixelSize: 11 }+ VButton { text: "还原通道"; ghost: true; onClicked: root.edited(root.channel, [{x:0,y:0},{x:1,y:1}]) }+ }+}diff --git a/qml/Veyra/ColourMixer.qml b/qml/Veyra/ColourMixer.qmlnew file mode 100644index 00000000..a53aa434--- /dev/null+++ b/qml/Veyra/ColourMixer.qml@@ -0,0 +1,87 @@+import QtQuick+import QtQuick.Layouts++ColumnLayout {+ id: root+ property int band: 0+ property var state: ({blackWhite:false,mixerHue:[0,0,0,0,0,0,0,0],mixerSaturation:[0,0,0,0,0,0,0,0],mixerLuminance:[0,0,0,0,0,0,0,0],blackWhiteMix:[0,0,0,0,0,0,0,0]})+ readonly property var names:["红色","橙色","黄色","绿色","浅绿色","蓝色","紫色","洋红"]+ readonly property var colors:["#FF5A5A","#FF9A3D","#F5D547","#4CD964","#3DD6C8","#4F8BFF","#9B6BFF","#FF5AC8"]+ signal edited(string name, real value)+ signal modeEdited(bool blackWhite)+ spacing:0+ RowLayout {+ id: modeRow+ objectName:"colour-mixer-mode-row"+ property string label:"模式"+ Layout.fillWidth:true+ Layout.preferredHeight:Theme.rowMinHeight+ spacing:12+ Text {+ Layout.fillWidth:true;Layout.minimumWidth:0+ text:modeRow.label;color:Theme.t2+ font.family:Theme.fontUi;font.pixelSize:Theme.fsBody+ elide:Text.ElideRight+ }+ VSeg {+ objectName:"colour-mixer-mode"+ options:[{id:"hsl",label:"HSL"},{id:"bw",label:"黑白"}]+ current:root.state.blackWhite?"bw":"hsl"+ onPicked:id=>root.modeEdited(id==="bw")+ }+ }+ RowLayout {+ Layout.fillWidth:true;Layout.topMargin:4;Layout.bottomMargin:6;spacing:6+ Repeater {+ model:8+ Rectangle {+ required property int index+ objectName:"colour-mixer-band-"+index+ Layout.fillWidth:true;implicitHeight:22;radius:7+ color:root.colors[index];border.width:2+ border.color:root.band===index?"#FFFFFF":"transparent"+ scale:root.band===index?1.08:1+ Behavior on scale { NumberAnimation {duration:Theme.d(400);easing.bezierCurve:Theme.spring} }+ Behavior on border.color { ColorAnimation {duration:Theme.d(200)} }+ TapHandler {onTapped:root.band=parent.index}+ Accessible.name:root.names[index]+ }+ }+ }+ Repeater {+ model:root.state.blackWhite?[{key:"blackWhiteMix",label:"黑白"}]:+ [{key:"mixerHue",label:"色相"},{key:"mixerSaturation",label:"饱和度"},{key:"mixerLuminance",label:"明亮度"}]+ delegate:RowLayout {+ required property var modelData+ objectName:"colour-mixer-row-"+modelData.key+ Layout.fillWidth:true+ Layout.preferredHeight:Theme.rowMinHeight+ spacing:12+ Text {+ Layout.fillWidth:true;Layout.minimumWidth:0+ text:root.names[root.band]+" · "+modelData.label;color:Theme.t2+ font.family:Theme.fontUi;font.pixelSize:Theme.fsBody+ elide:Text.ElideRight+ }+ VSlider {+ resettable:true;defaultValue:0+ valueFromModel:true+ objectName:"colour-mixer-"+modelData.key+ Layout.minimumWidth:150;Layout.maximumWidth:150;Layout.preferredWidth:150+ from:-100;to:100;center:true+ showCenterFill:true+ Accessible.name:root.names[root.band]+" · "+modelData.label+ value:root.state[modelData.key][root.band]+ onMoved:value=>root.edited(modelData.key+"."+root.band,Math.round(value))+ }+ Text {+ objectName:"colour-mixer-value-"+modelData.key+ Layout.minimumWidth:40;Layout.maximumWidth:40;Layout.preferredWidth:40+ readonly property int amount:Math.round(root.state[modelData.key][root.band])+ text:(amount>0?"+":"")+String(amount);color:Theme.t1+ font.family:Theme.fontMono;font.pixelSize:Theme.fsSmall+ horizontalAlignment:Text.AlignRight+ }+ }+ }+}diff --git a/qml/Veyra/ColourPanel.qml b/qml/Veyra/ColourPanel.qmlnew file mode 100644index 00000000..128fb4e4--- /dev/null+++ b/qml/Veyra/ColourPanel.qml@@ -0,0 +1,411 @@+import QtQuick+import QtQuick.Layouts+import QtQuick.Window++// Shared by list and node inspectors: the bridge selects the actual Color node.+ColumnLayout {+ id: panel+ required property var api+ readonly property var state:api.colourState+ property bool originalHeld: false+ onOriginalHeldChanged: api.holdOriginal(originalHeld)+ onVisibleChanged: { if (!visible) originalHeld = false }+ Component.onDestruction: { if (originalHeld) api.holdOriginal(false) }+ Connections {+ target: panel.Window.window+ function onActiveChanged() {+ if (panel.Window.window && !panel.Window.window.active) panel.originalHeld = false+ }+ }+ property string curveMode:"points"+ // Node cards (N2): only the groups, all folded, each with its item count;+ // the card header carries the switch.+ property bool compact:false+ // The tab redraw staggers this column's cards (ProPage M31).+ readonly property Item sectionColumn:panel+ readonly property var sectionCounts:[6,4,1,1,3,7,3,3]+ readonly property var sections:["亮","颜色","曲线","混色器","颜色分级","校准","LUT","效果"]+ readonly property var light:["exposure","contrast","highlights","shadows","whites","blacks"]+ readonly property var colour:["temperature","tint","vibrance","saturation"]+ readonly property var parametric:["paramHighlights","paramLights","paramDarks","paramShadows","splitHighlights","splitMidtones","splitShadows"]+ spacing:6+ Gradient {id:temperatureTrack;orientation:Gradient.Horizontal+ GradientStop {position:0;color:"#4F8BFF"}+ GradientStop {position:0.5;color:"#DDDDDD"}+ GradientStop {position:1;color:"#FFB547"}}+ Gradient {id:tintTrack;orientation:Gradient.Horizontal+ GradientStop {position:0;color:"#4CD964"}+ GradientStop {position:0.5;color:"#DDDDDD"}+ GradientStop {position:1;color:"#FF5AC8"}}+ Gradient {id:vibranceTrack;orientation:Gradient.Horizontal+ GradientStop {position:0;color:"#777777"}+ GradientStop {position:1;color:"#FF9A3D"}}+ Gradient {id:saturationTrack;orientation:Gradient.Horizontal+ GradientStop {position:0;color:"#777777"}+ GradientStop {position:1;color:"#FF5A5A"}}+ Gradient {id:greenCalibrationTrack;orientation:Gradient.Horizontal+ GradientStop {position:0;color:"#777777"}+ GradientStop {position:1;color:"#4CD964"}}+ Gradient {id:blueCalibrationTrack;orientation:Gradient.Horizontal+ GradientStop {position:0;color:"#777777"}+ GradientStop {position:1;color:"#4F8BFF"}}+ function valueFor(key){+ let value=state+ for(const part of key.split("."))value=value[part]+ return Number(value)+ }+ function descriptor(key){+ const found=api.colourParameters.find(p=>p.name===key)+ if(found)return found+ const parts=key.split(".")+ return {name:key,label:["红原色","绿原色","蓝原色"][Number(parts[1])]++ (parts[0]==="calibrationHue"?" · 色相":" · 饱和度"),min:-100,max:100,step:1,defaultValue:0}+ }+ component NameField: Rectangle {+ property alias text: field.text+ property string placeholder: ""+ signal accepted()+ implicitHeight: 30+ radius: 9+ color: Qt.rgba(1, 1, 1, 0.04)+ border.width: 1+ border.color: field.activeFocus ? Theme.accent : Theme.stroke+ TextInput {+ id: field+ anchors.fill: parent; anchors.leftMargin: 10; anchors.rightMargin: 10+ verticalAlignment: TextInput.AlignVCenter+ color: Theme.t1; font.family: Theme.fontUi; font.pixelSize: Theme.fsBody+ selectByMouse: true; clip: true; maximumLength: 48+ onAccepted: parent.accepted()+ }+ Text {+ anchors.verticalCenter: parent.verticalCenter+ anchors.left: parent.left; anchors.leftMargin: 10+ visible: field.text.length === 0+ text: parent.placeholder; color: Theme.t3+ font.family: Theme.fontUi; font.pixelSize: Theme.fsBody+ }+ }+ component ParameterRows: ColumnLayout {+ id: rows+ property var keys:[]+ spacing:0+ Repeater {+ model:rows.keys.length+ delegate:RowLayout {+ required property int index+ readonly property string key:rows.keys[index]+ readonly property var spec:panel.descriptor(key)+ Layout.fillWidth:true+ Layout.preferredHeight:Theme.rowMinHeight+ spacing:12+ Text {+ Layout.fillWidth:true;Layout.minimumWidth:0+ text:spec.label;color:Theme.t2+ font.family:Theme.fontUi;font.pixelSize:Theme.fsBody+ elide:Text.ElideRight+ }+ VSlider {+ objectName:"colour-param-"+key+ valueFromModel:true+ resettable:true;defaultValue:spec.defaultValue+ Layout.minimumWidth:150;Layout.maximumWidth:150;Layout.preferredWidth:150+ from:spec.min;to:spec.max;center:from<0&&to>0+ showCenterFill:true+ Accessible.name:spec.label+ value:panel.valueFor(key)+ trackGradient:key==="temperature"?temperatureTrack:key==="tint"?tintTrack:+ key==="vibrance"?vibranceTrack:key==="saturation"||key==="calibrationHue.0"?saturationTrack:+ key==="calibrationHue.1"?greenCalibrationTrack:key==="calibrationHue.2"?blueCalibrationTrack:null+ onMoved:value=>panel.api.setColourParameter(key,Math.round(value/spec.step)*spec.step)+ }+ Text {+ Layout.minimumWidth:40;Layout.maximumWidth:40;Layout.preferredWidth:40+ text:panel.valueFor(key).toFixed(spec.step<1?2:0);color:Theme.t1+ font.family:Theme.fontMono;font.pixelSize:Theme.fsSmall+ horizontalAlignment:Text.AlignRight+ }+ }+ }+ }+ // color.js .ctop: the 调色 switch with its note, then the tool row -+ // undo / redo / copy / paste on the left, 按住看原图 and 一键还原 on the right.+ Rectangle {+ id: colourTop+ objectName:"colour-top"+ visible:!panel.compact+ Layout.fillWidth:true+ implicitHeight:topCol.implicitHeight+10+ radius:12+ color:Theme.card2+ border.width:1+ border.color:Theme.stroke+ property real motionDy:0+ transform:Translate {y:colourTop.motionDy}+ ColumnLayout {+ id:topCol+ anchors.left:parent.left;anchors.right:parent.right;anchors.top:parent.top+ anchors.leftMargin:12;anchors.rightMargin:12;anchors.topMargin:2+ spacing:2+ RowLayout {+ Layout.fillWidth:true+ Layout.minimumHeight:44+ spacing:10+ ColumnLayout {+ Layout.fillWidth:true+ spacing:2+ Text {+ text:panel.state.index<0?"没有调色节点":veyra.nodeMode===1?"调色 · 实例 "+(panel.state.index+1):"调色"+ color:Theme.t1;font.family:Theme.fontUi;font.pixelSize:13+ font.weight:Font.DemiBold;font.variableAxes:Theme.axesDemiBold+ }+ Text {+ Layout.fillWidth:true+ text:panel.state.enabled?"关闭时这条链路不存在,零开销":"已关闭 · 参数保留但不生效"+ color:Theme.t3;font.family:Theme.fontUi;font.pixelSize:11+ elide:Text.ElideRight+ }+ }+ VSwitch {objectName:"colour-master";checked:panel.state.enabled;onToggled:checked=>panel.api.colorEnabled=checked}+ }+ RowLayout {+ objectName:"colour-tools"+ Layout.fillWidth:true+ Layout.bottomMargin:6+ spacing:2+ VButton {+ objectName:"colour-undo"+ icon:true;ghost:true;iconName:"undo";implicitWidth:28;implicitHeight:28+ tip:"撤销";enabled:panel.api.colourCanUndo+ onClicked:panel.api.colourUndo()+ }+ VButton {+ objectName:"colour-redo"+ icon:true;ghost:true;iconName:"refresh";implicitWidth:28;implicitHeight:28+ tip:"重做";enabled:panel.api.colourCanRedo+ onClicked:panel.api.colourRedo()+ }+ VButton {+ objectName:"colour-copy"+ icon:true;ghost:true;iconName:"copy";implicitWidth:28;implicitHeight:28+ tip:"复制调色参数";enabled:panel.state.index>=0+ onClicked:panel.api.colourCopy()+ }+ VButton {+ objectName:"colour-paste"+ icon:true;ghost:true;iconName:"import";implicitWidth:28;implicitHeight:28+ tip:"粘贴调色参数";enabled:panel.api.colourCanPaste&&panel.state.index>=0+ onClicked:panel.api.colourPaste()+ }+ Item {Layout.fillWidth:true}+ VButton {+ objectName:"colour-original-hold"+ implicitHeight:28+ iconName:"eye"+ text:panel.originalHeld?"松开恢复":"按住看原图"+ Accessible.name:"按住查看原图,松开恢复增强画面"+ MouseArea {+ anchors.fill:parent+ acceptedButtons:Qt.LeftButton+ onPressed:panel.originalHeld=true+ onReleased:panel.originalHeld=false+ onCanceled:panel.originalHeld=false+ }+ }+ VButton {+ objectName:"colour-reset-all"+ implicitHeight:28+ ghost:true;iconName:"reset";text:"一键还原"+ onClicked:panel.api.resetColourGroup(-1)+ }+ }+ }+ }+ // Colour presets: one Color node's settings (ColorLookStore), not the+ // whole-chain presets. Applying one replaces this instance only.+ VRow {+ visible:!panel.compact+ label:"颜色预设"+ VSelect {+ objectName:"colour-look-select"+ implicitWidth:170+ value:panel.api.colourLooks.length?"应用预设…":"暂无颜色预设"+ options:panel.api.colourLooks.map(l=>({id:String(l.index),label:l.name+(l.lut?" · LUT":"")}))+ onPicked:id=>panel.api.applyColourLook(Number(id))+ }+ }+ RowLayout {+ visible:!panel.compact+ Layout.fillWidth:true+ spacing:6+ NameField {+ id:lookName+ objectName:"colour-look-name"+ Layout.fillWidth:true+ placeholder:"新预设名称"+ onAccepted:saveLook.clicked()+ }+ VButton {+ id:saveLook+ objectName:"colour-look-save"+ text:"保存"+ enabled:lookName.text.trim().length>0&&panel.state.index>=0+ onClicked:{+ const name=lookName.text.trim()+ const exists=panel.api.colourLooks.some(l=>l.name===name)+ if(panel.api.saveColourLook(name,exists))lookName.text=""+ }+ }+ VButton {+ id:lookMore+ objectName:"colour-look-more"+ text:"管理";ghost:true+ Accessible.name:"颜色预设 · 导入/导出/删除"+ onClicked:lookMenu.openAt(lookMore,"down")+ }+ VMenu {+ id:lookMenu+ title:"颜色预设"+ items:[{act:"import",label:"导入 .vpcolor…",icon:"import"}]+ .concat(panel.api.colourLooks.map(l=>({act:"export",look:l.index,label:"导出「"+l.name+"」…",icon:"upload"})))+ .concat(panel.api.colourLooks.map(l=>({act:"delete",look:l.index,label:"删除「"+l.name+"」",icon:"trash"})))+ onPicked:(i,item)=>{+ if(item.act==="import")panel.api.importColourLookDialog()+ else if(item.act==="export")panel.api.exportColourLookDialog(item.look)+ else if(item.act==="delete")panel.api.deleteColourLook(item.look)+ }+ }+ }+ Repeater {+ model:8+ delegate:VAccordion {+ id: section+ required property int index+ objectName:"colour-section-"+index+ Layout.fillWidth:true+ title:panel.sections[index];glyph:"palette";hue:"#E0C341"+ summary:panel.compact?panel.sectionCounts[index]+" 项":""+ open:!panel.compact&&index<2+ enabledSwitch:false+ compactHeader:true+ bypassed:index<7&&(panel.state.groupBypassMask&(1<<index))!==0+ headerLeadingActions: [+ VButton {+ objectName:"colour-bypass-"+section.index+ visible:section.index<7+ icon:true;iconName:section.bypassed?"eyeoff":"eye"+ ghost:true;implicitWidth:24;implicitHeight:24;radius:7+ Accessible.name:panel.sections[section.index]+(section.bypassed?" · 恢复":" · 旁路")+ onClicked:panel.api.setColourOption("groupBypassMask",panel.state.groupBypassMask^(1<<section.index))+ }+ ]+ headerActions: [+ VButton {+ objectName:"colour-reset-"+section.index+ icon:true;iconName:"reset";ghost:true;implicitWidth:26;implicitHeight:26+ Accessible.name:panel.sections[section.index]+" · 还原"+ onClicked:panel.api.resetColourGroup(section.index)+ }+ ]+ ParameterRows {+ Layout.fillWidth:true+ visible:section.index===0||section.index===1||section.index===7+ keys:section.index===0?panel.light:section.index===1?panel.colour:+ section.index===7?["texture","clarity","dehaze"]:[]+ }+ Text {+ Layout.fillWidth:true;visible:section.index===1+ text:"色温为相对值;采集卡没有拍摄白平衡。"+ color:Theme.t3;font.pixelSize:11;wrapMode:Text.WordWrap+ }+ Loader {+ Layout.fillWidth:true;active:section.index===2;visible:active+ sourceComponent:ColumnLayout {+ VSeg {+ objectName:"colour-curve-mode"+ options:[{id:"points",label:"点曲线"},{id:"parametric",label:"参数曲线"}]+ current:panel.curveMode;onPicked:id=>panel.curveMode=id+ }+ ColourCurve {+ objectName:"colour-curve"+ Layout.fillWidth:true;visible:panel.curveMode==="points"+ curves:panel.state.curves;samples:panel.state.curveSamples+ onEdited:(channel,points)=>panel.api.setColourCurve(channel,points)+ }+ ParameterRows {Layout.fillWidth:true;visible:panel.curveMode==="parametric";keys:panel.parametric}+ }+ }+ Loader {+ Layout.fillWidth:true;active:section.index===3;visible:active+ sourceComponent:ColourMixer {+ objectName:"colour-mixer"+ state:panel.state+ onEdited:(name,value)=>panel.api.setColourParameter(name,value)+ onModeEdited:blackWhite=>panel.api.setColourOption("blackWhite",blackWhite?1:0)+ }+ }+ Loader {+ Layout.fillWidth:true;active:section.index===4;visible:active+ sourceComponent:ColumnLayout {+ GridLayout {+ Layout.fillWidth:true;columns:2;columnSpacing:14;rowSpacing:14+ Repeater {+ model:4+ delegate:ColourWheel {+ property bool sliderResetEnabled: true+ property bool sliderValueFromModel: true+ required property int index+ objectName:"colour-wheel-"+index+ Layout.fillWidth:true+ title:["阴影","中间调","高光","全局"][index]+ hue:panel.state.grading[index].hue+ saturation:panel.state.grading[index].saturation+ luminance:panel.state.grading[index].luminance+ onEdited:(h,s,l)=>panel.api.setColourWheel(index,h,s,l)+ }+ }+ }+ ParameterRows {Layout.fillWidth:true;keys:["gradingBlending","gradingBalance"]}+ }+ }+ ParameterRows {+ Layout.fillWidth:true;visible:section.index===5+ keys:section.index===5?["calibrationShadowTint","calibrationHue.0","calibrationSaturation.0","calibrationHue.1","calibrationSaturation.1","calibrationHue.2","calibrationSaturation.2"]:[]+ }+ Loader {+ Layout.fillWidth:true;active:section.index===6;visible:active+ sourceComponent:ColumnLayout {+ VRow {+ label:"LUT 文件"+ VSelect {+ objectName:"colour-lut-select"+ implicitWidth:170+ value:panel.state.lutName?panel.state.lutName:"未使用"+ options:[{id:"",label:"不使用 LUT"}].concat(panel.api.lutLibrary.map(n=>({id:n,label:n})))+ onPicked:id=>panel.api.setColourLut(id)+ }+ }+ RowLayout {+ Layout.fillWidth:true+ VButton {+ objectName:"colour-lut-import"+ text:"导入 .cube…";ghost:true+ onClicked:panel.api.importLutDialog()+ }+ Item {Layout.fillWidth:true}+ }+ ParameterRows {Layout.fillWidth:true;keys:["lutStrength"]}+ VSeg {+ options:[{id:"0",label:"Cineon"},{id:"1",label:"sRGB"},{id:"2",label:"PQ"}]+ current:String(panel.state.lutInputSpace)+ onPicked:id=>panel.api.setColourOption("lutInputSpace",Number(id))+ }+ Text {+ Layout.fillWidth:true;text:"导入的 .cube 保存在程序目录 runtime_local/luts,导出也使用同一份。"+ color:Theme.t3;font.pixelSize:11;wrapMode:Text.WordWrap+ }+ }+ }+ }+ }+}diff --git a/qml/Veyra/ColourWheel.qml b/qml/Veyra/ColourWheel.qmlnew file mode 100644index 00000000..d80d5a06--- /dev/null+++ b/qml/Veyra/ColourWheel.qml@@ -0,0 +1,64 @@+import QtQuick+import QtQuick.Layouts++// 1.4.4 contract: clockwise hue, saturation as radius; separate -100..100 L.+ColumnLayout {+ id: root+ property string title: ""+ property real hue: 0+ property real saturation: 0+ property real luminance: 0+ signal edited(real hue, real saturation, real luminance)+ spacing: 6+ Text { Layout.alignment:Qt.AlignHCenter; text:root.title; color:Theme.t2; font.pixelSize:12 }+ Item {+ Layout.alignment:Qt.AlignHCenter+ Layout.preferredWidth:Math.min(root.width,132)+ Layout.preferredHeight:width+ Canvas {+ id: disc+ objectName: "colour-wheel-disc"+ anchors.fill:parent; anchors.margins:7+ onWidthChanged:requestPaint()+ onHeightChanged:requestPaint()+ onPaint: {+ const c=getContext("2d");c.reset()+ const r=width/2,cx=width/2,cy=height/2+ for(let i=0;i<360;++i){+ c.beginPath();c.moveTo(cx,cy);c.arc(cx,cy,r,i*Math.PI/180,(i+1.5)*Math.PI/180);c.closePath()+ c.fillStyle=Qt.hsla(i/360,1,0.5,1);c.fill()+ }+ const g=c.createRadialGradient(cx,cy,0,cx,cy,r)+ g.addColorStop(0,"#D3D4D9");g.addColorStop(1,"rgba(211,212,217,0)")+ c.fillStyle=g;c.beginPath();c.arc(cx,cy,r,0,Math.PI*2);c.fill()+ }+ Rectangle {+ width:10;height:10;radius:5;color:"#F7F7FA";border.width:2;border.color:"#17191E"+ x:disc.width/2+Math.cos(root.hue*Math.PI/180)*root.saturation/100*disc.width/2-width/2+ y:disc.height/2+Math.sin(root.hue*Math.PI/180)*root.saturation/100*disc.height/2-height/2+ }+ MouseArea {+ anchors.fill:parent;preventStealing:true+ function updateWheel(x,y){+ const dx=(x-width/2)/(width/2),dy=(y-height/2)/(height/2)+ const s=Math.min(100,Math.hypot(dx,dy)*100)+ const h=s<0.001?root.hue:(Math.atan2(dy,dx)*180/Math.PI+360)%360+ root.edited(h,s,root.luminance)+ }+ onPressed: mouse=>updateWheel(mouse.x,mouse.y)+ onPositionChanged: mouse=>{if(pressed)updateWheel(mouse.x,mouse.y)}+ onDoubleClicked:root.edited(0,0,0)+ }+ }+ }+ VSlider {+ objectName:"colour-wheel-luminance"+ Layout.fillWidth:true;from:-100;to:100;center:true;value:root.luminance+ onMoved:value=>root.edited(root.hue,root.saturation,Math.round(value))+ }+ Text {+ Layout.alignment:Qt.AlignHCenter+ text:"H "+Math.round(root.hue)+"° · S "+Math.round(root.saturation)+" · L "+Math.round(root.luminance)+ color:Theme.t3;font.pixelSize:10+ }+}diff --git a/qml/Veyra/DialogHost.qml b/qml/Veyra/DialogHost.qmlindex b9a1bcb8..eb475dcd 100644--- a/qml/Veyra/DialogHost.qml+++ b/qml/Veyra/DialogHost.qml@@ -21,7 +21,14 @@ Item {// Which dialog is showing: "" | capture | ps5 | screen | subtitle | audioproperty string dialog: ""- function open(key) { host.dialog = key }+ function open(key) {+ if (key === "save") saveDialog.resetForOpen()+ if (key === "manage") {+ manageDialog.mode = veyra.nodeMode === 1 ? "node" : "list"+ manageDialog.feedback = ""+ }+ host.dialog = key+ }function close() { host.dialog = "" }signal startCapture()@@ -50,6 +57,8 @@ Item {property string glyph: ""property int dialogWidth: 640property var actions: []+ // dialogs.js `foot`: a quiet note at the left of the button row.+ property string foot: ""default property alias body: bodyCol.datasignal actionTriggered(string label)@@ -79,14 +88,23 @@ Item {Scale { origin.x: dlg.width / 2; origin.y: dlg.height / 2; xScale: dlg.motionS; yScale: dlg.motionS },Translate { y: dlg.motionDy }]- // Cut out of the native video window (main.cpp syncVideoCovers).+ // Cut out of the native video window (main.cpp syncVideoCovers). The flag,+ // not the objectName: each dialog below names itself for tests.objectName: "videoCover"+ readonly property bool videoCover: trueproperty real coverRadius: 16anchors.centerIn: parentwidth: dialogWidth- implicitHeight: Math.min(720, header.height + bodyScroll.contentHeight + footer.height + 40)+ // Never taller than the window: the body scrolls instead of the panel+ // being cut off at the top and bottom of a small window.+ // Header and footer each carry 16px margins top and bottom (64 in all); the+ // old +40 left every body 24px short, so short dialogs hid their last row.+ implicitHeight: Math.min(720, host.height - 24, header.height + bodyScroll.contentHeight + footer.height + 64)height: implicitHeight+ // Swallow presses on the panel itself so they never reach the scrim+ // below (a passive tap on a control used to close the whole dialog).+ MouseArea { anchors.fill: parent; acceptedButtons: Qt.AllButtons; z: -1 }radius: 16color: Theme.dialogborder.width: 1@@ -110,6 +128,11 @@ Item {Layout.fillWidth: truespacing: 2Text {+ // Fill: without a subtitle this is the column's only child, and+ // its natural width would cap the column and pull the close+ // button in beside the title.+ Layout.fillWidth: true+ elide: Text.ElideRighttext: dlg.titlecolor: Theme.t1font.family: Theme.fontUi@@ -137,10 +160,11 @@ Item {Layout.rightMargin: 20contentHeight: bodyCol.implicitHeightclip: true- ScrollBar.vertical: ScrollBar { }+ ScrollBar.vertical: VScrollBar { }ColumnLayout {id: bodyCol- width: parent.width+ // Keep the groups clear of the overlaid scroll bar.+ width: parent.width - (bodyScroll.contentHeight > bodyScroll.height ? 12 : 0)spacing: 0}}@@ -150,12 +174,23 @@ Item {Layout.fillWidth: trueLayout.margins: 16spacing: 8- Item { Layout.fillWidth: true }+ Text {+ objectName: "dialog-foot"+ Layout.fillWidth: true+ visible: dlg.foot.length > 0+ text: dlg.foot+ color: Theme.t3+ font.family: Theme.fontUi+ font.pixelSize: 11+ elide: Text.ElideRight+ }+ Item { Layout.fillWidth: true; visible: dlg.foot.length === 0 }Repeater {model: dlg.actionsdelegate: VButton {required property var modelDatatext: modelData.label+ iconName: modelData.icon || ""primary: modelData.primary === trueonClicked: dlg.actionTriggered(modelData.label)}@@ -165,35 +200,195 @@ Item {}// --- 采集卡 -----------------------------------------------------------+ // The 1.4.4 capture panel, in the new design: device details and formats are+ // queried asynchronously, only an explicitly chosen audio input is opened,+ // and the choice is remembered for "继续上次采集".DLayer {+ id: captureDialog+ objectName: "capture-dialog"key: "capture"glyph: "video"title: "采集卡"sub: "连接设备后,先关闭增强确认基础画面,再按需开启"- dialogWidth: 620+ dialogWidth: 660+ foot: "关闭其他占用同一采集卡的软件"actions: [{ label: "取消" },- { label: "连接并开始", primary: true }+ { label: "连接并开始", primary: true, icon: "play" }]onActionTriggered: label => {- host.close()- if (label === "连接并开始") host.startCapture()+ if (label !== "连接并开始") { host.close(); return }+ if (veyra.startCaptureSession()) { host.close(); host.startCapture() }+ }+ Connections {+ target: host+ function onDialogChanged() { if (host.dialog === "capture") veyra.refreshCaptureDevices() }+ }+ function labelOf(list, id, fallback) { const f = list.find(x => String(x.id) === String(id)); return f ? f.label : fallback }+ readonly property bool live: veyra.captureSignalLevel !== "idle"++ // dialogs.js .cap-prev: the picture and a signal line under it. The+ // picture is the session's own poster still when the engine made one;+ // there is no periodic frame grab here, because that would sit on the+ // live capture path. The status line is live.+ Rectangle {+ objectName: "capture-preview"+ Layout.fillWidth: true+ Layout.topMargin: 4+ implicitHeight: 180 + 34+ radius: 10+ color: Theme.videoBlack+ border.width: 1+ border.color: Theme.stroke+ clip: true+ Image {+ id: capturePoster+ objectName: "capture-preview-image"+ anchors.left: parent.left; anchors.right: parent.right; anchors.top: parent.top+ anchors.margins: 1+ height: 180+ fillMode: Image.PreserveAspectCrop+ source: captureDialog.live ? veyra.capturePreviewUrl : ""+ visible: status === Image.Ready+ }+ Column {+ anchors.horizontalCenter: parent.horizontalCenter+ y: 90 - height / 2+ spacing: 8+ visible: !capturePoster.visible+ VIcon { anchors.horizontalCenter: parent.horizontalCenter; name: "video"; size: 22; color: Theme.t3 }+ Text {+ text: captureDialog.live ? "画面在主窗口播放" : "连接后在主窗口显示画面"+ color: Theme.t3+ font.family: Theme.fontUi+ font.pixelSize: 12+ }+ }+ RowLayout {+ anchors.left: parent.left; anchors.right: parent.right; anchors.bottom: parent.bottom+ height: 34+ anchors.leftMargin: 10; anchors.rightMargin: 10+ spacing: 8+ VTag {+ objectName: "capture-signal"+ text: veyra.captureSignalText+ kind: veyra.captureSignalLevel === "ok" ? "ok" : veyra.captureSignalLevel === "warn" ? "warn" : ""+ }+ Text {+ Layout.fillWidth: true+ text: captureDialog.live+ ? veyra.sourceSummary.replace("x", "×") + " · " + veyra.captureFps.toFixed(2) + " fps"+ + (veyra.sourceFormatText.split(" · ").length > 2 ? " · " + veyra.sourceFormatText.split(" · ")[1] : "")+ : captureDialog.labelOf(veyra.captureFormats, veyra.captureFormatKey, "选择设备和格式后连接")+ color: Theme.t2+ font.family: Theme.fontMono+ font.pixelSize: 11+ elide: Text.ElideRight+ }+ }}DSection { text: "设备" }DGroup {VRow {label: "视频输入设备"- hint: veyra.captureDevices.length === 0 ? "未检测到采集设备" : ""+ hint: veyra.captureQueryBusy ? "正在查询…当前播放继续" : (veyra.captureDevices.length === 0 ? "未检测到采集设备" : "")+ RowLayout {+ spacing: 6+ VSelect {+ objectName: "capture-device"+ implicitWidth: 220+ value: veyra.captureDeviceLabel+ options: veyra.captureDevices+ onPicked: id => veyra.captureDeviceId = id+ }+ // M38: the refresh icon becomes a spinner while the query runs.+ Item {+ implicitWidth: Theme.ctlHeight; implicitHeight: Theme.ctlHeight+ VButton {+ objectName: "capture-refresh"+ anchors.fill: parent+ visible: !veyra.captureQueryBusy+ icon: true; ghost: true; iconName: "refresh"; tip: "刷新设备"+ onClicked: veyra.refreshCaptureDevices()+ }+ VSpinner { anchors.centerIn: parent; visible: veyra.captureQueryBusy }+ }+ }+ }+ VRow {+ label: "设备实际支持的格式"+ hint: { const f = veyra.captureFormats.find(x => x.id === veyra.captureFormatKey); return f && f.costHint ? "该格式比低延迟格式多一道处理环节,高分辨率/高帧率下建议优先低延迟格式" : "" }VSelect {- value: veyra.captureDeviceLabel- options: veyra.captureDevices- onPicked: id => veyra.captureDeviceId = id+ objectName: "capture-format"+ implicitWidth: 260+ value: captureDialog.labelOf(veyra.captureFormats, veyra.captureFormatKey, veyra.captureFormats.length ? "请选择格式" : "—")+ options: veyra.captureFormats+ onPicked: id => veyra.captureFormatKey = id+ }+ }+ VRow {+ label: "设备帧率 FPS"+ hint: "0 = 沿用所选格式;设备返回其他帧率会报错,不在软件中偷偷丢帧"+ VTextField {+ objectName: "capture-fps"+ implicitWidth: 100+ text: String(veyra.captureRequestedFps)+ onEdited: text => veyra.captureRequestedFps = Number(text)+ }+ }+ }+ DSection { text: "音频" }+ DGroup {+ VRow {+ label: "音频监听"+ hint: "只连接明确选中的输入,默认不监听"+ VSelect {+ objectName: "capture-audio"+ implicitWidth: 260+ value: captureDialog.labelOf(veyra.captureAudioInputs, veyra.captureAudioChoice, "不监听音频")+ options: veyra.captureAudioInputs+ onPicked: id => veyra.captureAudioChoice = Number(id)+ }+ }+ VRow {+ label: "Dolby / DTS 位流"+ VSeg {+ options: [{ id: "0", label: "自动" }, { id: "1", label: "强制 PCM" }, { id: "2", label: "位流优先" }]+ current: String(veyra.captureAudioIngress)+ onPicked: id => veyra.captureAudioIngress = Number(id)}}}DSection { text: "格式与画面" }DGroup {+ VRow {+ label: "输入色彩(SDR / HDR)"+ hint: "不确定就选「自动」。采集 HDR:采集格式选 P010,这里选「HDR · PQ」(游戏机、显卡的 HDR10 都是 PQ)。「HDR · HLG」用于广播信号。「SDR · 709」是普通画面。变更需重连"+ VSeg {+ options: [{ id: "0", label: "自动" }, { id: "1", label: "HDR · PQ" }, { id: "2", label: "HDR · HLG" }, { id: "3", label: "SDR · 709" }]+ current: String(veyra.captureColorSpace)+ onPicked: id => veyra.captureColorSpace = Number(id)+ }+ }+ VRow {+ label: "输入范围"+ hint: "Limited = 16–235,Full = 0–255。画面发灰选「有限」,暗部全黑、亮部过曝选「完全」"+ VSeg {+ options: [{ id: "0", label: "自动" }, { id: "1", label: "有限 · Limited" }, { id: "2", label: "完全 · Full" }]+ current: String(veyra.captureColorRange)+ onPicked: id => veyra.captureColorRange = Number(id)+ }+ }+ VRow {+ label: "设备缓冲"+ hint: "自动:1080p 及以下 2 帧,更高 3 帧;最小 1 帧延迟最低但可能丢帧"+ VSeg {+ options: [{ id: "0", label: "自动" }, { id: "1", label: "最小" }, { id: "2", label: "驱动默认" }]+ current: String(veyra.captureBufferMode)+ onPicked: id => veyra.captureBufferMode = Number(id)+ }+ }VRow {label: "转为 SDR 显示"hint: "收到 HDR 也按 SDR 预览,立即生效"@@ -211,66 +406,163 @@ Item {}}}- DSection { text: "尚未接入" }- DNote {- text: "格式列表(分辨率 · 帧率 · 像素格式)、色彩空间与范围、设备缓冲、"- + "音频监听设备、Dolby / DTS 位流、限定输入帧率:引擎侧尚未暴露这些设置,"- + "这里不放假控件。当前按设备默认格式打开。"- }+ DNote { visible: veyra.captureStatus.length > 0; text: veyra.captureStatus }}// --- PS5 串流 ---------------------------------------------------------+ // The 1.4.4 Remote Play panel: saved pairings are encrypted in the user's+ // %LOCALAPPDATA%\Veyra\remoteplay and shared with 1.4.4.DLayer {+ id: ps5Dialog+ objectName: "ps5-dialog"key: "ps5"glyph: "gamepad"title: "PS5 串流"sub: "局域网 Remote Play · 凭据加密保存在本机"- dialogWidth: 640+ dialogWidth: 680actions: [- { label: "取消" },- { label: "连接", primary: true }+ { label: veyra.ps5.active ? "断开" : "取消" },+ { label: veyra.ps5.active ? "应用设置并重连" : "连接", primary: true }]onActionTriggered: label => {- host.close()- if (label === "连接") host.startPs5()+ if (label === "断开") { veyra.ps5Cancel(); return }+ if (label === "取消") { if (veyra.ps5.busy) veyra.ps5Cancel(); else host.close(); return }+ if (veyra.ps5Connect()) { host.close(); host.startPs5() }+ }+ Connections {+ target: host+ function onDialogChanged() { if (host.dialog === "ps5") veyra.ps5Load() }}+ readonly property var qualities: [{ id: "0", label: "720p · 30 fps" }, { id: "1", label: "720p · 60 fps" }, { id: "2", label: "1080p · 30 fps" }, { id: "3", label: "1080p · 60 fps" }]+ readonly property var bitrates: [5, 10, 15, 20, 30, 50, 80, 100].map((m, i) => ({ id: String(i), label: m + " Mbps" }))DSection { text: "主机" }DGroup {VRow {- label: "串流状态"- hint: veyra.remotePlayState.length > 0 ? veyra.remotePlayState : "未连接"+ visible: veyra.ps5Profiles.length > 0+ label: "已保存主机"+ VSelect {+ objectName: "ps5-profile"+ implicitWidth: 220+ value: { const p = veyra.ps5Profiles.find(x => x.id === veyra.ps5.profile); return p ? p.label : "请选择" }+ options: veyra.ps5Profiles+ onPicked: id => veyra.ps5SelectProfile(id)+ }}VRow {label: "主机地址"- hint: "PS5 设置 → 网络 → 连接状态 → 查看连接状态"- VTextField {- implicitWidth: 180- placeholder: "192.168.1.x"- onEdited: text => veyra.remotePlayHost = text+ hint: "PS5 设置 → 网络 → 连接状态;找不到时可手填 IP"+ RowLayout {+ spacing: 6+ VTextField { objectName: "ps5-host"; implicitWidth: 170; placeholder: "192.168.1.x"; text: veyra.ps5.host || ""; onEdited: text => veyra.ps5Set("host", text) }+ VSpinner { visible: veyra.ps5.busy === true; Layout.alignment: Qt.AlignVCenter }+ VButton { text: "查找"; ghost: true; enabled: !veyra.ps5.busy; onClicked: veyra.ps5Scan() }+ VButton { text: "唤醒"; ghost: true; enabled: !veyra.ps5.busy && veyra.ps5.profile.length > 0; onClicked: veyra.ps5Wake() }}}}- DSection { text: "配对" }+ DSection { text: "配对(首次)" }DGroup {+ VRow {+ label: "PSN Account ID"+ hint: "账号数字 ID 或 8 字节 Base64,不是昵称;登录 PSN 后自动填入"+ VTextField { implicitWidth: 240; text: veyra.ps5.account || ""; onEdited: text => veyra.ps5Set("account", text) }+ }VRow {label: "8 位配对码"- hint: "首次配对需要:PS5 远程游玩 → 关联设备"- VTextField {- implicitWidth: 150- placeholder: "••••••••"- onEdited: text => veyra.remotePlayPin = text+ hint: "PS5 设置 → 系统 → 远程游玩 → 关联设备"+ RowLayout {+ spacing: 6+ VTextField { id: pairPin; implicitWidth: 120; placeholder: "••••••••" }+ VButton { text: "配对并保存"; enabled: !veyra.ps5.busy; onClicked: { veyra.ps5Pair(pairPin.text); pairPin.text = "" } }}}+ VRow {+ label: "删除配对"+ hint: "只删除本机保存的这台主机;以后需要重新配对"+ VButton { text: "删除"; ghost: true; enabled: !veyra.ps5.busy && veyra.ps5.profile.length > 0; onClicked: veyra.ps5Forget() }+ }}- DNote {- text: "输入分辨率、编码(H.264 / H.265)、请求码率、解码方式、"- + "DualSense 转发与陀螺仪校准:尚未接入界面。外网串流暂未实现。"+ DSection { text: "PSN 账号" }+ DGroup {+ VRow {+ label: veyra.ps5.psnReady ? "已登录" : "未登录"+ hint: "在 Sony 网页登录后复制回调地址再提交;软件不接触密码"+ RowLayout {+ spacing: 6+ VButton { text: "登录 PSN"; ghost: true; enabled: !veyra.ps5.busy; onClicked: veyra.ps5PsnLogin() }+ VButton { text: "提交登录结果"; ghost: true; enabled: !veyra.ps5.busy; onClicked: veyra.ps5PsnComplete() }+ VButton { text: "退出"; ghost: true; enabled: !veyra.ps5.busy && veyra.ps5.psnReady; onClicked: veyra.ps5PsnForget() }+ }+ }}+ DSection { text: "串流(重连生效)" }+ DGroup {+ VRow {+ label: "分辨率与帧率"+ VSelect { implicitWidth: 170; value: ps5Dialog.qualities[veyra.ps5.quality || 0].label; options: ps5Dialog.qualities; onPicked: id => veyra.ps5Set("quality", Number(id)) }+ }+ VRow {+ label: "编码"+ hint: "HDR 需要 PS5 实际输出 HDR 且 Windows HDR 开启"+ VSeg {+ options: [{ id: "0", label: "H.264" }, { id: "1", label: "H.265" }, { id: "2", label: "H.265 HDR" }]+ current: String(veyra.ps5.codec || 0)+ onPicked: id => veyra.ps5Set("codec", Number(id))+ }+ }+ VRow {+ label: "请求码率"+ hint: "发给 PS5 的带宽请求,主机不保证达到"+ VSelect { implicitWidth: 130; value: ps5Dialog.bitrates[veyra.ps5.bitrate || 0].label; options: ps5Dialog.bitrates; onPicked: id => veyra.ps5Set("bitrate", Number(id)) }+ }+ VRow {+ label: "解码"+ VSeg {+ options: [{ id: "0", label: "自动" }, { id: "1", label: "CPU 软件" }, { id: "2", label: "D3D12VA 硬件" }]+ current: String(veyra.ps5.decode || 0)+ onPicked: id => veyra.ps5Set("decode", Number(id))+ }+ }+ VRow {+ label: "采样"+ hint: "精细:按位置还原色度,放大用双三次;不是 AI 超分"+ VSeg {+ options: [{ id: "0", label: "兼容" }, { id: "1", label: "精细" }]+ current: String(veyra.ps5.sampling === undefined ? 1 : veyra.ps5.sampling)+ onPicked: id => veyra.ps5Set("sampling", Number(id))+ }+ }+ VRow {+ label: "仅观看"+ hint: "不向 PS5 转发电脑手柄输入"+ VSwitch { checked: veyra.ps5.viewOnly === true; onToggled: veyra.ps5Set("viewOnly", checked) }+ }+ VRow {+ label: "陀螺仪"+ hint: veyra.ps5.controller ? (veyra.ps5.gyro ? "手柄支持陀螺仪" : "手柄没有陀螺仪") : "连接串流及电脑手柄后可校准"+ VButton { text: veyra.ps5.calibrating ? "校准中…" : "校准"; ghost: true; onClicked: veyra.ps5Calibrate() }+ }+ }+ DSection { text: "登录 PIN" }+ DGroup {+ VRow {+ label: "PS5 提示时填写"+ hint: "不是 8 位配对码"+ RowLayout {+ spacing: 6+ VTextField { id: loginPin; implicitWidth: 120 }+ VButton { text: "提交"; ghost: true; onClicked: { veyra.ps5SendLoginPin(loginPin.text); loginPin.text = "" } }+ }+ }+ }+ DNote { visible: (veyra.ps5.status || "").length > 0; text: (veyra.ps5.busy ? "处理中 · " : "") + (veyra.ps5.status || "") }}// --- 屏幕捕获 ---------------------------------------------------------DLayer {+ id: screenDialog+ objectName: "screen-dialog"key: "screen"glyph: "monitor"title: "屏幕捕获"@@ -281,50 +573,329 @@ Item {{ label: "开始捕获", primary: true }]onActionTriggered: label => {- host.close()- if (label === "开始捕获") host.startScreen()+ if (label !== "开始捕获") { host.close(); return }+ if (veyra.startScreenCapture()) { host.close(); host.startScreen() }+ }+ Connections {+ target: host+ function onDialogChanged() { if (host.dialog === "screen") veyra.refreshCaptureTargets() }}+ readonly property var o: veyra.screenOptionsDSection { text: "目标" }DGroup {+ VRow {+ label: "类型"+ VSeg {+ objectName: "screen-kind"+ options: [{ id: "0", label: "窗口" }, { id: "1", label: "显示器" }]+ current: String(screenDialog.o.kind)+ onPicked: id => veyra.setScreenOption("kind", Number(id))+ }+ }VRow {label: "捕获目标"hint: veyra.screenTargets.length === 0 ? "未找到可捕获的窗口或显示器" : ""- VSelect {- value: veyra.screenTargetLabel- options: veyra.screenTargets- onPicked: id => veyra.screenTargetId = id+ RowLayout {+ spacing: 6+ VSelect {+ objectName: "screen-target"+ implicitWidth: 300+ value: veyra.screenTargetLabel+ options: veyra.screenTargets+ onPicked: id => veyra.screenTargetId = id+ }+ VButton { text: "刷新"; ghost: true; onClicked: veyra.refreshCaptureTargets() }}}+ }+ DSection { text: "采集" }+ DGroup {VRow {- label: "重新枚举"- hint: "窗口打开或关闭后刷新列表"- VButton {- text: "刷新"- onClicked: veyra.refreshCaptureTargets()+ label: "采集方式"+ hint: screenDialog.o.kind === 1 ? "DXGI 为显示器兼容方式,无鼠标指针" : "窗口只能用 Windows Graphics Capture"+ VSeg {+ enabled: screenDialog.o.kind === 1+ opacity: enabled ? 1 : 0.5+ options: [{ id: "0", label: "WGC" }, { id: "1", label: "DXGI" }]+ current: String(screenDialog.o.method)+ onPicked: id => veyra.setScreenOption("method", Number(id))+ }+ }+ VRow {+ label: "帧率上限"+ VSeg {+ options: [{ id: "0", label: "跟随" }, { id: "1", label: "30" }, { id: "2", label: "60" }, { id: "3", label: "120" }, { id: "4", label: "144" }, { id: "5", label: "240" }]+ current: String(screenDialog.o.fps)+ onPicked: id => veyra.setScreenOption("fps", Number(id))+ }+ }+ VRow {+ label: "显示鼠标指针"+ VSwitch {+ enabled: screenDialog.o.method === 0+ checked: screenDialog.o.cursor === true+ onToggled: veyra.setScreenOption("cursor", checked)+ }+ }+ VRow {+ label: "裁剪(像素)"+ hint: "左 / 上 / 右 / 下,按源像素"+ RowLayout {+ spacing: 4+ Repeater {+ model: ["left", "top", "right", "bottom"]+ delegate: VTextField {+ required property string modelData+ implicitWidth: 58+ text: String(screenDialog.o[modelData])+ onEdited: text => veyra.setScreenOption(modelData, Number(text))+ }+ }+ }+ }+ VRow {+ label: "画面"+ VSeg {+ options: [{ id: "fit", label: "适应窗口" }, { id: "fill", label: "填满窗口" }]+ current: screenDialog.o.fill ? "fill" : "fit"+ onPicked: id => veyra.setScreenOption("fill", id === "fill")}}- }- DNote {- text: "捕获方式(Windows Graphics Capture / DXGI)、帧率上限、"- + "鼠标指针、裁剪与“填满窗口”:尚未接入界面;当前按整块目标区域采集。"}}// --- 字幕设置 ---------------------------------------------------------DLayer {+ id: subtitleDialog+ objectName: "subtitle-dialog"key: "subtitle"glyph: "type"title: "字幕设置"sub: "实时预览,设置对所有文件生效"dialogWidth: 620- actions: [{ label: "完成", primary: true }]- onActionTriggered: host.close()+ actions: [{ label: "恢复默认" }, { label: "完成", primary: true }]+ onActionTriggered: label => {+ if (label !== "恢复默认") { host.close(); return }+ // The look only: tracks and the timing offset belong to the file.+ const defaults = { subtitleEnabled: true, subtitleSize: 22, subtitleFont: 0, subtitleOutline: 2,+ subtitleBackground: false, subtitleMargin: 0, subtitleFit: false, subtitleLines: 2 }+ for (const key in defaults) veyra.setPreference(key, defaults[key])+ veyra.logUi("ui-subtitle", "style reset to defaults")+ }++ readonly property var prefs: veyra.preferences+ function pref(key, fallback) { return prefs[key] !== undefined ? prefs[key] : fallback }+ readonly property var trackOptions: [{ id: "-1", label: "关闭" }]+ .concat(veyra.subtitleTracks.map(t => ({ id: String(t.index), label: t.label + " · " + t.note, disabled: !t.usable })))+ function trackLabel(index) {+ const t = veyra.subtitleTracks.find(x => x.index === index)+ return t ? t.label : "关闭"+ }- DNote {- text: "字幕轨选择、字号、字体、描边、背景条、底部距离与延时尚未接入:"- + "字幕样式与轨道由旧界面的字幕层持有,引擎侧没有对应设置,"- + "本轮不在这里维护第二份会与渲染结果不一致的状态。"+ // dialogs.js .sub-prev: a sample line over the picture, drawn with the+ // current style so every change shows at once.+ Rectangle {+ id: subPreview+ objectName: "subtitle-preview"+ Layout.fillWidth: true+ Layout.topMargin: 4+ implicitHeight: 180+ radius: 10+ border.width: 1+ border.color: Theme.stroke+ clip: true+ gradient: Gradient {+ GradientStop { position: 0; color: "#1B2230" }+ GradientStop { position: 1; color: "#0B0C10" }+ }+ readonly property real scaleFactor: height / 540+ Image {+ anchors.fill: parent+ anchors.margins: 1+ fillMode: Image.PreserveAspectCrop+ asynchronous: true+ visible: status === Image.Ready+ source: subtitleDialog.shown && veyra.hasSource && !veyra.isCapture && veyra.duration > 0+ ? "image://veyra-thumb/" + veyra.thumbnailGeneration + "/" + Math.floor(veyra.position / 2) * 2000 : ""+ }+ Column {+ objectName: "subtitle-preview-lines"+ visible: subtitleDialog.pref("subtitleEnabled", true)+ anchors.horizontalCenter: parent.horizontalCenter+ anchors.bottom: parent.bottom+ anchors.bottomMargin: 12 + subtitleDialog.pref("subtitleMargin", 0) * subPreview.scaleFactor+ spacing: 2+ Repeater {+ model: veyra.subtitleText.length > 0 ? veyra.subtitleText.split("\n").slice(0, 2)+ : ["这是字幕预览,", "改动会实时显示在这里。"]+ delegate: Rectangle {+ required property string modelData+ anchors.horizontalCenter: parent.horizontalCenter+ width: line.implicitWidth + 16+ height: line.implicitHeight + 2+ radius: 4+ color: subtitleDialog.pref("subtitleBackground", false) ? Qt.rgba(0, 0, 0, 0.6) : "transparent"+ Text {+ id: line+ anchors.centerIn: parent+ text: modelData+ color: "#FFFFFF"+ readonly property var families: ["", "SimHei", "SimSun", "DengXian", "Arial", "Segoe UI"]+ font.family: families[subtitleDialog.pref("subtitleFont", 0)] || Theme.fontUi+ font.pixelSize: Math.max(12, subtitleDialog.pref("subtitleSize", 22) * 0.8)+ font.weight: Font.DemiBold+ style: subtitleDialog.pref("subtitleOutline", 2) > 0 ? Text.Outline : Text.Normal+ styleColor: Qt.rgba(0, 0, 0, subtitleDialog.pref("subtitleOutline", 2) >= 3 ? 1 : 0.85)+ }+ }+ }+ }+ }++ DSection { text: "字幕轨" }+ DGroup {+ VRow {+ label: "主字幕"+ hint: veyra.subtitleTracks.length === 0 ? (veyra.hasSource ? "当前片源没有字幕" : "打开视频后显示可用字幕") : ""+ VSelect {+ objectName: "subtitle-primary"+ implicitWidth: 220+ value: subtitleDialog.trackLabel(veyra.subtitlePrimary)+ options: subtitleDialog.trackOptions+ onPicked: id => veyra.subtitlePrimary = Number(id)+ }+ }+ VRow {+ label: "副字幕(双语)"+ hint: "显示在主字幕上方"+ VSelect {+ objectName: "subtitle-secondary"+ implicitWidth: 220+ value: subtitleDialog.trackLabel(veyra.subtitleSecondary)+ options: subtitleDialog.trackOptions+ onPicked: id => veyra.subtitleSecondary = Number(id)+ }+ }+ VRow {+ label: "外挂字幕"+ hint: "SRT / ASS / SSA / WebVTT"+ VButton { objectName: "subtitle-load"; text: "加载文件…"; onClicked: veyra.loadSubtitleDialog() }+ }+ VRow {+ label: "默认显示副字幕"+ hint: "打开新文件时自动选第二条可用字幕"+ VSwitch {+ checked: subtitleDialog.pref("subtitleSecondLanguage", false)+ onToggled: veyra.setPreference("subtitleSecondLanguage", checked)+ }+ }+ }+ DSection { text: "时间" }+ DGroup {+ VRow {+ label: "主字幕延时"+ hint: "Z / X 微调 50 ms,Shift 为 1 s;正值 = 字幕推后"+ // .stepper: − value +, 50 ms a step; the value can be typed.+ RowLayout {+ objectName: "subtitle-delay-stepper"+ spacing: 4+ VButton { objectName: "subtitle-delay-minus"; icon: true; iconName: "minus"; implicitWidth: 28; implicitHeight: 28; onClicked: veyra.nudgeSubtitle(-50) }+ VTextField {+ objectName: "subtitle-delay-value"+ implicitWidth: 86+ text: veyra.subtitleOffsetMs + " ms"+ onEdited: text => { const v = parseInt(text); if (isFinite(v)) veyra.subtitleOffsetMs = v }+ }+ VButton { objectName: "subtitle-delay-plus"; icon: true; iconName: "plus"; implicitWidth: 28; implicitHeight: 28; onClicked: veyra.nudgeSubtitle(50) }+ }+ }+ VRow {+ label: "按音轨自动对齐"+ hint: veyra.subtitleStatus.length > 0 ? veyra.subtitleStatus : "分析前 30 分钟的人声与字幕时间"+ VButton {+ text: veyra.subtitleAligning ? "分析中…" : "自动对齐"+ enabled: !veyra.subtitleAligning && veyra.subtitlePrimary >= 0+ onClicked: veyra.autoAlignSubtitle()+ }+ }+ }+ DSection { text: "样式" }+ DGroup {+ VRow {+ label: "显示字幕"+ hint: "快捷键 B"+ VSwitch {+ objectName: "subtitle-enabled"+ checked: subtitleDialog.pref("subtitleEnabled", true)+ onToggled: veyra.setPreference("subtitleEnabled", checked)+ }+ }+ VRow {+ label: "字号"+ value: subtitleDialog.pref("subtitleSize", 22) + " px"+ VSlider {+ objectName: "subtitle-size"+ implicitWidth: 170+ from: 16; to: 56; value: subtitleDialog.pref("subtitleSize", 22)+ onMoved: veyra.setPreference("subtitleSize", Math.round(value))+ }+ }+ VRow {+ label: "字体"+ VSelect {+ objectName: "subtitle-font"+ implicitWidth: 170+ readonly property var names: ["字幕原字体", "黑体", "宋体", "等线", "Arial", "Segoe UI"]+ value: names[subtitleDialog.pref("subtitleFont", 0)]+ options: names.map((n, i) => ({ id: String(i), label: n }))+ onPicked: id => veyra.setPreference("subtitleFont", Number(id))+ }+ }+ VRow {+ label: "描边"+ VSeg {+ objectName: "subtitle-outline"+ options: [{ id: "0", label: "无" }, { id: "1", label: "细" }, { id: "2", label: "标准" }, { id: "3", label: "粗" }]+ current: String(subtitleDialog.pref("subtitleOutline", 2))+ onPicked: id => veyra.setPreference("subtitleOutline", Number(id))+ }+ }+ VRow {+ label: "背景条"+ VSwitch {+ checked: subtitleDialog.pref("subtitleBackground", false)+ onToggled: veyra.setPreference("subtitleBackground", checked)+ }+ }+ VRow {+ label: "底部距离"+ value: subtitleDialog.pref("subtitleMargin", 0) + " px"+ VSlider {+ objectName: "subtitle-margin"+ implicitWidth: 170+ from: 0; to: 240; value: subtitleDialog.pref("subtitleMargin", 0)+ onMoved: veyra.setPreference("subtitleMargin", Math.round(value))+ }+ }+ VRow {+ label: "长句自动缩小"+ hint: "默认保持字号;开启后超过目标行数才缩小"+ VSwitch {+ checked: subtitleDialog.pref("subtitleFit", false)+ onToggled: veyra.setPreference("subtitleFit", checked)+ }+ }+ VRow {+ visible: subtitleDialog.pref("subtitleFit", false)+ label: "目标行数"+ value: String(subtitleDialog.pref("subtitleLines", 2))+ VSlider {+ implicitWidth: 170+ from: 1; to: 8; value: subtitleDialog.pref("subtitleLines", 2)+ onMoved: veyra.setPreference("subtitleLines", Math.round(value))+ }+ }}}@@ -363,6 +934,11 @@ Item {anchors.leftMargin: 12anchors.rightMargin: 12spacing: 12+ // .trk .bars: the playing track's bars move (M39).+ VEqBars {+ objectName: "audio-track-bars-" + modelData.index+ active: veyra.selectedAudioTrack === modelData.index && veyra.running && !veyra.paused+ }ColumnLayout {Layout.fillWidth: truespacing: 2@@ -411,6 +987,16 @@ Item {}DSection { text: "音画同步" }DGroup {+ VRow {+ label: "声音同步"+ hint: veyra.audioSyncMode === 0 ? (veyra.audioSyncLive ? "软件估算补偿 " + veyra.audioCompensationMs.toFixed(0) + " ms" : "自动估算 · 采集卡 / PS5 实时输入时生效")+ : veyra.audioSyncMode === 1 ? "手动偏移 · 实时输入时生效" : "关闭补偿"+ VSeg {+ options: [{ id: "0", label: "自动估算" }, { id: "1", label: "手动" }, { id: "2", label: "关闭" }]+ current: String(veyra.audioSyncMode)+ onPicked: id => veyra.audioSyncMode = Number(id)+ }+ }VRow {label: "手动偏移"hint: "负值 = 声音提前"@@ -418,13 +1004,44 @@ Item {VSlider {implicitWidth: 170center: true- from: -500; to: 500; value: veyra.audioOffsetMs+ from: -250; to: 250; value: veyra.audioOffsetMs; enabledControl: veyra.audioSyncMode === 1onMoved: veyra.audioOffsetMs = Math.round(value / 10) * 10}}+ VRow {+ label: "当前偏差"+ hint: "软件内测得的音画偏差,不是扬声器实测;只在采集卡 / PS5 实时输入时有"+ value: veyra.audioSkewKnown ? (veyra.audioSkewMs >= 0 ? "+" : "") + veyra.audioSkewMs.toFixed(0) + " ms" : "未测"+ }+ }+ DSection { text: "输出设备" }+ DGroup {+ VRow {+ label: "输出设备"+ hint: veyra.audioOutputStatus+ VSelect {+ objectName: "audio-device"+ implicitWidth: 240+ readonly property string chosen: veyra.preferences.audioDevice || ""+ value: { const d = veyra.audioDevices.find(x => x.id === chosen); return d ? d.label : "跟随系统默认" }+ options: veyra.audioDevices+ onPicked: id => veyra.setPreference("audioDevice", id)+ }+ }+ VRow {+ label: "立体声下混"+ hint: "多声道片源混成双声道再输出(耳机);关闭时按设备声道布局映射"+ VSwitch {+ objectName: "audio-stereo"+ checked: veyra.preferences.audioForceStereo === true+ onToggled: veyra.setPreference("audioForceStereo", checked)+ }+ }}- DNote {- text: "输出设备选择与立体声下混尚未接入:当前跟随系统默认设备。"+ // The list is read when the dialog opens: devices come and go.+ Connections {+ target: host+ function onDialogChanged() { if (host.dialog === "audio") veyra.refreshAudioDevices() }}}@@ -433,41 +1050,154 @@ Item {// the user can see what they are about to store.DLayer {id: saveDialog+ objectName: "preset-save-dialog"key: "save"glyph: "plus"- title: "另存为预设"- sub: "预设会保存下面勾选的部分;应用时只覆盖勾选的部分"- dialogWidth: 620- property string presetName: ""+ readonly property string kindLabel: veyra.nodeMode === 1 ? "节点" : "列表"+ title: "另存为" + kindLabel + "预设"+ sub: kindLabel + "预设和" + (veyra.nodeMode === 1 ? "列表" : "节点") + "预设分开保存,互不影响;应用时只覆盖勾选的部分"+ dialogWidth: 580+ // presets.js currentItems: what the chain holds right now, one row per+ // node, with the parameters that matter.+ function nodeSummary(n) {+ switch (n.type) {+ case "sr": return veyra.srTargetLabel + (veyra.videoSrQuality > 0 ? " · 质量 " + veyra.videoSrQuality : "")+ case "nr": { const l = veyra.nrLayers.find(x => x.index === n.index); return l ? "强度 " + l.intensity.toFixed(2) : "NR" }+ case "video-hdr": return "峰值 " + (veyra.videoHdrParams.peakNits || 1000) + " nits"+ case "protection": return veyra.protectionRegions.length + " / 4 个区域"+ case "color": return "调色参数"+ case "frame-generation": return veyra.fgMultiplier + "X · " + (veyra.fgBackendName === "xess" ? "Intel XeSS" : "DLSS")+ }+ return ""+ }+ function nodeLabel(n) {+ if (n.type !== "nr") return n.label+ let k = 0+ for (const m of veyra.chain) { if (m.type === "nr") ++k; if (m.index === n.index) break }+ return "NR 层 " + k+ }+ readonly property bool nameTaken: presetNameField.text.trim().length > 0 &&+ veyra.presets.some(p => p.name === presetNameField.text.trim())property var chosen: ({})+ property var parts: []+ function resetForOpen() {+ const current = veyra.presetSaveParts+ const selected = {}+ for (const part of current) selected[part.id] = part.meaningful === true+ parts = current+ chosen = selected+ presetNameField.text = ""+ saveNote.text = ""+ saveAsDefault.checked = false+ }actions: [{ label: "取消" },- { label: "保存", primary: true }+ { label: "保存预设", primary: true, icon: "check" }]onActionTriggered: label => {- if (label !== "保存") { host.close(); return }- if (presetName.length === 0) { saveNote.text = "预设需要一个名字"; return }+ if (label !== "保存预设") { host.close(); return }+ const name = presetNameField.text.trim()+ if (name.length === 0) { saveNote.text = "预设需要一个名字"; return }let mask = 0- for (const part of veyra.presetSaveParts) {- if (chosen[part.id] === true) mask |= (1 << ["chain","color","fg","audio"].indexOf(part.id))+ const ids = ["chain", "color", "fg", "audio"]+ for (const part of parts) {+ const bit = ids.indexOf(part.id)+ if (bit >= 0 && chosen[part.id] === true) mask |= (1 << bit)+ }+ if (mask === 0) { saveNote.text = "至少选择一项内容"; return }+ if (veyra.savePresetAs(name, mask, veyra.nodeMode === 1)) {+ if (saveAsDefault.checked) {+ const saved = veyra.presets.find(p => p.name === name && p.nodeMode === (veyra.nodeMode === 1))+ if (saved) veyra.setDefaultPreset(saved.index)+ }+ host.close()}- if (veyra.savePresetAs(presetName, mask, false)) host.close()else saveNote.text = "保存失败:名称可能已存在"}- DSection { text: "将要保存的内容" }+ // .namebox: the name first, with a live note under it.+ ColumnLayout {+ Layout.fillWidth: true+ Layout.topMargin: 4+ spacing: 6+ Text { text: "预设名称"; color: Theme.t2; font.family: Theme.fontUi; font.pixelSize: 12 }+ VTextField {+ id: presetNameField+ objectName: "preset-name"+ Layout.fillWidth: true+ placeholder: "例如:夜间游戏"+ }+ Text {+ objectName: "preset-name-hint"+ Layout.fillWidth: true+ text: saveDialog.nameTaken ? "已有同名预设,换一个名称才能保存"+ : presetNameField.text.trim().length > 0 ? "可以保存"+ : "名称会显示在极简模式和导出页的预设菜单里"+ color: saveDialog.nameTaken ? Theme.warn : Theme.ok+ font.family: Theme.fontUi+ font.pixelSize: 11+ }+ }+ DSection { text: "将保存的内容 · 当前正在使用的" + saveDialog.kindLabel + "设置" }+ // .savelist: every node, a green dot when it runs; the list dims when+ // the effect chain itself is not part of the preset.+ ColumnLayout {+ objectName: "preset-save-list"+ Layout.fillWidth: true+ spacing: 4+ opacity: saveDialog.chosen["chain"] === true ? 1 : 0.45+ Behavior on opacity { NumberAnimation { duration: Theme.d(200) } }+ Repeater {+ model: saveDialog.shown ? veyra.chain : []+ delegate: Rectangle {+ required property var modelData+ Layout.fillWidth: true+ implicitHeight: 34+ radius: 8+ color: Qt.rgba(1, 1, 1, 0.03)+ RowLayout {+ anchors.fill: parent+ anchors.leftMargin: 10+ anchors.rightMargin: 10+ spacing: 10+ Rectangle {+ implicitWidth: 7; implicitHeight: 7; radius: 3.5+ color: modelData.enabled ? Theme.ok : Qt.rgba(1, 1, 1, 0.25)+ }+ Text {+ Layout.preferredWidth: 110+ text: saveDialog.nodeLabel(modelData)+ color: modelData.enabled ? Theme.t1 : Theme.t3+ font.family: Theme.fontUi; font.pixelSize: 12+ font.weight: Font.DemiBold; font.variableAxes: Theme.axesDemiBold+ elide: Text.ElideRight+ }+ Text {+ Layout.fillWidth: true+ text: saveDialog.nodeSummary(modelData)+ color: Theme.t3+ font.family: Theme.fontUi; font.pixelSize: 11+ elide: Text.ElideRight+ }+ VTag { visible: !modelData.enabled; text: "已关闭" }+ }+ }+ }+ }+ DSection { text: "选项" }DGroup {Repeater {- model: veyra.presetSaveParts+ model: saveDialog.shown ? saveDialog.parts : []delegate: VRow {required property var modelData- label: modelData.label+ label: "包含" + modelData.labelhint: modelData.summaryVSwitch {+ objectName: "preset-part-" + modelData.id// A part at its default is still offered, but starts off: a// preset that stored nothing would be a surprise.- checked: modelData.meaningful- onToggled: {+ checked: saveDialog.chosen[modelData.id] === true+ onToggled: checked => {const c = Object.assign({}, saveDialog.chosen)c[modelData.id] = checkedsaveDialog.chosen = c@@ -475,15 +1205,15 @@ Item {}}}- }- DSection { text: "名称" }- VTextField {- Layout.fillWidth: true- placeholder: "例如:夜间游戏"- onEdited: text => saveDialog.presetName = text+ VRow {+ label: "保存后设为启动默认"+ hint: "下次启动软件时自动应用这个预设"+ VSwitch { id: saveAsDefault; objectName: "preset-save-default"; checked: false }+ }}Text {id: saveNote+ objectName: "preset-save-error"Layout.fillWidth: trueLayout.topMargin: 6text: ""@@ -496,48 +1226,120 @@ Item {// --- 管理预设 ---------------------------------------------------------DLayer {+ id: manageDialogkey: "manage"glyph: "settings"title: "管理预设"- sub: "内置预设可以复制,不能改名或删除"+ sub: "导出页和极简模式都从这里的预设中选择"dialogWidth: 620+ property string mode: "list"+ property string feedback: ""+ property bool feedbackError: false+ function runAction(action, index, name) {+ let ok = false+ if (action === "rename") ok = veyra.renamePreset(index, name)+ else if (action === "duplicate") ok = veyra.duplicatePreset(index)+ else if (action === "delete") ok = veyra.deletePreset(index)+ else if (action === "default") ok = veyra.setDefaultPreset(index)+ feedbackError = !ok+ if (action === "rename")+ feedback = ok ? "预设已改名" : "改名失败:名称不能为空、超过48字或与已有预设重复"+ else if (action === "duplicate")+ feedback = ok ? "预设已复制" : "复制失败:预设数量可能已达上限"+ else if (action === "delete")+ feedback = ok ? "预设已删除" : "删除预设失败"+ else if (action === "default")+ feedback = ok ? (index < 0 ? "已取消启动默认预设" : "已设为启动默认预设") : "启动默认预设保存失败"+ return ok+ }actions: [{ label: "完成", primary: true }]onActionTriggered: host.close()ColumnLayout {Layout.fillWidth: true- spacing: 6+ spacing: 8+ // presets.js manage: the mode toggle, then 导入 / 导出 on the right.+ RowLayout {+ Layout.fillWidth: true+ spacing: 8+ VSeg {+ objectName: "preset-manage-mode"+ options: [{ id: "list", label: "列表预设" }, { id: "node", label: "节点预设" }]+ current: manageDialog.mode+ onPicked: mode => { manageDialog.mode = mode; manageDialog.feedback = "" }+ }+ Item { Layout.fillWidth: true }+ VButton { objectName: "preset-import"; ghost: true; iconName: "import"; text: "导入"; onClicked: veyra.importPresetDialog() }+ VButton {+ id: presetExportBtn+ objectName: "preset-export"+ ghost: true; iconName: "upload"; text: "导出"+ enabled: presetRows.count > 0+ onClicked: presetExportMenu.openAt(presetExportBtn, "down")+ }+ }Text {- visible: veyra.presets.length === 0- text: "还没有保存过预设。"+ visible: presetRows.count === 0+ text: "这个模式还没有预设。"color: Theme.t3font.family: Theme.fontUifont.pixelSize: Theme.fsSmall}Repeater {- model: veyra.presets+ id: presetRows+ model: manageDialog.shown+ ? veyra.presets.filter(p => p.nodeMode === (manageDialog.mode === "node")) : []delegate: Rectangle {+ id: presetRowrequired property var modelData+ objectName: "preset-row-" + modelData.indexLayout.fillWidth: true- implicitHeight: 46+ implicitHeight: 54radius: 12color: Theme.card2border.width: 1- border.color: veyra.defaultPresetIndex === modelData.index ? Theme.accent : Theme.stroke+ border.color: Theme.stroke+ readonly property bool isDefault: veyra.defaultPresetIndex === modelData.index+ // .prow.bye (M41): shrink and fade over .25s, then delete.+ property real motionS: 1+ scale: motionS+ ParallelAnimation {+ id: rowBye+ NumberAnimation { target: presetRow; property: "motionS"; to: 0.9; duration: Theme.d(250); easing.bezierCurve: Theme.easeOut }+ NumberAnimation { target: presetRow; property: "opacity"; to: 0; duration: Theme.d(250); easing.bezierCurve: Theme.easeOut }+ onFinished: manageDialog.runAction("delete", presetRow.modelData.index)+ }+ function remove() {+ if (Theme.d(250) <= 0) manageDialog.runAction("delete", modelData.index)+ else rowBye.restart()+ }RowLayout {anchors.fill: parentanchors.leftMargin: 10anchors.rightMargin: 8spacing: 8+ // .pico+ Rectangle {+ implicitWidth: 30; implicitHeight: 30; radius: 9+ color: Qt.rgba(1, 1, 1, 0.05)+ VIcon { anchors.centerIn: parent; name: modelData.nodeMode ? "nodes" : "layers"; size: 14; color: Theme.t2 }+ }ColumnLayout {Layout.fillWidth: truespacing: 2- Text {+ VTextField {+ id: presetNameEdit+ objectName: "preset-rename-" + modelData.index+ Layout.fillWidth: true+ enabled: !modelData.builtintext: modelData.name- color: Theme.t1- font.family: Theme.fontUi- font.pixelSize: Theme.fsBody- elide: Text.ElideRight+ onEdited: name => {+ const trimmed = name.trim()+ if (trimmed === modelData.name) return+ if (!manageDialog.runAction("rename", modelData.index, trimmed)) {+ presetNameEdit.text = modelData.name+ }+ }}Text {Layout.fillWidth: true@@ -549,28 +1351,47 @@ Item {elide: Text.ElideRight}}- VTag { visible: modelData.builtin; text: "内置" }- VTag { visible: veyra.defaultPresetIndex === modelData.index; kind: "acc"; text: "启动默认" }+ VTag { objectName: "preset-default-tag-" + modelData.index; visible: presetRow.isDefault; kind: "acc"; text: "启动默认" }VButton {- ghost: true- text: "复制"- onClicked: veyra.duplicatePreset(modelData.index)+ objectName: "preset-default-" + modelData.index+ icon: true; ghost: true; iconName: "home"+ tip: presetRow.isDefault ? "取消启动默认" : "设为启动默认"+ onClicked: manageDialog.runAction("default", presetRow.isDefault ? -1 : modelData.index)}VButton {- ghost: true- text: "设为默认"- visible: !modelData.builtin- onClicked: veyra.setDefaultPreset(modelData.index)+ objectName: "preset-duplicate-" + modelData.index+ icon: true; ghost: true; iconName: "dup"+ tip: "复制"+ onClicked: manageDialog.runAction("duplicate", modelData.index)}VButton {- ghost: true- text: "删除"- visible: !modelData.builtin- onClicked: veyra.deletePreset(modelData.index)+ objectName: "preset-delete-" + modelData.index+ icon: true; ghost: true; iconName: "trash"+ tip: "删除"+ enabled: !modelData.builtin+ onClicked: presetRow.remove()}}}}+ VMenu {+ id: presetExportMenu+ objectName: "preset-export-menu"+ title: "导出预设"+ items: veyra.presets.filter(p => p.nodeMode === (manageDialog.mode === "node"))+ .map(p => ({ label: p.name, note: p.note, icon: "upload", preset: p.index }))+ onPicked: (i, o) => veyra.exportPresetDialog(o.preset)+ }+ Text {+ objectName: "preset-manage-feedback"+ Layout.fillWidth: true+ visible: manageDialog.feedback.length > 0+ text: manageDialog.feedback+ color: manageDialog.feedbackError ? Theme.warn : Theme.t2+ font.family: Theme.fontUi+ font.pixelSize: Theme.fsSmall+ wrapMode: Text.WordWrap+ }}}diff --git a/qml/Veyra/ExportPage.qml b/qml/Veyra/ExportPage.qmlindex b712bbb7..293b5edb 100644--- a/qml/Veyra/ExportPage.qml+++ b/qml/Veyra/ExportPage.qml@@ -15,6 +15,88 @@ import QtQuick.LayoutsVPage {id: rootsignal requestPage(string page)+ // pages-b.js 类型: 视频 (the encoder settings) or 图片 (frame / batch).+ property string exportKind: "video"+ readonly property var rows: veyra.exportItems+ // The playing file is the first row unless the queue already carries it.+ readonly property bool currentListed: rows.some(r => r.current)+ function stateText(r) {+ switch (r.state) {+ case "running": return "导出中 " + (r.progress * 100).toFixed(0) + "%"+ case "paused": return "已暂停 " + (r.progress * 100).toFixed(0) + "%"+ case "queued": return "排队中"+ case "done": return "已完成"+ case "failed": return "失败" + (r.note.length > 0 ? ":" + r.note : "")+ case "cancelled": return "已取消"+ }+ return r.state+ }+ // .qitem: thumbnail, name, what it is / where it stands, progress.+ component QueueItem: Rectangle {+ id: qi+ property string thumb: ""+ property string name: ""+ property string meta: ""+ property real progress: 0+ property bool showProgress: false+ property bool selected: false+ property bool failed: false+ Layout.fillWidth: true+ implicitHeight: 56+ radius: 10+ color: selected ? Qt.rgba(1, 1, 1, 0.06) : qiHover.hovered ? Qt.rgba(1, 1, 1, 0.04) : "transparent"+ border.width: 1+ border.color: selected ? Theme.stroke2 : "transparent"+ HoverHandler { id: qiHover }+ RowLayout {+ anchors.fill: parent+ anchors.margins: 7+ spacing: 10+ Rectangle {+ implicitWidth: 64; implicitHeight: 40; radius: 7+ color: Theme.videoBlack+ clip: true+ Image {+ objectName: qi.objectName + "-image"+ anchors.fill: parent+ fillMode: Image.PreserveAspectCrop+ asynchronous: true+ source: qi.thumb+ }+ }+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 2+ Text {+ Layout.fillWidth: true+ text: qi.name+ color: Theme.t1+ font.family: Theme.fontUi; font.pixelSize: 12; font.weight: Font.Medium+ elide: Text.ElideMiddle+ }+ Text {+ Layout.fillWidth: true+ text: qi.meta+ color: qi.failed ? Theme.err : Theme.t3+ font.family: Theme.fontUi; font.pixelSize: 11+ elide: Text.ElideRight+ }+ Rectangle {+ visible: qi.showProgress+ Layout.fillWidth: true+ implicitHeight: 3+ radius: 9+ color: Qt.rgba(1, 1, 1, 0.08)+ Rectangle {+ width: parent.width * Math.max(0, Math.min(1, qi.progress))+ height: parent.height; radius: 9+ color: Theme.accent+ Behavior on width { NumberAnimation { duration: Theme.d(300) } }+ }+ }+ }+ }+ }// --- header -----------------------------------------------------------RowLayout {@@ -33,7 +115,7 @@ VPage {font.pixelSize: Theme.fsBody}Item { Layout.fillWidth: true }- VButton { text: "添加文件"; onClicked: veyra.addExportFilesDialog() }+ VButton { iconName: "plus"; text: "添加文件"; onClicked: veyra.addExportFilesDialog() }}// --- left column: what is being exported ------------------------------@@ -55,21 +137,51 @@ VPage {anchors.fill: parentanchors.margins: 12spacing: 8- VEyebrow { text: "导出内容" }- Text {+ RowLayout {Layout.fillWidth: true- text: veyra.hasSource ? veyra.sourceName : "未打开文件"- color: veyra.hasSource ? Theme.t1 : Theme.t3- font.family: Theme.fontUi- font.pixelSize: Theme.fsBody- elide: Text.ElideMiddle+ VEyebrow { text: "队列 · " + (root.rows.length + (root.currentListed || !veyra.hasSource ? 0 : 1)) }+ Item { Layout.fillWidth: true }+ VButton {+ objectName: "export-clear-finished"+ visible: root.rows.some(r => r.state !== "running" && r.state !== "queued" && r.state !== "paused")+ ghost: true; implicitHeight: 24; text: "清除已结束"+ onClicked: veyra.clearFinishedExportItems()+ }+ }+ // The playing file, first, unless the queue already holds it.+ QueueItem {+ objectName: "export-item-thumb"+ visible: veyra.hasSource && veyra.duration > 0 && !veyra.isCapture && !root.currentListed+ selected: true+ thumb: visible ? "image://veyra-thumb/" + veyra.thumbnailGeneration + "/" + Math.round(veyra.duration * 100) : ""+ name: veyra.sourceName+ meta: veyra.sourceRateText + " · " + veyra.durationText + " · 待导出"}Text {+ visible: !veyra.hasSource && root.rows.length === 0Layout.fillWidth: true- text: veyra.hasSource ? veyra.sourceSummary : ""+ text: "未打开文件;可用“添加文件”直接排队"color: Theme.t3- font.family: Theme.fontMono- font.pixelSize: Theme.fsSmall+ font.family: Theme.fontUi+ font.pixelSize: 11+ wrapMode: Text.WordWrap+ }+ Repeater {+ model: root.rows+ delegate: QueueItem {+ required property var modelData+ required property int index+ objectName: "export-queue-row-" + index+ selected: modelData.current+ thumb: modelData.current+ ? "image://veyra-thumb/" + veyra.thumbnailGeneration + "/" + Math.round(veyra.duration * 100)+ : veyra.fileThumbnailId(modelData.input, 10)+ name: modelData.name+ meta: root.stateText(modelData)+ failed: modelData.state === "failed"+ showProgress: modelData.state !== "queued"+ progress: modelData.progress+ }}Rectangle { Layout.fillWidth: true; implicitHeight: 1; color: Theme.stroke }Text {@@ -80,6 +192,16 @@ VPage {font.family: Theme.fontMonofont.pixelSize: 11}+ Text {+ objectName: "export-queue-failure"+ visible: veyra.exportQueueFailures > 0+ Layout.fillWidth: true+ text: veyra.exportQueueFailures + " 项未能开始 · 最近:" + veyra.exportQueueFailure+ color: Theme.err+ font.family: Theme.fontUi+ font.pixelSize: 11+ wrapMode: Text.WordWrap+ }Text {Layout.fillWidth: truetext: "按加入顺序逐项导出;每项独立保留 partial。"@@ -114,7 +236,56 @@ VPage {VH3 { text: "输出设置" }+ VRow {+ label: "类型"+ VSeg {+ objectName: "export-kind"+ options: [{ id: "video", label: "视频" }, { id: "image", label: "图片" }]+ current: root.exportKind+ onPicked: id => root.exportKind = id+ }+ }++ // 图片: each image runs through the player's list chain and the engine's+ // own frame save (PNG, JXR for HDR output).+ VGroup {+ visible: root.exportKind === "image"+ VRow {+ label: "当前画面"+ hint: "保存正在播放的这一帧"+ hintBelow: true+ VButton {+ objectName: "export-frame"+ text: "导出当前画面…"+ enabled: veyra.hasSource && !veyra.imageBatchActive+ onClicked: veyra.saveFrameDialog()+ }+ }+ VRow {+ label: "批量图片"+ hint: "选择多张图片,按当前列表链逐张处理"+ hintBelow: true+ VButton {+ objectName: "export-images"+ text: veyra.imageBatchActive ? "取消批量" : "批量处理图片…"+ onClicked: veyra.imageBatchActive ? veyra.cancelImageBatch() : veyra.exportImagesDialog()+ }+ }+ Text {+ objectName: "image-batch-status"+ visible: veyra.imageBatchStatus.length > 0+ Layout.fillWidth: true+ Layout.bottomMargin: 8+ text: veyra.imageBatchStatus+ color: veyra.imageBatchFailures > 0 ? Theme.warn : Theme.t3+ font.family: Theme.fontUi+ font.pixelSize: 11+ wrapMode: Text.WordWrap+ }+ }+VGroup {+ visible: root.exportKind === "video"VRow {label: "编码"VSeg {@@ -126,12 +297,16 @@ VPage {VRow {label: "分辨率"hint: "跟随所选预设,或指定输出尺寸"+ hintBelow: trueVSeg {options: [{ id: "-1", label: "预设" },{ id: "0", label: "源" },{ id: "1", label: "2K" },{ id: "2", label: "4K" },+ { id: "4", label: "5K" },+ { id: "5", label: "6K" },+ { id: "6", label: "7K" },{ id: "3", label: "8K" }]current: String(veyra.exportSrTargetIndex)@@ -141,12 +316,27 @@ VPage {VRow {label: "码率"value: veyra.exportBitrateMbps > 0 ? veyra.exportBitrateMbps + " Mbps" : "恒定质量"- VSlider {- implicitWidth: 110- from: 0- to: 200- value: veyra.exportBitrateMbps- onMoved: veyra.exportBitrateMbps = Math.round(value)+ RowLayout {+ spacing: 6+ VSlider {+ implicitWidth: 90+ from: 0+ to: 200+ value: Math.min(200, veyra.exportBitrateMbps)+ onMoved: veyra.exportBitrateMbps = Math.round(value)+ }+ // Any value 0–2000 Mbps can be typed (0 = 恒定质量).+ DialogHost.VTextField {+ id: bitrateField+ objectName: "export-bitrate-field"+ implicitWidth: 56+ text: String(veyra.exportBitrateMbps)+ onEdited: value => {+ const v = Math.round(Number(value))+ if (isFinite(v)) veyra.exportBitrateMbps = Math.max(0, Math.min(2000, v))+ bitrateField.text = String(veyra.exportBitrateMbps)+ }+ }}}VRow {@@ -160,19 +350,43 @@ VPage {}VGroup {+ visible: root.exportKind === "video"VRow {label: "增强预设"hint: "节点预设待执行器接入"+ hintBelow: trueVSelect {value: veyra.exportPresetNameoptions: veyra.presetChoicesonPicked: id => veyra.selectExportPreset(parseInt(id))}}+ // The export copies the audio track that is playing, untouched.+ VRow {+ label: "音轨"+ visible: veyra.hasSource && !veyra.isCapture+ hint: veyra.audioTracks.length > 0 ? "原样复制,不重新编码;与播放时选的音轨相同" : (veyra.hasSource ? "这个文件没有音轨" : "")+ hintBelow: true+ VSelect {+ objectName: "export-audio-track"+ implicitWidth: 170+ visible: veyra.audioTracks.length > 0+ readonly property var tracks: veyra.audioTracks.map(t => ({ id: String(t.index), label: t.label }))+ options: tracks+ value: (tracks.find(t => Number(t.id) === veyra.selectedAudioTrack) || tracks[0] || { label: "默认" }).label+ onPicked: id => veyra.selectedAudioTrack = Number(id)+ }+ }+ VRow {+ label: "预计大小"+ hint: veyra.exportSizeEstimate+ visible: veyra.exportSizeEstimate.length > 0+ }}// What the export will run with. Frozen when it starts.Rectangle {+ visible: root.exportKind === "video"Layout.fillWidth: trueimplicitHeight: pinfo.implicitHeight + 16radius: 9@@ -201,21 +415,37 @@ VPage {}}+ // pages-b.js 保存到: a field with the path and a folder icon.VRow {+ visible: root.exportKind === "video"label: "保存到"- VButton {- text: veyra.exportTarget.length > 0 ? "重新选择…" : "选择…"- onClicked: veyra.chooseExportPath()+ Rectangle {+ objectName: "export-target"+ implicitWidth: 200+ implicitHeight: Theme.ctlHeight+ radius: Theme.rCtl+ color: targetHover.hovered ? Theme.card3 : Theme.card2+ border.width: 1+ border.color: Theme.stroke2+ RowLayout {+ anchors.fill: parent+ anchors.leftMargin: 10+ anchors.rightMargin: 8+ spacing: 6+ Text {+ Layout.fillWidth: true+ text: veyra.exportTarget.length > 0 ? veyra.exportTarget : "选择输出位置…"+ color: veyra.exportTarget.length > 0 ? Theme.t1 : Theme.t3+ font.family: Theme.fontUi+ font.pixelSize: 12+ elide: Text.ElideMiddle+ }+ VIcon { name: "folder"; size: 14; color: Theme.t3 }+ }+ HoverHandler { id: targetHover; cursorShape: Qt.PointingHandCursor }+ TapHandler { onTapped: veyra.chooseExportPath() }}}- Text {- Layout.fillWidth: true- text: veyra.exportTarget.length > 0 ? veyra.exportTarget : "未选择输出位置"- color: Theme.t3- font.family: Theme.fontUi- font.pixelSize: 11- elide: Text.ElideMiddle- }Item { Layout.fillHeight: true }@@ -224,6 +454,22 @@ VPage {Layout.fillWidth: truespacing: 8+ // pages-b.js .go: "预计 … · 约 …" over the progress bar.+ Text {+ objectName: "export-estimate"+ Layout.fillWidth: true+ visible: root.exportKind === "video" && text.length > 0+ // Only real figures: a remaining time while exporting, a size when a+ // bitrate fixes it (constant quality has no size until it runs).+ readonly property bool sized: veyra.exportBitrateMbps > 0 && veyra.exportSizeEstimate.length > 0+ text: veyra.exportRunning && veyra.exportEtaSeconds > 0+ ? "预计还需 " + veyra.formatTime(veyra.exportEtaSeconds) + (sized ? " · " + veyra.exportSizeEstimate : "")+ : sized ? "预计大小 " + veyra.exportSizeEstimate + " · 耗时开始后估算" : ""+ color: Theme.t3+ font.family: Theme.fontUi+ font.pixelSize: 12+ elide: Text.ElideRight+ }RowLayout {Layout.fillWidth: trueText {@@ -273,8 +519,12 @@ VPage {Layout.fillWidth: truespacing: 8VButton {+ objectName: "export-start"Layout.fillWidth: true+ implicitHeight: 42primary: !veyra.exportRunning+ enabled: root.exportKind === "video"+ iconName: veyra.exportRunning ? (veyra.exportPaused ? "upload" : "pause") : "upload"text: veyra.exportRunning ? (veyra.exportPaused ? "继续导出" : "暂停导出") : "开始导出"onClicked: veyra.exportRunning ? veyra.pauseExport(!veyra.exportPaused): veyra.startExport()@@ -310,6 +560,25 @@ VPage {id: videoAreaobjectName: "videoArea"anchors.fill: parent+ // 分屏对比 on the export preview: drag the divider across the picture.+ MouseArea {+ objectName: "export-compare-drag"+ anchors.fill: parent+ enabled: veyra.compareMode === 2+ visible: enabled+ cursorShape: Qt.SplitHCursor+ preventStealing: true+ function drag(mouse) {+ const content = videoArea.Window.contentItem+ let host = null+ for (let i = 0; content && i < content.children.length; ++i)+ if (content.children[i].objectName === "videoHost") host = content.children[i]+ const p = videoArea.mapToItem(content, mouse.x, mouse.y)+ veyra.setCompareSplitAt(host && host.width > 0 ? (p.x - host.x) / host.width : mouse.x / width)+ }+ onPressed: mouse => drag(mouse)+ onPositionChanged: mouse => { if (pressed) drag(mouse) }+ }Text {anchors.centerIn: parentvisible: !veyra.hasSource@@ -318,6 +587,24 @@ VPage {font.family: Theme.fontUifont.pixelSize: Theme.fsH3}+ // .exp .compare .lb: which side is which. Each label is cut out of the+ // native video (videoCover) so it shows above the picture.+ Repeater {+ model: veyra.compareMode === 2 && veyra.hasSource ? [{ t: "原画", left: true }, { t: "增强后(预览)", left: false }] : []+ delegate: Rectangle {+ required property var modelData+ objectName: "export-compare-label-" + (modelData.left ? "left" : "right")+ readonly property bool videoCover: true+ property real coverRadius: 6+ x: modelData.left ? 10 : videoArea.width - width - 10+ y: 10+ width: lb.implicitWidth + 16+ height: lb.implicitHeight + 8+ radius: 6+ color: Qt.rgba(0, 0, 0, 0.6)+ Text { id: lb; anchors.centerIn: parent; text: modelData.t; color: "#FFFFFF"; font.family: Theme.fontUi; font.pixelSize: 11 }+ }+ }}}@@ -332,39 +619,152 @@ VPage {color: Theme.cardborder.width: 1border.color: Theme.stroke- RowLayout {+ // 入点 / 出点 (user request 2026-09-29): play or scrub to a spot, then+ // mark it. One timeline shows the playhead, the kept range and both marks.+ readonly property bool editable: veyra.hasSource && !veyra.exportRunning && veyra.duration > 0+ readonly property real inAt: veyra.exportTrimStart+ readonly property real outAt: veyra.exportTrimEnd > 0 ? veyra.exportTrimEnd : veyra.duration+ function frac(t) { return veyra.duration > 0 ? Math.max(0, Math.min(1, t / veyra.duration)) : 0 }+ function markIn() {+ if (!editable) return+ const t = veyra.position+ if (t >= outAt - 0.05) { veyra.exportTrimEnd = 0 }+ veyra.exportTrimStart = t+ }+ function markOut() {+ if (!editable) return+ const t = veyra.position+ if (t <= inAt + 0.05) { veyra.exportTrimStart = 0 }+ veyra.exportTrimEnd = t >= veyra.duration - 0.05 ? 0 : t+ }+ Shortcut { sequence: "I"; enabled: trimCard.visible && trimCard.editable && root.visible; onActivated: trimCard.markIn() }+ Shortcut { sequence: "O"; enabled: trimCard.visible && trimCard.editable && root.visible; onActivated: trimCard.markOut() }+ ColumnLayout {anchors.fill: parentanchors.margins: 12- spacing: 6- Text {- text: "导出范围"- color: Theme.t2- font.family: Theme.fontUi- font.pixelSize: Theme.fsBody- }- Text {- text: veyra.formatTime(veyra.exportTrimStart) + " — "- + veyra.formatTime(veyra.exportTrimEnd > 0 ? veyra.exportTrimEnd : veyra.duration)- color: Theme.t1- font.family: Theme.fontMono- font.pixelSize: Theme.fsSmall- }- Item { Layout.fillWidth: true }- VSlider {+ spacing: 8+ Item {+ id: timeline+ objectName: "export-timeline"Layout.fillWidth: true- from: 0- to: Math.max(0.001, veyra.duration)- value: veyra.exportTrimStart- enabledControl: veyra.hasSource && !veyra.exportRunning && veyra.duration > 0- onMoved: veyra.exportTrimStart = value+ Layout.preferredHeight: 30+ property bool scrubbing: false+ property real scrubFrac: 0+ readonly property real head: scrubbing ? scrubFrac : trimCard.frac(veyra.position)+ // Film strip: frames along the source (seek-preview decoder).+ Row {+ objectName: "export-filmstrip"+ anchors.fill: parent+ visible: veyra.hasSource && veyra.duration > 0 && !veyra.isCapture+ opacity: 0.55+ clip: true+ readonly property int count: Math.max(1, Math.floor(width / 46))+ Repeater {+ model: parent.visible ? parent.count : 0+ delegate: Image {+ required property int index+ width: timeline.width / parent.count+ height: timeline.height+ fillMode: Image.PreserveAspectCrop+ asynchronous: true+ sourceSize.height: 48+ // 2-second buckets, the same keys the seek preview uses.+ source: "image://veyra-thumb/" + veyra.thumbnailGeneration + "/"+ + Math.floor((index + 0.5) / parent.count * veyra.duration / 2) * 2000+ }+ }+ }+ Rectangle {+ id: rail+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width; height: 6; radius: 3+ color: Qt.rgba(1, 1, 1, 0.10)+ }+ // The kept range.+ Rectangle {+ objectName: "export-range"+ anchors.verticalCenter: rail.verticalCenter+ x: trimCard.frac(trimCard.inAt) * timeline.width+ width: Math.max(2, (trimCard.frac(trimCard.outAt) - trimCard.frac(trimCard.inAt)) * timeline.width)+ height: 6; radius: 3+ color: Theme.accent+ opacity: 0.55+ }+ // In and out marks: brackets that stand above the rail.+ Repeater {+ model: [{ at: trimCard.inAt, isIn: true }, { at: trimCard.outAt, isIn: false }]+ delegate: Rectangle {+ required property var modelData+ x: trimCard.frac(modelData.at) * timeline.width - (modelData.isIn ? 0 : width)+ y: 0+ width: 3; height: timeline.height+ radius: 1+ color: Theme.accent+ Rectangle {+ y: 0; x: modelData.isIn ? 0 : -5+ width: 8; height: 3; radius: 1; color: Theme.accent+ }+ Rectangle {+ y: parent.height - 3; x: modelData.isIn ? 0 : -5+ width: 8; height: 3; radius: 1; color: Theme.accent+ }+ }+ }+ // Playhead.+ Rectangle {+ objectName: "export-playhead"+ width: 12; height: 12; radius: 6+ color: "#FFFFFF"+ anchors.verticalCenter: rail.verticalCenter+ x: timeline.head * timeline.width - width / 2+ visible: veyra.duration > 0+ }+ Timer {+ id: exportScrub+ interval: 120+ onTriggered: if (timeline.scrubbing) veyra.seekTo(timeline.scrubFrac * veyra.duration)+ }+ MouseArea {+ anchors.fill: parent+ enabled: veyra.duration > 0 && !veyra.isCapture+ cursorShape: Qt.PointingHandCursor+ preventStealing: true+ function f(x) { return Math.max(0, Math.min(1, x / Math.max(1, timeline.width))) }+ onPressed: mouse => { timeline.scrubFrac = f(mouse.x); timeline.scrubbing = true; exportScrub.start() }+ onPositionChanged: mouse => { if (timeline.scrubbing) { timeline.scrubFrac = f(mouse.x); if (!exportScrub.running) exportScrub.start() } }+ onReleased: mouse => { exportScrub.stop(); timeline.scrubbing = false; veyra.seekTo(f(mouse.x) * veyra.duration) }+ onCanceled: { exportScrub.stop(); timeline.scrubbing = false }+ }}- VSlider {+ RowLayout {Layout.fillWidth: true- from: 0- to: Math.max(0.001, veyra.duration)- value: veyra.exportTrimEnd > 0 ? veyra.exportTrimEnd : veyra.duration- enabledControl: veyra.hasSource && !veyra.exportRunning && veyra.duration > 0- onMoved: veyra.exportTrimEnd = value+ spacing: 8+ VButton { icon: true; ghost: true; iconName: (veyra.running && !veyra.paused) ? "pause" : "play"; onClicked: veyra.togglePlayPause() }+ Text {+ text: veyra.positionText+ color: Theme.t2; font.family: Theme.fontMono; font.pixelSize: Theme.fsSmall+ }+ Item { Layout.preferredWidth: 6 }+ VButton { objectName: "export-mark-in"; text: "设为入点 I"; enabled: trimCard.editable; onClicked: trimCard.markIn() }+ VButton { objectName: "export-mark-out"; text: "设为出点 O"; enabled: trimCard.editable; onClicked: trimCard.markOut() }+ VSeg {+ objectName: "export-compare"+ options: [{ id: "0", label: "增强" }, { id: "2", label: "分屏对比" }]+ current: veyra.compareMode === 2 ? "2" : "0"+ onPicked: id => veyra.compareMode = Number(id)+ }+ VButton {+ objectName: "export-mark-clear"+ text: "清除"; ghost: true+ enabled: trimCard.editable && (veyra.exportTrimStart > 0 || veyra.exportTrimEnd > 0)+ onClicked: { veyra.exportTrimStart = 0; veyra.exportTrimEnd = 0 }+ }+ Item { Layout.fillWidth: true }+ Text {+ text: "导出 " + veyra.formatTime(trimCard.inAt) + " — " + veyra.formatTime(trimCard.outAt)+ + "(" + veyra.formatTime(Math.max(0, trimCard.outAt - trimCard.inAt)) + ")"+ color: Theme.t1; font.family: Theme.fontMono; font.pixelSize: Theme.fsSmall+ }}}}diff --git a/qml/Veyra/FullscreenBar.qml b/qml/Veyra/FullscreenBar.qmlindex c4c3e219..66a673ff 100644--- a/qml/Veyra/FullscreenBar.qml+++ b/qml/Veyra/FullscreenBar.qml@@ -19,6 +19,7 @@ Window {required property Window ownerproperty bool shown: falsesignal requestPage(string page)+ signal requestDialog(string key)signal requestFullscreen()signal requestLock()// Pointer movement over the bar keeps the controls up (the main window cannot@@ -97,6 +98,7 @@ Window {transform: Translate { y: (win.cinema ? 0 : (1 - win.fade) * 30) + win.enterDy }scale: win.enterScaleonRequestPage: p => win.requestPage(p)+ onRequestDialog: k => win.requestDialog(k)onRequestFullscreen: win.requestFullscreen()onRequestLock: win.requestLock()HoverHandler {diff --git a/qml/Veyra/HomePage.qml b/qml/Veyra/HomePage.qmlindex 9f137e62..05c4b62a 100644--- a/qml/Veyra/HomePage.qml+++ b/qml/Veyra/HomePage.qml@@ -174,8 +174,11 @@ VPage {// the recorded session, and the row is absent when there is none.Rectangle {id: resume+ objectName: "home-resume"Layout.alignment: Qt.AlignHCenter- visible: veyra.hasCaptureSession+ // The last source actually used: capture card, PS5 or screen capture.+ readonly property var last: veyra.lastSource+ visible: last.kind !== undefinedimplicitWidth: 692implicitHeight: 54radius: 14@@ -194,7 +197,11 @@ VPage {Rectangle {implicitWidth: 34; implicitHeight: 34; radius: 10color: Theme.accentSoft- VIcon { anchors.centerIn: parent; name: "gamepad"; color: Theme.accent }+ VIcon {+ anchors.centerIn: parent+ name: resume.last.kind === "screen" ? "monitor" : resume.last.kind === "capture" ? "video" : "gamepad"+ color: Theme.accent+ }}ColumnLayout {Layout.fillWidth: true@@ -208,7 +215,7 @@ VPage {}Text {Layout.fillWidth: true- text: veyra.captureSessionSummary+ text: resume.last.summary || ""color: Theme.t2font.family: Theme.fontUifont.pixelSize: 12@@ -219,7 +226,7 @@ VPage {text: "开始"iconName: "play"primary: true- onClicked: veyra.resumeCaptureSession()+ onClicked: veyra.resumeLastSource()}}}diff --git a/qml/Veyra/Main.qml b/qml/Veyra/Main.qmlindex d77f7192..0d56cc38 100644--- a/qml/Veyra/Main.qml+++ b/qml/Veyra/Main.qml@@ -30,28 +30,53 @@ Window {// Page ids match the prototype's PAGES keys so a design screenshot and an// app screenshot can be compared under the same name.property string page: "home"+ // The node page splitter: height of its video card (picture + 40px bar).+ property real nodeVideoHeight: 330+ // Every navigation goes through here: "专业" means the node page while the+ // node configuration is active, so the dock never drops into the list UI.+ function goPage(p) {+ if (p === "pro" && veyra.nodeMode === 1) p = "node"+ page = p+ }// Test switches from the command line (main.cpp, G0.3); empty in normal use.readonly property var test: typeof vyTest !== "undefined" ? vyTest : ({})readonly property real testAspect: test.aspect !== undefined ? test.aspect : 0readonly property bool cinema: page === "min"+ // Maximized behaves like fullscreen for geometry: the screen owns the size,+ // so the cinema aspect rule must not fight the window manager.+ readonly property bool maximized: visibility === Window.Maximized+ readonly property bool screenSized: fullTarget || maximized+ function toggleMaximized() {+ if (fullscreen) return+ visibility = maximized ? Window.Windowed : Window.Maximized+ veyra.logUi("ui-window", "maximized=" + (visibility === Window.Maximized))+ }Binding { target: Theme; property: "reduced"; value: veyra.reducedMotion || root.test.reducedMotion === true }+ Binding { target: Theme; property: "accentName"; value: veyra.preferences.accent || "orange" }+ Binding { target: Theme; property: "backdropLevel"; value: veyra.preferences.backdrop !== undefined ? veyra.preferences.backdrop : 1 }// Cinema geometry: the main window ends at the picture. The independent pill// can extend below it without leaving an opaque strip in this window.- property real filmAspect: 2.39+ // 16:9 until a source reports its own shape: a PS5 / capture session has no+ // aspect while it connects, and 2.39 then left a thin black strip.+ property real filmAspect: 16 / 9+ readonly property real reportedAspect: veyra.previewAspect+ onReportedAspectChanged: if (reportedAspect < 0.2) fitToFilm(16 / 9)+ property string lastPage: "home"+ property real heightBeforeCinema: 0readonly property real pictureHeight: Math.round(width / filmAspect)function fitToFilm(aspect) {if (aspect > 0.2 && aspect < 5.0) filmAspect = aspect- if (cinema && !fullTarget) height = Math.round(pictureHeight)+ if (cinema && !screenSized) height = Math.round(pictureHeight)}// .vy.cine transition: height .7s var(--spring-soft)Behavior on height {- enabled: root.cinema && !root.fullTarget+ enabled: root.cinema && !root.screenSizedNumberAnimation { duration: Theme.d(700); easing.bezierCurve: Theme.springSoft }}onWidthChanged: {- if (cinema && !fullTarget) height = Math.round(pictureHeight)+ if (cinema && !screenSized) height = Math.round(pictureHeight)videoHost.syncRect()}// The window height animates towards the film's aspect, so the picture area has@@ -59,12 +84,27 @@ Window {// previous height and the picture sat inside black bars - exactly what cinema// mode exists to avoid.onHeightChanged: videoHost.syncRect()+ onMaximizedChanged: {+ if (!maximized && cinema && !fullTarget) height = Math.round(pictureHeight)+ videoHost.syncRect()+ }onPageChanged: {+ if (page === "node" && veyra.nodeMode !== 1) {+ veyra.nodeMode = 1+ if (veyra.nodeMode !== 1) { page = "pro"; return }+ }// Tell the bridge where the user is, so a command like "open a file" can// behave differently from home than from the professional page.if (veyra.currentPage !== page) veyra.currentPage = page- if (fullTarget) { /* the screen is the window */ }- else if (cinema) height = Math.round(pictureHeight)+ // Test the page itself: the cinema binding may not have caught up with+ // this change yet, and a stale value shrank the page after min instead.+ // Leaving 极简 gives the window back the height it had before (core.js+ // clears the cinema height on any other page).+ const wasCinema = lastPage === "min"+ lastPage = page+ if (screenSized) { /* the screen is the window */ }+ else if (page === "min") { if (!wasCinema) heightBeforeCinema = height; height = Math.round(pictureHeight) }+ else if (wasCinema && heightBeforeCinema >= 400) height = heightBeforeCinemaelse if (height < 600) height = 800// core.js app.go: the old page sinks (.22s) and the new one shows 150 ms// later with its [data-in] items rising. Reduced motion shows it at once.@@ -129,7 +169,7 @@ Window {function videoRect() {// Fullscreen is a video-only viewport (AppShell): the picture is the screen// and the controls float above it in their own window (FullscreenBar).- if (fullscreen && page !== "home" && page !== "set")+ if ((fullscreen || (maximized && page === "min")) && page !== "home" && page !== "set")return { x: 0, y: 0, width: width, height: height }switch (page) {case "min":@@ -144,8 +184,9 @@ Window {width: Math.max(1, width - 376 - 14 * 2 - 10 - 14),height: Math.max(1, height - 14 * 2 - 32 - 10 - 172 - 10 - 36) }case "node":- // .nodeview padding 14; .nv-top is a fixed 330px, minus its 40px bar.- return { x: 14, y: 14, width: Math.max(1, width - 28), height: 330 - 40 }+ // .nodeview padding 14; .nv-top (330px by default, the splitter under+ // it resizes it) minus its 40px bar.+ return { x: 14, y: 14, width: Math.max(1, width - 28), height: root.nodeVideoHeight - 40 }case "exp":// .exp grid: 250px 1fr 330px; the video is column 2 row 2.return { x: 14 + 250 + 10,@@ -165,52 +206,99 @@ Window {// In fullscreen the picture covers the page, and the native video window// passes the pointer through: a hidden page control must not take a click// meant for the picture.- visible: !root.fullscreen || root.page === "home" || root.page === "set"+ visible: !root.fullscreen || root.page === "home" || root.page === "set" || root.quickPanelShown// Each page is shown while current or while sinking out; the sinking one// takes no input (.page.leave { pointer-events: none }).- HomePage { pageId: "home"; onRequestPage: p => root.page = p }+ HomePage { pageId: "home"; onRequestPage: p => root.goPage(p) }MinimalPage {pageId: "min"- onRequestPage: p => root.page = p+ onRequestPage: p => root.goPage(p)onRequestAspect: aspect => { if (root.testAspect <= 0) root.fitToFilm(aspect) }onRequestFullscreen: root.toggleFullscreen()}ProPage {id: proPagepageId: "pro"- onRequestPage: p => root.page = p+ overlay: root.quickPanelShown+ onRequestFullscreen: root.toggleFullscreen()+ onRequestPage: p => root.goPage(p)onRequestDialog: key => dialogs.open(key)}- NodePage { pageId: "node"; onRequestPage: p => root.page = p }- ExportPage { pageId: "exp"; onRequestPage: p => root.page = p }- SettingsPage { pageId: "set"; onRequestPage: p => root.page = p }+ NodePage {+ pageId: "node"+ videoHeight: root.nodeVideoHeight+ onVideoHeightEdited: h => { root.nodeVideoHeight = h; videoHost.syncRect() }+ onRequestFullscreen: root.toggleFullscreen()+ onRequestPage: p => root.goPage(p)+ onRequestDialog: key => dialogs.open(key)+ onRequestInspector: (index, type) => {+ proPage.selectedEffect = index+ veyra.selectedNrLayer = index+ veyra.selectedColourLayer = index+ proPage.tab = type === "color" ? "color" : "quality"+ root.page = "pro"+ }+ }+ ExportPage { pageId: "exp"; onRequestPage: p => root.goPage(p) }+ SettingsPage { pageId: "set"; onRequestPage: p => root.goPage(p) }}// The five dialogs sit above the pages and below the dock's own tooltips.DialogHost {id: dialogsanchors.fill: parent- onStartCapture: {- if (veyra.captureDeviceId.length > 0) root.page = "min"- else toast.show("先选择一个采集设备", true)- }- onStartPs5: root.page = "min"- onStartScreen: {- if (veyra.screenTargetId.length > 0) root.page = "min"- else toast.show("先选择一个捕获目标", true)- }+ // The dialogs open the source through the bridge; show the picture.+ onStartCapture: if (root.page === "home") root.goPage("min")+ onStartPs5: if (root.page === "home") root.goPage("min")+ onStartScreen: if (root.page === "home") root.goPage("min")}// The dock floats above every page and retracts on its own.TopDock {id: dockanchors.horizontalCenter: parent.horizontalCenter- currentPage: root.page- pinned: root.test.dockPinned === true+ // The node page is the professional mode's node view.+ currentPage: root.page === "node" ? "pro" : root.page+ maximized: root.maximized+ pinned: root.test.dockPinned === true || veyra.preferences.dockPinned === truelocked: root.fullLockedforcedTip: root.test.tip !== undefined ? root.test.tip : ""opened: pinned- onRequestPage: p => root.page = p+ onRequestPage: p => root.goPage(p)+ onRequestMinimize: root.showMinimized()+ onRequestMaximize: root.toggleMaximized()+ onRequestClose: root.close()+ onRequestMove: if (!root.fullscreen) root.startSystemMove()+ }++ // Frameless window: the system resizes from 6px borders and 12px corners.+ Repeater {+ model: [+ { e: Qt.LeftEdge, c: Qt.SizeHorCursor }, { e: Qt.RightEdge, c: Qt.SizeHorCursor },+ { e: Qt.TopEdge, c: Qt.SizeVerCursor }, { e: Qt.BottomEdge, c: Qt.SizeVerCursor },+ { e: Qt.LeftEdge | Qt.TopEdge, c: Qt.SizeFDiagCursor }, { e: Qt.RightEdge | Qt.BottomEdge, c: Qt.SizeFDiagCursor },+ { e: Qt.RightEdge | Qt.TopEdge, c: Qt.SizeBDiagCursor }, { e: Qt.LeftEdge | Qt.BottomEdge, c: Qt.SizeBDiagCursor }+ ]+ delegate: MouseArea {+ required property var modelData+ readonly property bool l: (modelData.e & Qt.LeftEdge) !== 0+ readonly property bool r: (modelData.e & Qt.RightEdge) !== 0+ readonly property bool t: (modelData.e & Qt.TopEdge) !== 0+ readonly property bool b: (modelData.e & Qt.BottomEdge) !== 0+ readonly property bool corner: (l || r) && (t || b)+ objectName: "window-resize-" + modelData.e+ // Above the dialog layer (z 100): an open dialog must not stop the+ // window from being resized.+ z: 130+ enabled: !root.fullscreen && !root.maximized+ visible: enabled+ width: corner ? 12 : (l || r) ? 6 : root.width - 24+ height: corner ? 12 : (t || b) ? 6 : root.height - 24+ x: l ? 0 : r ? root.width - width : 12+ y: t ? 0 : b ? root.height - height : 12+ cursorShape: modelData.c+ onPressed: root.startSystemResize(modelData.e)+ }}// Drag and drop opens the file (AppShell WM_DROPFILES).@@ -231,11 +319,18 @@ Window {// cinema rule would otherwise snap that fullscreen size back to the film.property bool fullTarget: falseproperty bool fullLocked: false+ // Fullscreen quick-adjust panel (Home): the list mode's inspector on the left+ // of the picture, with the performance orbs. List mode only.+ property bool quickPanel: false+ readonly property bool quickPanelShown: fullscreen && quickPanel && page === "pro" && !fullLocked+ onQuickPanelShownChanged: veyra.logUi("ui-fullscreen", "quick panel shown=" + quickPanelShown)onFullscreenChanged: {+ veyra.setPresentationFullscreen(fullscreen)fullTarget = fullscreenif (!fullscreen) {fullLocked = false- if (cinema) height = Math.round(pictureHeight)+ quickPanel = false+ if (cinema && !maximized) height = Math.round(pictureHeight)}fullControls = truefullHide.restart()@@ -275,7 +370,7 @@ Window {// hides with the controls, as in AppShell.HoverHandler {id: pointerWatch- cursorShape: root.fullscreen && (!root.fullControls || root.fullLocked) ? Qt.BlankCursor : Qt.ArrowCursor+ cursorShape: root.fullscreen && (!root.fullControls || root.fullLocked) && !root.quickPanelShown ? Qt.BlankCursor : Qt.ArrowCursor// Qt re-sends hover while anything animates under a still pointer; only a// real change of position counts as movement.property point last: Qt.point(-1, -1)@@ -284,13 +379,34 @@ Window {if (Math.abs(p.x - last.x) < 1 && Math.abs(p.y - last.y) < 1) returnlast = proot.pointerActivity()+ // Fullscreen: the top edge brings the dock down (极简 / 专业 switch in+ // place). Its own 12px hot zone sits under the native picture, where+ // hover is not always delivered, so the window-wide handler helps it.+ if (root.fullscreen && !root.fullLocked) {+ if (p.y <= 14) dock.open()+ else if (p.y > 90 && dock.opened && !dock.pinned) dock.opened = false+ }}}- // AppShell VideoSurface: a double click on the picture leaves fullscreen,- // unless locked.+ // AppShell VideoSurface: a double click on the picture toggles fullscreen+ // (1.4.4 did both directions), unless locked. Windowed, only a double click+ // inside the picture counts; with the quick panel up, not one on the panel.TapHandler {- enabled: root.fullscreen && !root.fullLocked- onDoubleTapped: root.toggleFullscreen()+ enabled: !root.fullLocked+ onDoubleTapped: (eventPoint, button) => {+ const p = eventPoint.position+ if (root.fullscreen) {+ if (root.quickPanelShown && proPage.overlayContains(p.x, p.y)) return+ root.toggleFullscreen()+ return+ }+ if (root.page !== "min" && root.page !== "pro" && root.page !== "node") return+ if (dialogs.dialog !== "" || !veyra.hasSource) return+ if (veyra.protectionDrawShape.length > 0 || veyra.compareMode === 2) return+ if (p.x < videoHost.x || p.y < videoHost.y || p.x > videoHost.x + videoHost.width+ || p.y > videoHost.y + videoHost.height) return+ root.toggleFullscreen()+ }}FullscreenBar {id: fullBar@@ -298,12 +414,13 @@ Window {// Windowed cinema: the pill straddles the picture edge (D1). It hides under// an open dialog, which lives in the main window below it.cinema: root.cinema && !root.fullscreen- pillTop: root.pictureHeight - 46+ pillTop: (root.maximized ? root.height : root.pictureHeight) - 46shown: veyra.hasSource && (root.fullscreen ? root.fullControls && !root.fullLocked: root.cinema && root.shownPage === "min"&& root.leavingPage === "" && dialogs.dialog === ""&& root.visibility !== Window.Minimized)- onRequestPage: p => { root.toggleFullscreen(); root.page = p }+ onRequestPage: p => { if (root.fullscreen) root.toggleFullscreen(); root.goPage(p) }+ onRequestDialog: k => dialogs.open(k)onRequestFullscreen: root.toggleFullscreen()onRequestLock: root.toggleLock()onActivity: root.pointerActivity()@@ -315,10 +432,30 @@ Window {toast.show(fullLocked ? "已锁定全屏 · Ctrl+L 解锁,Esc 退出全屏" : "已解锁全屏", false)veyra.logUi("ui-fullscreen", "locked=" + fullLocked + " shortcut=Ctrl+L")}- function subtitleKey(k) { toast.show("字幕尚未接入(" + k + ")", true) }- Shortcut { sequence: "Space"; onActivated: veyra.togglePlayPause() }+ // Subtitles keep clear of the control pill: fullscreen bar 24px margin + pill,+ // windowed cinema pill straddling the picture's bottom edge.+ Binding { target: veyra; property: "subtitleBottomInset"; value: fullBar.shown ? (root.fullscreen ? 84 : 56) : 0 }+ // Rebindable (设置 → 快捷键); the hold-to-compare key is handled by the bridge's+ // application event filter because it needs the key release too.+ Shortcut { sequence: veyra.shortcuts.playPause; onActivated: veyra.togglePlayPause() }+ Shortcut { sequence: veyra.shortcuts.fullscreen; onActivated: root.toggleFullscreen() }+ Shortcut { sequence: veyra.shortcuts.screenshot; onActivated: veyra.takeScreenshot() }+ Shortcut {+ sequence: veyra.shortcuts.toggleMode+ enabled: dialogs.dialog === ""+ onActivated: root.goPage(root.page === "min" ? "pro" : "min")+ }Shortcut { sequences: ["F11", "Alt+Return", "Alt+Enter"]; onActivated: root.toggleFullscreen() }Shortcut { sequence: "Esc"; enabled: root.fullscreen; onActivated: root.toggleFullscreen() }+ // Home: the fullscreen quick-adjust panel, list mode only.+ Shortcut {+ sequence: "Home"+ enabled: root.fullscreen && !root.fullLocked && dialogs.dialog === ""+ onActivated: {+ if (root.page !== "pro") { toast.show("快速调节只在专业模式的列表视图可用", false); return }+ root.quickPanel = !root.quickPanel+ }+ }Shortcut { sequence: "Left"; onActivated: veyra.seekBy(-10) }Shortcut { sequence: "Right"; onActivated: veyra.seekBy(10) }Shortcut { sequence: "Up"; onActivated: veyra.volume = Math.min(1, veyra.volume + 0.05) }@@ -326,15 +463,19 @@ Window {Shortcut { sequence: "Ctrl+O"; onActivated: veyra.openFileDialog() }Shortcut { sequence: "Ctrl+E"; onActivated: root.page = "exp" }Shortcut {- sequence: "Ctrl+L"+ sequence: veyra.shortcuts.lockenabled: root.fullscreenonActivated: root.toggleLock()}- Shortcut { sequence: "B"; onActivated: root.subtitleKey("B") }- Shortcut { sequences: ["Z", "Shift+Z"]; onActivated: root.subtitleKey("Z") }- Shortcut { sequences: ["X", "Shift+X"]; onActivated: root.subtitleKey("X") }- Shortcut { sequence: "T"; onActivated: root.subtitleKey("T") }- Shortcut { sequence: "Y"; onActivated: root.subtitleKey("Y") }+ // Subtitle keys, as in 1.4.4: B on/off, Z/X -/+50 ms (Shift: 1 s), T/Y cycle+ // the primary/secondary track.+ Shortcut { sequence: "B"; onActivated: veyra.toggleSubtitles() }+ Shortcut { sequence: "Z"; onActivated: veyra.nudgeSubtitle(-50) }+ Shortcut { sequence: "Shift+Z"; onActivated: veyra.nudgeSubtitle(-1000) }+ Shortcut { sequence: "X"; onActivated: veyra.nudgeSubtitle(50) }+ Shortcut { sequence: "Shift+X"; onActivated: veyra.nudgeSubtitle(1000) }+ Shortcut { sequence: "T"; onActivated: veyra.cycleSubtitle(false) }+ Shortcut { sequence: "Y"; onActivated: veyra.cycleSubtitle(true) }// Toasts: a refused edit, a finished export, a failed open.// pages.css .canvas-toast: top 12px, padding 7px 12px, from translate -8px and@@ -388,7 +529,7 @@ Window {dialogs.open(p)return}- root.page = (p === "export" ? "exp" : p)+ root.goPage(p === "export" ? "exp" : p)}}@@ -398,9 +539,10 @@ Window {target: veyrafunction onSnapshotChanged() {if (root.testAspect > 0) return- if (veyra.sourceAspect > 0.2 && Math.abs(veyra.sourceAspect - root.filmAspect) > 0.02)- root.fitToFilm(veyra.sourceAspect)+ if (veyra.previewAspect > 0.2 && Math.abs(veyra.previewAspect - root.filmAspect) > 0.02)+ root.fitToFilm(veyra.previewAspect)}+ function onCompareChanged() { if(root.testAspect <= 0) root.fitToFilm(veyra.previewAspect) }}// Motion probe (G0.5, --motion-probe): starts one motion 800 ms after load and logs@@ -459,10 +601,29 @@ Window {}}+ // 设置 → 启动窗口大小: a fixed size or the last one, clamped to the screen+ // and centred. A --size test switch resizes after this, so tests keep theirs.+ function applyStartupSize() {+ const choice = veyra.preferences.windowSize || "1280x800"+ const text = choice === "last" ? (veyra.preferences.lastWindow || "1280x800") : choice+ const wh = text.split("x").map(Number)+ if (wh.length !== 2 || !(wh[0] > 0) || !(wh[1] > 0)) return+ const sw = root.screen ? root.screen.desktopAvailableWidth : wh[0]+ const sh = root.screen ? root.screen.desktopAvailableHeight : wh[1]+ root.width = Math.max(root.minimumWidth, Math.min(wh[0], sw - 40))+ root.height = Math.max(root.minimumHeight, Math.min(wh[1], sh - 40))+ if (root.screen) {+ root.x = root.screen.virtualX + Math.round((sw - root.width) / 2)+ root.y = root.screen.virtualY + Math.round((sh - root.height) / 2)+ }+ }+ onClosing: if (!root.fullscreen && !root.maximized && !root.cinema) veyra.rememberWindowSize(root.width, root.height)Component.onCompleted: {+ applyStartupSize()// Open on the configured page: the user's saved preference, or the// override a test passes on the command line.- if (veyra.initialPage.length > 0) root.page = veyra.initialPage+ if (veyra.initialPage.length > 0)+ root.page = veyra.initialPage === "pro" && veyra.nodeMode === 1 ? "node" : veyra.initialPageif (root.test.tab !== undefined) proPage.tab = root.test.tabif (root.testAspect > 0) root.fitToFilm(root.testAspect)if (root.test.dialog !== undefined) dialogs.open(root.test.dialog)diff --git a/qml/Veyra/MinimalPage.qml b/qml/Veyra/MinimalPage.qmlindex 5cf0b220..f7dfb409 100644--- a/qml/Veyra/MinimalPage.qml+++ b/qml/Veyra/MinimalPage.qml@@ -63,12 +63,40 @@ VPage {Text {anchors.centerIn: parent- visible: !veyra.hasSource+ visible: !veyra.hasSource && veyra.liveOpeningText.length === 0text: "选择一个片源开始"color: Theme.t3font.family: Theme.fontUifont.pixelSize: Theme.fsH3}+ // A PS5 / capture session that is still connecting: a pill in the+ // middle of the (still black) picture, cut out of the native video.+ Rectangle {+ objectName: "min-live-opening"+ readonly property bool videoCover: true+ property real coverRadius: height / 2+ visible: veyra.liveOpeningText.length > 0+ anchors.centerIn: parent+ width: openingRow.implicitWidth + 32+ height: 40+ radius: height / 2+ color: Qt.rgba(22 / 255, 22 / 255, 26 / 255, 0.92)+ border.width: 1+ border.color: Theme.stroke2+ Row {+ id: openingRow+ anchors.centerIn: parent+ spacing: 10+ VSpinner { anchors.verticalCenter: parent.verticalCenter }+ Text {+ anchors.verticalCenter: parent.verticalCenter+ text: veyra.liveOpeningText+ color: Theme.t1+ font.family: Theme.fontUi+ font.pixelSize: Theme.fsBody+ }+ }+ }}// Report the film aspect upward so the window can snap to it.diff --git a/qml/Veyra/NodePage.qml b/qml/Veyra/NodePage.qmlindex 9c819d79..e84698d9 100644--- a/qml/Veyra/NodePage.qml+++ b/qml/Veyra/NodePage.qml@@ -16,15 +16,319 @@ import QtQuick.ShapesVPage {id: rootsignal requestPage(string page)+ signal requestDialog(string key)+ signal requestInspector(int nodeIndex, string nodeType)+ signal requestFullscreen()- property real panX: 0+ property real panX: 220property real panY: 0property real zoom: 1.0property int selectedNode: -1+ property int selectedId: -1+ property int wireFrom: -1+ // Height of the video card; the splitter under it edits it (Main keeps the+ // native video window in step).+ property real videoHeight: 330+ signal videoHeightEdited(real height)+ // Where a node picked from the add menu lands (world coordinates).+ property var addAt: null+ readonly property real cardWidth: 236+ // Fixed boxes (输入 / 光流 / 输出) move on the canvas like any card; their+ // positions are editor furniture saved by the bridge (node-anchors.json).+ readonly property var anchorDefaults: ({ input: Qt.point(-190, 30), flow: Qt.point(-190, 106), output: Qt.point(1120, 30) })+ function anchorPos(key) {+ const a = veyra.nodeAnchors[key]+ return a ? Qt.point(a.x, a.y) : anchorDefaults[key]+ }+ // Wire drag / click-to-connect preview and the link a dragged node would enter.+ property point pointerWorld: Qt.point(0, 0)+ property bool dragWire: false+ property int hotFrom: -1+ property int hotTo: -1- onPanXChanged: canvasGrid.requestPaint()- onPanYChanged: canvasGrid.requestPaint()- onZoomChanged: canvasGrid.requestPaint()+ // A pointer on a card, a port (ports stick out past the card edge), or an+ // anchor box belongs to that item, never to the empty canvas.+ function hitWorld(p) {+ const w = world.mapFromItem(canvasCard, p.x, p.y)+ for (const c of world.children) {+ if (!c.visible || c.width <= 0) continue+ if (w.x >= c.x - 14 && w.x <= c.x + c.width + 14 && w.y >= c.y - 6 && w.y <= c.y + c.height + 6) return true+ }+ return false+ }+ function clearSelection() { selectedId = -1; selectedNode = -1; wireFrom = -1; dragWire = false; marked = []; wires.requestPaint() }+ // Ids picked with the rubber band (left drag on empty canvas).+ property var marked: []+ // pages-node.js / data.js hue per node type: the card header is tinted+ // with it (N1).+ function hueOf(type) {+ switch (type) {+ case "color": return "#E0C341"+ case "sr": return "#4F7BFF"+ case "nr": return "#FF8A3D"+ case "protection": return "#8A8A96"+ case "video-hdr": return "#FFB547"+ case "frame-generation": case "dlss-fg": case "xess-fg": case "fsr3-fg": case "fsr4-fg": return "#3DDC84"+ }+ return "#55555C"+ }+ // M33 .bnode.born / die: the node just added pops in (scale .6 over .6s+ // --spring); a removed one shrinks to .7 and fades over .22s first.+ property int bornId: -1+ Timer { id: bornReset; interval: 900; onTriggered: root.bornId = -1 }+ function markBorn(id) { bornId = id; bornReset.restart() }+ function removeNodeAnimated(id) {+ const card = nodeRepeater.itemAt(veyra.nodeIndexForId(id))+ const drop = () => { const i = veyra.nodeIndexForId(id); if (i >= 0) veyra.removeEffect(i) }+ if (card && card.die) card.die(drop)+ else drop()+ }+ // Centre the view on a node and select it (timing strip clicks).+ function focusNode(id) {+ const card = nodeRepeater.itemAt(veyra.nodeIndexForId(id))+ if (!card) return+ selectId(id)+ panX = canvasCard.width / 2 - (card.x + card.width / 2) * zoom+ panY = Math.min(40, canvasCard.height / 3 - (card.y + 40) * zoom)+ }+ // Delete (the key) removes the marked nodes, or the selected one. Frame+ // generation stays: it is pinned to the end and can only be switched off.+ function deleteSelected() {+ const ids = marked.length > 0 ? marked.slice() : (selectedId > 1 ? [selectedId] : [])+ let removed = 0, pinned = 0+ for (const id of ids) {+ const n = veyra.chain.find(x => x.id === id)+ if (!n) continue+ if (n.mustBeLast) { ++pinned; continue }+ if (veyra.nodeIndexForId(id) >= 0) { root.removeNodeAnimated(id); ++removed }+ }+ clearSelection()+ veyra.logUi("ui-node", "delete ids=" + ids.length + " removed=" + removed + " pinned=" + pinned)+ }+ Shortcut {+ sequence: "Delete"+ enabled: root.visible && (root.marked.length > 0 || root.selectedId > 1)+ onActivated: root.deleteSelected()+ }+ Shortcut { sequence: "Escape"; enabled: root.visible && root.marked.length > 0; onActivated: root.marked = [] }+ // Every box with its TARGET position (where the spring is heading), not the+ // animated on-screen one; a box being dragged uses where the pointer holds it.+ function boxes() {+ const anchor = (key, item) => {+ const p = item.animate ? anchorPos(key) : Qt.point(item.x, item.y)+ return { key: key, item: item, x: p.x, y: p.y, w: item.width, h: item.height }+ }+ const out = [anchor("input", inputBox), anchor("output", outputBox)]+ for (let i = 0; i < nodeRepeater.count; ++i) {+ const c = nodeRepeater.itemAt(i)+ if (!c || !c.node || c.node.id === undefined) continue+ out.push({ key: "n" + c.node.id, item: c, index: c.node.index,+ x: c.animate ? c.node.x : c.x, y: c.animate ? c.node.y : c.y, w: c.width, h: c.height })+ }+ return out+ }+ function overlapping(gap) {+ const r = boxes(), g = gap || 0+ for (let i = 0; i < r.length; ++i) for (let j = i + 1; j < r.length; ++j) {+ const a = r[i], b = r[j]+ if (Math.min(a.x + a.w, b.x + b.w) + g > Math.max(a.x, b.x) && Math.min(a.y + a.h, b.y + b.h) + g > Math.max(a.y, b.y)) return true+ }+ return false+ }+ // 适配视图 (pages-node.js fit): every box in view.+ function fitView() {+ let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9+ for (const b of boxes()) {+ x0 = Math.min(x0, b.x); y0 = Math.min(y0, b.y)+ x1 = Math.max(x1, b.x + b.w); y1 = Math.max(y1, b.y + b.h)+ }+ x0 -= 20; y0 -= 20; x1 += 20; y1 += 20+ const k = Math.max(0.25, Math.min(1.0, Math.min((canvasCard.width - 40) / (x1 - x0),+ (canvasCard.height - 90) / (y1 - y0))))+ zoom = k+ panX = (canvasCard.width - (x1 - x0) * k) / 2 - x0 * k+ panY = 30 - y0 * k+ veyra.logUi("ui-node", "fit view zoom=" + k.toFixed(3))+ }+ function pathIds() {+ const next = {}+ for (const e of veyra.nodeConnections) next[e.from] = e.to+ const path = []+ let id = 0, guard = 0+ while (next[id] !== undefined && next[id] > 1 && guard++ < 32) { id = next[id]; path.push(id) }+ return path+ }+ // 自动排列 (pages-node.js data-auto): the wired path left to right, detached+ // cards on a row below, output after the last card. Saved like a drag.+ function autoArrange() {+ const path = pathIds(), GAP = 40+ let x = 40, bottom = 30+ path.forEach((nid, i) => {+ const index = veyra.nodeIndexForId(nid), c = nodeRepeater.itemAt(index)+ const y = 30 + (i % 2) * 24+ veyra.setEffectPosition(index, x, y)+ x += (c ? c.width : cardWidth) + GAP+ bottom = Math.max(bottom, y + (c ? c.height : 200))+ })+ veyra.setNodeAnchor("input", -190, 30)+ veyra.setNodeAnchor("output", x, 30)+ // Detached cards on their own row below the tallest chained card.+ let fx = 40+ for (const n of veyra.chain)+ if (path.indexOf(n.id) < 0) {+ const c = nodeRepeater.itemAt(n.index)+ veyra.setEffectPosition(n.index, fx, bottom + 80); fx += (c ? c.width : cardWidth) + GAP+ }+ veyra.logUi("ui-node", "auto arrange path=" + path.length + " detached=" + (veyra.chain.length - path.length))+ Qt.callLater(() => { settle(""); fitView() })+ }+ // settle() from pages-node.js: boxes closer than GAP push apart, the held+ // box (and the input) stays put; linked cards are pushed sideways so the+ // chain reads left to right. Positions animate with the spring (Behavior).+ function settle(fixedKey) {+ const list = boxes(), GAP = 28+ const r = list.map(b => ({ key: b.key, index: b.index, x: b.x, y: b.y, w: b.w, h: b.h }))+ const linked = new Set(pathIds().map(id => "n" + id))+ const moved = new Set()+ for (let pass = 0; pass < 80; ++pass) {+ let any = false+ for (let i = 0; i < r.length; ++i) for (let j = i + 1; j < r.length; ++j) {+ const a = r[i], b = r[j]+ const ox = Math.min(a.x + a.w, b.x + b.w) + GAP - Math.max(a.x, b.x)+ const oy = Math.min(a.y + a.h, b.y + b.h) + GAP - Math.max(a.y, b.y)+ if (ox <= 0 || oy <= 0) continue+ const fixed = k => k === fixedKey || k === "input"+ if (fixed(a.key) && fixed(b.key)) continue+ any = true+ // Chains read left to right: the right-hand box moves right (the+ // left one moves left only when the right one is held). Loose+ // cards stack downwards the same way.+ // A box squeezed between a held box and a neighbour would bounce+ // sideways forever; after 20 passes the rest resolve downwards.+ const horiz = pass < 20 && (ox < oy * 1.4 || linked.has(a.key) || linked.has(b.key) || a.key === "output" || b.key === "output")+ let mover, delta+ if (horiz) {+ const right = (b.x + b.w / 2 >= a.x + a.w / 2) ? b : a, left = right === a ? b : a+ if (!fixed(right.key)) { mover = right; mover.x += ox } else { mover = left; mover.x -= ox }+ } else {+ const lower = (b.y + b.h / 2 >= a.y + a.h / 2) ? b : a, upper = lower === a ? b : a+ if (!fixed(lower.key)) { mover = lower; mover.y += oy } else { mover = upper; mover.y -= oy }+ }+ moved.add(mover.key)+ }+ if (!any) break+ }+ for (const b of r) {+ if (!moved.has(b.key)) continue+ if (b.index !== undefined) veyra.setEffectPosition(b.index, b.x, b.y)+ else veyra.setNodeAnchor(b.key, b.x, b.y)+ }+ if (moved.size) veyra.logUi("ui-node", "settle moved=" + Array.from(moved).join(","))+ }+ // Replace an output's or an input's existing wire rather than refusing; if+ // the engine rejects the new link, the old wiring is put back.+ function rewire(from, to) {+ if (from === to || from === 1 || to === 0) return false+ const edges = veyra.nodeConnections+ const oldOut = edges.find(e => e.from === from), oldIn = edges.find(e => e.to === to)+ if (oldOut && oldOut.to === to) return true+ if (oldOut) veyra.disconnectNode(from)+ if (oldIn && oldIn.from !== from) veyra.disconnectNode(oldIn.from)+ if (veyra.connectNodes(from, to)) { veyra.logUi("ui-node", "wire " + from + "->" + to); return true }+ if (oldIn && oldIn.from !== from) veyra.connectNodes(oldIn.from, to)+ if (oldOut) veyra.connectNodes(from, oldOut.to)+ return false+ }+ // Take a wired node out of the path and join its neighbours (design detach()).+ function detach(id, nudge) {+ const edges = veyra.nodeConnections+ const prev = edges.find(e => e.to === id), next = edges.find(e => e.from === id)+ if (!prev && !next) return+ if (prev) veyra.disconnectNode(prev.from)+ if (next) veyra.disconnectNode(id)+ if (prev && next) veyra.connectNodes(prev.from, next.to)+ const index = veyra.nodeIndexForId(id)+ const c = nodeRepeater.itemAt(index)+ if (nudge && c) veyra.setEffectPosition(index, c.x, c.y + 330)+ veyra.logUi("ui-node", "detach " + id)+ Qt.callLater(() => settle("n" + id))+ }+ // The link under a dragged card (pages-node.js nearestLink).+ function nearestLink(cx, cy, selfId) {+ let best = null, bd = 70 / zoom+ for (const e of veyra.nodeConnections) {+ if (e.from === selfId || e.to === selfId) continue+ const a = endpoint(e.from, true), b = endpoint(e.to, false)+ if (!a || !b || cx < a.x - 40 || cx > b.x + 40) continue+ const t = Math.max(0, Math.min(1, (cx - a.x) / Math.max(1, b.x - a.x)))+ const my = a.y + (b.y - a.y) * (3 * t * t - 2 * t * t * t)+ const d = Math.abs(cy - my)+ if (d < bd) { bd = d; best = e }+ }+ return best+ }+ // The input port under a world point (for drag-to-connect).+ function inputAt(w) {+ const o = outputBox+ if (Math.abs(w.x - o.x) < 18 && Math.abs(w.y - (o.y + 28)) < 18) return 1+ for (let i = 0; i < nodeRepeater.count; ++i) {+ const c = nodeRepeater.itemAt(i)+ if (c && Math.abs(w.x - c.x) < 18 && Math.abs(w.y - (c.y + 16)) < 18) return c.node.id+ }+ return -1+ }++ function endpoint(id, output) {+ if (id === 0) return Qt.point(inputBox.x + inputBox.width, inputBox.y + 28)+ if (id === 1) return Qt.point(outputBox.x, outputBox.y + 28)+ const index = veyra.nodeIndexForId(id)+ const card = nodeRepeater.itemAt(index)+ return card ? Qt.point(card.x + (output ? card.width : 0), card.y + 16) : null+ }+ function selectId(id) {+ selectedId = id+ selectedNode = veyra.nodeIndexForId(id)+ }+ Connections {+ target: veyra+ function onChainChanged() {+ root.selectedNode = veyra.nodeIndexForId(root.selectedId)+ if (root.wireFrom > 1 && veyra.nodeIndexForId(root.wireFrom) < 0) root.wireFrom = -1+ wires.requestPaint()+ }+ function onNodeAnchorsChanged() { wires.requestPaint() }+ }+ Shortcut { sequence: "Escape"; enabled: root.wireFrom >= 0; onActivated: root.clearSelection() }+ // Card sizes are only known after their editors lay out (and change on+ // collapse / section switches): settle once the sizes stop changing.+ // A layout that overlaps once the cards have their real sizes after the page+ // opens (legacy grid positions, or cards that grew their full editors) is+ // laid out properly left to right once; later size changes only settle.+ property bool layoutChecked: false+ Timer {+ id: settleTimer+ interval: 120+ onTriggered: {+ // Hidden pages have no reliable sizes; the check runs when shown.+ if (!root.visible) return+ if (!root.layoutChecked) {+ root.layoutChecked = true+ if (root.overlapping(20)) { veyra.logUi("ui-node", "overlapping layout on show: auto arrange"); root.autoArrange(); return }+ // An empty graph (the node editor's starting point): bring input and+ // output into view without moving them, leaving the space between+ // them for the nodes the user adds.+ if (veyra.chain.length === 0) { root.fitView(); return }+ }+ root.settle("")+ }+ }+ onVisibleChanged: if (visible) { layoutChecked = false; settleTimer.restart() }+ Component.onCompleted: settleTimer.restart()+ Shortcut { sequence: "Escape"; enabled: root.wireFrom >= 0; onActivated: root.wireFrom = -1 }++ onPanXChanged: { canvasGrid.requestPaint(); wires.requestPaint() }+ onPanYChanged: { canvasGrid.requestPaint(); wires.requestPaint() }+ onZoomChanged: { canvasGrid.requestPaint(); wires.requestPaint() }ColumnLayout {anchors.fill: parent@@ -35,7 +339,7 @@ VPage {Rectangle {id: nvTopLayout.fillWidth: true- Layout.preferredHeight: 330+ Layout.preferredHeight: root.videoHeightradius: Theme.rCardcolor: Theme.videoBlackborder.width: 1@@ -75,6 +379,17 @@ VPage {anchors.rightMargin: 8spacing: 8+ // pages-node.js .nv-bar: the source first, as on the list page.+ VButton {+ id: nodeSourceBtn+ objectName: "node-source-button"+ iconName: veyra.sourceKind === "ps5" ? "gamepad" : veyra.sourceKind === "screen" ? "monitor"+ : veyra.sourceKind === "image" ? "image" : veyra.sourceKind === "file" ? "film" : "video"+ text: veyra.sourceTitle.length > 0 ? veyra.sourceTitle : "片源"+ maxTextWidth: 180+ trailingIcon: "down"+ onClicked: nodeSourceMenu.openAt(this, "down")+ }VButton {icon: trueiconName: (veyra.running && !veyra.paused) ? "pause" : "play"@@ -86,15 +401,16 @@ VPage {// .nv-stats: each entry separated by a hairline, mono numbers.RowLayout {Layout.fillWidth: true+ Layout.minimumWidth: 0+ clip: truespacing: 0Repeater {model: [{ k: "输入", v: veyra.sourceSummary, hi: false },- { k: "输出", v: veyra.outputSummary, hi: false },+ { k: "输出", v: veyra.outputSummary.length > 0 ? veyra.outputSummary : "未测", hi: false },{ k: "显示 fps", v: veyra.displayFpsKnown ? veyra.displayFps.toFixed(1) : "未测", hi: true },- { k: "提交 fps", v: veyra.submitFpsKnown ? veyra.submitFps.toFixed(1) : "未测", hi: false },- { k: "排队", v: veyra.queuedFrames.toFixed(1) + " 帧", hi: false },- { k: "链路总耗时", v: veyra.chainTotalMs > 0 ? veyra.chainTotalMs.toFixed(1) + " ms" : "未测", hi: false }+ { k: veyra.submitFpsLabel + " fps", v: veyra.submitFpsKnown ? veyra.submitFps.toFixed(1) : "未测", hi: false },+ { k: "待呈现", v: veyra.queuedFramesKnown ? veyra.queuedFrames.toFixed(0) + " 帧" : "未测", hi: false }]delegate: RowLayout {required property var modelData@@ -122,13 +438,38 @@ VPage {}}- VButton { text: "列表模式"; onClicked: root.requestPage("pro") }+ // Total time / GPU / output-vs-target orbs (replace "已测增强 P95").+ ProPage.PerfOrbs { objectName: "node-perf-orbs"; size: 32; showLabels: false; spacing: 6 }+ VButton {+ objectName: "node-fullscreen"+ icon: true; iconName: "max"+ tip: "全屏画面(双击画面 / F11)"+ onClicked: root.requestFullscreen()+ }+ // .viewtog: 列表 asks first (the list configuration comes back).+ VSeg {+ objectName: "node-mode-switch"+ options: [{ id: "list", label: "列表", icon: "list" }, { id: "node", label: "节点", icon: "nodes" }]+ current: "node"+ onPicked: id => { if (id === "list") returnDialog.open() }+ }+ VButton { objectName: "node-return-list"; visible: false; text: "返回列表"; onClicked: returnDialog.open() }+ VButton {+ id: nodePresetBtn+ objectName: "node-preset-button"+ iconName: "nodes"+ trailingIcon: "down"+ maxTextWidth: 150+ text: "节点预设:" + veyra.currentPresetName+ onClicked: nodePresetMenu.openAt(this, "down")+ }}}}// --- split handle (10px) -------------------------------------------Item {+ objectName: "node-splitter"Layout.fillWidth: trueLayout.preferredHeight: 10Rectangle {@@ -139,6 +480,19 @@ VPage {color: splitHover.hovered ? Theme.accent : Qt.rgba(1, 1, 1, 0.18)}HoverHandler { id: splitHover; cursorShape: Qt.SizeVerCursor }+ // Drag to share the height between the picture and the canvas: the+ // picture keeps at least 180px, the canvas at least 200px.+ DragHandler {+ id: splitDrag+ target: null+ cursorShape: Qt.SizeVerCursor+ property real origin: 0+ onActiveChanged: if (active) origin = root.videoHeight+ onActiveTranslationChanged: if (active) {+ const most = Math.max(180, root.height - 28 - 10 - 200)+ root.videoHeightEdited(Math.round(Math.max(180, Math.min(most, origin + activeTranslation.y))))+ }+ }}// --- canvas --------------------------------------------------------@@ -173,112 +527,468 @@ VPage {// Hint and the right-click affordance.Text {+ objectName: "node-canvas-tip"anchors.left: parent.left- anchors.bottom: parent.bottom+ anchors.top: parent.topanchors.leftMargin: 12- anchors.bottomMargin: 34- text: "双击空白处添加效果 · 右键节点删除 · 拖动节点移动"+ anchors.topMargin: 10+ z: 4+ text: root.wireFrom >= 0 ? "请选择输入端口完成连接 · Esc 取消" :+ (veyra.chainValid ? "右键空白添加 · 拖到连线上插入 · 拖远(上下超过一截)或按住 Alt 松手即断开 · 端口拖拽/点击连线 · 中键平移 · 滚轮缩放" : veyra.chainError)color: Theme.t3font.family: Theme.fontUifont.pixelSize: 11}+ Canvas {+ id: wires+ anchors.fill: parent+ onPaint: {+ const ctx = getContext("2d")+ ctx.reset(); ctx.clearRect(0, 0, width, height)+ ctx.save(); ctx.translate(root.panX, root.panY); ctx.scale(root.zoom, root.zoom)+ const curve = (a, b) => {+ const bend = Math.max(60, Math.abs(b.x - a.x) / 2)+ ctx.beginPath(); ctx.moveTo(a.x, a.y)+ ctx.bezierCurveTo(a.x + bend, a.y, b.x - bend, b.y, b.x, b.y); ctx.stroke()+ }+ for (const edge of veyra.nodeConnections) {+ const a = root.endpoint(edge.from, true), b = root.endpoint(edge.to, false)+ if (!a || !b) continue+ const hot = edge.from === root.hotFrom && edge.to === root.hotTo+ ctx.strokeStyle = hot ? "#FF8A3D" : "#8291AA"; ctx.lineWidth = (hot ? 4 : 2) / root.zoom+ curve(a, b)+ }+ // Rubber band from the chosen output port to the pointer.+ if (root.wireFrom >= 0) {+ const a = root.endpoint(root.wireFrom, true)+ if (a) {+ ctx.setLineDash([6 / root.zoom, 4 / root.zoom])+ ctx.strokeStyle = "#FF8A3D"; ctx.lineWidth = 2 / root.zoom+ curve(a, root.pointerWorld)+ ctx.setLineDash([])+ }+ }+ ctx.restore()+ }+ onWidthChanged: requestPaint()+ onHeightChanged: requestPaint()+ }+Item {id: worldx: root.panXy: root.panYtransform: Scale { origin.x: 0; origin.y: 0; xScale: root.zoom; yScale: root.zoom }- // Input and output anchors, so the pipeline's ends are visible.- Rectangle {- x: -190; y: 30; width: 150; height: 56- radius: 10- color: "#1D1D22"- border.width: 1- border.color: Theme.stroke2- Text { anchors.centerIn: parent; text: "输入"; color: Theme.t2; font.family: Theme.fontUi; font.pixelSize: Theme.fsBody }+ // Input, shared optical-flow and output boxes: fixed in the chain,+ // free on the canvas (user decision 2026-09-28).+ // 输入: the source plus the shared optical-flow choice (moved in+ // from its own box, user request 2026-09-29). Port 0 starts the chain.+ AnchorBox {+ id: inputBox+ key: "input"; width: 250; height: inCol.implicitHeight + 20; handleHeight: 30+ objectName: "node-input-anchor"+ NodePort { nodeId: 0; output: true; x: parent.width - width / 2; y: 28 - height / 2 }+ ColumnLayout {+ id: inCol+ anchors.left: parent.left; anchors.right: parent.right; anchors.top: parent.top+ anchors.margins: 10; spacing: 8+ Text { text: "输入 · 光流"; color: Theme.t1; font.family: Theme.fontUi; font.pixelSize: Theme.fsBody; font.weight: Font.Medium }+ Text {+ Layout.fillWidth: true+ text: veyra.sourceSummary.length > 0 ? veyra.sourceSummary : "未打开片源"+ color: Theme.t3; font.family: Theme.fontMono; font.pixelSize: 10; elide: Text.ElideRight+ }+ VSelect {+ objectName: "node-flow-choice"+ Layout.fillWidth: true+ title: "光流算法"+ options: [{id:"0",label:"NVIDIA NVOF"},{id:"1",label:"AMD FidelityFX"}]+ value: options[veyra.opticalFlowChoice]?.label ?? (veyra.opticalFlowChoice === 2 ? "GPU DIS 已移除,请重选" : "未知配置")+ onPicked: id => veyra.setOpticalFlowChoice(Number(id))+ }+ NodeLabel { text: "运动估算质量" }+ VSeg {+ objectName: "node-flow-quality"+ Layout.fillWidth: true+ options: [{ id: "0", label: "性能" }, { id: "1", label: "平衡" }, { id: "2", label: "质量" }]+ current: String(veyra.flowQuality)+ onPicked: id => veyra.flowQuality = Number(id)+ }+ RowLayout {+ Layout.fillWidth: true+ visible: veyra.opticalFlowChoice === 1+ NodeLabel { Layout.fillWidth: true; text: "AMD 性能档(宽高减半)" }+ VSwitch { objectName: "node-amd-half"; checked: veyra.amdFlowHalf; onToggled: veyra.amdFlowHalf = checked }+ }+ NodeLabel { text: "内容节奏" }+ VSelect {+ objectName: "node-content-rate"+ Layout.fillWidth: true+ title: "内容节奏"+ options: root.contentRates+ value: (root.contentRates[veyra.contentRate] || root.contentRates[0]).label+ onPicked: id => veyra.contentRate = Number(id)+ }+ Text {+ Layout.fillWidth: true+ text: "补帧与 NR 共用,输入后计算一次,不随节点重复。"+ color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 10+ wrapMode: Text.WordWrap+ }+ }}Repeater {- model: veyra.chain+ id: nodeRepeater+ // A count, not the array: delegates survive position updates so+ // the settle spring can animate them.+ model: veyra.chain.length+ // New cards settle through settleTimer once their size is known.+ onItemAdded: settleTimer.restart()+ onItemRemoved: wires.requestPaint()delegate: NodeCard {- required property var modelData- node: modelData+ required property int index+ node: veyra.chain[index] || ({})}}- Rectangle {- x: 60; y: 380; width: 150; height: 56- radius: 10- color: "#1D1D22"- border.width: 1- border.color: Theme.stroke2- Text { anchors.centerIn: parent; text: "输出"; color: Theme.t2; font.family: Theme.fontUi; font.pixelSize: Theme.fsBody }+ // 输出: plus the sound settings. Audio is not a processing step, so+ // it lives on the output box rather than as a node in the chain.+ AnchorBox {+ id: outputBox+ key: "output"; width: 280; height: outCol.implicitHeight + 20; handleHeight: 30+ objectName: "node-output-anchor"+ NodePort { nodeId: 1; output: false; x: -width / 2; y: 28 - height / 2 }+ ColumnLayout {+ id: outCol+ anchors.left: parent.left; anchors.right: parent.right; anchors.top: parent.top+ anchors.margins: 10; spacing: 6+ Text { text: "输出 · 声音"; color: Theme.t1; font.family: Theme.fontUi; font.pixelSize: Theme.fsBody; font.weight: Font.Medium }+ Text {+ Layout.fillWidth: true+ text: veyra.outputSummary.length > 0 ? veyra.outputSummary : "未输出"+ color: Theme.t3; font.family: Theme.fontMono; font.pixelSize: 10; elide: Text.ElideRight+ }+ RowLayout {+ Layout.fillWidth: true; spacing: 6+ VIcon { name: "vol"; size: 14; color: Theme.t2 }+ VSlider {+ objectName: "node-out-volume"+ Layout.fillWidth: true+ from: 0; to: 1; value: veyra.volume+ onMoved: value => veyra.volume = value+ }+ Text { text: Math.round(veyra.volume * 100) + "%"; color: Theme.t2; font.family: Theme.fontMono; font.pixelSize: 10 }+ VSwitch { objectName: "node-out-mute"; checked: !veyra.muted; onToggled: veyra.muted = !checked }+ }+ VSeg {+ objectName: "node-out-sync"+ Layout.fillWidth: true+ options: [{ id: "0", label: "自动估算" }, { id: "1", label: "手动" }, { id: "2", label: "关闭" }]+ current: String(veyra.audioSyncMode)+ onPicked: id => veyra.audioSyncMode = Number(id)+ }+ RowLayout {+ Layout.fillWidth: true; spacing: 6+ visible: veyra.audioSyncMode === 1+ Text { text: "偏移"; color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 10 }+ VSlider {+ Layout.fillWidth: true+ center: true+ from: -250; to: 250; value: veyra.audioOffsetMs+ onMoved: value => veyra.audioOffsetMs = Math.round(value)+ }+ Text { text: veyra.audioOffsetMs + " ms"; color: Theme.t2; font.family: Theme.fontMono; font.pixelSize: 10 }+ }+ Text {+ Layout.fillWidth: true+ visible: veyra.audioSyncMode === 0+ text: veyra.audioSyncLive ? "软件估算补偿 " + veyra.audioCompensationMs.toFixed(0) + " ms" : "自动估算:采集卡 / PS5 实时输入时生效"+ color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 10; wrapMode: Text.WordWrap+ }+ // 显示同步 / 输出上限: presentation belongs to the output.+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 6+ enabled: !veyra.presentationOwned+ opacity: enabled ? 1 : 0.5+ NodeLabel { text: veyra.presentationOwned ? "显示同步 · Intel XeSS 接管呈现" : "显示同步" }+ VSeg {+ objectName: "node-display-sync"+ Layout.fillWidth: true+ options: [{ id: "0", label: "允许撕裂" }, { id: "1", label: "垂直同步" }, { id: "2", label: "自动" }]+ current: String(veyra.displaySync)+ onPicked: id => veyra.displaySync = Number(id)+ }+ NodeLabel { text: "输出上限" }+ VSeg {+ objectName: "node-output-rate"+ Layout.fillWidth: true+ options: [{ id: "0", label: "关闭" }, { id: "1", label: "跟随显示器" }, { id: "2", label: "自定义" }]+ current: String(veyra.outputRateMode)+ onPicked: id => veyra.outputRateMode = Number(id)+ }+ RowLayout {+ Layout.fillWidth: true+ visible: veyra.outputRateMode === 2+ NodeLabel { Layout.fillWidth: true; text: "自定义上限(FPS)" }+ DialogHost.VTextField {+ objectName: "node-custom-fps"+ implicitWidth: 90+ text: veyra.outputCustomFps.toFixed(3)+ onEdited: text => { const v = Number(text); if (isFinite(v)) veyra.outputCustomFps = v }+ }+ }+ }+ NodeLabel { text: "输出设备" }+ VSelect {+ objectName: "node-out-device"+ Layout.fillWidth: true+ title: "输出设备"+ readonly property string chosen: veyra.preferences.audioDevice || ""+ value: { const d = veyra.audioDevices.find(x => x.id === chosen); return d ? d.label : "跟随系统默认" }+ options: veyra.audioDevices+ onPicked: id => veyra.setPreference("audioDevice", id)+ }+ }}}- // Pan on drag of empty canvas; zoom with the wheel (clamped so a- // layout cannot be shrunk into nothing).+ // The pointer in world coordinates, for the rubber-band wire.+ HoverHandler {+ onPointChanged: {+ if (root.wireFrom < 0) return+ root.pointerWorld = world.mapFromItem(canvasCard, point.position.x, point.position.y)+ wires.requestPaint()+ }+ }++ // Middle-button drag pans (user decision 2026-09-28): the left button+ // only selects. The wheel zooms (clamped so a layout cannot vanish).DragHandler {+ objectName: "node-canvas-pan"target: null- onTranslationChanged: {- root.panX += activeTranslation.x- root.panY += activeTranslation.y+ acceptedButtons: Qt.MiddleButton+ property real originX: 0+ property real originY: 0+ onActiveChanged: if (active) { originX = root.panX; originY = root.panY }+ onActiveTranslationChanged: {+ root.panX = originX + activeTranslation.x+ root.panY = originY + activeTranslation.y}}WheelHandler {onWheel: event => {- root.zoom = Math.max(0.4, Math.min(2.0, root.zoom * (event.angleDelta.y > 0 ? 1.1 : 0.9)))+ root.zoom = Math.max(0.25, Math.min(2.0, root.zoom * (event.angleDelta.y > 0 ? 1.1 : 0.9)))}}- // The add menu opens under the double-clicked point.+ // Left click on empty canvas clears the selection; right click on empty+ // canvas opens the add menu there and the new node lands at that point.Item { id: tapAnchor; width: 1; height: 1 }TapHandler {acceptedButtons: Qt.LeftButton- onDoubleTapped: eventPoint => {- tapAnchor.x = eventPoint.position.x- tapAnchor.y = eventPoint.position.y- addMenu.openAt(tapAnchor, "down")+ onTapped: eventPoint => { if (!root.hitWorld(eventPoint.position)) root.clearSelection() }+ }+ TapHandler {+ objectName: "node-canvas-context"+ acceptedButtons: Qt.RightButton+ onTapped: eventPoint => {+ const p = eventPoint.position+ if (root.hitWorld(p)) return+ tapAnchor.x = p.x+ tapAnchor.y = p.y+ root.addAt = Qt.point((p.x - root.panX) / root.zoom, (p.y - root.panY) / root.zoom)+ addMenu.openAt(tapAnchor, "at")+ }+ }++ // Rubber band: a left drag that starts on empty canvas marks every+ // card it touches; Delete then removes them.+ DragHandler {+ id: marquee+ objectName: "node-canvas-marquee"+ target: null+ acceptedButtons: Qt.LeftButton+ // Never take a drag from a card, a port or a fixed box: those+ // handlers sit deeper and must win; the band only gets drags+ // nobody else wants (it was stealing the input box's drag).+ grabPermissions: PointerHandler.CanTakeOverFromItems | PointerHandler.ApprovesTakeOverByAnything+ property bool live: false+ property point from: Qt.point(0, 0)+ property point to: Qt.point(0, 0)+ onActiveChanged: {+ if (active) {+ live = root.wireFrom < 0 && !root.hitWorld(centroid.pressPosition)+ from = centroid.pressPosition; to = from+ return+ }+ if (!live) return+ live = false+ const a = world.mapFromItem(canvasCard, Math.min(from.x, to.x), Math.min(from.y, to.y))+ const b = world.mapFromItem(canvasCard, Math.max(from.x, to.x), Math.max(from.y, to.y))+ const picked = []+ for (let i = 0; i < nodeRepeater.count; ++i) {+ const c = nodeRepeater.itemAt(i)+ if (!c || !c.node || c.node.id === undefined) continue+ if (c.x < b.x && c.x + c.width > a.x && c.y < b.y && c.y + c.height > a.y) picked.push(c.node.id)+ }+ root.selectedId = -1; root.selectedNode = -1+ root.marked = picked+ veyra.logUi("ui-node", "marquee marked=" + picked.length)}+ onCentroidChanged: if (active && live) to = centroid.position+ }+ Rectangle {+ objectName: "node-canvas-band"+ visible: marquee.active && marquee.live+ x: Math.min(marquee.from.x, marquee.to.x); y: Math.min(marquee.from.y, marquee.to.y)+ width: Math.abs(marquee.to.x - marquee.from.x); height: Math.abs(marquee.to.y - marquee.from.y)+ z: 5+ color: Qt.rgba(1, 138 / 255, 61 / 255, 0.10)+ border.width: 1+ border.color: Theme.accent}- // .timing strip: each stage coloured by its cost; the remainder is- // drawn hatched, exactly as the design's .tspare does.+ // .canvas-tools: 适配视图 · 自动排列 | 添加节点 | chain summary.Rectangle {+ id: canvasTools+ objectName: "node-canvas-tools"+ anchors.horizontalCenter: parent.horizontalCenter+ anchors.bottom: parent.bottom+ anchors.bottomMargin: 12 + 16 + 8+ z: 4+ width: toolsRow.implicitWidth + 8+ height: toolsRow.implicitHeight + 8+ radius: 12+ color: Qt.rgba(20 / 255, 20 / 255, 24 / 255, 0.94)+ border.width: 1+ border.color: Theme.stroke2+ RowLayout {+ id: toolsRow+ anchors.centerIn: parent+ spacing: 2+ VButton { objectName: "node-fit"; icon: true; ghost: true; iconName: "fit"; onClicked: root.fitView() }+ VButton { objectName: "node-auto"; icon: true; ghost: true; iconName: "magnet"; onClicked: root.autoArrange() }+ Rectangle { implicitWidth: 1; implicitHeight: 16; color: Theme.stroke2 }+ VButton {+ id: toolsAdd+ objectName: "node-add"+ ghost: true; iconName: "plus"; text: "添加节点"+ onClicked: {+ root.addAt = Qt.point((canvasCard.width / 2 - root.panX) / root.zoom - root.cardWidth / 2,+ (canvasCard.height / 3 - root.panY) / root.zoom)+ addMenu.openAt(toolsAdd, "up")+ }+ }+ VButton {+ id: nodePresetButton+ objectName: "node-presets"+ ghost: true; text: "预设"+ onClicked: nodePresetMenu.openAt(nodePresetButton, "up")+ }+ Rectangle { implicitWidth: 1; implicitHeight: 16; color: Theme.stroke2 }+ Text {+ Layout.leftMargin: 8; Layout.rightMargin: 8+ text: veyra.chain.length + " 个节点 · " + (veyra.chainValid ? "处理链有效" : "草稿未运行")+ color: Theme.t3+ font.family: Theme.fontUi+ font.pixelSize: 11+ }+ }+ }++ // The chain's cost, node by node (user request 2026-09-29): only the+ // enabled nodes on the running path, in processing order, each as+ // wide as its own GPU time; the rest of the source-frame budget is the+ // striped tail. A node still waiting for samples keeps a small+ // labelled slot. Click a segment to find its node.+ Rectangle {+ id: timingStrip+ objectName: "node-timing-strip"anchors.left: parent.leftanchors.right: parent.rightanchors.bottom: parent.bottomanchors.margins: 12- height: 16+ height: 18radius: 5color: Qt.rgba(10 / 255, 10 / 255, 13 / 255, 0.85)-+ visible: segments.length > 0+ readonly property var hues: ({ sr: "#6EA8FF", nr: "#FF8A3D", color: "#A8A8B8", "video-hdr": "#E58BD9",+ "frame-generation": "#3DDC84", protection: "#E7B868" })+ readonly property var segments: {+ const timings = veyra.nodeTimings, chain = veyra.chain+ const byId = {}+ for (const n of chain) byId[n.id] = n+ const out = []+ for (const id of root.pathIds()) {+ const n = byId[id]+ if (!n || !n.enabled) continue+ const t = timings[String(id)] || {}+ out.push({ id: id, label: n.label, color: hues[n.type] || Theme.accent,+ measured: t.state === "measured", ms: t.state === "measured" ? t.ms : 0, state: t.state || "" })+ }+ return out+ }+ readonly property real measuredTotal: segments.reduce((a, g) => a + g.ms, 0)+ readonly property int waiting: segments.filter(g => !g.measured).length+ readonly property real scale: Math.max(measuredTotal, veyra.stageBudgetMs)+ readonly property real spare: veyra.stageBudgetMs > measuredTotal && measuredTotal > 0 ? veyra.stageBudgetMs - measuredTotal : 0+ function widthOf(g) {+ const free = width - 2 - waiting * 74 - Math.max(0, segments.length - 1)+ if (!g.measured) return 72+ return scale > 0 ? Math.max(40, free * g.ms / scale) : 40+ }Row {anchors.fill: parentanchors.margins: 1spacing: 1Repeater {- model: veyra.stageTimings+ model: timingStrip.segmentsdelegate: Rectangle {required property var modelDataheight: parent.height- width: modelData.measured ? Math.max(4, parent.width * modelData.fraction) : 24+ width: timingStrip.widthOf(modelData)+ radius: 4color: modelData.measured ? modelData.color : Qt.rgba(1, 1, 1, 0.12)+ Behavior on width { NumberAnimation { duration: Theme.d(600); easing.bezierCurve: Theme.springSoft } }Text {anchors.centerIn: parent- // Only draw the label where the segment is wide enough- // to hold it; an elided repeat of every stage name- // made the strip unreadable.- visible: parent.width > 64- text: modelData.measured ? modelData.label + " " + modelData.ms.toFixed(1) : "未接入"- color: Qt.rgba(0, 0, 0, 0.78)+ width: parent.width - 6+ horizontalAlignment: Text.AlignHCenter+ elide: Text.ElideRight+ text: modelData.label + " " + (modelData.measured ? modelData.ms.toFixed(1) + " ms"+ : modelData.state === "sdk" ? "SDK内部" : modelData.state === "fused" ? "并入输入" : "等待样本")+ color: modelData.measured ? Qt.rgba(0, 0, 0, 0.8) : Theme.t3font.family: Theme.fontUifont.pixelSize: 10font.weight: Font.DemiBold; font.variableAxes: Theme.axesDemiBold- elide: Text.ElideRight- width: parent.width - 6- horizontalAlignment: Text.AlignHCenter}+ HoverHandler { id: segHover; cursorShape: Qt.PointingHandCursor }+ ToolTip.visible: segHover.hovered+ ToolTip.text: modelData.label + ":" + (modelData.measured ? modelData.ms.toFixed(2) + " ms(GPU P95)" : "暂无本节点计时")+ TapHandler {+ gesturePolicy: TapHandler.WithinBounds+ onTapped: root.focusNode(modelData.id)+ }+ }+ }+ // 源帧预算余量: striped, as in the design.+ Rectangle {+ visible: timingStrip.spare > 0+ height: parent.height+ width: Math.max(0, parent.width - x)+ radius: 4+ color: "transparent"+ border.width: 1+ border.color: Qt.rgba(1, 1, 1, 0.12)+ clip: true+ Text {+ anchors.centerIn: parent+ visible: parent.width > 90+ text: "余量 " + timingStrip.spare.toFixed(1) + " ms"+ color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 10}}}@@ -286,70 +996,261 @@ VPage {}}- // A node card: header with its own cost, then its parameters on the card.+ // A small caption above a control inside the fixed boxes.+ component NodeLabel: Text {+ color: Theme.t3+ font.family: Theme.fontUi+ font.pixelSize: 10+ }+ // engine::ContentRate order (same list as the professional page).+ readonly property var contentRates: [+ { id: "0", label: "采用源时间戳" }, { id: "1", label: "自动识别内容节奏" },+ { id: "2", label: "识别 30fps 内容" }, { id: "3", label: "识别 50fps 内容" },+ { id: "4", label: "识别 60fps 内容" }, { id: "5", label: "采集 60→30(PS5 30 帧)" }+ ]+ // A draggable fixed box (输入 / 光流 / 输出). The top strip (or the whole box+ // when it has no controls) is the drag handle.+ component AnchorBox: Rectangle {+ id: box+ required property string key+ property real handleHeight: height+ property bool animate: true+ readonly property point saved: root.anchorPos(key)+ x: saved.x+ y: saved.y+ Behavior on x { enabled: box.animate; NumberAnimation { duration: Theme.d(550); easing.bezierCurve: Theme.spring } }+ Behavior on y { enabled: box.animate; NumberAnimation { duration: Theme.d(550); easing.bezierCurve: Theme.spring } }+ onXChanged: wires.requestPaint()+ onYChanged: wires.requestPaint()+ radius: 10+ color: "#1D1D22"+ border.width: 1+ border.color: Theme.stroke2+ Item {+ width: parent.width; height: box.handleHeight+ z: -1+ HoverHandler { cursorShape: Qt.SizeAllCursor }+ DragHandler {+ target: null+ property real ox: 0+ property real oy: 0+ // Scene coordinates: the handle moves with the box, so its own+ // local translation would feed back into itself.+ property point start: Qt.point(0, 0)+ onActiveChanged: {+ if (active) { box.animate = false; ox = box.x; oy = box.y; start = centroid.scenePressPosition; return }+ veyra.setNodeAnchor(box.key, box.x, box.y)+ box.x = Qt.binding(() => box.saved.x); box.y = Qt.binding(() => box.saved.y)+ box.animate = true+ root.settle(box.key)+ }+ onCentroidChanged: if (active) {+ box.x = ox + (centroid.scenePosition.x - start.x) / root.zoom+ box.y = oy + (centroid.scenePosition.y - start.y) / root.zoom+ }+ }+ }+ }++ // A node card: header (drag handle, collapse, cost, switch, detach) and the+ // node's FULL parameters on the card, the same editors and bridge calls as+ // the list page (user decision 2026-09-28).component NodeCard: Rectangle {id: card- required property var node+ property var node: ({})+ property bool collapsed: false+ property bool animate: true+ property bool willDetach: false+ objectName: "node-card-" + node.index+ readonly property var nr: veyra.nrLayers.find(layer => layer.index === node.index) || nullreadonly property bool locked: node.mustBeLast === true+ readonly property bool linked: veyra.nodeConnections.some(e => e.to === node.id)- x: node.x- y: node.y- width: 236- height: node.type === "nrEnhance" ? 248 : 104+ x: node.x !== undefined ? node.x : 0+ y: node.y !== undefined ? node.y : 0+ Behavior on x { enabled: card.animate; NumberAnimation { duration: Theme.d(550); easing.bezierCurve: Theme.spring } }+ Behavior on y { enabled: card.animate; NumberAnimation { duration: Theme.d(550); easing.bezierCurve: Theme.spring } }+ onXChanged: wires.requestPaint()+ onYChanged: wires.requestPaint()+ onHeightChanged: { wires.requestPaint(); if (!headDrag.active) settleTimer.restart() }+ onWidthChanged: settleTimer.restart()+ z: root.selectedId === node.id ? 3 : (headDrag.active ? 4 : 1)+ width: node.type === "color" ? 360 : node.type === "nr" ? 320 : 272+ height: body.implicitHeightradius: 10color: "#1D1D22"- border.width: 1- border.color: root.selectedNode === node.index ? "#FFFFFF" : Qt.rgba(1, 1, 1, 0.1)+ opacity: (node.enabled ? 1 : 0.74) * lifeOpacity+ property real lifeScale: 1+ property real lifeOpacity: 1+ scale: lifeScale+ Component.onCompleted: if (node.id === root.bornId && Theme.d(600) > 0) { lifeScale = 0.6; lifeOpacity = 0; bornAnim.start() }+ ParallelAnimation {+ id: bornAnim+ NumberAnimation { target: card; property: "lifeScale"; to: 1; duration: Theme.d(600); easing.bezierCurve: Theme.spring }+ NumberAnimation { target: card; property: "lifeOpacity"; to: 1; duration: Theme.d(300) }+ }+ property var dieDone: null+ function die(done) {+ dieDone = done+ if (Theme.d(220) <= 0) { const f = dieDone; dieDone = null; if (f) f(); return }+ dieAnim.restart()+ }+ ParallelAnimation {+ id: dieAnim+ NumberAnimation { target: card; property: "lifeScale"; to: 0.7; duration: Theme.d(220); easing.bezierCurve: Theme.easeOut }+ NumberAnimation { target: card; property: "lifeOpacity"; to: 0; duration: Theme.d(220); easing.bezierCurve: Theme.easeOut }+ onFinished: { const f = card.dieDone; card.dieDone = null; if (f) f() }+ }+ border.width: willDetach || root.marked.indexOf(node.id) >= 0 ? 2 : 1+ border.color: willDetach ? Theme.err : root.selectedId === node.id ? "#FFFFFF"+ : root.marked.indexOf(node.id) >= 0 ? Theme.accent : Qt.rgba(1, 1, 1, 0.1)Behavior on border.color { ColorAnimation { duration: Theme.d(200) } }+ Behavior on opacity { NumberAnimation { duration: Theme.d(200) } }- DragHandler {- id: drag- enabled: !card.locked- target: null- onActiveTranslationChanged: {- card.x = Math.max(-800, card.x + activeTranslation.x / root.zoom)- card.y = Math.max(-600, card.y + activeTranslation.y / root.zoom)- }- onActiveChanged: if (!active) veyra.setEffectPosition(card.node.index, card.x, card.y)- }TapHandler {acceptedButtons: Qt.LeftButton- onTapped: root.selectedNode = card.node.index+ onTapped: root.selectId(card.node.id)}TapHandler {acceptedButtons: Qt.RightButton- onTapped: if (!card.locked) veyra.removeEffect(card.node.index)+ onTapped: eventPoint => {+ root.selectId(card.node.id)+ nodeMenu.targetId = card.node.id+ // The menu opens where the pointer is, not under the card.+ const p = card.mapToItem(canvasCard, eventPoint.position.x, eventPoint.position.y)+ tapAnchor.x = p.x; tapAnchor.y = p.y+ nodeMenu.openAt(tapAnchor, "at")+ }+ }++ NodePort { nodeId: card.node.id !== undefined ? card.node.id : -1; output: false; x: -width / 2; y: 16 - height / 2 }+ NodePort { nodeId: card.node.id !== undefined ? card.node.id : -1; output: true; x: card.width - width / 2; y: 16 - height / 2 }++ // Per-card adapter so ColourPanel edits THIS colour node: reads its own+ // state, writes through the selected-layer setters after selecting it.+ QtObject {+ id: colourApi+ function select() { veyra.selectedColourLayer = card.node.index }+ readonly property var colourState: (veyra.chain, veyra.colourStateAt(card.node.index))+ readonly property var colourParameters: veyra.colourParameters+ property bool colorEnabled: false+ onColorEnabledChanged: if (colorEnabled !== !!colourState.enabled) { select(); veyra.colorEnabled = colorEnabled }+ function setColourParameter(k, v) { select(); return veyra.setColourParameter(k, v) }+ function setColourCurve(c, points) { select(); return veyra.setColourCurve(c, points) }+ function setColourOption(n, v) { select(); return veyra.setColourOption(n, v) }+ function setColourWheel(z, h, s, l) { select(); return veyra.setColourWheel(z, h, s, l) }+ function resetColourGroup(g) { select(); return veyra.resetColourGroup(g) }+ readonly property var lutLibrary: veyra.lutLibrary+ readonly property var colourLooks: veyra.colourLooks+ function importLutDialog() { select(); veyra.importLutDialog() }+ function setColourLut(n) { select(); return veyra.setColourLut(n) }+ function saveColourLook(n, r) { select(); return veyra.saveColourLook(n, r) }+ function applyColourLook(i) { select(); return veyra.applyColourLook(i) }+ function deleteColourLook(i) { return veyra.deleteColourLook(i) }+ function importColourLookDialog() { veyra.importColourLookDialog() }+ function exportColourLookDialog(i) { veyra.exportColourLookDialog(i) }+ function holdOriginal(held) { veyra.holdOriginal(held) }+ readonly property bool colourCanUndo: veyra.colourCanUndo+ readonly property bool colourCanRedo: veyra.colourCanRedo+ readonly property bool colourCanPaste: veyra.colourCanPaste+ function colourUndo() { return veyra.colourUndo() }+ function colourRedo() { return veyra.colourRedo() }+ function colourCopy() { select(); veyra.colourCopy() }+ function colourPaste() { select(); return veyra.colourPaste() }}+ Binding { target: colourApi; property: "colorEnabled"; value: !!colourApi.colourState.enabled }ColumnLayout {- anchors.fill: parent+ id: body+ width: card.widthspacing: 0- // Header: colour plate, title, the node's own cost, the lock, the switch.+ // Header: the drag handle.Rectangle {+ id: head+ objectName: "node-head-" + card.node.idLayout.fillWidth: true- implicitHeight: 32+ implicitHeight: 34radius: 9- color: "#26262C"+ // .bnode .bh: linear-gradient(90deg, hue 55 % into the card+ // colour, hue 18 %), per node type.+ readonly property color hue: root.hueOf(card.node.type)+ function mix(a) { return Qt.rgba(hue.r * a + 0.114 * (1 - a), hue.g * a + 0.114 * (1 - a), hue.b * a + 0.133 * (1 - a), 1) }+ gradient: Gradient {+ orientation: Gradient.Horizontal+ GradientStop { position: 0; color: head.mix(0.55) }+ GradientStop { position: 1; color: head.mix(0.18) }+ }+ // The grip stops 14px short of both sides: the ports straddle the+ // card's edges at header height, and a press there belongs to the+ // port (drag a wire), not to moving the card.+ Item {+ id: headGrip+ anchors.fill: parent+ anchors.leftMargin: 14+ anchors.rightMargin: 14+ HoverHandler { cursorShape: Qt.SizeAllCursor }+ DragHandler {+ id: headDrag+ target: null+ property real ox: 0+ property real oy: 0+ property point start: Qt.point(0, 0)+ onActiveChanged: {+ if (active) { card.animate = false; ox = card.x; oy = card.y; start = centroid.scenePressPosition; root.selectId(card.node.id); return }+ const id = card.node.id, index = card.node.index+ const alt = (centroid.modifiers & Qt.AltModifier) !== 0+ const hot = root.hotFrom >= 0 ? { from: root.hotFrom, to: root.hotTo } : null+ root.hotFrom = root.hotTo = -1+ card.willDetach = false+ veyra.logUi("ui-node", "drop " + id + " at " + Math.round(card.x) + "," + Math.round(card.y) + " linked=" + card.linked + " hot=" + (hot ? hot.from + ">" + hot.to : "none"))+ veyra.setEffectPosition(index, card.x, card.y)+ card.x = Qt.binding(() => card.node.x); card.y = Qt.binding(() => card.node.y)+ card.animate = true+ if (hot) {+ if (veyra.insertNodeAfter(id, hot.from)) veyra.logUi("ui-node", "insert " + id + " after " + hot.from)+ } else if (card.linked && (alt || Math.abs(card.y - oy) > 220)) {+ root.detach(id, false); return+ }+ Qt.callLater(() => root.settle("n" + id))+ }+ onCentroidChanged: {+ if (!active) return+ card.x = ox + (centroid.scenePosition.x - start.x) / root.zoom+ card.y = oy + (centroid.scenePosition.y - start.y) / root.zoom+ const alt = (centroid.modifiers & Qt.AltModifier) !== 0+ const e = (!card.linked || alt) ? root.nearestLink(card.x + card.width / 2, card.y + 30, card.node.id) : null+ root.hotFrom = e ? e.from : -1; root.hotTo = e ? e.to : -1+ card.willDetach = card.linked && (alt || Math.abs(card.y - oy) > 220)+ wires.requestPaint()+ }+ }+ }RowLayout {anchors.fill: parent- anchors.leftMargin: 8+ anchors.leftMargin: 6anchors.rightMargin: 6- spacing: 6+ spacing: 5+ Item {+ implicitWidth: 18; implicitHeight: 18+ VIcon { anchors.centerIn: parent; name: "down"; size: 12; color: Theme.t2; rotation: card.collapsed ? -90 : 0+ Behavior on rotation { NumberAnimation { duration: Theme.d(300); easing.bezierCurve: Theme.spring } } }+ TapHandler { onTapped: { card.collapsed = !card.collapsed; Qt.callLater(() => root.settle("n" + card.node.id)) } }+ }Rectangle {width: 8; height: 8; radius: 4- color: card.node.enabled ? Theme.accent : Theme.t3+ color: card.node.enabled ? "#FFFFFF" : Qt.rgba(1, 1, 1, 0.35)}Text {Layout.fillWidth: true- text: card.node.label+ text: card.node.label || ""color: Theme.t1font.family: Theme.fontUifont.pixelSize: Theme.fsBodyfont.weight: Font.DemiBold; font.variableAxes: Theme.axesDemiBoldelide: Text.ElideRight}- // .ms badge: this node's cost, or "未接入" when it has none.+ // .ms badge: this node's own GPU cost, or why there is none.Rectangle {implicitWidth: msText.implicitWidth + 12implicitHeight: 18@@ -357,67 +1258,333 @@ VPage {color: Qt.rgba(0, 0, 0, 0.35)Text {id: msText+ objectName: "node-ms-" + card.node.id+ readonly property var timing: veyra.nodeTimings[String(card.node.id)] || ({})anchors.centerIn: parent- text: card.node.costMs > 0 ? card.node.costMs.toFixed(1) + " ms" : "未接入"- color: card.node.costMs > 0 ? "#FFFFFF" : Theme.t3+ text: {+ switch (timing.state) {+ case "measured": return timing.ms.toFixed(2) + " ms"+ case "fused": return "并入输入"+ case "sdk": return "SDK内部"+ case "disabled": return "已停用"+ case "idle": return "未连接"+ case "draft": return "草稿未运行"+ case "pending": return "等待样本"+ case "stopped": return "未播放"+ case "hdr-sdr": return "SDR显示未转换"+ case "fg-skipped": return "预算拒绝"+ default: return "不计时"+ }+ }+ color: timing.state === "measured" ? Theme.t1 : Theme.t3font.family: Theme.fontMonofont.pixelSize: 10font.weight: Font.DemiBold; font.variableAxes: Theme.axesDemiBold}}VIcon { visible: card.locked; name: "key"; size: 10; color: Theme.t3 }+ VSwitch {+ objectName: "node-enable-" + card.node.id+ checked: card.node.enabled === true+ onToggled: veyra.setEffectEnabled(card.node.index, checked)+ }+ VButton {+ objectName: "node-unlink-" + card.node.id+ visible: card.linked+ icon: true; ghost: true; iconName: "unlink"+ onClicked: root.detach(card.node.id, true)+ }}}- // Node parameters live on the node itself, per the design.- ColumnLayout {+ Loader {+ id: editorLoaderLayout.fillWidth: trueLayout.margins: 10- spacing: 4- visible: card.node.type === "nrEnhance"+ visible: !card.collapsed+ active: card.node.type !== undefined+ sourceComponent: card.node.type === "nr" ? nrEditor+ : card.node.type === "color" ? colourEditor+ : card.node.type === "sr" ? srEditor+ : card.node.type === "video-hdr" ? hdrEditor+ : card.node.type === "frame-generation" ? fgEditor : null+ }+ Item { implicitHeight: card.collapsed ? 0 : 4 }+ }- Text { text: "强度"; color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 10 }- VSlider {- Layout.fillWidth: true- from: 0; to: 1; value: veyra.nrIntensity- onMoved: veyra.nrIntensity = value+ Component {+ id: nrEditor+ NrLayerEditor {+ objectName: "node-nr-editor-" + card.node.id+ listControls: false+ layerData: card.nr || ({index: card.node.index, sizePolicy: 0, intensity: 0, tone: 0, structure: 0, skin: -1, style: 0, autoMask: false, uiCorrection: false, total: 0, darken: 0, brighten: 0, color: 0, luminance: 0, temporal: false})+ layerCount: veyra.nrLayers.length+ onEdited: (i, k, v) => veyra.setNrLayerParameter(i, k, v)+ }+ }+ Component {+ id: colourEditor+ ColourPanel { objectName: "node-colour-editor-" + card.node.id; api: colourApi; compact: true }+ }+ Component {+ id: srEditor+ ColumnLayout {+ objectName: "node-sr-editor-" + card.node.id+ spacing: 6+ VRow {+ label: "目标尺寸"+ hint: "决定输出分辨率"+ VSeg {+ options: [{ id: "1", label: "2K" }, { id: "2", label: "4K" }, { id: "4", label: "5K" }, { id: "5", label: "6K" }, { id: "6", label: "7K" }, { id: "3", label: "8K" }]+ current: String(veyra.srTargetIndex)+ onPicked: id => veyra.srTargetIndex = parseInt(id)+ }+ }+ VRow {+ label: "超分运动来源"+ hint: "零运动会限制时序重建;RTX 视频超分不使用此输入"+ VSeg { options: [{id:"0",label:"零运动"},{id:"1",label:"光流"}]; current: String(veyra.srMotionSource); onPicked: id => veyra.srMotionSource = Number(id) }}- Text { text: "局部明暗"; color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 10 }- VSlider {+ VRow {+ label: "质量"+ hint: "RTX 视频超分档位"+ VSeg {+ options: [{ id: "1", label: "1" }, { id: "2", label: "2" }, { id: "3", label: "3" }, { id: "4", label: "4" }]+ current: String(veyra.videoSrQuality)+ onPicked: id => veyra.videoSrQuality = parseInt(id)+ }+ }+ }+ }+ Component {+ id: hdrEditor+ ColumnLayout {+ objectName: "node-hdr-editor-" + card.node.id+ spacing: 4+ Text {Layout.fillWidth: true- from: 0; to: 1; value: veyra.nrTone- onMoved: veyra.nrTone = value+ text: veyra.videoHdrStatus.length > 0 ? veyra.videoHdrStatus : "SDR → HDR,在补帧之前"+ color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 11; wrapMode: Text.WordWrap+ }+ Repeater {+ model: [{key:"contrast",label:"对比度",from:0,to:200,def:125},+ {key:"saturation",label:"饱和度",from:0,to:200,def:75},+ {key:"middleGray",label:"中灰",from:10,to:100,def:44},+ {key:"peakNits",label:"峰值亮度 (nit)",from:400,to:2000,def:1000}]+ delegate: VRow {+ required property var modelData+ label: modelData.label+ value: String(veyra.videoHdrParams[modelData.key] ?? "—")+ VSlider {+ objectName: "node-hdr-" + modelData.key+ implicitWidth: 110+ valueFromModel: true+ resettable: true; defaultValue: modelData.def+ from: modelData.from; to: modelData.to+ value: veyra.videoHdrParams[modelData.key] ?? modelData.def+ onMoved: value => veyra.setVideoHdrParameter(modelData.key, Math.round(value))+ }+ }}- Text { text: "局部结构"; color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 10 }- VSlider {+ }+ }+ Component {+ id: fgEditor+ ColumnLayout {+ objectName: "node-fg-editor-" + card.node.id+ spacing: 6+ Text {Layout.fillWidth: true- from: 0; to: 1; value: veyra.nrStructure- onMoved: veyra.nrStructure = value+ text: "链路中固定为最后一步;画布上可移动"+ color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 11; wrapMode: Text.WordWrap+ }+ VRow {+ label: "补帧方式"+ hint: veyra.fgProviderText+ VSelect {+ objectName: "node-fg-backend"+ options: veyra.fgBackendChoices+ value: (options.find(o => o.id === veyra.fgBackendName) || options[0]).label+ onPicked: id => veyra.fgBackendName = id+ }+ }+ VRow {+ label: "倍率"+ hint: veyra.fgMaxMultiplier + "X 为上限"+ VSeg {+ objectName: "node-fg-multiplier"+ options: veyra.fgMultiplierChoices+ current: String(veyra.fgMultiplier)+ onPicked: id => veyra.fgMultiplier = parseInt(id)+ }+ }+ VRow {+ label: "补帧运动来源"+ hint: "XeSS 默认零运动;FSR 仍有自身的光流计算"+ VSeg { objectName: "node-fg-motion"; options: [{id:"0",label:"零运动"},{id:"1",label:"光流"}]; current: String(veyra.fgMotionSource); onPicked: id => veyra.fgMotionSource = Number(id) }+ }+ VRow {+ label: "严格补帧节奏"+ hint: "帧同步 · 默认关闭"+ VSwitch { checked: veyra.fgStrict; onToggled: veyra.fgStrict = checked }+ }+ VRow {+ label: "低延迟队列"+ hint: "减少排队;不宣称延迟下降"+ VSwitch { checked: veyra.fgLowQueue; onToggled: veyra.fgLowQueue = checked }}}+ }+ }- // A non-NR node shows its summary so the card is not blank.- Text {- Layout.fillWidth: true- Layout.margins: 10- visible: card.node.type !== "nrEnhance"- text: card.locked ? "固定为最后一步,不能拖动"- : (card.node.enabled ? "已启用" : "已关闭")- color: Theme.t3- font.family: Theme.fontUi- font.pixelSize: 11- wrapMode: Text.WordWrap+ component NodePort: Rectangle {+ id: port+ required property int nodeId+ required property bool output+ objectName: (output ? "node-out-" : "node-in-") + nodeId+ z: 5; width: 22; height: 22; radius: 11+ color: root.wireFrom === nodeId && output ? Theme.accent : (portHover.hovered ? Theme.accentSoft : Theme.card3)+ border.width: 2; border.color: portHover.hovered ? Theme.accent : Theme.stroke2+ HoverHandler { id: portHover; cursorShape: Qt.CrossCursor }+ // Click an output, then an input (or press Esc / click empty canvas).+ TapHandler {+ acceptedButtons: Qt.LeftButton+ onTapped: {+ if (port.output) { root.wireFrom = port.nodeId; root.pointerWorld = root.endpoint(port.nodeId, true); wires.requestPaint() }+ else if (root.wireFrom >= 0) { root.rewire(root.wireFrom, port.nodeId); root.wireFrom = -1; wires.requestPaint() }+ }+ }+ // Or drag from an output straight onto an input.+ DragHandler {+ enabled: port.output+ target: null+ onActiveChanged: {+ if (active) { root.wireFrom = port.nodeId; return }+ const to = root.inputAt(root.pointerWorld)+ if (to >= 0) root.rewire(port.nodeId, to)+ root.wireFrom = -1; wires.requestPaint()+ }+ onCentroidChanged: if (active) {+ root.pointerWorld = world.mapFromItem(port, centroid.position.x, centroid.position.y)+ wires.requestPaint()}+ }+ TapHandler { acceptedButtons: Qt.RightButton; onTapped: if (port.output) veyra.disconnectNode(port.nodeId) }+ ToolTip.visible: portHover.hovered+ ToolTip.text: output ? "拖到输入端口连接,或点击后再点输入端口;右键断开" : "连接到此输入"+ }- Item { Layout.fillHeight: true }+ VMenu {+ id: nodePresetMenu+ objectName: "node-preset-menu"+ title: "节点预设"+ items: veyra.presets.filter(p => p.nodeMode === true)+ .map(p => ({ label: p.name, note: p.note, checked: p.name === veyra.currentPresetName,+ tag: p.builtin ? "内置" : "", preset: p.index }))+ .concat([{ sep: true },+ { label: "把当前设置另存为预设…", icon: "plus", act: "save" },+ { label: "管理预设…", icon: "settings", act: "manage" }])+ onPicked: (i, o) => {+ if (o.act) root.requestDialog(o.act)+ else veyra.applyPresetIndex(o.preset)+ }+ }++ VMenu {+ id: nodeMenu+ objectName: "node-context-menu"+ property int targetId: -1+ readonly property var targetNode: veyra.chain.find(n => n.id === targetId) || ({})+ readonly property var descriptor: veyra.effectDescriptor(targetNode.type || "")+ readonly property bool canCopy: descriptor.repeatable === true &&+ veyra.chain.filter(n => n.type === targetNode.type).length < descriptor.maxInstances+ title: targetNode.label || "节点"+ items: [+ {label: "删除节点", id: "delete", disabled: targetNode.mustBeLast === true, note: targetNode.mustBeLast ? "补帧固定末位,可关闭" : ""},+ {label: "复制节点", id: "copy", disabled: !canCopy, note: canCopy ? "完整参数副本,旁置未连接" : "单例节点或数量已达上限"},+ {label: "重置节点", id: "reset"}+ ]+ onPicked: (i, item) => {+ const index = veyra.nodeIndexForId(targetId)+ if (index < 0) return+ if (item.id === "delete") root.removeNodeAnimated(targetId)+ else if (item.id === "reset") veyra.resetNode(targetId)+ else {+ const copy = veyra.duplicateNode(targetId)+ if (copy >= 0) { root.markBorn(veyra.chain[copy].id); root.selectId(veyra.chain[copy].id) }+ }}}VMenu {id: addMenu+ objectName: "node-add-menu"title: "添加节点"items: veyra.effectCatalog.map(e => ({ label: e.label, id: e.id, tag: e.experimental ? "实验" : "", tagKind: e.experimental ? "warn" : "" }))- onPicked: (i, o) => veyra.addEffect(o.id)+ onPicked: (i, o) => {+ // The new card's id is only known after it exists; the next id the+ // chain will hand out is one past the largest.+ root.markBorn(veyra.chain.reduce((m, n) => Math.max(m, n.id), 1) + 1)+ const index = veyra.addEffect(o.id)+ if (index >= 0 && root.addAt)+ veyra.setEffectPosition(index, root.addAt.x, root.addAt.y)+ root.addAt = null+ if (index >= 0 && index < veyra.chain.length) root.markBorn(veyra.chain[index].id)+ if (index >= 0 && index < veyra.chain.length) root.selectId(veyra.chain[index].id)+ }+ }++ VMenu {+ id: nodeSourceMenu+ objectName: "node-source-menu"+ title: "片源"+ items: (veyra.sourceTitle.length > 0+ ? [{ label: veyra.sourceTitle, note: veyra.sourceFormatText, checked: true, icon: "video", act: "" }] : [])+ .concat([{ label: "打开文件…", icon: "folder", act: "file" },+ { label: "PS5 串流…", icon: "gamepad", act: "ps5" },+ { label: "屏幕捕获…", icon: "monitor", act: "screen" },+ { sep: true },+ { label: "采集卡设置…", icon: "settings", act: "capture" }])+ onPicked: (i, o) => {+ if (o.act === "file") veyra.openFileDialog()+ else if (o.act === "ps5") veyra.openPs5Dialog()+ else if (o.act === "screen") veyra.openScreenCaptureDialog()+ else if (o.act === "capture") veyra.openCaptureDialog()+ }+ }+ VConfirm {+ id: returnDialog+ objectName: "node-return-dialog"+ cardWidth: 480+ glyph: "list"+ title: "切换回列表模式?"+ acceptText: "切换到列表模式"+ acceptIcon: "list"+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 6+ Repeater {+ model: ["回到列表模式,恢复列表之前的设置和预设。", "节点链会保留,下次切回节点模式时继续使用。",+ "切换会重建处理链,画面可能停顿几百毫秒。"]+ delegate: RowLayout {+ required property string modelData+ Layout.fillWidth: true+ spacing: 8+ Rectangle { Layout.alignment: Qt.AlignTop; Layout.topMargin: 7; implicitWidth: 4; implicitHeight: 4; radius: 2; color: Theme.t3 }+ Text {+ Layout.fillWidth: true+ text: modelData+ color: Theme.t2+ font.family: Theme.fontUi; font.pixelSize: 12+ wrapMode: Text.WordWrap+ }+ }+ }+ }+ onAccepted: {+ veyra.nodeMode = 0+ if (veyra.nodeMode === 0) root.requestPage("pro")+ }}// [data-in] entrance order from pages-node.js.diff --git a/qml/Veyra/NrLayerEditor.qml b/qml/Veyra/NrLayerEditor.qmlnew file mode 100644index 00000000..89b16008--- /dev/null+++ b/qml/Veyra/NrLayerEditor.qml@@ -0,0 +1,216 @@+// One NR layer's full parameter set, shared by the list page's NR card and the+// node page's NR node so both edit exactly the same values through the same+// bridge calls (user decision 2026-09-28: node parameters equal to the list).+import QtQuick+import QtQuick.Layouts++ColumnLayout {+ id: editor+ required property var layerData+ property int layerCount: 1+ property bool nrFirst: false+ // The list page owns copy/delete and the list-wide NR->SR order; the node+ // page uses its node menu and wiring instead.+ property bool listControls: true+ signal edited(int nodeIndex, string key, double amount)+ signal duplicateRequested(int nodeIndex)+ signal removeRequested(int nodeIndex)+ signal orderEdited(bool enabled)+ readonly property var sizeChoices: [+ {id:"2",label:"480p"}, {id:"3",label:"720p"}, {id:"4",label:"900p"},+ {id:"0",label:"1080p · 默认"}, {id:"5",label:"1440p"}, {id:"1",label:"原生"}+ ]+ readonly property string sizeLabel: sizeChoices.find(o => Number(o.id) === layerData.sizePolicy)?.label ?? "未知"+ spacing: 6++ component NrValueRow: VRow {+ id: valueRow+ required property var spec+ required property double amount+ signal edited(double amount)+ label: spec.label+ value: amount.toFixed(2)+ VSlider {+ objectName: "nr-" + valueRow.spec.key+ valueFromModel: true+ resettable: true; defaultValue: valueRow.spec.key === "skin" ? -1 : 1+ implicitWidth: 110+ from: valueRow.spec.min; to: valueRow.spec.max+ value: valueRow.amount+ onMoved: value => valueRow.edited(value)+ }+ }++ RowLayout {+ Layout.fillWidth: true+ visible: editor.listControls+ VButton {+ objectName: "nr-copy"+ text: "复制此层"; enabled: editor.layerCount < 4+ onClicked: editor.duplicateRequested(editor.layerData.index)+ }+ VButton {+ objectName: "nr-reset"+ text: "恢复默认"; ghost: true+ onClicked: veyra.resetNrLayer(editor.layerData.index)+ }+ VButton {+ objectName: "nr-remove"+ text: "删除此层"+ onClicked: editor.removeRequested(editor.layerData.index)+ }+ }+ VRow {+ label: "NR 版本"+ hint: "全链共享 · 切换会重建 NR 管线"+ VSelect {+ objectName: "nr-runtime"+ value: editor.layerData.runtime === 2 ? "RTX 20–50 · SF-v2" : "RTX 50 · Lecram"+ options: [{id:"0",label:"RTX 50 · Lecram"},{id:"2",label:"RTX 20–50 · SF-v2"}]+ onPicked: id => editor.edited(editor.layerData.index, "runtime", Number(id))+ }+ }+ VRow {+ label: "NR 运动来源"+ hint: "全链共享;抗闪烁开启时仍需估算光流"+ VSeg {+ objectName: "nr-motion-source"+ options: [{id:"0",label:"零运动"},{id:"1",label:"光流"}]+ current: String(veyra.nrMotionSource)+ onPicked: id => veyra.nrMotionSource = Number(id)+ }+ }+ VRow {+ label: "内部处理分辨率"+ hint: "内部降采样 · 不改变输出尺寸"+ VSelect {+ objectName: "nr-resolution"+ value: editor.sizeLabel; options: editor.sizeChoices+ onPicked: id => editor.edited(editor.layerData.index, "sizePolicy", Number(id))+ }+ }+ Text {+ Layout.fillWidth: true+ text: "预览保留比例且不放大小输入;图片/视频导出仍完整处理。"+ color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 11+ wrapMode: Text.WordWrap+ }+ NrValueRow {+ spec: ({key:"intensity",label:"模型强度",min:0,max:1})+ amount: editor.layerData.intensity+ onEdited: amount => editor.edited(editor.layerData.index, "intensity", amount)+ }+ VSubGroup {+ objectName: "nr-model-group"+ Layout.fillWidth: true+ label: "模型参数"; count: 6+ Repeater {+ model: [{key:"tone",label:"局部明暗",min:0,max:1},+ {key:"structure",label:"局部结构",min:0,max:1}]+ delegate: NrValueRow {+ required property var modelData+ spec: modelData; amount: editor.layerData[modelData.key]+ onEdited: amount => editor.edited(editor.layerData.index, modelData.key, amount)+ }+ }+ VRow {+ label: "肤质 · 未证实"+ VSelect {+ objectName: "nr-skin-mode"+ value: editor.layerData.skin < 0 ? "未指定" : "自定义"+ options: [{id:"-1",label:"未指定"},{id:"0",label:"自定义"}]+ onPicked: id => editor.edited(editor.layerData.index,"skin",Number(id))+ }+ }+ NrValueRow {+ visible: editor.layerData.skin >= 0+ spec: ({key:"skin",label:"肤质数值",min:0,max:2})+ amount: Math.max(0,editor.layerData.skin)+ onEdited: amount => editor.edited(editor.layerData.index,"skin",amount)+ }+ VRow {+ label: "风格 · 实验"+ VSeg {+ objectName: "nr-style"+ options: [{id:"0",label:"0"},{id:"1",label:"1"},{id:"2",label:"2"}]+ current: String(editor.layerData.style)+ onPicked: id => editor.edited(editor.layerData.index,"style",Number(id))+ }+ }+ VRow {+ label: "自动遮罩 · 实验"+ VSwitch {+ objectName: "nr-autoMask"+ checked: editor.layerData.autoMask+ onToggled: checked => editor.edited(editor.layerData.index,"autoMask",checked?1:0)+ }+ }+ VRow {+ label: "UI 修正 · 未证实"+ VSwitch {+ objectName: "nr-uiCorrection"+ checked: editor.layerData.uiCorrection+ onToggled: checked => editor.edited(editor.layerData.index,"uiCorrection",checked?1:0)+ }+ }+ }+ VSubGroup {+ objectName: "nr-residual-group"+ Layout.fillWidth: true+ label: "增强变化量"; count: 5+ Repeater {+ model: [{key:"total",label:"总变化强度",min:0,max:2},+ {key:"darken",label:"暗化变化",min:0,max:2},+ {key:"brighten",label:"亮化变化",min:0,max:2},+ {key:"color",label:"色彩变化",min:0,max:2},+ {key:"luminance",label:"明度变化",min:0,max:2}]+ delegate: NrValueRow {+ required property var modelData+ spec: modelData; amount: editor.layerData[modelData.key]+ onEdited: amount => editor.edited(editor.layerData.index,modelData.key,amount)+ }+ }+ }+ VSubGroup {+ objectName: "nr-experimental-group"+ Layout.fillWidth: true+ label: "实验"; count: editor.layerData.temporal ? 3 : 2+ VRow {+ label: "时间域防闪烁"+ hint: "需要光流;关掉则不做时域累积"+ VSwitch {+ objectName: "nr-temporal"+ checked: editor.layerData.temporal+ onToggled: checked => editor.edited(editor.layerData.index,"temporal",checked?1:0)+ }+ }+ VRow {+ objectName: "nr-antiflicker-row"+ // Only meaningful when temporal accumulation is on; the tier picks+ // how the accumulation behaves, not whether it runs.+ visible: editor.layerData.temporal+ label: "抗闪烁档位"+ hint: "静态最稳、光流为默认、低频保留高频细节"+ VSelect {+ objectName: "nr-antiflicker"+ options: [+ {id:"1",label:"静态累积"},+ {id:"2",label:"光流累积 · 默认"},+ {id:"3",label:"光流累积+"},+ {id:"4",label:"低频时域重建"}+ ]+ value: options.find(o => Number(o.id) === editor.layerData.antiFlicker)?.label ?? "光流累积 · 默认"+ onPicked: id => editor.edited(editor.layerData.index,"antiFlicker",Number(id))+ }+ }+ VRow {+ visible: editor.listControls+ label: "NR → SR · 全层"+ hint: "低延迟顺序,仅预览、全层同步"+ VSwitch {+ checked: editor.nrFirst+ onToggled: editor.orderEdited(checked)+ }+ }+ }+}diff --git a/qml/Veyra/ProPage.qml b/qml/Veyra/ProPage.qmlindex 6854f747..e5f4be99 100644--- a/qml/Veyra/ProPage.qml+++ b/qml/Veyra/ProPage.qml@@ -10,21 +10,341 @@// reached through the view toggle (which confirms first, per the design).import QtQuickimport QtQuick.Controls+import QtQuick.Controls.Basic as Basicimport QtQuick.Layoutsimport QtQuick.Shapes+import QtQuick.EffectsVPage {id: rootsignal requestPage(string page)signal requestDialog(string key)+ signal requestFullscreen()+ // Fullscreen quick-adjust (Home, Main.qml): only the inspector is shown, moved+ // to the left of the picture, with the performance orbs beside it. Both are cut+ // out of the native video window like any other cover.+ property bool overlay: false+ function overlayContains(x, y) {+ const hit = item => x >= item.x && x <= item.x + item.width && y >= item.y && y <= item.y + item.height+ return overlay && (hit(insp) || hit(quickOrbs))+ }+ // Leaving the page (or switching to the node editor) disarms region drawing;+ // showing it replays the GPU bars' staggered entrance (M27).+ onVisibleChanged: {+ if (!visible && veyra.protectionDrawShape.length > 0) veyra.beginProtectionDraw("")+ if (visible) armBars()+ }++ // M27 .bar u: width 0 -> value over .8s --spring-soft, bar i starting at+ // 120 + i*60 ms after the page shows; later readings move without the delay.+ property bool barsArmed: false+ property bool barsSettled: false+ function armBars() { barsSettled = false; barsArmed = false; barsArmTimer.restart() }+ Timer { id: barsArmTimer; interval: 16; onTriggered: { root.barsArmed = true; barsSettleTimer.restart() } }+ Timer { id: barsSettleTimer; interval: 1600; onTriggered: root.barsSettled = true }+ Component.onCompleted: armBars()++ // M31: switching tabs redraws the tab's cards one after another+ // (pages-pro.js render(true): 460 ms, i*30 ms, y 10).+ Component { id: staggerComp; VRise.Stagger {} }+ function stagger(col, step, span, dy) {+ if (Theme.reduced || !col) return+ let i = 0+ for (let k = 0; k < col.children.length; ++k) {+ const c = col.children[k]+ if (!c.visible || c.motionDy === undefined) continue+ staggerComp.createObject(root, { target: c, delay: i * step, span: span, dy: dy }).start()+ ++i+ }+ }+ onTabChanged: Qt.callLater(() => stagger(tab === "quality" ? qualityCol : tab === "fg" ? fgCol+ : tab === "color" ? colourPanel.sectionColumn+ : tab === "audio" ? audioCol : displayCol, 30, 460, 10))++ // M30: the NR layer card that was just added pops in; the number is reset+ // shortly after so a later rebuild of the list does not pop it again.+ property int popLayer: -1+ Timer { id: popReset; interval: 900; onTriggered: root.popLayer = -1 }+ function markPop(number) { popLayer = number; popReset.restart() }// Design's st.tab: quality / fg / color / audio / display.property string tab: "quality"property int selectedEffect: -1+ // engine::ContentRate order.+ readonly property var contentRates: [+ { id: "0", label: "采用源时间戳" }, { id: "1", label: "自动识别内容节奏" },+ { id: "2", label: "识别 30fps 内容" }, { id: "3", label: "识别 50fps 内容" },+ { id: "4", label: "识别 60fps 内容" }, { id: "5", label: "采集 60→30(PS5 30 帧)" }+ ]+ // 处理顺序 "点击定位": switch to the chip's tab, open its card and scroll+ // the inspector so the card sits at the top.+ function locateNode(chip) {+ selectedEffect = chip.index+ let target = ""+ if (chip.type === "frame-generation") { tab = "fg"; target = "list-fg-group" }+ else if (chip.type === "color") { tab = "color"; target = "" }+ else {+ tab = "quality"+ if (chip.type === "sr") target = "list-sr"+ else if (chip.type === "video-hdr") target = "list-video-hdr"+ else if (chip.type === "protection") target = "list-global-protection"+ else if (chip.type === "nr") {+ nrStage.open = true+ let ordinal = 0+ for (const n of veyra.chain) { if (n.type === "nr") ++ordinal; if (n.index === chip.index) break }+ target = "nr-card-" + ordinal+ }+ }+ Qt.callLater(() => {+ const find = item => {+ if (!item) return null+ if (target.length > 0 && item.objectName === target) return item+ for (let i = 0; i < item.children.length; ++i) { const r = find(item.children[i]); if (r) return r }+ return null+ }+ const card = target.length > 0 ? find(body) : null+ if (card && card.open !== undefined) card.open = true+ if (card && card.flash !== undefined) card.flash()+ const y = card ? card.mapToItem(body, 0, 0).y - 4 : 0+ inspFlick.contentY = Math.max(0, Math.min(y, Math.max(0, inspFlick.contentHeight - inspFlick.height)))+ })+ }+ onSelectedEffectChanged: {+ veyra.selectedNrLayer = selectedEffect+ veyra.selectedColourLayer = selectedEffect+ }++ // The NR layer card wraps the shared editor (NrLayerEditor.qml).+ // 显示同步 and 输出上限 (1.4.4 PresentationSettings), shared by the list 补帧+ // page and the node editor's output box (ProPage.PresentationRows).+ component PresentationRows: ColumnLayout {+ Layout.fillWidth: true+ spacing: 0+ VRow {+ label: "显示同步"+ hint: "独立于低延迟队列 · 自动:不撕裂,也不等待垂直同步"+ VSeg {+ objectName: "presentation-display-sync"+ options: [{ id: "0", label: "允许撕裂" }, { id: "1", label: "垂直同步" }, { id: "2", label: "自动" }]+ current: String(veyra.displaySync)+ onPicked: id => veyra.displaySync = Number(id)+ }+ }+ VRow {+ label: "输出上限"+ enabled: !veyra.presentationOwned+ hint: veyra.presentationStatus+ VSeg {+ objectName: "presentation-output-rate"+ options: [{ id: "0", label: "关闭" }, { id: "1", label: "跟随显示器" }, { id: "2", label: "自定义" }]+ current: String(veyra.outputRateMode)+ onPicked: id => veyra.outputRateMode = Number(id)+ }+ }+ VRow {+ label: "自定义上限"+ enabled: !veyra.presentationOwned+ visible: veyra.outputRateMode === 2+ RowLayout {+ spacing: 6+ DialogHost.VTextField {+ objectName: "presentation-custom-fps"+ implicitWidth: 90+ text: veyra.outputCustomFps.toFixed(3)+ onEdited: text => { const v = Number(text); if (isFinite(v)) veyra.outputCustomFps = v }+ }+ Text { text: "FPS"; color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 11 }+ }+ }+ }+ // A performance orb: a ring filled to `fraction` (green under 70 %, amber+ // under 100 %, red above), the value in the middle, the label under it.+ // Shared with the node page as ProPage.PerfOrb.+ component PerfOrb: Item {+ id: orb+ property real fraction: 0+ property bool known: false+ property string value: "—"+ property string label: ""+ property string tip: ""+ property int size: 56+ // Compact (the node page's 40px bar): no label under the ring; the+ // tooltip names the orb instead.+ property bool showLabel: true+ readonly property color tone: !known ? Qt.rgba(1, 1, 1, 0.25)+ : fraction < 0.7 ? Theme.ok : fraction < 1.0 ? "#F2B941" : Theme.err+ implicitWidth: Math.max(size, labelText.implicitWidth)+ implicitHeight: showLabel ? size + 4 + labelText.implicitHeight : size+ property real shown: known ? Math.min(1, Math.max(0, fraction)) : 0+ Behavior on shown { NumberAnimation { duration: Theme.d(600); easing.bezierCurve: Theme.springSoft } }+ onShownChanged: ring.requestPaint()+ onToneChanged: ring.requestPaint()+ Canvas {+ id: ring+ width: orb.size; height: orb.size+ anchors.horizontalCenter: parent.horizontalCenter+ onPaint: {+ const c = getContext("2d"); c.reset()+ const r = width / 2 - 4, cx = width / 2, cy = height / 2+ c.lineWidth = 5; c.lineCap = "round"+ c.strokeStyle = Qt.rgba(1, 1, 1, 0.08)+ c.beginPath(); c.arc(cx, cy, r, 0, Math.PI * 2); c.stroke()+ if (orb.shown > 0.001) {+ c.strokeStyle = orb.tone+ c.shadowColor = orb.tone; c.shadowBlur = 8+ c.beginPath(); c.arc(cx, cy, r, -Math.PI / 2, -Math.PI / 2 + Math.PI * 2 * orb.shown); c.stroke()+ }+ }+ }+ Text {+ anchors.centerIn: ring+ width: orb.size - 12+ horizontalAlignment: Text.AlignHCenter+ text: orb.value+ color: orb.known ? Theme.t1 : Theme.t3+ font.family: Theme.fontMono+ font.pixelSize: orb.size >= 50 ? 11 : 9+ font.weight: Font.DemiBold; font.variableAxes: Theme.axesDemiBold+ fontSizeMode: Text.HorizontalFit; minimumPixelSize: 8+ }+ Text {+ id: labelText+ visible: orb.showLabel+ anchors.top: ring.bottom; anchors.topMargin: 4+ anchors.horizontalCenter: parent.horizontalCenter+ text: orb.label+ color: Theme.t3+ font.family: Theme.fontUi+ font.pixelSize: 10+ }+ HoverHandler { id: orbHover }+ ToolTip.visible: orbHover.hovered && (orb.tip.length > 0 || !orb.showLabel)+ ToolTip.text: (orb.showLabel ? "" : orb.label + ":") + orb.tip+ }+ // The three orbs every performance readout shows: total processing time+ // against the source frame budget, GPU utilization, and whether the output+ // keeps up with its target rate.+ component PerfOrbs: RowLayout {+ property int size: 56+ property bool showLabels: true+ spacing: 10+ PerfOrb {+ size: parent.size+ showLabel: parent.showLabels+ known: veyra.chainTotalMsKnown && veyra.stageBudgetMs > 0+ fraction: known ? veyra.chainTotalMs / veyra.stageBudgetMs : 0+ value: veyra.chainTotalMsKnown ? veyra.chainTotalMs.toFixed(1) + "ms" : "—"+ label: "处理耗时"+ tip: "增强链总耗时 P95,环 = 占源帧预算" + (veyra.stageBudgetMs > 0 ? " " + veyra.stageBudgetMs.toFixed(1) + " ms" : "") + " 的比例"+ }+ PerfOrb {+ size: parent.size+ showLabel: parent.showLabels+ known: veyra.gpuUtilizationKnown+ fraction: veyra.gpuUtilization / 100+ value: known ? Math.round(veyra.gpuUtilization) + "%" : "—"+ label: "GPU 占用"+ tip: "Windows GPU 引擎占用率(最忙的引擎类型,全系统),每秒采样"+ }+ PerfOrb {+ size: parent.size+ showLabel: parent.showLabels+ known: veyra.outputRateRatio >= 0+ // Full ring = on target; a shortfall shows as a gap and turns amber/red.+ fraction: known ? (veyra.outputRateRatio >= 0.95 ? 0.5 : veyra.outputRateRatio >= 0.8 ? 0.85 : 1.1) : 0+ value: known ? Math.round(Math.min(1.5, veyra.outputRateRatio) * 100) + "%" : "—"+ label: "负载预算"+ tip: "实际输出帧率 / 目标帧率(源帧率 × 补帧倍率):" + veyra.runStatus+ }+ }+ // The status light: 1.4.4's 当前状态 (正常 / 补帧调度降档 / 输出未达标 /+ // 输入帧率不足 …) as a glowing strip with the detail beside it.+ component StatusLight: RowLayout {+ id: light+ spacing: 8+ readonly property color tone: veyra.runStatusLevel === "ok" ? Theme.ok+ : veyra.runStatusLevel === "warn" ? "#F2B941"+ : veyra.runStatusLevel === "err" ? Theme.err : Qt.rgba(1, 1, 1, 0.3)+ Rectangle {+ Layout.fillWidth: true+ Layout.preferredHeight: 4+ radius: 2+ color: light.tone+ opacity: veyra.runStatusLevel === "idle" ? 0.35 : 0.9+ Behavior on color { ColorAnimation { duration: Theme.d(300) } }+ layer.enabled: veyra.runStatusLevel !== "idle"+ layer.effect: MultiEffect { shadowEnabled: true; shadowColor: light.tone; shadowBlur: 0.6; shadowVerticalOffset: 0; blurMax: 12; autoPaddingEnabled: true }+ }+ Text {+ text: veyra.runStatus + (veyra.runStatusDetail.length > 0 ? " · " + veyra.runStatusDetail : "")+ color: light.tone+ font.family: Theme.fontUi+ font.pixelSize: 11+ font.weight: Font.Medium+ }+ }++ component NrLayerCard: VAccordion {+ id: card+ required property var layerData+ property int layerNumber: 1+ property int layerCount: 1+ property bool nrFirst: false+ signal edited(int nodeIndex, string key, double amount)+ signal enabledEdited(int nodeIndex, bool enabled)+ signal duplicateRequested(int nodeIndex)+ signal removeRequested(int nodeIndex)+ signal orderEdited(bool enabled)+ objectName: "nr-card-" + layerNumber+ Layout.fillWidth: true+ glyph: "wand"; hue: Theme.accent+ compactHeader: true+ popIn: layerNumber === root.popLayer+ title: "NR 层 " + layerNumber+ // .lnum: the layer number where a stage card has its icon.+ headerLeadingActions: Rectangle {+ implicitWidth: 22; implicitHeight: 22; radius: 7+ color: Qt.rgba(1, 138 / 255, 61 / 255, 0.16)+ Text {+ anchors.centerIn: parent+ text: card.layerNumber+ color: Theme.accent+ font.family: Theme.fontMono; font.pixelSize: 11+ font.weight: Font.DemiBold; font.variableAxes: Theme.axesDemiBold+ }+ }+ headerActions: VButton {+ objectName: "nr-card-more-" + card.layerNumber+ icon: true; ghost: true; iconName: "dup"+ implicitWidth: 26; implicitHeight: 26+ tip: "复制 · 恢复默认 · 删除"+ onClicked: { nrLayerMenu.layer = card; nrLayerMenu.openAt(this, "down") }+ }+ // This layer's own GPU time (list mode keys a node by its index + 2).+ readonly property var timing: veyra.nodeTimings[String(layerData.index + 2)] || ({})+ readonly property string timingText: timing.state === "measured" ? timing.ms.toFixed(2) + " ms"+ : timing.state === "pending" ? "等待样本" : ""+ summary: nrEditor.sizeLabel + " · 强度 " + layerData.intensity.toFixed(2)+ + (layerData.enabled ? (timingText.length > 0 ? " · " + timingText : "") : " · 已旁路")+ on: layerData.enabled+ onToggled: on => enabledEdited(layerData.index, on)+ NrLayerEditor {+ id: nrEditor+ Layout.fillWidth: true+ layerData: card.layerData+ layerCount: card.layerCount+ nrFirst: card.nrFirst+ onEdited: (i, k, v) => card.edited(i, k, v)+ onDuplicateRequested: i => card.duplicateRequested(i)+ onRemoveRequested: i => card.removeRequested(i)+ onOrderEdited: e => card.orderEdited(e)+ }+ }// --- header (32px) ----------------------------------------------------RowLayout {id: head+ visible: !root.overlayanchors.left: parent.leftanchors.right: parent.rightanchors.top: parent.top@@ -32,25 +352,42 @@ VPage {height: 32spacing: 8+ // pages-pro.js data-srcbtn: what is playing, with a chevron for the menu.VButton {id: sourceBtn- iconName: "video"- text: veyra.isCapture ? "采集卡" : "片源"+ objectName: "pro-source-button"+ iconName: veyra.sourceKind === "ps5" ? "gamepad" : veyra.sourceKind === "screen" ? "monitor"+ : veyra.sourceKind === "image" ? "image" : veyra.sourceKind === "file" ? "film" : "video"+ text: veyra.sourceTitle.length > 0 ? veyra.sourceTitle : "片源"+ maxTextWidth: 260+ trailingIcon: "down"onClicked: sourceMenu.openAt(this, "down")}- VTag { text: veyra.sourceSummary.length > 0 ? veyra.sourceSummary : "未打开" }+ // "1080p60 · YUY2 · SDR": reported values only.+ VTag {+ objectName: "pro-format-tag"+ text: veyra.sourceFormatText.length > 0 ? veyra.sourceFormatText : "未打开"+ }Item { Layout.fillWidth: true }// View toggle. Choosing 节点 asks first, because switching rebuilds the// whole processing chain (design note: 切换需要确认,会重建处理链).VSeg {- options: [{ id: "list", label: "列表" }, { id: "node", label: "节点" }]- current: "list"- onPicked: id => { if (id === "node") switchDialog.open() }+ objectName: "pro-mode-switch"+ options: [{ id: "list", label: "列表", icon: "list" }, { id: "node", label: "节点", icon: "nodes" }]+ current: veyra.nodeMode === 1 ? "node" : "list"+ onPicked: id => {+ const target = id === "node" ? 1 : 0+ if (target === veyra.nodeMode) { if (target === 1) root.requestPage("node"); return }+ switchDialog.targetMode = target+ switchDialog.open()+ }}VButton { iconName: "camera"; text: "截图"; onClicked: veyra.takeScreenshot() }VButton {id: presetBtn+ iconName: "layers"+ trailingIcon: "down"text: "预设:" + veyra.currentPresetNameonClicked: presetMenu.openAt(this, "down")}@@ -59,7 +396,9 @@ VPage {// --- video + transport bar -------------------------------------------Rectangle {id: vwrap+ visible: !root.overlayanchors.left: parent.left+ anchors.leftMargin: 14anchors.top: head.bottomanchors.topMargin: 10width: root.width - 376 - 14 * 2 - 10@@ -78,6 +417,55 @@ VPage {anchors.right: parent.rightanchors.top: parent.topheight: parent.height - 34+ // Drawing an NR protection region: the native video window lets the+ // pointer through, so this catches the drag; the outline itself is+ // drawn by the bridge on a layered child of the video window.+ MouseArea {+ id: protectionDraw+ objectName: "pro-protection-draw"+ anchors.fill: parent+ enabled: veyra.protectionDrawShape.length > 0+ visible: enabled+ cursorShape: Qt.CrossCursor+ preventStealing: true+ property point start+ // Fractions of the video host, whatever the page layout is.+ function hostFraction(x, y) {+ const content = protectionDraw.Window.contentItem+ let host = null+ for (let i = 0; content && i < content.children.length; ++i)+ if (content.children[i].objectName === "videoHost") host = content.children[i]+ const p = protectionDraw.mapToItem(content, x, y)+ if (!host || host.width <= 0 || host.height <= 0) return Qt.point(x / width, y / height)+ return Qt.point((p.x - host.x) / host.width, (p.y - host.y) / host.height)+ }+ onPressed: mouse => { start = hostFraction(mouse.x, mouse.y) }+ onPositionChanged: mouse => {+ const p = hostFraction(mouse.x, mouse.y)+ veyra.updateProtectionDraw(start.x, start.y, p.x, p.y)+ }+ onReleased: mouse => {+ const p = hostFraction(mouse.x, mouse.y)+ veyra.commitProtectionDraw(start.x, start.y, p.x, p.y)+ }+ }+ // 分屏对比: drag the divider (the presenter draws it) across the picture.+ MouseArea {+ objectName: "pro-compare-drag"+ anchors.fill: parent+ enabled: veyra.compareMode === 2 && veyra.protectionDrawShape.length === 0+ visible: enabled+ cursorShape: Qt.SplitHCursor+ preventStealing: true+ function drag(mouse) { veyra.setCompareSplitAt(protectionDraw.hostFraction(mouse.x, mouse.y).x) }+ onPressed: mouse => drag(mouse)+ onPositionChanged: mouse => { if (pressed) drag(mouse) }+ }+ Shortcut {+ sequence: "Escape"+ enabled: veyra.protectionDrawShape.length > 0+ onActivated: veyra.beginProtectionDraw("")+ }Text {anchors.centerIn: parentvisible: !veyra.hasSource@@ -115,6 +503,7 @@ VPage {}Item {id: proSeekArea+ objectName: "pro-seek"Layout.fillWidth: trueimplicitHeight: 14Rectangle {@@ -124,15 +513,50 @@ VPage {radius: 9color: Qt.rgba(1, 1, 1, 0.14)Rectangle {- width: parent.width * Math.max(0, Math.min(1, veyra.progress))+ width: parent.width * proSeekArea.fracheight: parent.heightradius: 9color: "#FFFFFF"}}- HoverHandler { cursorShape: Qt.PointingHandCursor }- TapHandler {- onTapped: point => veyra.seekTo(Math.max(0, Math.min(1, point.position.x / proSeekArea.width)) * veyra.duration)+ // Press or drag anywhere on the rail: the picture follows the+ // pointer (a seek every 120 ms) and lands on release.+ property bool scrubbing: false+ property real scrubFrac: 0+ readonly property real frac: scrubbing ? scrubFrac : Math.max(0, Math.min(1, veyra.progress))+ Rectangle {+ width: 11; height: 11; radius: 5.5+ color: "#FFFFFF"+ anchors.verticalCenter: parent.verticalCenter+ x: proSeekArea.frac * proSeekArea.width - width / 2+ visible: proSeekMouse.containsMouse || proSeekArea.scrubbing+ }+ Timer {+ id: proScrubSeek+ interval: 120+ onTriggered: if (proSeekArea.scrubbing) veyra.seekTo(proSeekArea.scrubFrac * veyra.duration)+ }+ MouseArea {+ id: proSeekMouse+ anchors.fill: parent+ hoverEnabled: true+ enabled: veyra.duration > 0 && !veyra.isCapture+ cursorShape: Qt.PointingHandCursor+ preventStealing: true+ function fracAt(x) { return Math.max(0, Math.min(1, x / Math.max(1, proSeekArea.width))) }+ onPressed: mouse => { proSeekArea.scrubFrac = fracAt(mouse.x); proSeekArea.scrubbing = true; proScrubSeek.start() }+ onPositionChanged: mouse => {+ if (!proSeekArea.scrubbing) return+ proSeekArea.scrubFrac = fracAt(mouse.x)+ if (!proScrubSeek.running) proScrubSeek.start()+ }+ onReleased: mouse => {+ proScrubSeek.stop()+ const target = fracAt(mouse.x) * veyra.duration+ proSeekArea.scrubbing = false+ veyra.seekTo(target)+ }+ onCanceled: { proScrubSeek.stop(); proSeekArea.scrubbing = false }}}Text {@@ -141,19 +565,32 @@ VPage {font.family: Theme.fontMonofont.pixelSize: Theme.fsSmall}- VTag { text: veyra.sourceSummary }- VTag { text: veyra.outputSummary }+ VTag { visible: veyra.sourceRateText.length > 0; text: "源 " + veyra.sourceRateText }+ VTag { visible: veyra.outputSummary.length > 0; text: "输出 " + veyra.outputSummary.replace("x", "×") }VTag {- visible: veyra.fgActive- kind: "acc"- text: veyra.fgMultiplier + "X"+ objectName: "pro-fg-tag"+ visible: veyra.hasSource+ kind: veyra.fgEnabled ? "acc" : ""+ text: veyra.fgEnabled ? veyra.fgMultiplier + "X" : "补帧关"+ }+ // Fullscreen, at the picture's bottom-right corner where players put it.+ Item {+ objectName: "pro-fullscreen"+ implicitWidth: 28; implicitHeight: 28+ VIcon { anchors.centerIn: parent; name: "max"; color: fullHover.hovered ? Theme.t1 : Theme.t2 }+ HoverHandler { id: fullHover; cursorShape: Qt.PointingHandCursor }+ TapHandler { onTapped: root.requestFullscreen() }+ ToolTip.visible: fullHover.hovered+ ToolTip.text: "全屏(双击画面 / F11)· 全屏后按 Home 打开快速调节"}}}// --- meters (fixed 172px, three cards) --------------------------------RowLayout {- anchors.left: parent.left+ id: meters+ visible: !root.overlay+ anchors.left: vwrap.leftanchors.top: vwrap.bottomanchors.topMargin: 10anchors.bottom: parent.bottom@@ -221,6 +658,8 @@ VPage {// listed; a stage with no measurement is drawn as unmeasured.Rectangle {id: meter2+ objectName: "pro-meter-stages"+ clip: trueLayout.fillWidth: trueLayout.fillHeight: trueLayout.preferredWidth: 1.5@@ -234,7 +673,7 @@ VPage {spacing: 5RowLayout {Layout.fillWidth: true- VEyebrow { text: "各阶段 GPU 耗时"; Layout.fillWidth: true }+ VEyebrow { text: "GPU 阶段采样 P95"; Layout.fillWidth: true }Text {text: "预算 " + veyra.stageBudgetMs.toFixed(1) + " ms / 源帧"color: Theme.t3@@ -242,18 +681,32 @@ VPage {font.pixelSize: 11}}+ // Eight stages in two columns of four: a single column of eight+ // overflowed the fixed 172px card.+ GridLayout {+ objectName: "pro-stage-grid"+ Layout.fillWidth: true+ columns: 2+ columnSpacing: 16+ rowSpacing: 6+ flow: GridLayout.TopToBottom+ rows: Math.ceil(veyra.stageTimings.length / 2)Repeater {model: veyra.stageTimingsdelegate: RowLayout {+ id: stageRowrequired property var modelData+ required property int indexLayout.fillWidth: true- spacing: 10+ Layout.preferredWidth: 1+ spacing: 8Text {- Layout.preferredWidth: 44+ Layout.preferredWidth: 52text: modelData.labelcolor: Theme.t2font.family: Theme.fontUifont.pixelSize: Theme.fsSmall+ elide: Text.ElideRight}Item {Layout.fillWidth: true@@ -265,15 +718,18 @@ VPage {radius: 9color: Qt.rgba(1, 1, 1, 0.08)Rectangle {- width: parent.width * Math.max(0, Math.min(1, modelData.fraction))+ width: root.barsArmed ? parent.width * Math.max(0, Math.min(1, modelData.fraction)) : 0height: parent.heightradius: 9color: modelData.color+ Behavior on width { SequentialAnimation {+ PauseAnimation { duration: root.barsSettled ? 0 : Theme.d(120 + stageRow.index * 60) }+ NumberAnimation { duration: Theme.d(800); easing.bezierCurve: Theme.springSoft } } }}}}Text {- Layout.preferredWidth: 52+ Layout.preferredWidth: 48text: modelData.measured ? modelData.ms.toFixed(1) + " ms" : "未测量"color: modelData.measured ? Theme.t1 : Theme.t3font.family: Theme.fontMono@@ -282,6 +738,7 @@ VPage {}}}+ }Item { Layout.fillHeight: true }}}@@ -289,6 +746,7 @@ VPage {// Card 3: frame rate and cadence.Rectangle {id: meter3+ readonly property bool wide: width >= 380Layout.fillWidth: trueLayout.fillHeight: trueLayout.preferredWidth: 1.15@@ -300,61 +758,140 @@ VPage {anchors.fill: parentanchors.margins: 14spacing: 6- VEyebrow { text: "帧率与节奏" }-- // The design puts "显示 fps" first and "提交 fps" after it, and its- // own note is explicit: a display rate is only real if the system- // display event can be read, and when it cannot it must say 未测- // rather than reuse the submit rate.RowLayout {- spacing: 6- Text {- text: veyra.displayFpsKnown ? veyra.displayFps.toFixed(1) : "未测"- color: veyra.displayFpsKnown ? Theme.ok : Theme.t3- font.family: Theme.fontMono- font.pixelSize: 22- font.weight: Font.DemiBold; font.variableAxes: Theme.axesDemiBold- }- Text { text: "显示 fps"; color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 11 }- Rectangle { implicitWidth: 1; implicitHeight: 12; color: Theme.stroke2 }- Text {- text: veyra.submitFpsKnown ? veyra.submitFps.toFixed(1) : "未测"- color: Theme.t1- font.family: Theme.fontMono- font.pixelSize: 13- font.weight: Font.DemiBold; font.variableAxes: Theme.axesDemiBold- }- Text { text: "提交"; color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 11 }- }- GridLayout {Layout.fillWidth: true- columns: 2- columnSpacing: 14- rowSpacing: 3- Text { text: "进程内排队"; color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 12 }- Text {- Layout.fillWidth: true- text: veyra.queuedFrames.toFixed(1) + " 帧"- color: Theme.t1; font.family: Theme.fontMono; font.pixelSize: 12- horizontalAlignment: Text.AlignRight- }- Text { text: "跳过源帧"; color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 12 }- Text {+ Layout.fillHeight: true+ spacing: 12+ ColumnLayout {Layout.fillWidth: true- text: String(veyra.skippedFrames)- color: Theme.t1; font.family: Theme.fontMono; font.pixelSize: 12- horizontalAlignment: Text.AlignRight+ Layout.alignment: Qt.AlignTop+ spacing: 6+ VEyebrow { text: "帧率与节奏" }++ // The design puts "显示 fps" first and "提交 fps" after it, and its+ // own note is explicit: a display rate is only real if the system+ // display event can be read, and when it cannot it must say 未测+ // rather than reuse the submit rate.+ RowLayout {+ spacing: 6+ Text {+ text: veyra.displayFpsKnown ? veyra.displayFps.toFixed(1) : "未测"+ color: veyra.displayFpsKnown ? Theme.ok : Theme.t3+ font.family: Theme.fontMono+ font.pixelSize: 22+ font.weight: Font.DemiBold; font.variableAxes: Theme.axesDemiBold+ }+ Text { text: "显示 fps"; color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 11 }+ Rectangle { implicitWidth: 1; implicitHeight: 12; color: Theme.stroke2 }+ Text {+ text: veyra.submitFpsKnown ? veyra.submitFps.toFixed(1) : "未测"+ color: Theme.t1+ font.family: Theme.fontMono+ font.pixelSize: 13+ font.weight: Font.DemiBold; font.variableAxes: Theme.axesDemiBold+ }+ Text { text: veyra.submitFpsLabel; color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 11 }+ }+ // Frame-time line (design .spark): submit interval over the last+ // 12 s, the dashed line is the source frame budget.+ Canvas {+ id: spark+ objectName: "fps-sparkline"+ visible: meter3.wide+ Layout.fillWidth: true+ Layout.preferredHeight: 24+ readonly property var points: veyra.frameTimes+ onPointsChanged: requestPaint()+ onWidthChanged: requestPaint()+ onPaint: {+ const g = getContext("2d"); g.reset()+ const pts = points || []+ const budget = veyra.stageBudgetMs+ if (pts.length < 2) return+ let lo = budget > 0 ? budget : pts[0], hi = lo+ for (const v of pts) { lo = Math.min(lo, v); hi = Math.max(hi, v) }+ const pad = Math.max(0.5, (hi - lo) * 0.2); lo -= pad; hi += pad+ const y = v => height - 2 - (v - lo) / (hi - lo) * (height - 4)+ if (budget > 0) {+ g.strokeStyle = Qt.rgba(1, 1, 1, 0.12); g.lineWidth = 1; g.setLineDash([3, 3])+ g.beginPath(); g.moveTo(0, y(budget)); g.lineTo(width, y(budget)); g.stroke(); g.setLineDash([])+ }+ const x = i => i / 47 * width + (48 - pts.length) / 47 * width+ const grad = g.createLinearGradient(0, 0, 0, height)+ grad.addColorStop(0, Qt.rgba(61 / 255, 220 / 255, 132 / 255, 0.25)); grad.addColorStop(1, Qt.rgba(61 / 255, 220 / 255, 132 / 255, 0))+ g.beginPath(); pts.forEach((v, i) => i ? g.lineTo(x(i), y(v)) : g.moveTo(x(i), y(v)))+ g.lineTo(x(pts.length - 1), height); g.lineTo(x(0), height); g.closePath(); g.fillStyle = grad; g.fill()+ g.beginPath(); pts.forEach((v, i) => i ? g.lineTo(x(i), y(v)) : g.moveTo(x(i), y(v)))+ g.strokeStyle = Theme.ok; g.lineWidth = 1.5; g.stroke()+ }+ }+ GridLayout {+ visible: meter3.wide+ Layout.fillWidth: true+ columns: 2+ columnSpacing: 14+ rowSpacing: 3+ Text { text: "进程内待呈现"; color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 12 }+ Text {+ Layout.fillWidth: true+ text: veyra.queuedFramesKnown ? veyra.queuedFrames.toFixed(0) + " 帧" : "未测"+ color: Theme.t1; font.family: Theme.fontMono; font.pixelSize: 12+ horizontalAlignment: Text.AlignRight+ }+ Text { text: "跳过源帧"; color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 12 }+ Text {+ Layout.fillWidth: true+ text: String(veyra.skippedFrames)+ color: Theme.t1; font.family: Theme.fontMono; font.pixelSize: 12+ horizontalAlignment: Text.AlignRight+ }+ }+ PerfOrbs { visible: !meter3.wide; size: 38; spacing: 6 }}+ PerfOrbs { visible: meter3.wide; size: 50; Layout.alignment: Qt.AlignVCenter }}- Item { Layout.fillHeight: true }+ StatusLight { Layout.fillWidth: true }}}}// --- inspector (376px, rows 2-3) --------------------------------------+ // Performance orbs beside the quick-adjust panel (fullscreen only).+ Rectangle {+ id: quickOrbs+ objectName: "pro-quick-orbs"+ readonly property bool videoCover: root.overlay+ property real coverRadius: radius+ visible: root.overlay+ x: insp.x + insp.width + 10+ y: insp.y+ width: quickOrbRow.implicitWidth + 24+ height: quickOrbRow.implicitHeight + 16+ radius: 18+ color: Qt.rgba(22 / 255, 22 / 255, 26 / 255, 0.94)+ border.width: 1+ border.color: Theme.stroke2+ RowLayout {+ id: quickOrbRow+ anchors.centerIn: parent+ spacing: 12+ PerfOrbs { size: 46; spacing: 10 }+ Text {+ text: "Home 关闭"+ color: Theme.t3+ font.family: Theme.fontUi+ font.pixelSize: 11+ }+ }+ }+Rectangle {id: insp+ objectName: "pro-inspector"+ readonly property bool videoCover: root.overlay+ property real coverRadius: radiusanchors.right: parent.right+ anchors.rightMargin: 14anchors.top: head.bottomanchors.topMargin: 10anchors.bottom: parent.bottom@@ -365,9 +902,20 @@ VPage {border.width: 1border.color: Theme.strokeclip: true+ // Quick-adjust: the same panel on the left edge of the fullscreen picture.+ states: State {+ name: "overlay"+ when: root.overlay+ AnchorChanges { target: insp; anchors.right: undefined; anchors.left: root.left; anchors.top: root.top }+ PropertyChanges { target: insp; anchors.leftMargin: 16; anchors.topMargin: 16; anchors.bottomMargin: 16 }+ }+ // A click on the panel's own background is not a click on the picture.+ MouseArea { anchors.fill: parent; acceptedButtons: Qt.AllButtons; onWheel: wheel => wheel.accepted = true }ColumnLayout {anchors.fill: parent+ anchors.leftMargin: root.tab === "color" ? insp.border.width : 0+ anchors.rightMargin: root.tab === "color" ? insp.border.width : 0spacing: 0// .insp-tabs: five tabs, equal width, 30px, radius 9.@@ -412,6 +960,9 @@ VPage {Layout.leftMargin: 10Layout.rightMargin: 10implicitHeight: chainCol.implicitHeight + 20+ objectName: "pro-processing-order"+ // The design draws the chain bar on the 画质 tab only.+ visible: root.tab === "quality"radius: 12color: Qt.rgba(1, 1, 1, 0.03)border.width: 1@@ -429,6 +980,23 @@ VPage {Flow {Layout.fillWidth: truespacing: 2+ // .c.io: the chain starts at the input, which is not a node.+ Rectangle {+ width: inChip.implicitWidth + 18+ height: 24+ radius: 99+ color: "transparent"+ border.width: 1+ border.color: Theme.stroke+ Text {+ id: inChip+ anchors.centerIn: parent+ text: "输入"+ color: Theme.t3+ font.family: Theme.fontUi+ font.pixelSize: 12+ }+ }Repeater {model: veyra.chaindelegate: Row {@@ -453,7 +1021,7 @@ VPage {font.strikeout: !modelData.enabled}HoverHandler { cursorShape: Qt.PointingHandCursor }- TapHandler { onTapped: root.selectedEffect = modelData.index }+ TapHandler { gesturePolicy: TapHandler.WithinBounds; onTapped: root.locateNode(modelData) }}}}@@ -465,21 +1033,29 @@ VPage {// engine has no control yet, the panel says so instead of offering one// that would do nothing.Flickable {+ id: inspFlickLayout.fillWidth: trueLayout.fillHeight: trueLayout.topMargin: 8contentHeight: body.implicitHeightclip: true- ScrollBar.vertical: ScrollBar { }+ ScrollBar.vertical: VScrollBar {+ id: inspectorScroll+ objectName: "pro-inspector-scrollbar"+ wide: root.tab === "color"+ }ColumnLayout {id: body- width: parent.width - 20+ // CSS thin scrollbars consume 10px on the reference host;+ // reserve their gutter instead of drawing over the colour card.+ width: parent.width - 20 - (root.tab === "color" && inspectorScroll.size < 1 ? inspectorScroll.implicitWidth : 0)x: 10spacing: 6// --- 画质 -------------------------------------------------ColumnLayout {+ id: qualityColLayout.fillWidth: truespacing: 6visible: root.tab === "quality"@@ -488,6 +1064,7 @@ VPage {// flat rows: an icon, a title, a live summary line, a switch// and a chevron, with nested groups inside.VAccordion {+ objectName: "list-sr"Layout.fillWidth: trueglyph: "sparkles"hue: "#4F7BFF"@@ -506,12 +1083,20 @@ VPage {options: [{ id: "1", label: "2K" },{ id: "2", label: "4K" },+ { id: "4", label: "5K" },+ { id: "5", label: "6K" },+ { id: "6", label: "7K" },{ id: "3", label: "8K" }]current: String(veyra.srTargetIndex)onPicked: id => veyra.srTargetIndex = parseInt(id)}}+ VRow {+ label: "超分运动来源"+ hint: "零运动会限制时序重建;RTX 视频超分不使用此输入"+ VSeg { options: [{id:"0",label:"零运动"},{id:"1",label:"光流"}]; current: String(veyra.srMotionSource); onPicked: id => veyra.srMotionSource = Number(id) }+ }VRow {label: "质量"hint: "RTX 视频超分档位"@@ -528,113 +1113,253 @@ VPage {}}+ // RTX Video HDR: SDR -> HDR before frame generation. Runs+ // only on an HDR display path; the status says why not.+ VAccordion {+ objectName: "list-video-hdr"+ Layout.fillWidth: true+ glyph: "sun"+ hue: "#E58BD9"+ title: "RTX Video HDR"+ summary: veyra.videoHdr ? (veyra.videoHdrStatus.length > 0 ? veyra.videoHdrStatus : "已开启") : "已关闭"+ on: veyra.videoHdr+ onToggled: veyra.videoHdr = on+ Repeater {+ model: [{key:"contrast",label:"对比度",from:0,to:200,def:125},+ {key:"saturation",label:"饱和度",from:0,to:200,def:75},+ {key:"middleGray",label:"中灰",from:10,to:100,def:44},+ {key:"peakNits",label:"峰值亮度 (nit)",from:400,to:2000,def:1000}]+ delegate: VRow {+ required property var modelData+ label: modelData.label+ value: String(veyra.videoHdrParams[modelData.key] ?? "—")+ VSlider {+ objectName: "list-hdr-" + modelData.key+ implicitWidth: 120+ valueFromModel: true+ resettable: true; defaultValue: modelData.def+ from: modelData.from; to: modelData.to+ value: veyra.videoHdrParams[modelData.key] ?? modelData.def+ onMoved: value => veyra.setVideoHdrParameter(modelData.key, Math.round(value))+ }+ }+ }+ }++ // .stage: one NR card, its layers inside (pages-pro.js nrStage):+ // "N 层依次处理 · 每层参数独立", a bar per layer lit when it+ // runs, the add button at the bottom of the stage.VAccordion {+ id: nrStage+ objectName: "list-nr-stage"Layout.fillWidth: trueglyph: "wand"hue: Theme.accenttitle: "NR 画面增强"- summary: "每层参数独立 · 强度 " + veyra.nrIntensity.toFixed(2)- on: veyra.nrEnabled- onToggled: veyra.nrEnabled = on-- VRow {- label: "模型强度"- value: veyra.nrIntensity.toFixed(2)- VSlider {- implicitWidth: 140- from: 0; to: 1; value: veyra.nrIntensity- onMoved: veyra.nrIntensity = value+ summary: veyra.nrLayers.length > 0 ? veyra.nrLayers.length + " 层依次处理 · 每层参数独立" : "未添加 NR 层"+ enabledSwitch: false+ open: true+ headerActions: [+ VTag { text: "实验"; kind: "exp" },+ Row {+ objectName: "list-nr-count"+ spacing: 3+ Repeater {+ model: veyra.nrLayers+ delegate: Rectangle {+ required property var modelData+ width: 14; height: 4; radius: 3+ color: modelData.enabled ? Theme.accent : Qt.rgba(1, 1, 1, 0.18)+ Behavior on color { ColorAnimation { duration: Theme.d(200) } }+ }+ }+ }+ ]+ Repeater {+ // Numeric count preserves delegates during slider edits.+ model: veyra.nrLayers.length+ delegate: NrLayerCard {+ id: layerCard+ required property int index+ Layout.topMargin: 4+ layerData: veyra.nrLayers[index]+ layerNumber: index + 1+ layerCount: veyra.nrLayers.length+ nrFirst: veyra.lowLatency+ onEdited: (nodeIndex,key,amount) => veyra.setNrLayerParameter(nodeIndex,key,amount)+ onEnabledEdited: (nodeIndex,enabled) => veyra.setEffectEnabled(nodeIndex,enabled)+ onDuplicateRequested: nodeIndex => { root.markPop(layerNumber + 1); root.selectedEffect = veyra.duplicateNrLayer(nodeIndex) }+ onRemoveRequested: nodeIndex => layerCard.bye(() => veyra.removeEffect(nodeIndex))+ onOrderEdited: enabled => veyra.lowLatency = enabled}}- VSubGroup {- label: "模型参数"- count: 3- VRow {- label: "局部明暗"- value: veyra.nrTone.toFixed(2)- VSlider {- implicitWidth: 130- from: 0; to: 1; value: veyra.nrTone- onMoved: veyra.nrTone = value++ // .addlayer: dashed, inside the stage; list mode adds and+ // toggles layers, never reorders them.+ Rectangle {+ id: addLayer+ objectName: "list-nr-add"+ Layout.fillWidth: true+ Layout.topMargin: 4+ implicitHeight: 36+ radius: 10+ readonly property bool full: veyra.nrLayers.length >= 4+ opacity: full ? 0.45 : 1+ color: addHover.hovered && !full ? Theme.accentSoft : "transparent"+ Shape {+ anchors.fill: parent+ ShapePath {+ strokeWidth: 1+ strokeColor: addHover.hovered && !addLayer.full ? Theme.accent : Qt.rgba(1, 1, 1, 0.2)+ fillColor: "transparent"+ strokeStyle: ShapePath.DashLine+ dashPattern: [5, 4]+ PathRectangle {+ x: 0; y: 0+ width: addLayer.width+ height: addLayer.height+ radius: 10+ }}}- VRow {- label: "局部结构"- value: veyra.nrStructure.toFixed(2)- VSlider {- implicitWidth: 130- from: 0; to: 1; value: veyra.nrStructure- onMoved: veyra.nrStructure = value+ Row {+ anchors.centerIn: parent+ spacing: 6+ Text {+ text: "+ 添加 NR 层"+ color: addHover.hovered && !addLayer.full ? Theme.accent : Theme.t2+ font.family: Theme.fontUi+ font.pixelSize: Theme.fsBody+ font.weight: Font.Medium}- }- VRow {- label: "肤质 · 未证实"- value: veyra.nrSkin.toFixed(2)- VSlider {- implicitWidth: 130- from: -1; to: 1; value: veyra.nrSkin- onMoved: veyra.nrSkin = value+ Text {+ anchors.baseline: parent.children[0].baseline+ text: addLayer.full ? "(最多 4 层)" : "(加在 NR " + veyra.nrLayers.length + " 之后 · 最多 4 层)"+ color: Theme.t3+ font.family: Theme.fontUi+ font.pixelSize: 11}}+ HoverHandler { id: addHover; cursorShape: addLayer.full ? Qt.ArrowCursor : Qt.PointingHandCursor }+ TapHandler {+ enabled: !addLayer.full+ onTapped: { root.markPop(veyra.nrLayers.length + 1); root.selectedEffect = veyra.addEffect("nr") }+ }}- VSubGroup {- label: "实验"- count: 2- VRow {- label: "时间域防闪烁"- hint: "在 NR 之后稳定残差"- VSwitch {- checked: veyra.nrTemporal- onToggled: veyra.nrTemporal = checked- }+ }++ // Stage-5 output stabiliser. Global, not per-layer: it+ // runs once after the whole NR stack. Default off, and+ // off means the pass is never even dispatched.+ VAccordion {+ objectName: "list-output-stabiliser"+ Layout.fillWidth: true+ visible: veyra.nodeMode === 0+ title: "输出稳定器 · 抗闪烁"+ glyph: "shield"; hue: Theme.accent+ summary: veyra.nrHoldStrength > 0+ ? "已开启 · 强度 " + Math.round(veyra.nrHoldStrength * 100) + "%"+ : "默认关闭 · 只稳住没变化的画面,动的地方不拖影"+ on: veyra.nrHoldStrength > 0+ onToggled: on => veyra.nrHoldStrength = on ? 0.8 : 0+ Text {+ Layout.fillWidth: true+ text: "比较源画面与上一帧:没有明显变化的像素沿用上一帧输出,明显变化的位置直接用新结果。" ++ "不重投影、不用光流,所以运动区域不会拖影。放在最后一层 NR 之后、超分与补帧之前。"+ wrapMode: Text.WordWrap+ color: Theme.t3+ font.family: Theme.fontUi; font.pixelSize: 11+ }+ VRow {+ label: "稳定强度"+ hint: "越高越稳,过高会显得发闷"+ visible: veyra.nrHoldStrength > 0+ VSlider {+ objectName: "list-hold-strength"+ from: 0.1; to: 1.0+ value: veyra.nrHoldStrength+ onMoved: veyra.nrHoldStrength = value}- VRow {- label: "低延迟模式"- hint: "先 NR 再超分,仅预览"- VSwitch {- checked: veyra.lowLatency- onToggled: veyra.lowLatency = checked- }+ }+ VRow {+ label: "变化容差"+ hint: "越小越敏感,越大稳得越多"+ visible: veyra.nrHoldStrength > 0+ VSlider {+ objectName: "list-hold-tolerance"+ from: 0.005; to: 0.10+ value: veyra.nrHoldTolerance+ onMoved: veyra.nrHoldTolerance = value}}}- // Adding an NR layer. List mode allows adding layers and- // toggling them, never reordering.- Rectangle {- id: addLayer+ VAccordion {+ objectName: "list-global-protection"Layout.fillWidth: true- implicitHeight: 36- radius: 10- // A dashed outline as in the design: a Rectangle border- // cannot be dashed, so the outline is drawn as a shape.- color: addHover.hovered ? Theme.accentSoft : "transparent"- Shape {- anchors.fill: parent- ShapePath {- strokeWidth: 1- strokeColor: addHover.hovered ? Theme.accent : Qt.rgba(1, 1, 1, 0.2)- fillColor: "transparent"- strokeStyle: ShapePath.DashLine- dashPattern: [5, 4]- PathRectangle {- x: 0; y: 0- width: addLayer.width- height: addLayer.height- radius: 10+ visible: veyra.nodeMode === 0+ title: "NR 全局保护区域"+ glyph: "shield"; hue: Theme.accent+ summary: "区域内排除所有 NR 层 · 仅列表模式"+ on: veyra.protectionEnabled+ onToggled: on => veyra.protectionEnabled = on+ Text {+ Layout.fillWidth: true+ text: veyra.protectionDrawShape.length > 0+ ? "在画面上按住左键拖出" + (veyra.protectionDrawShape === "ellipse" ? "圆形 / 椭圆" : "矩形") + "区域 · Esc 取消"+ : "在画面上画出矩形或圆形区域(最多 4 个),区域内的画面不做任何一层 NR 处理。"+ wrapMode: Text.WordWrap+ color: veyra.protectionDrawShape.length > 0 ? Theme.accent : Theme.t3+ font.family: Theme.fontUi; font.pixelSize: 11+ }+ RowLayout {+ Layout.fillWidth: true+ spacing: 6+ VButton {+ objectName: "list-protection-draw-rect"+ text: "画矩形"+ primary: veyra.protectionDrawShape === "rect"+ onClicked: veyra.beginProtectionDraw(veyra.protectionDrawShape === "rect" ? "" : "rect")+ }+ VButton {+ objectName: "list-protection-draw-ellipse"+ text: "画圆形"+ primary: veyra.protectionDrawShape === "ellipse"+ onClicked: veyra.beginProtectionDraw(veyra.protectionDrawShape === "ellipse" ? "" : "ellipse")+ }+ Item { Layout.fillWidth: true }+ VButton {+ text: "清空"; ghost: true+ visible: veyra.protectionRegions.length > 0+ onClicked: veyra.clearProtectionRegions()+ }+ }+ Repeater {+ model: veyra.protectionRegions+ delegate: VRow {+ required property var modelData+ required property int index+ label: (modelData.ellipse ? "圆形 " : "矩形 ") + (index + 1)+ value: Math.round(modelData.left * 100) + "," + Math.round(modelData.top * 100) + " → "+ + Math.round(modelData.right * 100) + "," + Math.round(modelData.bottom * 100) + " %"+ VButton {+ objectName: "list-protection-remove-" + index+ icon: true; ghost: true; iconName: "x"+ onClicked: veyra.removeProtectionRegion(modelData.index)}}}- Text {- anchors.centerIn: parent- text: "+ 增加 NR 层"- color: addHover.hovered ? Theme.accent : Theme.t2- font.family: Theme.fontUi- font.pixelSize: Theme.fsBody- font.weight: Font.Medium+ VRow {+ label: "羽化像素"+ value: Number(veyra.protectionState.feather).toFixed(0) + " px"+ VSlider {+ objectName: "list-protection-feather"+ implicitWidth: 110+ from: 0; to: 64+ value: veyra.protectionState.feather+ onMoved: value => veyra.setProtectionFeather(Math.round(value))+ }}- HoverHandler { id: addHover; cursorShape: Qt.PointingHandCursor }- TapHandler { onTapped: veyra.addEffect("nrEnhance") }}// A refused edit explains itself here rather than in a modal.@@ -650,25 +1375,49 @@ VPage {}// --- 补帧 -------------------------------------------------- // Per the design: DLSS frame generation and Intel XeSS- // (experimental) only. AMD FSR frame generation stays hidden.+ // pages-pro.js fg tab: one 补帧 card with its switch ("始终在所有+ // 画质效果之后"), the optical-flow and presentation groups nested+ // as sub-panels. Backend choices share the node editor's+ // bridge contract; FSR 4 requests never silently become 3.1.ColumnLayout {+ id: fgColLayout.fillWidth: truespacing: 6visible: root.tab === "fg"+ objectName: "list-fg-group"++ VAccordion {+ id: fgCard+ objectName: "list-fg-card"+ Layout.fillWidth: true+ glyph: "layers"+ hue: "#3DDC84"+ title: "补帧"+ summary: "始终在所有画质效果之后" + (veyra.fgEnabled+ ? " · " + veyra.fgMultiplier + "X " + (veyra.fgBackendChoices.find(o => o.id === veyra.fgBackendName) || {}).label+ : " · 已关闭")+ switchObjectName: "list-fg-enabled"+ on: veyra.fgEnabled+ onToggled: on => veyra.fgEnabled = on+ open: true- VGroup {VRow {label: "补帧方式"+ hint: veyra.fgProviderTextVSelect {- value: veyra.fgBackendName- options: [- { id: "dlss", label: "DLSS 帧生成" },- { id: "xess", label: "Intel XeSS · 实验" }- ]+ id: fgBackendSelect+ objectName: "list-fg-backend"+ options: veyra.fgBackendChoices+ // The label of the chosen backend, not its id.+ value: (options.find(o => o.id === veyra.fgBackendName) || options[0]).labelonPicked: id => veyra.fgBackendName = id}}+ VRow {+ label: "补帧运动来源"+ hint: "XeSS 默认零运动;FSR 仍有自身的光流计算"+ VSeg { objectName: "list-fg-motion"; options: [{id:"0",label:"零运动"},{id:"1",label:"光流"}]; current: String(veyra.fgMotionSource); onPicked: id => veyra.fgMotionSource = Number(id) }+ }VRow {label: "倍率"hint: veyra.fgMaxMultiplier + "X 为上限"@@ -686,12 +1435,59 @@ VPage {onToggled: veyra.fgStrict = checked}}- }- VGroup {+ VSubGroup {+ objectName: "list-fg-flow-group"+ Layout.fillWidth: true+ Layout.topMargin: 6+ label: "光流 · 运动估算"+ count: veyra.opticalFlowChoice === 1 ? 4 : 3+ expanded: true+ VRow {+ label: "光流算法"+ hint: "补帧与 NR 共用 · 输入后计算一次"+ VSelect {+ objectName: "list-flow-choice"+ options: [{id:"0",label:"NVIDIA NVOF"},{id:"1",label:"AMD FidelityFX"}]+ value: options[veyra.opticalFlowChoice]?.label ?? (veyra.opticalFlowChoice === 2 ? "GPU DIS 已移除,请重选" : "未知配置")+ onPicked: id => veyra.setOpticalFlowChoice(Number(id))+ }+ }+ VRow {+ label: "AMD 性能档"+ hint: "光流宽高减半,更省但更糙"+ visible: veyra.opticalFlowChoice === 1+ VSwitch {+ objectName: "list-amd-half"+ checked: veyra.amdFlowHalf+ onToggled: veyra.amdFlowHalf = checked+ }+ }+ VRow {+ label: "运动估算质量"+ VSeg {+ objectName: "list-flow-quality"+ options: [{ id: "0", label: "性能" }, { id: "1", label: "平衡" }, { id: "2", label: "质量" }]+ current: String(veyra.flowQuality)+ onPicked: id => veyra.flowQuality = Number(id)+ }+ }+ VRow {+ label: "内容节奏"+ hint: "游戏 30 帧、采集卡输出 60 帧时选“采集 60→30”"+ VSelect {+ objectName: "list-content-rate"+ implicitWidth: 170+ options: root.contentRates+ value: (root.contentRates[veyra.contentRate] || root.contentRates[0]).label+ onPicked: id => veyra.contentRate = Number(id)+ }+ }+ }VRow {label: "低延迟队列"- hint: "减少排队;本机无法验收,不宣称延迟下降"+ hint: "减少软件排队;屏幕延迟需要实测"VSwitch {+ objectName: "list-low-queue"checked: veyra.fgLowQueueonToggled: veyra.fgLowQueue = checked}@@ -700,81 +1496,17 @@ VPage {}// --- 色彩 -------------------------------------------------- // Built from the engine's own parameter catalogue, so a control- // can only exist for a field ColorSettings really carries. The- // groups follow the design's sections (亮 / 效果 / 颜色 / 曲线 /- // 颜色分级 / 校准 / LUT).- ColumnLayout {+ // The same real-instance editor is used by the node inspector.+ ColourPanel {+ id: colourPanelLayout.fillWidth: true- spacing: 6visible: root.tab === "color"-- VAccordion {- Layout.fillWidth: true- glyph: "palette"- hue: "#E0C341"- title: "调色"- summary: veyra.colorEnabled- ? ("曝光 " + veyra.colourParameter("exposure").toFixed(2)- + " · 对比 " + Math.round(veyra.colourParameter("contrast")))- : "已关闭"- on: veyra.colorEnabled- open: true- onToggled: veyra.colorEnabled = on-- Repeater {- model: veyra.colourGroups- delegate: VSubGroup {- required property var modelData- Layout.fillWidth: true- label: modelData.group- count: modelData.items.length- Repeater {- model: modelData.items- delegate: VRow {- required property var modelData- label: modelData.label- value: veyra.colourParameter(modelData.name).toFixed(2)- VSlider {- implicitWidth: 130- center: modelData.center- from: modelData.min- to: modelData.max- value: veyra.colourParameter(modelData.name)- onMoved: veyra.setColourParameter(modelData.name, value)- }- }- }- }- }- }-- // The design's colour page also has a curves editor, a mixer,- // grading wheels and a LUT picker. Those need drawing widgets- // (a curve canvas, colour wheels) that are not built yet, so- // this says so rather than showing sliders that stand in for- // them.- Rectangle {- Layout.fillWidth: true- implicitHeight: noteText.implicitHeight + 20- radius: 9- color: Qt.rgba(0.961, 0.784, 0.294, 0.06)- Text {- id: noteText- anchors.fill: parent- anchors.margins: 10- text: "曲线编辑器、混色器、颜色分级轮、原色校准与 LUT 选择尚未接入:"- + "引擎已支持这些参数,但界面还需要曲线画布与色轮控件,本轮未做。"- color: Theme.t2- font.family: Theme.fontUi- font.pixelSize: Theme.fsSmall- wrapMode: Text.WordWrap- }- }+ api: veyra}// --- 声音 -------------------------------------------------ColumnLayout {+ id: audioColLayout.fillWidth: truespacing: 6visible: root.tab === "audio"@@ -795,6 +1527,16 @@ VPage {onToggled: veyra.muted = checked}}+ VRow {+ label: "声音同步"+ hint: veyra.audioSyncMode === 0 ? (veyra.audioSyncLive ? "软件估算补偿 " + veyra.audioCompensationMs.toFixed(0) + " ms" : "自动估算 · 采集卡 / PS5 实时输入时生效")+ : veyra.audioSyncMode === 1 ? "手动偏移 · 实时输入时生效" : "关闭补偿"+ VSeg {+ options: [{ id: "0", label: "自动估算" }, { id: "1", label: "手动" }, { id: "2", label: "关闭" }]+ current: String(veyra.audioSyncMode)+ onPicked: id => veyra.audioSyncMode = Number(id)+ }+ }VRow {label: "音频偏移"hint: "正值延后音频"@@ -802,7 +1544,7 @@ VPage {VSlider {implicitWidth: 150center: true- from: -2000; to: 2000; value: veyra.audioOffsetMs+ from: -250; to: 250; value: veyra.audioOffsetMs; enabledControl: veyra.audioSyncMode === 1onMoved: veyra.audioOffsetMs = Math.round(value)}}@@ -830,7 +1572,10 @@ VPage {anchors.leftMargin: 12anchors.rightMargin: 12spacing: 12- VDot { off: veyra.selectedAudioTrack !== modelData.index }+ VEqBars {+ active: veyra.selectedAudioTrack === modelData.index && veyra.running && !veyra.paused+ opacity: veyra.selectedAudioTrack === modelData.index ? 1 : 0.6+ }ColumnLayout {Layout.fillWidth: truespacing: 2@@ -856,9 +1601,67 @@ VPage {// --- 显示 -------------------------------------------------ColumnLayout {+ id: displayColLayout.fillWidth: truespacing: 6visible: root.tab === "display"+ VGroup {+ PresentationRows { }+ VRow {+ label: "原画 / 增强对比"+ hint: veyra.compareMode === 2 ? "在画面上按住左键拖动分割线:左边原画、右边增强" : ""+ VSeg {+ objectName: "display-compare"+ options: [{ id: "0", label: "关闭" }, { id: "2", label: "分屏" }, { id: "1", label: "只看原画" }]+ current: String(veyra.compareMode)+ onPicked: id => veyra.compareMode = Number(id)+ }+ }+ VRow {+ label: "对照底图"+ hint: "低延迟 NR 先行时,“增强前底图”是原图缩放,不是独立超分对照"+ visible: veyra.compareMode !== 0+ VSeg {+ objectName: "display-compare-base"+ options: [{ id: "0", label: "输入原画" }, { id: "1", label: "增强前底图" }]+ current: veyra.compareBase ? "1" : "0"+ onPicked: id => veyra.compareBase = id === "1"+ }+ }+ VRow {+ label: "按住 V 查看原画"+ hint: "按键可在 设置 → 快捷键 里改"+ VSwitch {+ objectName: "display-hold-compare"+ checked: veyra.preferences.holdCompare !== false+ onToggled: veyra.setPreference("holdCompare", checked)+ }+ }+ VRow {+ label: "画面比例"+ hint: veyra.aspectMode === 1 ? "原始 = 一个输出像素对一个屏幕像素" : veyra.aspectMode === 2 ? "填满窗口,超出部分裁掉" : ""+ VSelect {+ objectName: "display-aspect"+ options: [{ id: "0", label: "适应" }, { id: "1", label: "原始像素" }, { id: "2", label: "填充裁切" }, { id: "3", label: "拉伸铺满" }, { id: "4", label: "16:9" }, { id: "5", label: "4:3" }, { id: "6", label: "21:9" }]+ value: options[veyra.aspectMode].label+ onPicked: id => veyra.aspectMode = Number(id)+ }+ }+ VRow {+ label: "强制 SDR 预览"+ hint: "HDR 片源也按 SDR 显示;与采集卡的“转为 SDR 显示”是同一设置"+ VSwitch {+ objectName: "display-force-sdr"+ checked: veyra.captureForceSdr+ onToggled: veyra.captureForceSdr = checked+ }+ }+ VRow {+ label: "HDR 输出格式"+ hint: "补帧路径固定 HDR10;需要 Windows HDR 开启"+ VSeg { objectName: "display-hdr-output"; options: [{id:"0",label:"HDR10"},{id:"1",label:"scRGB 浮点"}]; current: String(veyra.hdrOutputMode); onPicked: id => veyra.hdrOutputMode = Number(id) }+ }+ }VGroup {VRow {label: "提交帧率"@@ -937,35 +1740,144 @@ VPage {// presets.js VY.presetMenu(app, anchor, 'list').VMenu {id: presetMenu- title: "列表预设"- items: veyra.presets.filter(p => !p.nodeMode)+ title: veyra.nodeMode === 1 ? "节点预设" : "列表预设"+ items: veyra.presets.filter(p => p.nodeMode === (veyra.nodeMode === 1)).map(p => ({ label: p.name, note: p.note, checked: p.name === veyra.currentPresetName,tag: p.builtin ? "内置" : "", preset: p.index })).concat([{ sep: true },{ label: "把当前设置另存为预设…", icon: "plus", act: "save" },- { label: "管理预设…", note: "重命名 · 删除 · 设为启动默认", icon: "settings", act: "manage" }])+ { label: "管理预设…", note: "重命名 · 复制 · 删除", icon: "settings", act: "manage" }])onPicked: (i, o) => {if (o.act) root.requestDialog(o.act)else veyra.applyPresetIndex(o.preset)}}- // Switching to node mode rebuilds the chain, so the design asks first.- Dialog {- id: switchDialog- anchors.centerIn: parent- modal: true- title: "切换到节点模式?"- standardButtons: Dialog.Ok | Dialog.Cancel+ // pages-pro.js layer "更多": copy as a new layer, back to defaults, remove.+ VMenu {+ id: nrLayerMenu+ objectName: "nr-layer-menu"+ property Item layer: null+ title: layer ? "NR 层 " + layer.layerNumber : ""+ items: layer ? [+ { label: "复制为新层", icon: "dup", act: "dup", disabled: veyra.nrLayers.length >= 4 },+ { label: "恢复默认", icon: "reset", act: "reset" },+ { label: "删除这一层", icon: "trash", act: "del", disabled: veyra.nrLayers.length <= 1 }+ ] : []+ onPicked: (i, o) => {+ const card = layer+ if (!card) return+ const nodeIndex = card.layerData.index+ if (o.act === "dup") { root.markPop(card.layerNumber + 1); root.selectedEffect = veyra.duplicateNrLayer(nodeIndex) }+ else if (o.act === "reset") veyra.resetNrLayer(nodeIndex)+ else if (o.act === "del") card.bye(() => veyra.removeEffect(nodeIndex))+ }+ }++ // presets.js DIALOGS.toNode / toList: the two modes side by side, then what+ // switching means. Independent configurations; the node canvas starts empty+ // the first time and keeps its chain afterwards.+ component ModeCard: Rectangle {+ id: mc+ property string glyph: ""+ property string heading: ""+ property string detail: ""+ property string tag: ""+ property bool active: false+ Layout.fillWidth: true+ Layout.preferredWidth: 1+ implicitHeight: modeCol.implicitHeight + 24+ radius: 12+ color: active ? Qt.rgba(1, 138 / 255, 61 / 255, 0.08) : Theme.card2+ border.width: 1+ border.color: active ? Theme.accent : Theme.stroke+ ColumnLayout {+ id: modeCol+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.top: parent.top+ anchors.margins: 12+ spacing: 6+ Rectangle {+ implicitWidth: 28; implicitHeight: 28; radius: 8+ color: Qt.rgba(1, 1, 1, 0.06)+ VIcon { anchors.centerIn: parent; name: mc.glyph; size: 14 }+ }+ Text {+ text: mc.heading+ color: Theme.t1+ font.family: Theme.fontUi; font.pixelSize: 13+ font.weight: Font.DemiBold; font.variableAxes: Theme.axesDemiBold+ }+ Text {+ Layout.fillWidth: true+ text: mc.detail+ color: Theme.t3+ font.family: Theme.fontUi; font.pixelSize: 11+ wrapMode: Text.WordWrap+ }+ VTag { text: mc.tag; kind: mc.active ? "acc" : "" }+ }+ }+ component Bullet: RowLayout {+ id: bl+ property string text: ""+ Layout.fillWidth: true+ spacing: 8+ Rectangle { Layout.alignment: Qt.AlignTop; Layout.topMargin: 7; implicitWidth: 4; implicitHeight: 4; radius: 2; color: Theme.t3 }Text {- width: 380- wrapMode: Text.WordWrap- text: "列表与节点是两套独立配置和预设。切换会重建处理链;切回列表时恢复列表原来的设置。"+ Layout.fillWidth: true+ text: bl.textcolor: Theme.t2- font.family: Theme.fontUi- font.pixelSize: Theme.fsBody+ font.family: Theme.fontUi; font.pixelSize: 12+ wrapMode: Text.WordWrap+ lineHeight: 1.25+ }+ }++ VConfirm {+ id: switchDialog+ property int targetMode: 1+ objectName: "node-switch-dialog"+ cardWidth: targetMode === 1 ? 560 : 480+ glyph: targetMode === 1 ? "nodes" : "list"+ title: targetMode === 1 ? "切换到节点模式?" : "切换回列表模式?"+ acceptText: targetMode === 1 ? "切换到节点模式" : "切换到列表模式"+ acceptIcon: targetMode === 1 ? "nodes" : "list"+ RowLayout {+ objectName: "node-switch-cards"+ visible: switchDialog.targetMode === 1+ Layout.fillWidth: true+ spacing: 8+ ModeCard {+ glyph: "list"+ heading: "列表模式"+ detail: "固定顺序:超分 → NR → 保护 → HDR → 补帧"+ tag: "当前 · 设置会原样保留"+ }+ VIcon { name: "right"; color: Theme.t3 }+ ModeCard {+ glyph: "nodes"+ heading: "节点模式"+ detail: "自由排列节点,按连线顺序运行"+ tag: "首次进入为空白画布,之后保留上次的节点链"+ active: true+ }+ }+ ColumnLayout {+ Layout.fillWidth: true+ spacing: 6+ Bullet { visible: switchDialog.targetMode === 1; text: "两种模式的设置、预设完全分开保存,切回列表时恢复列表原来的设置。" }+ Bullet { visible: switchDialog.targetMode === 1; text: "切换会重建处理链,画面可能停顿几百毫秒。" }+ Bullet { visible: switchDialog.targetMode === 1; text: "节点模式按连线顺序真实执行;离线导出仅支持列表模式。" }+ Bullet { visible: switchDialog.targetMode === 0; text: "回到列表模式,恢复列表之前的设置和预设。" }+ Bullet { visible: switchDialog.targetMode === 0; text: "节点链会保留,下次切回节点模式时继续使用。" }+ Bullet { visible: switchDialog.targetMode === 0; text: "切换会重建处理链,画面可能停顿几百毫秒。" }+ }+ onAccepted: {+ veyra.nodeMode = targetMode+ if (veyra.nodeMode === targetMode) root.requestPage(targetMode === 1 ? "node" : "pro")}- onAccepted: root.requestPage("node")}// [data-in] entrance order from pages-pro.js.diff --git a/qml/Veyra/SettingsPage.qml b/qml/Veyra/SettingsPage.qmlindex ccfd8f8a..87d003b7 100644--- a/qml/Veyra/SettingsPage.qml+++ b/qml/Veyra/SettingsPage.qml@@ -15,14 +15,35 @@ VPage {signal requestPage(string page)property string section: "look"+ // The shortcut row waiting for a new key ("" = none).+ property string capturingKey: ""+ onSectionChanged: {+ capturingKey = ""+ if (section === "ps5") veyra.ps5Load()+ // M32: the section's groups redraw one after another (pages-b.js+ // render(true): 480 ms, i*40 ms, y 12).+ Qt.callLater(() => stagger(sectionColumns[section] || null))+ }+ readonly property var sectionColumns: ({ look: secLook, play: secPlay, ps5: secPs5, keys: secKeys, comp: secComp, about: secAbout })+ Component { id: staggerComp; VRise.Stagger {} }+ function stagger(col) {+ if (Theme.reduced || !col) return+ let i = 0+ for (let k = 0; k < col.children.length; ++k) {+ const c = col.children[k]+ if (!c.visible || c.motionDy === undefined) continue+ staggerComp.createObject(root, { target: c, delay: i * 40, span: 480, dy: 12 }).start()+ ++i+ }+ }readonly property var sections: [- { id: "look", label: "通用与外观" },- { id: "play", label: "播放" },- { id: "ps5", label: "PS5 串流" },- { id: "keys", label: "快捷键" },- { id: "comp", label: "组件与许可" },- { id: "about", label: "关于" }+ { id: "look", label: "通用与外观", icon: "home" },+ { id: "play", label: "播放", icon: "play" },+ { id: "ps5", label: "PS5 串流", icon: "gamepad" },+ { id: "keys", label: "快捷键", icon: "zap" },+ { id: "comp", label: "组件与许可", icon: "box" },+ { id: "about", label: "关于", icon: "info" }]// --- nav ---------------------------------------------------------------@@ -56,15 +77,27 @@ VPage {color: root.section === modelData.id ? Theme.card3: navHover.hovered ? Qt.rgba(1, 1, 1, 0.04) : "transparent"Behavior on color { ColorAnimation { duration: Theme.d(200) } }- Text {+ // .setnav button: icon, 10px, label.+ Row {anchors.left: parent.leftanchors.leftMargin: 10anchors.verticalCenter: parent.verticalCenter- text: modelData.label- color: root.section === modelData.id ? Theme.t1 : Theme.t2- font.family: Theme.fontUi- font.pixelSize: 13- font.weight: Font.Medium+ spacing: 10+ VIcon {+ anchors.verticalCenter: parent.verticalCenter+ name: modelData.icon+ size: 15+ color: navLabel.color+ }+ Text {+ id: navLabel+ anchors.verticalCenter: parent.verticalCenter+ text: modelData.label+ color: root.section === modelData.id ? Theme.t1 : Theme.t2+ font.family: Theme.fontUi+ font.pixelSize: 13+ font.weight: Font.Medium+ }}HoverHandler { id: navHover; cursorShape: Qt.PointingHandCursor }TapHandler { onTapped: root.section = modelData.id }@@ -95,17 +128,19 @@ VPage {anchors.fill: parentcontentHeight: body.implicitHeight + 44clip: true- ScrollBar.vertical: ScrollBar { }+ ScrollBar.vertical: VScrollBar { }ColumnLayout {id: bodyx: 26y: 22- width: parent.width - 52+ // .setbody section { max-width: 720px }+ width: Math.min(parent.width - 52, 720)spacing: 12// --- 通用与外观 ------------------------------------------ColumnLayout {+ id: secLookLayout.fillWidth: truespacing: 12visible: root.section === "look"@@ -121,9 +156,37 @@ VPage {label: "页面切换栏"hint: "平时隐藏;鼠标碰到窗口顶部时弹下来"VSeg {+ objectName: "set-dock"options: [{ id: "auto", label: "自动隐藏" }, { id: "always", label: "始终显示" }]- current: "auto"- onPicked: id => {}+ current: veyra.preferences.dockPinned === true ? "always" : "auto"+ onPicked: id => veyra.setPreference("dockPinned", id === "always")+ }+ }+ VRow {+ label: "强调色"+ hint: "开关、进度、选中状态"+ // .swatch: two colour dots, the chosen one ringed and 1.12x.+ Row {+ objectName: "set-accent"+ spacing: 10+ Repeater {+ model: [{ id: "orange", c: "#FF8A3D", tip: "橙色" }, { id: "white", c: "#F3F3F5", tip: "白色光晕" }]+ delegate: Rectangle {+ required property var modelData+ readonly property bool on: (veyra.preferences.accent || "orange") === modelData.id+ objectName: "set-accent-" + modelData.id+ width: 24; height: 24; radius: 12+ color: modelData.c+ border.width: 2+ border.color: on ? "#FFFFFF" : "transparent"+ scale: on ? 1.12 : 1+ Behavior on scale { NumberAnimation { duration: Theme.d(400); easing.bezierCurve: Theme.spring } }+ HoverHandler { id: swHover; cursorShape: Qt.PointingHandCursor }+ TapHandler { onTapped: veyra.setPreference("accent", modelData.id) }+ ToolTip.visible: swHover.hovered+ ToolTip.text: modelData.tip+ }+ }}}VRow {@@ -134,24 +197,75 @@ VPage {onToggled: veyra.reducedMotion = checked}}+ VRow {+ label: "背景渐变强度"+ hint: "深黑底上的极轻渐变与抖动(防色带)"+ VSeg {+ objectName: "set-backdrop"+ options: [{ id: "0", label: "无" }, { id: "1", label: "轻" }, { id: "2", label: "中" }]+ current: String(veyra.preferences.backdrop !== undefined ? veyra.preferences.backdrop : 1)+ onPicked: id => veyra.setPreference("backdrop", Number(id))+ }+ }+ VRow {+ label: "界面缩放"+ hint: (veyra.preferences.uiScale || 0) !== veyra.uiScaleActive ? "重启后生效" : "自动 = 跟随 Windows 显示缩放"+ VSeg {+ objectName: "set-scale"+ options: [{ id: "0", label: "自动" }, { id: "100", label: "100%" }, { id: "125", label: "125%" }, { id: "150", label: "150%" }]+ current: String(veyra.preferences.uiScale || 0)+ onPicked: id => veyra.setPreference("uiScale", Number(id))+ }+ }+ VRow {+ label: "启动窗口大小"+ hint: "下次启动生效;超过屏幕时按屏幕缩小并居中"+ VSelect {+ objectName: "set-window-size"+ readonly property var sizes: [+ { id: "1280x800", label: "1280 × 800" },+ { id: "1600x1000", label: "1600 × 1000" },+ { id: "1920x1200", label: "1920 × 1200" },+ { id: "last", label: "记住上次大小" }+ ]+ options: sizes+ value: (sizes.find(o => o.id === (veyra.preferences.windowSize || "1280x800")) || sizes[0]).label+ onPicked: id => veyra.setPreference("windowSize", id)+ }+ }+ }+ VGroup {VRow {label: "打开时的默认页面"hint: "首页 = 选择片源的页面(点顶部 Logo 也能回到这里)"- VSelect {- value: veyra.defaultPageLabel+ VSeg {+ objectName: "set-default-page"options: [{ id: "home", label: "首页" },{ id: "min", label: "极简模式" },- { id: "pro", label: "专业模式" }+ { id: "pro", label: "专业模式" },+ { id: "last", label: "上次" }]+ current: veyra.defaultPageonPicked: id => veyra.defaultPage = id}}+ VRow {+ label: "界面语言"+ hint: "2.0 只提供简体中文界面"+ VSelect {+ objectName: "set-language"+ implicitWidth: 140+ value: "简体中文"+ options: [{ id: "zh-CN", label: "简体中文" }]+ }+ }}}// --- 播放 ------------------------------------------------ColumnLayout {+ id: secPlayLayout.fillWidth: truespacing: 12visible: root.section === "play"@@ -163,6 +277,93 @@ VPage {font.pixelSize: Theme.fsBody}VGroup {+ VRow {+ label: "解码"+ hint: (veyra.preferences.decode || "auto") === "hardware"+ ? "强制硬解 = 只用硬件解码,打不开时报错不回退;下次打开文件生效"+ : "自动 = 优先硬解,失败回退软解;下次打开文件生效"+ VSeg {+ objectName: "set-decode"+ options: [{ id: "auto", label: "自动" }, { id: "hardware", label: "强制硬解" }, { id: "software", label: "软解" }]+ current: veyra.preferences.decode || "auto"+ onPicked: id => veyra.setPreference("decode", id)+ }+ }+ VRow {+ label: "HDR 输出格式"+ hint: "HDR10 默认;补帧固定 HDR10,需要 Windows HDR 开启"+ VSeg { options: [{id:"0",label:"HDR10"},{id:"1",label:"scRGB 浮点"}]; current: String(veyra.hdrOutputMode); onPicked: id => veyra.hdrOutputMode = Number(id) }+ }+ VRow {+ label: "记住播放位置"+ hint: "重新打开同一个文件时从上次位置继续"+ VSwitch {+ objectName: "set-resume"+ checked: veyra.preferences.rememberPosition !== false+ onToggled: veyra.setPreference("rememberPosition", checked)+ }+ }+ VRow {+ label: "字幕默认字号"+ hint: "双行不自动缩小;更多样式在字幕设置里"+ VSeg {+ objectName: "set-subsize"+ readonly property int size: veyra.preferences.subtitleSize || 22+ options: [{ id: "18", label: "小" }, { id: "22", label: "中" }, { id: "28", label: "大" }]+ current: size <= 19 ? "18" : size >= 26 ? "28" : "22"+ onPicked: id => veyra.setPreference("subtitleSize", Number(id))+ }+ }+ VRow {+ label: "截图保存位置"+ hint: veyra.screenshotDirectory + "(SDR 存 PNG,HDR 存 JPEG XR)"+ RowLayout {+ spacing: 6+ VButton { text: "打开"; ghost: true; onClicked: veyra.openScreenshotDirectory() }+ VButton { objectName: "set-shotdir"; text: "更改…"; onClicked: veyra.chooseScreenshotDirectory() }+ }+ }+ }+ // 补帧说明 (moved here from the 补帧 page, user decision 2026-09-29).+ VGroup {+ objectName: "set-smooth-motion"+ VRow {+ label: "Smooth Motion 开启方法"+ hint: "NVIDIA 驱动级 AI 插帧,与软件内补帧二选一"+ VButton {+ text: smoothHelp.visible ? "收起" : "查看"+ ghost: true+ onClicked: smoothHelp.visible = !smoothHelp.visible+ }+ }+ Text {+ id: smoothHelp+ visible: false+ Layout.fillWidth: true+ Layout.leftMargin: 12; Layout.rightMargin: 12; Layout.bottomMargin: 10+ text: "只用驱动补帧时:在专业模式的补帧页关闭补帧,再到 NVIDIA App 打开 Smooth Motion(AI 插帧)。+"+ + "只用 DLSS / XeSS 补帧时:到 NVIDIA App 关闭 Smooth Motion。+"+ + "软件不检测、不拦截两者叠加,也不修改驱动配置;AMD FSR 补帧暂不提供。"+ color: Theme.t2+ font.family: Theme.fontUi+ font.pixelSize: 12+ wrapMode: Text.WordWrap+ lineHeight: 1.3+ }+ }+ VGroup {+ VRow {+ label: "声音同步"+ hint: veyra.audioSyncMode === 0 ? (veyra.audioSyncLive ? "软件估算补偿 " + veyra.audioCompensationMs.toFixed(0) + " ms" : "自动估算 · 采集卡 / PS5 实时输入时生效")+ : veyra.audioSyncMode === 1 ? "手动偏移 · 实时输入时生效" : "关闭补偿"+ VSeg {+ options: [{ id: "0", label: "自动估算" }, { id: "1", label: "手动" }, { id: "2", label: "关闭" }]+ current: String(veyra.audioSyncMode)+ onPicked: id => veyra.audioSyncMode = Number(id)+ }+ }VRow {label: "音频偏移"hint: "正值延后音频"@@ -170,7 +371,7 @@ VPage {VSlider {implicitWidth: 150center: true- from: -2000; to: 2000; value: veyra.audioOffsetMs+ from: -250; to: 250; value: veyra.audioOffsetMs; enabledControl: veyra.audioSyncMode === 1onMoved: veyra.audioOffsetMs = Math.round(value)}}@@ -184,26 +385,18 @@ VPage {}}}- Rectangle {- Layout.fillWidth: true- implicitHeight: subNote.implicitHeight + 20- radius: 9- color: Qt.rgba(0.961, 0.784, 0.294, 0.06)- Text {- id: subNote- anchors.fill: parent- anchors.margins: 10- text: "字幕默认字号、描边与截图保存位置尚未接入设置;引擎侧没有对应字段,这里不放假控件。"- color: Theme.t2- font.family: Theme.fontUi- font.pixelSize: Theme.fsSmall- wrapMode: Text.WordWrap+ VGroup {+ VRow {+ label: "输出设备与下混"+ hint: veyra.audioOutputStatus+ VButton { text: "音频设置…"; onClicked: veyra.openAudioDialog() }}}}// --- PS5 串流 --------------------------------------------ColumnLayout {+ id: secPs5Layout.fillWidth: truespacing: 12visible: root.section === "ps5"@@ -216,10 +409,54 @@ VPage {}VGroup {VRow {- label: "串流状态"- hint: veyra.remotePlayState.length > 0 ? veyra.remotePlayState : "未连接"+ label: "已保存主机"+ hint: (veyra.ps5.host || "").length > 0 ? veyra.ps5.host + (veyra.remotePlayState.length > 0 ? " · " + veyra.remotePlayState : "") : "还没有配对的主机"VButton { text: "管理"; onClicked: veyra.openPs5Dialog() }}+ VRow {+ label: "画质"+ VSelect {+ objectName: "set-ps5-quality"+ implicitWidth: 170+ readonly property var qualities: [{ id: "0", label: "720p · 30 fps" }, { id: "1", label: "720p · 60 fps" }, { id: "2", label: "1080p · 30 fps" }, { id: "3", label: "1080p · 60 fps" }]+ options: qualities+ value: qualities[veyra.ps5.quality || 0].label+ onPicked: id => veyra.ps5Set("quality", Number(id))+ }+ }+ VRow {+ label: "编码"+ hint: "HDR 需要 PS5 实际输出 HDR 且 Windows HDR 开启"+ VSeg {+ objectName: "set-ps5-codec"+ options: [{ id: "0", label: "H.264" }, { id: "1", label: "H.265" }, { id: "2", label: "H.265 HDR" }]+ current: String(veyra.ps5.codec || 0)+ onPicked: id => veyra.ps5Set("codec", Number(id))+ }+ }+ VRow {+ label: "请求码率"+ hint: "发给 PS5 的带宽请求,主机不保证达到"+ VSelect {+ objectName: "set-ps5-bitrate"+ implicitWidth: 130+ readonly property var bitrates: [5, 10, 15, 20, 30, 50, 80, 100].map((m, i) => ({ id: String(i), label: m + " Mbps" }))+ options: bitrates+ value: bitrates[veyra.ps5.bitrate || 0].label+ onPicked: id => veyra.ps5Set("bitrate", Number(id))+ }+ }+ VRow {+ label: "PSN 账号"+ hint: veyra.ps5.psnReady ? "已登录" : "未登录 · 在 PS5 串流窗口里登录"+ VButton {+ objectName: "set-ps5-psn-logout"+ text: veyra.ps5.psnReady ? "退出" : "去登录"+ ghost: true+ enabled: !veyra.ps5.busy+ onClicked: veyra.ps5.psnReady ? veyra.ps5PsnForget() : veyra.openPs5Dialog()+ }+ }}Rectangle {Layout.fillWidth: true@@ -230,7 +467,7 @@ VPage {id: psNoteanchors.fill: parentanchors.margins: 10- text: "串流编码、请求码率与 PSN 账号管理尚未接入设置页;这些参数在 PS5 对话框里调整。"+ text: "这里和 PS5 串流窗口是同一份设置,下次连接时一起保存到该主机的配对档案。"color: Theme.t2font.family: Theme.fontUifont.pixelSize: Theme.fsSmall@@ -241,12 +478,13 @@ VPage {// --- 快捷键 ----------------------------------------------ColumnLayout {+ id: secKeysLayout.fillWidth: truespacing: 12visible: root.section === "keys"VH1 { text: "快捷键" }Text {- text: "当前生效的快捷键;重新绑定尚未实现。"+ text: "点击右侧按键,再按下新的组合键即可重新绑定;Esc 取消。"color: Theme.t2font.family: Theme.fontUifont.pixelSize: Theme.fsBody@@ -254,21 +492,93 @@ VPage {VGroup {Repeater {model: [- { a: "播放 / 暂停", k: "Space" },+ { id: "playPause", a: "播放 / 暂停" },+ { id: "fullscreen", a: "全屏", note: "F11 / Alt+Enter 也可以" },+ { id: "lock", a: "锁定全屏控制条" },+ { id: "hold", a: "按住查看原画" },+ { id: "screenshot", a: "截图" },+ { id: "toggleMode", a: "切换极简 / 专业" }+ ]+ delegate: VRow {+ id: keyRow+ required property var modelData+ label: modelData.a+ hint: modelData.note || ""+ Rectangle {+ objectName: "key-" + keyRow.modelData.id+ readonly property bool capturing: root.capturingKey === keyRow.modelData.id+ implicitWidth: Math.max(64, keyText.implicitWidth + 20)+ implicitHeight: 26+ radius: 7+ color: capturing ? Theme.accentSoft : Qt.rgba(1, 1, 1, 0.06)+ border.width: 1+ border.color: capturing ? Theme.accent : Theme.stroke+ Text {+ id: keyText+ anchors.centerIn: parent+ text: parent.capturing ? "按下新按键…" : veyra.shortcuts[keyRow.modelData.id]+ color: Theme.t1+ font.family: Theme.fontMono+ font.pixelSize: Theme.fsSmall+ }+ HoverHandler { cursorShape: Qt.PointingHandCursor }+ TapHandler { onTapped: { root.capturingKey = keyRow.modelData.id; keyCatcher.forceActiveFocus() } }+ }+ }+ }+ VRow {+ label: "恢复默认"+ VButton { text: "全部还原"; ghost: true; onClicked: veyra.resetShortcuts() }+ }+ }+ VGroup {+ Repeater {+ model: [{ a: "后退 / 前进 10 秒", k: "← / →" },- { a: "截图", k: "Ctrl + S" }+ { a: "音量", k: "↑ / ↓" },+ { a: "打开文件 / 导出页", k: "Ctrl+O / Ctrl+E" },+ { a: "字幕开关 / 主轨 / 副轨", k: "B / T / Y" },+ { a: "字幕延时 50 ms(Shift = 1 s)", k: "Z / X" }]delegate: VRow {required property var modelDatalabel: modelData.a+ hint: "固定"VTag { text: modelData.k }}}}+ // Captures the next key combination for the row being rebound.+ Item {+ id: keyCatcher+ focus: false+ Keys.onPressed: event => {+ if (root.capturingKey === "") return+ event.accepted = true+ if (event.key === Qt.Key_Escape) { root.capturingKey = ""; return }+ const modifierOnly = [Qt.Key_Control, Qt.Key_Shift, Qt.Key_Alt, Qt.Key_Meta].indexOf(event.key) >= 0+ if (modifierOnly) return+ const parts = []+ if (event.modifiers & Qt.ControlModifier) parts.push("Ctrl")+ if (event.modifiers & Qt.AltModifier) parts.push("Alt")+ if (event.modifiers & Qt.ShiftModifier) parts.push("Shift")+ const names = { [Qt.Key_Space]: "Space", [Qt.Key_Tab]: "Tab", [Qt.Key_Return]: "Return", [Qt.Key_Enter]: "Enter",+ [Qt.Key_Backspace]: "Backspace", [Qt.Key_Delete]: "Del", [Qt.Key_Home]: "Home", [Qt.Key_End]: "End",+ [Qt.Key_PageUp]: "PgUp", [Qt.Key_PageDown]: "PgDown", [Qt.Key_Insert]: "Ins" }+ let name = names[event.key]+ if (!name && event.key >= Qt.Key_F1 && event.key <= Qt.Key_F24) name = "F" + (event.key - Qt.Key_F1 + 1)+ if (!name && event.text && event.text.trim().length === 1) name = event.text.toUpperCase()+ if (!name && event.key >= 0x20 && event.key < 0x7F) name = String.fromCharCode(event.key)+ if (!name) return+ parts.push(name)+ if (veyra.setShortcut(root.capturingKey, parts.join("+"))) root.capturingKey = ""+ }+ }}// --- 组件与许可 ------------------------------------------ColumnLayout {+ id: secCompLayout.fillWidth: truespacing: 12visible: root.section === "comp"@@ -301,6 +611,7 @@ VPage {// --- 关于 ------------------------------------------------ColumnLayout {+ id: secAboutLayout.fillWidth: truespacing: 12visible: root.section === "about"@@ -325,14 +636,34 @@ VPage {VGroup {VRow {label: "检查更新"- hint: "GitHub · Likely7/Veyra-NRVideo"- VButton { text: "打开"; onClicked: veyra.openProjectPage() }+ hint: "GitHub · Likely7/Veyra-NRVideo · 发布页"+ VButton { text: "检查"; onClicked: veyra.openReleasesPage() }+ }+ VRow {+ label: "反馈问题"+ hint: "打开 GitHub Issues,诊断信息已自动复制"+ VButton { text: "打开"; onClicked: veyra.openFeedbackPage() }+ }+ VRow {+ label: "交流群与赞助"+ hint: "项目主页 README 里的二维码"+ VButton { text: "查看"; onClicked: veyra.openProjectPage() }}VRow {label: "诊断信息"hint: "复制后附在反馈里"VButton { text: "复制"; onClicked: veyra.copyDiagnostics() }}+ VRow {+ label: "日志"+ hint: veyra.logFile+ VButton { text: "打开目录"; ghost: true; onClicked: veyra.openLogFolder() }+ }+ VRow {+ label: "用户数据"+ hint: veyra.dataDirectory+ VButton { text: "打开目录"; ghost: true; onClicked: veyra.openDataFolder() }+ }}// The diagnostics the engine actually reports, shown verbatim.Rectangle {@@ -346,6 +677,7 @@ VPage {anchors.margins: 10contentHeight: diagText.implicitHeightclip: true+ ScrollBar.vertical: VScrollBar { }Text {id: diagTextwidth: parent.widthdiff --git a/qml/Veyra/Theme.qml b/qml/Veyra/Theme.qmlindex 78d6b4e4..35b05493 100644--- a/qml/Veyra/Theme.qml+++ b/qml/Veyra/Theme.qml@@ -28,10 +28,15 @@ QtObject {readonly property color t3: Qt.rgba(0.953, 0.953, 0.961, 0.38)// --- accent and state -------------------------------------------------- readonly property color accent: "#FF8A3D"- readonly property color accentInk: "#1B0E04"- readonly property color accentSoft: Qt.rgba(1, 0.541, 0.239, 0.14)- readonly property color accentGlow: Qt.rgba(1, 0.541, 0.239, 0.35)+ // 设置 → 强调色: orange (default) or the design's .accent-white variant.+ property string accentName: "orange"+ readonly property bool accentWhite: accentName === "white"+ readonly property color accent: accentWhite ? "#F3F3F5" : "#FF8A3D"+ readonly property color accentInk: accentWhite ? "#0B0B0E" : "#1B0E04"+ readonly property color accentSoft: accentWhite ? Qt.rgba(1, 1, 1, 0.1) : Qt.rgba(1, 0.541, 0.239, 0.14)+ readonly property color accentGlow: accentWhite ? Qt.rgba(1, 1, 1, 0.35) : Qt.rgba(1, 0.541, 0.239, 0.35)+ // 设置 → 背景渐变强度: 0 none, 1 light (the design default), 2 medium.+ property int backdropLevel: 1readonly property color ok: "#3DDC84"readonly property color okGlow: Qt.rgba(0.239, 0.863, 0.518, 0.16)readonly property color warn: "#F5C84B"diff --git a/qml/Veyra/TopDock.qml b/qml/Veyra/TopDock.qmlindex 20bcebaf..f6ac8e96 100644--- a/qml/Veyra/TopDock.qml+++ b/qml/Veyra/TopDock.qml@@ -20,6 +20,12 @@ Item {required property string currentPagesignal requestPage(string page)+ // Frameless window controls live in the capsule (user decision 2026-09-28).+ property bool maximized: false+ signal requestMinimize()+ signal requestMaximize()+ signal requestClose()+ signal requestMove()property bool opened: false// Mirrors st.dockPinned in the design: pinned stays open regardless of hover.@@ -46,6 +52,9 @@ Item {height: 12// Leaving the zone for anywhere but the dock retracts it (closeDock).HoverHandler { onHoveredChanged: if (hovered) dockRoot.open(); else if (!barHover.hovered) retract.restart() }+ // The top strip is the title bar: drag moves, double click maximizes.+ DragHandler { target: null; onActiveChanged: if (active) dockRoot.requestMove() }+ TapHandler { onDoubleTapped: dockRoot.requestMaximize() }}Rectangle {id: handle@@ -96,6 +105,12 @@ Item {id: barHoveronHoveredChanged: if (hovered) dockRoot.open(); else retract.restart()}+ // Dragging the capsule moves the window, as a title bar would.+ DragHandler {+ objectName: "dock-move"+ target: null+ onActiveChanged: if (active) dockRoot.requestMove()+ }RowLayout {id: content@@ -228,6 +243,76 @@ Item {implicitHeight: 30VDot { anchors.centerIn: parent; off: !veyra.running; warn: veyra.captureRecovering }}++ Rectangle { implicitWidth: 1; implicitHeight: 16; color: Qt.rgba(1, 1, 1, 0.14) }++ // Window controls: minimize, maximize/restore, close.+ Repeater {+ model: [+ { id: "min", icon: "minus", tip: "最小化" },+ { id: "max", icon: "max", tip: dockRoot.maximized ? "还原" : "最大化" },+ { id: "close", icon: "x", tip: "关闭" }+ ]+ delegate: Item {+ id: wbtn+ required property var modelData+ objectName: "window-" + modelData.id+ implicitWidth: 30+ implicitHeight: 30+ scale: wtap.pressed ? 0.86 : 1+ Behavior on scale { NumberAnimation { duration: Theme.d(450); easing.bezierCurve: Theme.spring } }+ Rectangle {+ anchors.fill: parent+ radius: height / 2+ color: whover.hovered ? (wbtn.modelData.id === "close" ? Qt.rgba(1, 0.365, 0.365, 0.22) : "#1A1A1F") : "transparent"+ Behavior on color { ColorAnimation { duration: Theme.d(200) } }+ }+ VIcon {+ anchors.centerIn: parent+ name: wbtn.modelData.icon+ size: 13+ color: whover.hovered && wbtn.modelData.id === "close" ? "#FF8A8A" : "#FFFFFF"+ opacity: whover.hovered ? 1.0 : 0.45+ Behavior on opacity { NumberAnimation { duration: Theme.d(200) } }+ }+ Rectangle {+ objectName: "videoCover"+ property real coverRadius: 7+ readonly property bool on: whover.hovered+ x: (wbtn.width - width) / 2+ y: 38+ width: wtipText.implicitWidth + 18+ height: wtipText.implicitHeight + 10+ radius: 7+ color: Theme.popover+ border.width: 1+ border.color: Theme.stroke2+ opacity: on ? 1 : 0+ visible: opacity > 0+ scale: on ? 1 : 0.85+ transformOrigin: Item.Top+ Behavior on opacity { NumberAnimation { duration: Theme.d(150) } }+ Behavior on scale { NumberAnimation { duration: Theme.d(300); easing.bezierCurve: Theme.spring } }+ Text {+ id: wtipText+ anchors.centerIn: parent+ text: wbtn.modelData.tip+ color: "#FFFFFF"+ font.family: Theme.fontUi+ font.pixelSize: 11+ }+ }+ HoverHandler { id: whover; cursorShape: Qt.PointingHandCursor }+ TapHandler {+ id: wtap+ onTapped: {+ if (wbtn.modelData.id === "min") dockRoot.requestMinimize()+ else if (wbtn.modelData.id === "max") dockRoot.requestMaximize()+ else dockRoot.requestClose()+ }+ }+ }+ }}}}diff --git a/qml/Veyra/VAccordion.qml b/qml/Veyra/VAccordion.qmlindex 7a55a6c0..1af33ea6 100644--- a/qml/Veyra/VAccordion.qml+++ b/qml/Veyra/VAccordion.qml@@ -18,17 +18,73 @@ Rectangle {property string glyph: ""property color hue: Theme.accentproperty bool enabledSwitch: true+ property string switchObjectName: ""property bool on: trueproperty bool open: false// [{ label, count, open }] — nested groups, as the design draws them.property var groups: []signal toggled(bool on)signal headerClicked()+ // A brief accent pulse on the border: "here it is" after 处理顺序 locates a card.+ function flash() { flashAnim.restart() }+ property real flashLevel: 0+ SequentialAnimation {+ id: flashAnim+ NumberAnimation { target: acc; property: "flashLevel"; to: 1; duration: Theme.d(160) }+ // The hold is information, not motion: it stays with reduced motion+ // (only the fades collapse to instant).+ PauseAnimation { duration: 700 }+ NumberAnimation { target: acc; property: "flashLevel"; to: 0; duration: Theme.d(520) }+ }+ // M30 .acc.new / .acc.bye: a card that was just added pops in (scale .85,+ // y -8 -> rest over .6s --spring); a removed one shrinks to .9 and fades+ // over .3s --out, then `done` runs the actual removal.+ property bool popIn: false+ property real motionS: 1+ property real motionDy: 0+ transform: [+ Scale { origin.x: acc.width / 2; origin.y: acc.height / 2; xScale: acc.motionS; yScale: acc.motionS },+ Translate { y: acc.motionDy }+ ]+ Component.onCompleted: if (popIn && Theme.d(600) > 0) { motionS = 0.85; motionDy = -8; opacity = 0; popAnim.start() }+ ParallelAnimation {+ id: popAnim+ NumberAnimation { target: acc; property: "motionS"; to: 1; duration: Theme.d(600); easing.bezierCurve: Theme.spring }+ NumberAnimation { target: acc; property: "motionDy"; to: 0; duration: Theme.d(600); easing.bezierCurve: Theme.spring }+ NumberAnimation { target: acc; property: "opacity"; to: 1; duration: Theme.d(300) }+ }+ property var byeDone: null+ function bye(done) {+ byeDone = done+ if (Theme.d(300) <= 0) { const f = byeDone; byeDone = null; if (f) f(); return }+ byeAnim.restart()+ }+ ParallelAnimation {+ id: byeAnim+ NumberAnimation { target: acc; property: "motionS"; to: 0.9; duration: Theme.d(300); easing.bezierCurve: Theme.easeOut }+ NumberAnimation { target: acc; property: "opacity"; to: 0; duration: Theme.d(300); easing.bezierCurve: Theme.easeOut }+ onFinished: { const f = acc.byeDone; acc.byeDone = null; if (f) f() }+ }+ Rectangle {+ anchors.fill: parent+ z: 10+ radius: acc.radius+ color: Qt.rgba(1, 138 / 255, 61 / 255, 0.08 * acc.flashLevel)+ border.width: 2+ border.color: Theme.accent+ opacity: acc.flashLevel+ visible: acc.flashLevel > 0+ }// Caller-supplied rows land in the body. Declared here, on the root, because// a default property belongs to the component it is declared in.default property alias content: body.data+ // Optional actions stay in the header; ordinary accordions remain unchanged.+ property alias headerActions: headerTools.data+ property alias headerLeadingActions: leadingTools.data+ property bool compactHeader: false+ property bool bypassed: false- readonly property int headerHeight: 48+ readonly property int headerHeight: compactHeader ? 42 : 48implicitHeight: headerHeight + (open ? body.implicitHeight + 8 : 0)radius: 12color: Theme.card2@@ -53,10 +109,17 @@ Rectangle {anchors.fill: parentanchors.leftMargin: 10anchors.rightMargin: 10- spacing: 9+ spacing: acc.compactHeader ? 8 : 9++ RowLayout {+ id: leadingTools+ spacing: 0+ visible: children.length > 0+ }// .sico: a 26px plate tinted by the effect's own hue.Rectangle {+ visible: !leadingTools.visibleimplicitWidth: 26implicitHeight: 26radius: 8@@ -75,7 +138,8 @@ Rectangle {Text {Layout.fillWidth: truetext: acc.title- color: Theme.t1+ color: acc.bypassed ? Theme.t3 : Theme.t1+ font.strikeout: acc.bypassedfont.family: Theme.fontUifont.pixelSize: 13font.weight: Font.DemiBold; font.variableAxes: Theme.axesDemiBold@@ -92,7 +156,14 @@ Rectangle {}}+ RowLayout {+ id: headerTools+ spacing: 2+ visible: children.length > 0+ }+VSwitch {+ objectName: acc.switchObjectNamevisible: acc.enabledSwitchchecked: acc.ononToggled: acc.toggled(checked)@@ -108,22 +179,29 @@ Rectangle {}HoverHandler { cursorShape: Qt.PointingHandCursor }- TapHandler { onTapped: { acc.open = !acc.open; acc.headerClicked() } }+ TapHandler { onTapped: point => {+ for (const tools of [leadingTools, headerTools]) {+ const p = tools.mapFromItem(parent, point.position.x, point.position.y)+ if (tools.visible && p.x >= 0 && p.x <= tools.width+ && p.y >= 0 && p.y <= tools.height) return+ }+ acc.open = !acc.open; acc.headerClicked()+ } }}// --- body --------------------------------------------------------ColumnLayout {id: bodyLayout.fillWidth: true- Layout.leftMargin: 12- Layout.rightMargin: 12+ Layout.leftMargin: 12 + (acc.compactHeader ? acc.border.width : 0)+ Layout.rightMargin: 12 + (acc.compactHeader ? acc.border.width : 0)Layout.bottomMargin: 10spacing: 2visible: acc.open || acc.height > acc.headerHeight// .acc-b .inner: opacity .2s and translateY(-6px) -> 0 over .45s --spring,// delayed .06s when opening; closing starts at once.property real dy: acc.open ? 0 : -6- opacity: acc.open ? 1 : 0+ opacity: acc.open ? (acc.bypassed ? 0.45 : 1) : 0transform: Translate { y: body.dy }Behavior on opacity { SequentialAnimation {PauseAnimation { duration: acc.open ? Theme.d(60) : 0 }diff --git a/qml/Veyra/VBackdrop.qml b/qml/Veyra/VBackdrop.qmlindex a165db94..aa5f54ae 100644--- a/qml/Veyra/VBackdrop.qml+++ b/qml/Veyra/VBackdrop.qml@@ -17,19 +17,25 @@ Shape {layer.enabled: truelayer.samples: 4+ // fillItem must be a texture provider (an Image), not a container: a+ // Rectangle holding images filled the shape white.+ // 设置 → 背景渐变强度: 0 = flat base colour, 1 = the design's gradient,+ // 2 = backdrop-strong.png: the same generator (tools/qt_probe/make-backdrop.py,+ // same seed and grain) with the stops' distance from the edge colour x1.8.Image {id: fillvisible: falsewidth: backdrop.widthheight: backdrop.height- source: "backdrop.png"+ source: Theme.backdropLevel === 2 ? "backdrop-strong.png" : "backdrop.png"smooth: true}ShapePath {strokeWidth: 1strokeColor: backdrop.strokeColor- fillItem: fill+ fillColor: Theme.bgOuter+ fillItem: Theme.backdropLevel === 0 ? null : fillPathRectangle {x: 0.5; y: 0.5width: backdrop.width - 1; height: backdrop.height - 1diff --git a/qml/Veyra/VButton.qml b/qml/Veyra/VButton.qmlindex cfdbbac6..7500d58c 100644--- a/qml/Veyra/VButton.qml+++ b/qml/Veyra/VButton.qml@@ -10,6 +10,12 @@ Rectangle {property string glyph: ""// A Lucide name from IconData.js; drawn before the text with the design's 7px gap.property string iconName: ""+ // A chevron (or any icon) after the text: the design's dropdown buttons.+ property string trailingIcon: ""+ // Hover tooltip, for icon-only buttons.+ property string tip: ""+ // Long labels (a file name in the source button) elide in the middle.+ property int maxTextWidth: 0signal clicked()implicitWidth: icon ? Theme.ctlHeight : (content.implicitWidth + 24)@@ -22,6 +28,8 @@ Rectangle {border.color: hover.hovered ? Qt.rgba(1, 1, 1, 0.2) : Theme.stroke2Behavior on color { ColorAnimation { duration: Theme.d(Theme.durFast) } }// .btn:active { transform: scale(.95) }+ // A disabled button reads as such (undo with nothing to undo).+ opacity: enabled ? 1.0 : 0.4scale: tap.pressed ? 0.95 : 1.0Behavior on scale { NumberAnimation { duration: Theme.d(400); easing.bezierCurve: Theme.spring } }@@ -38,6 +46,8 @@ Rectangle {Text {id: labelvisible: text.length > 0+ width: btn.maxTextWidth > 0 ? Math.min(implicitWidth, btn.maxTextWidth) : implicitWidth+ elide: Text.ElideMiddleanchors.verticalCenter: parent.verticalCentertext: btn.glyph.length > 0 ? btn.glyph + (btn.text.length > 0 ? " " + btn.text : "") : btn.textcolor: btn.primary ? Theme.accentInk : (btn.ghost ? Theme.t2 : Theme.t1)@@ -46,7 +56,17 @@ Rectangle {font.weight: btn.primary ? Font.DemiBold : Font.Mediumfont.variableAxes: btn.primary ? Theme.axesDemiBold : ({})}+ VIcon {+ visible: btn.trailingIcon.length > 0+ anchors.verticalCenter: parent.verticalCenter+ name: btn.trailingIcon+ size: 12+ color: Theme.t3+ }}+ ToolTip.visible: tip.length > 0 && hover.hovered+ ToolTip.delay: 500+ ToolTip.text: tipHoverHandler { id: hover; cursorShape: Qt.PointingHandCursor }- TapHandler { id: tap; onTapped: btn.clicked() }+ TapHandler { id: tap; gesturePolicy: TapHandler.WithinBounds; onTapped: btn.clicked() }}diff --git a/qml/Veyra/VConfirm.qml b/qml/Veyra/VConfirm.qmlnew file mode 100644index 00000000..776c6277--- /dev/null+++ b/qml/Veyra/VConfirm.qml@@ -0,0 +1,126 @@+// A confirmation in the app's own dialog chrome (DialogHost's DLayer look):+// scrim, #dialog card with radius 16, glyph + title, body, 取消 / 确定.+// Replaces the platform Dialog whose white title bar and OK/Cancel buttons did+// not belong to this design.+import QtQuick+import QtQuick.Layouts++Item {+ id: box+ anchors.fill: parent+ z: 50+ property string title: ""+ property string text: ""+ property string glyph: "info"+ property string acceptText: "确定"+ property string rejectText: "取消"+ property bool shown: false+ // Wider cards and custom content (the design's 列表 / 节点 comparison) go+ // between the text and the buttons.+ property int cardWidth: 440+ property string acceptIcon: ""+ default property alias extra: extraCol.data+ signal accepted()+ signal rejected()+ function open() { shown = true }+ function close() { shown = false }+ visible: scrim.opacity > 0++ Keys.onEscapePressed: { box.close(); box.rejected() }++ Rectangle {+ id: scrim+ anchors.fill: parent+ color: Qt.rgba(0, 0, 0, 0.55)+ opacity: box.shown ? 1 : 0+ Behavior on opacity { NumberAnimation { duration: Theme.d(200) } }+ TapHandler { onTapped: { box.close(); box.rejected() } }+ }++ Rectangle {+ id: card+ // Cut out of the native video window (main.cpp syncVideoCovers).+ objectName: "videoCover"+ property real coverRadius: 16+ anchors.centerIn: parent+ width: Math.min(box.cardWidth, box.width - 32)+ height: col.implicitHeight + 32+ radius: 16+ color: Theme.dialog+ border.width: 1+ border.color: Theme.stroke2+ opacity: box.shown ? 1 : 0+ visible: opacity > 0+ Behavior on opacity { NumberAnimation { duration: Theme.d(200) } }+ property real motionS: box.shown ? 1 : 0.9+ property real motionDy: box.shown ? 0 : 14+ Behavior on motionS { NumberAnimation { duration: Theme.d(550); easing.bezierCurve: Theme.spring } }+ Behavior on motionDy { NumberAnimation { duration: Theme.d(550); easing.bezierCurve: Theme.spring } }+ transform: [+ Scale { origin.x: card.width / 2; origin.y: card.height / 2; xScale: card.motionS; yScale: card.motionS },+ Translate { y: card.motionDy }+ ]+ // Swallow clicks so they do not reach the scrim.+ MouseArea { anchors.fill: parent; acceptedButtons: Qt.AllButtons }++ ColumnLayout {+ id: col+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.top: parent.top+ anchors.margins: 16+ spacing: 14+ RowLayout {+ Layout.fillWidth: true+ spacing: 12+ Rectangle {+ implicitWidth: 34; implicitHeight: 34; radius: 10+ color: Qt.rgba(1, 1, 1, 0.06)+ VIcon { anchors.centerIn: parent; name: box.glyph }+ }+ Text {+ Layout.fillWidth: true+ text: box.title+ color: Theme.t1+ font.family: Theme.fontUi+ font.pixelSize: Theme.fsH2+ font.weight: Font.DemiBold; font.variableAxes: Theme.axesDemiBold+ wrapMode: Text.WordWrap+ }+ }+ Text {+ Layout.fillWidth: true+ visible: box.text.length > 0+ text: box.text+ color: Theme.t2+ font.family: Theme.fontUi+ font.pixelSize: Theme.fsBody+ wrapMode: Text.WordWrap+ lineHeight: 1.3+ }+ ColumnLayout {+ id: extraCol+ Layout.fillWidth: true+ spacing: 10+ visible: children.length > 0+ }+ RowLayout {+ Layout.fillWidth: true+ spacing: 8+ Item { Layout.fillWidth: true }+ VButton {+ objectName: box.objectName + "-reject"+ text: box.rejectText+ onClicked: { box.close(); box.rejected() }+ }+ VButton {+ objectName: box.objectName + "-accept"+ text: box.acceptText+ iconName: box.acceptIcon+ primary: true+ onClicked: { box.close(); box.accepted() }+ }+ }+ }+ }+}diff --git a/qml/Veyra/VEqBars.qml b/qml/Veyra/VEqBars.qmlnew file mode 100644index 00000000..a8b4d39f--- /dev/null+++ b/qml/Veyra/VEqBars.qml@@ -0,0 +1,43 @@+// .trk .bars (pages.css, M39): four thin bars beside an audio track. Idle they+// sit at 30 %; on the playing track they bounce 25 % <-> 100 % over 1s,+// ease-in-out, each bar out of phase (-.3s, -.6s, -.15s).+import QtQuick++Item {+ id: eq+ property bool active: false+ property color color: Theme.accent+ implicitWidth: 4 * 3 + 3 * 2+ implicitHeight: 14+ // One linear 0..1 clock; each bar reads it with its own phase offset, the+ // cosine giving the design's ease-in-out between 25 % and 100 %.+ property real phase: 0+ NumberAnimation on phase {+ from: 0; to: 1+ duration: 1000+ loops: Animation.Infinite+ running: eq.active && eq.visible && !Theme.reduced+ }+ Row {+ anchors.fill: parent+ spacing: 2+ Repeater {+ model: [0, 0.3, 0.6, 0.15]+ delegate: Item {+ required property real modelData+ width: 3+ height: eq.height+ Rectangle {+ anchors.bottom: parent.bottom+ width: parent.width+ radius: 1+ color: eq.active ? eq.color : Theme.t3+ readonly property real level: !eq.active ? 0.3+ : Theme.reduced ? 0.6+ : 0.625 - 0.375 * Math.cos(2 * Math.PI * (eq.phase + modelData))+ height: Math.max(2, parent.height * level)+ }+ }+ }+ }+}diff --git a/qml/Veyra/VGroup.qml b/qml/Veyra/VGroup.qmlindex d0bc7493..9b317f4c 100644--- a/qml/Veyra/VGroup.qml+++ b/qml/Veyra/VGroup.qml@@ -14,6 +14,9 @@ import QtQuick.LayoutsRectangle {id: groupdefault property alias body: inner2.data+ // For the staggered tab redraw (VRise.Stagger).+ property real motionDy: 0+ transform: Translate { y: group.motionDy }Layout.fillWidth: trueradius: 12color: Theme.card2diff --git a/qml/Veyra/VMenu.qml b/qml/Veyra/VMenu.qmlindex 8f829ed7..a77d37b5 100644--- a/qml/Veyra/VMenu.qml+++ b/qml/Veyra/VMenu.qml@@ -34,6 +34,18 @@ Popup {const r = anchorItem.mapToItem(win, 0, 0)const ph = heightconst pw = width+ // "at": a context menu whose top-left corner sits at the pointer (the+ // anchor is a 1px item moved there), flipped to stay inside the window.+ if (placement === "at") {+ const ax = r.x + 2 + pw > win.width - 8 ? r.x - pw - 2 : r.x + 2+ const ay = r.y + 2 + ph > win.height - 8 ? r.y - ph - 2 : r.y + 2+ const cx = Math.max(8, Math.min(ax, win.width - pw - 8)), cy = Math.max(8, Math.min(ay, win.height - ph - 8))+ above = cy < r.y+ originX = r.x - cx+ const q = parent.mapFromItem(win, cx, cy)+ x = q.x; y = q.y+ return+ }let px = Math.max(8, Math.min(r.x + anchorItem.width / 2 - pw / 2, win.width - pw - 8))let py = placement === "down" ? r.y + anchorItem.height + 8 : r.y - ph - 8if (placement !== "down" && aboveLimit >= 0)@@ -46,12 +58,13 @@ Popup {const p = parent.mapFromItem(win, px, py)x = p.x; y = p.y}- // place: "up" (the design's default) or "down" (selects).+ // place: "up" (the design's default), "down" (selects) or "at" (context+ // menus, at the pointer).function openAt(anchor, place) {anchorItem = anchorplacement = placechecks = items.map(o => o.checked === true)- width = Math.max(220, anchor.width)+ width = place === "at" ? 220 : Math.max(220, anchor.width)positionAtAnchor()open()Qt.callLater(positionAtAnchor)@@ -64,6 +77,8 @@ Popup {parent: Overlay.overlaypadding: 0modal: false+ // Takes focus so Esc closes it (CloseOnEscape needs the popup focused).+ focus: trueclosePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutsideimplicitHeight: Math.min(420, col.implicitHeight + 12)background: null@@ -133,6 +148,7 @@ Popup {contentHeight: col.implicitHeightimplicitHeight: col.implicitHeightboundsBehavior: Flickable.StopAtBounds+ ScrollBar.vertical: VScrollBar { }ColumnLayout {id: colwidth: parent.width@@ -227,6 +243,7 @@ Popup {HoverHandler { id: optHover; enabled: !row.modelData.disabled; cursorShape: Qt.PointingHandCursor }TapHandler {enabled: !row.modelData.disabled+ gesturePolicy: TapHandler.WithinBoundsonTapped: {pop.checks = pop.items.map((o, i) => i === row.index)pickTimer.index = row.indexdiff --git a/qml/Veyra/VPill.qml b/qml/Veyra/VPill.qmlindex cc0b739d..56aa2733 100644--- a/qml/Veyra/VPill.qml+++ b/qml/Veyra/VPill.qml@@ -5,6 +5,9 @@ Rectangle {id: pillproperty string key: ""property string value: ""+ // Child items (e.g. a status dot) sit in the row before the text, not at+ // the pill's top-left corner.+ default property alias leading: lead.datasignal clicked()implicitWidth: pillRow.implicitWidth + 21implicitHeight: Theme.ctlHeight@@ -18,9 +21,10 @@ Rectangle {id: pillRowanchors.centerIn: parentspacing: 7- Text { text: pill.key; color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: Theme.fsBody }+ Row { id: lead; visible: children.length > 0; Layout.alignment: Qt.AlignVCenter }+ Text { visible: pill.key.length > 0; text: pill.key; color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: Theme.fsBody }Text { text: pill.value; color: Theme.t1; font.family: Theme.fontUi; font.pixelSize: Theme.fsBody; font.weight: Font.Medium }}HoverHandler { id: hover; cursorShape: Qt.PointingHandCursor }- TapHandler { id: tap; onTapped: pill.clicked() }+ TapHandler { id: tap; gesturePolicy: TapHandler.WithinBounds; onTapped: pill.clicked() }}diff --git a/qml/Veyra/VRise.qml b/qml/Veyra/VRise.qmlindex 73c29dbd..02ccbba9 100644--- a/qml/Veyra/VRise.qml+++ b/qml/Veyra/VRise.qml@@ -10,6 +10,25 @@ import QtQuickItem {id: rise+ // M31 / M32: a tab or a settings section redraws its cards one after+ // another - opacity 0 -> 1 and y +dy -> 0, each `delay` later than the last+ // (pages-pro.js 460 ms / i*30 / y10; pages-b.js 480 ms / i*40 / y12). Items+ // opt in with a `motionDy` property (VAccordion, VGroup). Created per item+ // by the page (Component { VRise.Stagger {} }) and destroyed when done.+ component Stagger: SequentialAnimation {+ id: st+ property Item target+ property int delay: 0+ property int span: 460+ property real dy: 10+ ScriptAction { script: { st.target.opacity = 0; st.target.motionDy = st.dy } }+ PauseAnimation { duration: st.delay }+ ParallelAnimation {+ NumberAnimation { target: st.target; property: "opacity"; to: 1; duration: st.span; easing.bezierCurve: Theme.springSoft }+ NumberAnimation { target: st.target; property: "motionDy"; to: 0; duration: st.span; easing.bezierCurve: Theme.spring }+ }+ onFinished: destroy()+ }required property Item targetproperty int d: 0property Item page: parentdiff --git a/qml/Veyra/VRow.qml b/qml/Veyra/VRow.qmlindex e0adb49b..6a3ae814 100644--- a/qml/Veyra/VRow.qml+++ b/qml/Veyra/VRow.qml@@ -6,23 +6,39 @@ Item {property string label: ""property string hint: ""property string value: ""+ // Narrow panels with a wide control (导出 输出设置): the hint runs under the+ // whole row instead of being squeezed beside the control.+ property bool hintBelow: falsedefault property alias control: slot.data// The layout reads Layout.preferredHeight. `height` is deliberately NOT set: a// layout-managed item that sets its own height is undefined behaviour, and this// row is only ever placed inside a layout.- implicitHeight: hint.length > 0 ? Theme.rowMinHeight + 12 : Theme.rowMinHeight+ // A hint that wraps (narrow panels) grows the row instead of running into+ // the next one.+ implicitHeight: hintBelow+ ? mainRow.height + (hint.length > 0 ? belowHint.implicitHeight + 6 : 0)+ : Math.max(hint.length > 0 ? Theme.rowMinHeight + 12 : Theme.rowMinHeight,+ textColumn.implicitHeight + 12, slot.implicitHeight + 8)Layout.preferredHeight: implicitHeightLayout.fillWidth: trueRowLayout {- anchors.fill: parent+ id: mainRow+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.top: parent.top+ height: row.hintBelow ? Math.max(Theme.rowMinHeight, slot.implicitHeight + 8) : parent.heightspacing: 12ColumnLayout {+ id: textColumnLayout.fillWidth: truespacing: 2- Text { text: row.label; color: Theme.t2; font.family: Theme.fontUi; font.pixelSize: Theme.fsBody }+ // fillWidth here too: without a hint the label is the column's only child,+ // and a layout with no filling child cannot grow, which left the control+ // beside the label instead of at the row's right edge.+ Text { Layout.fillWidth: true; text: row.label; color: Theme.t2; font.family: Theme.fontUi; font.pixelSize: Theme.fsBody; elide: Text.ElideRight }Text {- visible: row.hint.length > 0+ visible: row.hint.length > 0 && !row.hintBelowtext: row.hintcolor: Theme.t3font.family: Theme.fontUi@@ -33,6 +49,7 @@ Item {}Item {id: slot+ implicitHeight: childrenRect.heightLayout.preferredWidth: childrenRect.widthLayout.preferredHeight: childrenRect.height}@@ -46,4 +63,17 @@ Item {horizontalAlignment: Text.AlignRight}}+ Text {+ id: belowHint+ visible: row.hintBelow && row.hint.length > 0+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.top: mainRow.bottom+ anchors.topMargin: -4+ text: row.hint+ color: Theme.t3+ font.family: Theme.fontUi+ font.pixelSize: 11+ wrapMode: Text.WordWrap+ }}diff --git a/qml/Veyra/VScrollBar.qml b/qml/Veyra/VScrollBar.qmlnew file mode 100644index 00000000..1eb266f5--- /dev/null+++ b/qml/Veyra/VScrollBar.qml@@ -0,0 +1,23 @@+// The one scrollbar style: a thin rounded thumb, no track or arrows (the+// prototype's thin CSS scrollbar). The platform style drew a white Windows bar.+import QtQuick+import QtQuick.Controls.Basic as Basic++Basic.ScrollBar {+ id: bar+ // A wider gutter where the content sits flush against it (colour panel).+ property bool wide: false+ implicitWidth: wide ? 10 : 6+ implicitHeight: wide ? 10 : 6+ padding: wide ? 2 : 0+ minimumSize: 0.08+ contentItem: Rectangle {+ implicitWidth: 6+ implicitHeight: 6+ radius: 3+ visible: bar.size < 1+ color: bar.pressed ? Theme.t2 : bar.hovered ? Qt.rgba(1, 1, 1, 0.28) : Theme.stroke2+ Behavior on color { ColorAnimation { duration: Theme.d(150) } }+ }+ background: Item {}+}diff --git a/qml/Veyra/VSeg.qml b/qml/Veyra/VSeg.qmlindex 06a5019e..d123a9f0 100644--- a/qml/Veyra/VSeg.qml+++ b/qml/Veyra/VSeg.qml@@ -73,20 +73,33 @@ Rectangle {model: seg.optionsdelegate: Item {required property var modelData- implicitWidth: segLabel.implicitWidth + 20+ implicitWidth: segContent.implicitWidth + 20implicitHeight: 24- Text {- id: segLabel+ // { id, label, icon? }: the design's 列表 / 节点 toggle carries icons.+ Row {+ id: segContentanchors.centerIn: parent- text: modelData.label- color: seg.current === modelData.id ? Theme.t1 : Theme.t2- Behavior on color { ColorAnimation { duration: Theme.d(200) } }- font.family: Theme.fontUi- font.pixelSize: Theme.fsBody- font.weight: Font.Medium+ spacing: 6+ VIcon {+ visible: (modelData.icon || "").length > 0+ anchors.verticalCenter: parent.verticalCenter+ name: modelData.icon || ""+ size: 13+ color: segLabel.color+ }+ Text {+ id: segLabel+ anchors.verticalCenter: parent.verticalCenter+ text: modelData.label+ color: seg.current === modelData.id ? Theme.t1 : Theme.t2+ Behavior on color { ColorAnimation { duration: Theme.d(200) } }+ font.family: Theme.fontUi+ font.pixelSize: Theme.fsBody+ font.weight: Font.Medium+ }}HoverHandler { cursorShape: Qt.PointingHandCursor }- TapHandler { onTapped: seg.picked(modelData.id) }+ TapHandler { gesturePolicy: TapHandler.WithinBounds; onTapped: seg.picked(modelData.id) }}}}diff --git a/qml/Veyra/VSelect.qml b/qml/Veyra/VSelect.qmlindex 8b29b428..14831df6 100644--- a/qml/Veyra/VSelect.qml+++ b/qml/Veyra/VSelect.qml@@ -16,7 +16,7 @@ Rectangle {border.width: 1border.color: Theme.strokeHoverHandler { id: hover; cursorShape: Qt.PointingHandCursor }- TapHandler { onTapped: menu.openAt(sel, "down") }+ TapHandler { gesturePolicy: TapHandler.WithinBounds; onTapped: menu.openAt(sel, "down") }RowLayout {anchors.fill: parentdiff --git a/qml/Veyra/VSlider.qml b/qml/Veyra/VSlider.qmlindex 4c2ce66e..cfccea88 100644--- a/qml/Veyra/VSlider.qml+++ b/qml/Veyra/VSlider.qml@@ -8,29 +8,56 @@ Item {property real from: 0property real to: 1property bool center: false // fill from the middle instead of the left+ property bool showCenterFill: false // Colour controls opt in; other pages keep their visuals.property bool enabledControl: true+ // A containing parameter widget can opt in without changing non-parameter sliders.+ property bool resettable: parent && typeof parent.sliderResetEnabled !== "undefined" && parent.sliderResetEnabled+ property real defaultValue: 0+ // Model-owned parameters must never lose their value binding on user input.+ // Standalone sliders retain their existing locally owned value behavior.+ property bool valueFromModel: parent && typeof parent.sliderValueFromModel !== "undefined" && parent.sliderValueFromModel+ property real dragValue: 0+ property Gradient trackGradient: null // Opt-in; existing effect sliders keep their track.signal moved(real value)+ // Live: the owner hears the value while the knob is dragged (every 40 ms)+ // and once more on release, instead of only on release.+ property bool live: true+ // True while the knob is held (tests read it; the owner may too).+ readonly property bool dragging: drag.active+ Timer {+ id: liveTimer+ interval: 40+ onTriggered: if (drag.active) slider.moved(slider.valueFromModel ? slider.dragValue : slider.value)+ }+ function commitValue(amount) {+ if (!valueFromModel) value = amount+ moved(amount)+ }implicitHeight: 20implicitWidth: 160- readonly property real frac: (to > from) ? Math.max(0, Math.min(1, (value - from) / (to - from))) : 0+ readonly property real displayedValue: valueFromModel && drag.active ? dragValue : value+ readonly property real frac: (to > from) ? Math.max(0, Math.min(1, (displayedValue - from) / (to - from))) : 0+ readonly property real trackWidth: track.widthRectangle {id: trackanchors.verticalCenter: parent.verticalCenter- width: parent.width+ width: Math.max(1, parent.width - (slider.resettable ? 28 : 0))height: 4radius: 9color: Qt.rgba(1, 1, 1, 0.12)+ gradient: slider.trackGradient}Rectangle {+ objectName: "vslider-fill"anchors.verticalCenter: track.verticalCenterheight: 4radius: 9color: Theme.accent- visible: !slider.center- width: track.width * slider.frac- x: 0+ visible: (!slider.center || slider.showCenterFill) && !slider.trackGradient+ width: track.width * (slider.center ? Math.abs(slider.frac - 0.5) : slider.frac)+ x: slider.center ? track.width * Math.min(0.5, slider.frac) : 0}Rectangle {id: knob@@ -53,6 +80,10 @@ Item {autoPaddingEnabled: true}}+ Item {+ id: trackInput+ width: track.width+ height: parent.heightHoverHandler { id: hover; cursorShape: Qt.PointingHandCursor; enabled: slider.enabledControl }DragHandler {id: drag@@ -63,16 +94,46 @@ Item {property real startX: 0onActiveTranslationChanged: {const x = Math.max(0, Math.min(track.width, startX + activeTranslation.x))- slider.value = slider.from + (x / track.width) * (slider.to - slider.from)+ slider.dragValue = slider.from + (x / track.width) * (slider.to - slider.from)+ if (!slider.valueFromModel) slider.value = slider.dragValue+ if (slider.live && !liveTimer.running) liveTimer.start()+ }+ onActiveChanged: {+ if (active) {+ slider.dragValue = slider.value+ startX = track.width * slider.frac+ } else { liveTimer.stop(); slider.commitValue(slider.valueFromModel ? slider.dragValue : slider.value) }}- onActiveChanged: { if (active) startX = track.width * slider.frac; else slider.moved(slider.value) }}TapHandler {enabled: slider.enabledControl+ // Node cards may overlap: consume track clicks rather than also+ // activating an inspector button on a card underneath this slider.+ gesturePolicy: TapHandler.WithinBoundsonTapped: point => {const x = Math.max(0, Math.min(track.width, point.position.x))- slider.value = slider.from + (x / track.width) * (slider.to - slider.from)- slider.moved(slider.value)+ slider.commitValue(slider.from + (x / track.width) * (slider.to - slider.from))+ }+ }+ }+ ToolButton {+ objectName: "vslider-reset"+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ width: 22; height: 20; padding: 0+ visible: slider.resettable+ enabled: slider.enabledControl && Math.abs(slider.value - slider.defaultValue) > 0.000001+ text: "↺"+ Accessible.name: qsTr("重置此参数")+ ToolTip.visible: hovered+ ToolTip.text: qsTr("还原默认值:%1").arg(slider.defaultValue)+ contentItem: Text {+ text: parent.text; color: parent.enabled ? Theme.t2 : Theme.t3+ font.pixelSize: 16; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter+ }+ background: Rectangle { radius: 4; color: parent.hovered ? Qt.rgba(1,1,1,0.08) : "transparent" }+ onClicked: {+ slider.commitValue(slider.defaultValue)}}}diff --git a/qml/Veyra/VSpinner.qml b/qml/Veyra/VSpinner.qmlnew file mode 100644index 00000000..b1d4fe9d--- /dev/null+++ b/qml/Veyra/VSpinner.qml@@ -0,0 +1,31 @@+// .spin (pages.css): a 14px ring, 2px, the top quarter bright, turning once+// every .8s linear (M38). Runs only while visible; reduced motion keeps the+// ring still, since a busy state is already said by the text beside it.+import QtQuick++Item {+ id: spin+ property int size: 14+ property color color: "#FFFFFF"+ implicitWidth: size+ implicitHeight: size+ Canvas {+ id: ring+ anchors.fill: parent+ onPaint: {+ const g = getContext("2d"); g.reset()+ const r = width / 2 - 1.5+ g.lineWidth = 2+ g.strokeStyle = Qt.rgba(1, 1, 1, 0.2)+ g.beginPath(); g.arc(width / 2, height / 2, r, 0, Math.PI * 2); g.stroke()+ g.strokeStyle = spin.color+ g.beginPath(); g.arc(width / 2, height / 2, r, -Math.PI / 2, 0); g.stroke()+ }+ RotationAnimation on rotation {+ from: 0; to: 360+ duration: 800+ loops: Animation.Infinite+ running: spin.visible && !Theme.reduced+ }+ }+}diff --git a/qml/Veyra/VSubGroup.qml b/qml/Veyra/VSubGroup.qmlindex df31d81d..61fd259a 100644--- a/qml/Veyra/VSubGroup.qml+++ b/qml/Veyra/VSubGroup.qml@@ -58,7 +58,7 @@ Rectangle {}}HoverHandler { cursorShape: Qt.PointingHandCursor }- TapHandler { onTapped: sub.expanded = !sub.expanded }+ TapHandler { gesturePolicy: TapHandler.WithinBounds; onTapped: sub.expanded = !sub.expanded }}ColumnLayout {diff --git a/qml/Veyra/VSwitch.qml b/qml/Veyra/VSwitch.qmlindex a5cd161f..716e6c4b 100644--- a/qml/Veyra/VSwitch.qml+++ b/qml/Veyra/VSwitch.qml@@ -23,5 +23,5 @@ Rectangle {Behavior on width { NumberAnimation { duration: Theme.d(200) } }}HoverHandler { cursorShape: Qt.PointingHandCursor }- TapHandler { id: tap; onTapped: { sw.checked = !sw.checked; sw.toggled(sw.checked) } }+ TapHandler { id: tap; gesturePolicy: TapHandler.WithinBounds; onTapped: { sw.checked = !sw.checked; sw.toggled(sw.checked) } }}diff --git a/qml/Veyra/backdrop-strong.png b/qml/Veyra/backdrop-strong.pngnew file mode 100644index 00000000..cbe1d443Binary files /dev/null and b/qml/Veyra/backdrop-strong.png differdiff --git a/qml/Veyra/qmldir b/qml/Veyra/qmldirindex 542b7e44..d6de6625 100644--- a/qml/Veyra/qmldir+++ b/qml/Veyra/qmldir@@ -26,3 +26,12 @@ VPage 1.0 VPage.qmlVRise 1.0 VRise.qmlCineBar 1.0 CineBar.qmlFullscreenBar 1.0 FullscreenBar.qml+ColourCurve 1.0 ColourCurve.qml+ColourWheel 1.0 ColourWheel.qml+ColourMixer 1.0 ColourMixer.qml+ColourPanel 1.0 ColourPanel.qml+VScrollBar 1.0 VScrollBar.qml+VConfirm 1.0 VConfirm.qml+NrLayerEditor 1.0 NrLayerEditor.qml+VSpinner 1.0 VSpinner.qml+VEqBars 1.0 VEqBars.qmldiff --git a/scripts/acceptance/capture-format-matrix.ps1 b/scripts/acceptance/capture-format-matrix.ps1index 123b2b6f..6e90f338 100644--- a/scripts/acceptance/capture-format-matrix.ps1+++ b/scripts/acceptance/capture-format-matrix.ps1@@ -6,18 +6,23 @@param([Parameter(Mandatory = $true)][string]$Root,[string]$BuildDirectory,+ [Parameter(Mandatory = $true)][string]$PlayerExe,+ [Parameter(Mandatory = $true)][ValidateSet('legacy')][string]$UiTarget,[int]$Device = 0,[int]$CaseSeconds = 10,- [string]$OutputDirectory,+ [string]$OutputDirectory = 'E:\项目\Veyra\logs\ui-qml-migration-20260925\capture-matrix',[int[]]$Only = @())$ErrorActionPreference = 'Stop'$root = (Resolve-Path -LiteralPath $Root).Path-$bin = Join-Path $root 'out/build/x64-release'-if ($BuildDirectory) { $bin = (Resolve-Path -LiteralPath $BuildDirectory).Path }-$player = Join-Path $bin 'veyra.exe'+$player = (Resolve-Path -LiteralPath $PlayerExe).Path+$bin = if ($BuildDirectory) { (Resolve-Path -LiteralPath $BuildDirectory).Path } else { Split-Path -Parent $player }$lister = Join-Path $bin 'veyra_capture_tests.exe'-$out = if ($OutputDirectory) { [IO.Path]::GetFullPath($OutputDirectory) } else { Join-Path $root ('logs/capture-matrix/' + [Guid]::NewGuid().ToString('N')) }+$out = [IO.Path]::GetFullPath($OutputDirectory)+[IO.Directory]::CreateDirectory($out) | Out-Null+$entryScript = Join-Path $PSScriptRoot 'resolve-ui-migration-entry.ps1'+$null = & $entryScript -Root $root -UiTarget $UiTarget -PlayerExe $player -BuildDirectory $BuildDirectory -StagingDirectory (Split-Path -Parent $player) -ArtifactDirectory $out -OutputFile (Join-Path $out 'entry.json')+if ($UiTarget -ne 'legacy') { throw 'capture-format-matrix.ps1 is legacy-only; QML uses the separate qml-ui-smoke contract.' }[IO.Directory]::CreateDirectory($out) | Out-Null$formats = [Collections.Generic.List[object]]::new()diff --git a/scripts/acceptance/capture-paths-smoke.ps1 b/scripts/acceptance/capture-paths-smoke.ps1index ea118d42..77856616 100644--- a/scripts/acceptance/capture-paths-smoke.ps1+++ b/scripts/acceptance/capture-paths-smoke.ps1@@ -9,21 +9,25 @@# floor below is the decisive check.param([Parameter(Mandatory = $true)][string]$Root,- [string]$BuildDirectory,+ [Parameter(Mandatory = $true)][string]$BuildDirectory,+ [Parameter(Mandatory = $true)][string]$PlayerExe,+ [Parameter(Mandatory = $true)][ValidateSet('legacy')][string]$UiTarget,[int]$CaseSeconds = 12,[int]$Device = 0,- [string]$OutputDirectory+ [string]$OutputDirectory = 'E:\项目\Veyra\logs\ui-qml-migration-20260925\capture-paths')$ErrorActionPreference = 'Stop'$root = (Resolve-Path -LiteralPath $Root).Path-$bin = Join-Path $root 'out/build/x64-release'-if ($BuildDirectory) { $bin = (Resolve-Path -LiteralPath $BuildDirectory).Path }-$player = Join-Path $bin 'veyra.exe'+$player = (Resolve-Path -LiteralPath $PlayerExe).Path+$bin = if ($BuildDirectory) { (Resolve-Path -LiteralPath $BuildDirectory).Path } else { Split-Path -Parent $player }$lister = Join-Path $bin 'veyra_capture_tests.exe'if (-not (Test-Path -LiteralPath $player)) { throw "missing $player" }if (-not (Test-Path -LiteralPath $lister)) { throw "missing $lister" }-$out = if ($OutputDirectory) { [IO.Path]::GetFullPath($OutputDirectory) } else { Join-Path $root ('logs/capture-paths/' + [Guid]::NewGuid().ToString('N')) }+$out = [IO.Path]::GetFullPath($OutputDirectory)[IO.Directory]::CreateDirectory($out) | Out-Null+$entryScript = Join-Path $PSScriptRoot 'resolve-ui-migration-entry.ps1'+$null = & $entryScript -Root $root -UiTarget $UiTarget -PlayerExe $player -BuildDirectory $BuildDirectory -StagingDirectory (Split-Path -Parent $player) -ArtifactDirectory $out -OutputFile (Join-Path $out 'entry.json')+if ($UiTarget -ne 'legacy') { throw 'capture-paths-smoke.ps1 is legacy-only; QML uses the separate qml-ui-smoke contract.' }$listing = & $lister --list 2>$null$native = $nulldiff --git a/scripts/acceptance/fg-fsr-xess-control.py b/scripts/acceptance/fg-fsr-xess-control.pynew file mode 100644index 00000000..9cf8785b--- /dev/null+++ b/scripts/acceptance/fg-fsr-xess-control.py@@ -0,0 +1,161 @@+"""Bounded local FG acceptance; all generated files stay under the E: artifact root.++Guard compares the complete checkout with the immutable pre-task hashes. The+allowlist permits changes, it does not replace those hashes or claim acceptance.+"""+import argparse+import hashlib+import json+import os+from pathlib import Path+import subprocess+import sys+import time++BASE = Path("E:/项目/Veyra")+TAG = "fg-fsr-xess-20260930"+ROOT = BASE / "worktrees/p0-p1-r53-20260927"+BASELINE = BASE / "archives/fg-fsr-xess-20260930-start/scope-baseline-d.json"+BASELINE_SHA = "dd0791c996344ea9f0cf8f516e84b5086dd8810eedbf36c7b400a1707dc90bfc"+++def guard():+ raw = BASELINE.read_bytes()+ if hashlib.sha256(raw).hexdigest() != BASELINE_SHA:+ raise RuntimeError("immutable scope baseline hash changed")+ baseline = json.loads(raw)+ if Path(baseline["root"]) != ROOT:+ raise RuntimeError("scope baseline checkout mismatch")+ names = subprocess.check_output(+ ["git", "ls-files", "-c", "-o", "--exclude-standard", "-z"], cwd=ROOT+ ).decode("utf-8").split("\0")+ allow, hashes = set(baseline["allow"]), baseline["hashes"]+ outside = []+ for name in filter(None, names):+ if name not in allow:+ path = ROOT / name+ if not path.is_file() or hashlib.sha256(path.read_bytes()).hexdigest() != hashes.get(name):+ outside.append(name)+ outside += [name for name in hashes if name not in allow and not (ROOT / name).is_file()]+ head = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip()+ branch = subprocess.check_output(["git", "branch", "--show-current"], cwd=ROOT, text=True).strip()+ if head != baseline["head"] or branch != "codex/fg-fsr-xess-20260930":+ outside.append("Git baseline/branch changed")+ print("SCOPE", "FAIL" if outside else "PASS", "files", len(names) - 1, outside, flush=True)+ return not outside+++def run_cases(group, app, out):+ env = os.environ.copy()+ env["TEMP"] = env["TMP"] = str(BASE / "tmp" / TAG)+ env["PATH"] = str(app) + os.pathsep + env.get("PATH", "")+ env["QML2_IMPORT_PATH"] = str(app / "qml")+ if group == "unit":+ cases = [("repair-contract", "veyra_repair_contract_tests", []),+ ("repair-presets", "veyra_repair_preset_tests", [str(out / "repair-presets.v1")]),+ ("effect-chain", "veyra_effect_chain_tests", []),+ ("preset-library", "veyra_preset_library_tests", [])]+ elif group == "qml":+ cases = [("qml-data", "veyra_qml_data_tests", [str(out / "qml-data-scratch")]),+ ("qml-easing", "veyra_qml_easing_tests", ["-platform", "offscreen"]),+ ("qml-quick", "veyra_qml_quick_tests", ["-platform", "offscreen", "-input", str(app / "qml-tests")])]+ else:+ cases = [("fsr-independent-nvidia", "veyra_fsr_dispatch_tests", []),+ ("fsr-independent-amd", "veyra_fsr_dispatch_tests", ["amd"]),+ ("fsr-switch-nvidia", "veyra_fsr_switch_tests", [str(out / "switch-nvidia")]),+ ("fsr-switch-amd", "veyra_fsr_switch_tests", [str(out / "switch-amd"), "amd"]),+ ("dlss-presentation", "veyra_fg_presentation_tests", [str(out / "dlss"), str(app / "runtime/experimental")])]+ results = []+ for name, binary, args in cases:+ log = out / (name + ".log")+ command = [str(app / (binary + ".exe")), *args]+ started = time.monotonic()+ with log.open("w", encoding="utf-8") as stream:+ try:+ code = subprocess.run(command, cwd=app, env=env, stdout=stream,+ stderr=subprocess.STDOUT, timeout=300).returncode+ except subprocess.TimeoutExpired:+ code = 124+ lines = log.read_text(encoding="utf-8", errors="replace").splitlines()+ last = lines[-1] if lines else ""+ result = dict(test=name, command=command, exit=code,+ seconds=round(time.monotonic() - started, 2), log=str(log), last=last)+ results.append(result)+ print(name, "exit", code, "seconds", result["seconds"], last[:180], flush=True)+ (out / "summary.json").write_text(json.dumps(results, ensure_ascii=False, indent=2), encoding="utf-8")+ return all(item["exit"] == 0 for item in results)+++def run_ui(app, out):+ profile=BASE / "tests" / TAG / ("ui-data-"+out.name)+ if profile.exists():+ raise RuntimeError("UI profile already exists; use a fresh run id")+ main=app / "qml/Veyra/Main.qml"+ original=main.read_bytes()+ source=original.decode("utf-8-sig")+ snippet=(ROOT / "scripts/acceptance/fg-fsr-xess.qml").read_text(encoding="utf-8")+ closing=source.rfind("}")+ if closing<0:+ raise RuntimeError("staged Main.qml has no root closing brace")+ env=os.environ.copy()+ env["TEMP"]=env["TMP"]=str(BASE / "tmp" / TAG)+ env["QML_DISABLE_DISK_CACHE"]="1"+ env["QML2_IMPORT_PATH"]=str(app / "qml")+ results=[]+ try:+ main.write_text(source[:closing]+snippet+source[closing:],encoding="utf-8")+ for phase in ("live","restore"):+ log=out / (phase+".log")+ env["VEYRA_LOG_FILE"]=str(log)+ command=[str(app / "veyra_qml_ui.exe"),"--data-dir",str(profile),"--exit-after","180000"]+ if phase=="restore":+ command.append("--fg-restore")+ started=time.monotonic()+ with (out / (phase+".stdio.log")).open("w",encoding="utf-8") as stream:+ process=subprocess.Popen(command,cwd=app,env=env,stdout=stream,stderr=subprocess.STDOUT)+ print("UI",phase,"pid",process.pid,flush=True)+ try:+ code=process.wait(timeout=210)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=10)+ code=124+ lines=log.read_text(encoding="utf-8",errors="replace").splitlines() if log.exists() else []+ sentinel="FG_UI_RESTORE_PASS" if phase=="restore" else "FG_UI_PASS"+ passed=code==0 and any(sentinel in line for line in lines) and not any("FG_UI_FAIL" in line for line in lines)+ result=dict(phase=phase,command=command,pid=process.pid,exit=code,+ seconds=round(time.monotonic()-started,2),passed=passed,log=str(log))+ results.append(result)+ print(result,flush=True)+ print("\n".join(line for line in lines if "FG_UI_" in line),flush=True)+ (out / "summary.json").write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding="utf-8")+ if not passed:+ break+ finally:+ main.write_bytes(original)+ return len(results)==2 and all(result["passed"] for result in results)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("group", choices=["guard", "unit", "qml", "gpu", "ui"])+ parser.add_argument("--app", type=Path, default=BASE / "tests" / TAG / "candidate")+ parser.add_argument("--out", type=Path)+ args = parser.parse_args()+ if not guard():+ return 3+ if args.group == "guard":+ return 0+ out = args.out or BASE / "logs" / TAG / args.group+ for path in (args.app, out):+ if not path.resolve().is_relative_to(BASE.resolve()):+ raise RuntimeError("acceptance paths must stay under E:/项目/Veyra")+ if out.exists() and any(out.iterdir()):+ raise RuntimeError("use a new output directory; prior test evidence is immutable")+ out.mkdir(parents=True, exist_ok=True)+ accepted=run_ui(args.app.resolve(),out) if args.group=="ui" else run_cases(args.group,args.app.resolve(),out)+ return 0 if accepted else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/acceptance/fg-fsr-xess.qml b/scripts/acceptance/fg-fsr-xess.qmlnew file mode 100644index 00000000..6e2e7b64--- /dev/null+++ b/scripts/acceptance/fg-fsr-xess.qml@@ -0,0 +1,133 @@+ // Inject only into a disposable staged Main.qml, never the product source.+ Timer {+ interval: 250; running: true; repeat: true+ property int step: 0+ property int ticks: 0+ property int total: 0+ property int current: 0+ property double beforePosition: 0+ property bool restore: Qt.application.arguments.indexOf("--fg-restore") >= 0+ property var cases: [+ {backend:"fsr3", multiplier:2}, {backend:"xess", multiplier:4},+ {backend:"xess", multiplier:2}, {backend:"xess", multiplier:3},+ {backend:"xess", multiplier:4}, {backend:"dlss", multiplier:4},+ {backend:"fsr3", multiplier:2}+ ]+ function check(value, label) { if (!value) throw new Error(label) }+ function next(value) { step = value; ticks = 0 }+ function preset(name) {+ for (var i=0;i<veyra.presets.length;++i)+ if (veyra.presets[i].name === name) return i+ return -1+ }+ function startCase() {+ var c=cases[current]+ beforePosition=veyra.position+ veyra.fgBackendName=c.backend+ veyra.fgEnabled=true+ veyra.fgMultiplier=c.multiplier+ next(2)+ }+ onTriggered: { try {+ ++ticks; ++total+ if (total>680) throw new Error("bounded step="+step+" ticks="+ticks)+ if (step===0) {+ if (ticks<8) return+ check(veyra.fgBackendChoices.length===4, "four independent backend choices")+ if (restore) {+ check(veyra.nodeMode===0 && veyra.fgBackendName==="fsr3", "list session restored")+ check(preset("FG List FSR31")>=0 && preset("FG Node FSR31")>=0 && preset("FG Node FSR4")>=0, "preset library restored")+ veyra.nodeMode=1+ check(veyra.applyPresetIndex(preset("FG Node FSR4")), "FSR4 node preset applies")+ check(veyra.fgBackendName==="fsr4" && veyra.fgMaxMultiplier===2, "FSR4 restored without DLSS label")+ check(veyra.applyPresetIndex(preset("FG Node FSR31")), "FSR3 node preset applies")+ check(veyra.fgBackendName==="fsr3", "independent FSR3 restored")+ veyra.nodeMode=0+ check(veyra.fgBackendName==="fsr3", "list configuration survives node choices")+ console.log("FG_UI_RESTORE_PASS"); Qt.quit(); return+ }+ veyra.muted=true; veyra.nrEnabled=false; veyra.srEnabled=false+ root.page="pro"+ veyra.openPath("E:/项目/Veyra/tests/nr-fg-opt-20260929/media/gta6-4k30-silent-180s.mp4")+ next(1); return+ }+ if (step===1) {+ if (!veyra.running || !veyra.hasSource || veyra.applying) return+ startCase(); return+ }+ if (step===2) {+ if (ticks<20 || veyra.applying) return+ var c=cases[current]+ check(veyra.running && veyra.fgActive, "FG inactive "+c.backend+" "+veyra.statusText)+ check(veyra.fgBackendName===c.backend && veyra.fgMultiplier===c.multiplier, "backend/multiplier not applied")+ check(veyra.position>beforePosition+0.5, "source position stopped "+c.backend)+ if (c.backend==="fsr3") {+ check(veyra.fgProviderText.indexOf("3.1.")>=0, "actual FSR3 provider absent")+ check(veyra.runStatusDetail.indexOf("FSR 3.1")>=0 && veyra.runStatusDetail.indexOf("DLSS")<0, "FSR status mislabeled")+ check(veyra.fgMultiplierChoices.length===1 && veyra.fgMaxMultiplier===2, "FSR2X ceiling")+ var old=veyra.fgMultiplier+ veyra.fgMultiplier=4+ check(veyra.fgMultiplier===old, "illegal FSR4X mutated settings")+ }+ if (c.backend==="xess") check(veyra.fgMaxMultiplier===4 && veyra.fgMultiplierChoices.length===3, "XeSS 4X option disappeared")+ console.log("FG_UI_CASE backend="+c.backend+" multiplier="+c.multiplier+" fps="+veyra.submitFps.toFixed(1)+" position="+veyra.position.toFixed(2)+" provider="+veyra.fgProviderText)+ ++current+ if (current<cases.length) { startCase(); return }+ check(veyra.savePresetAs("FG List FSR31",15,false), "save list FSR3 preset")+ beforePosition=veyra.position; veyra.fgBackendName="fsr4"+ next(3); return+ }+ if (step===3) {+ if (ticks<20 || veyra.applying) return+ check(veyra.running && veyra.fgActive && veyra.fgBackendName==="fsr3", "unsupported FSR4 did not restore FSR3 backend="+veyra.fgBackendName+" active="+veyra.fgActive+" running="+veyra.running)+ check(veyra.backendWarning.indexOf("FSR 4")>=0, "FSR4 failure not explained")+ check(veyra.position>beforePosition+0.5, "FSR4 rejection stopped playback")+ console.log("FG_UI_FSR4_ROLLBACK warning="+veyra.backendWarning)+ veyra.togglePlayPause(); next(4); return+ }+ if (step===4) {+ if (!veyra.paused) return+ veyra.seekTo(40); root.width=1160; root.height=740+ next(5); return+ }+ if (step===5) {+ if (ticks<12) return+ check(veyra.paused && veyra.position>=39, "paused seek not complete")+ veyra.togglePlayPause(); next(6); return+ }+ if (step===6) {+ if (ticks<16 || veyra.applying) return+ check(veyra.running && !veyra.paused && veyra.fgActive && veyra.position>40.5, "pause/seek/resize/resume failed")+ veyra.nodeMode=1; root.page="node"+ next(7); return+ }+ if (step===7) {+ if (ticks<12 || veyra.applying) return+ check(veyra.effectCatalog.some(function(o){return o.id==="fsr3-fg"}) &&+ veyra.effectCatalog.some(function(o){return o.id==="fsr4-fg"}), "FSR node add menu absent")+ check(veyra.addEffect("fsr3-fg")>=0, "add FSR3 node failed")+ next(8); return+ }+ if (step===8) {+ if (ticks<20 || veyra.applying) return+ check(veyra.fgActive && veyra.fgBackendName==="fsr3" && veyra.chainValid, "node FSR3 not active")+ check(veyra.chain.some(function(o){return o.type==="frame-generation" && o.label.indexOf("FSR 3.1")>=0}), "node mislabeled")+ check(veyra.savePresetAs("FG Node FSR31",15,true), "save node FSR3 preset")+ veyra.stopPlayback(); next(9); return+ }+ if (step===9) {+ if (ticks<16 || veyra.hasSource) return+ veyra.fgBackendName="fsr4"+ check(veyra.fgBackendName==="fsr4", "idle FSR4 selection failed")+ check(veyra.savePresetAs("FG Node FSR4",15,true), "save FSR4 node preset failed")+ check(veyra.applyPresetIndex(preset("FG Node FSR31")), "restore FSR3 node preset")+ veyra.nodeMode=0; root.page="pro"+ check(veyra.fgBackendName==="fsr3", "list state was overwritten by node FSR4")+ next(10); return+ }+ if (step===10) {+ if (ticks<8) return+ console.log("FG_UI_PASS"); Qt.quit()+ }+ } catch(e) { console.warn("FG_UI_FAIL "+e.message); Qt.quit() } }+ }diff --git a/scripts/acceptance/field-issues-control.py b/scripts/acceptance/field-issues-control.pynew file mode 100644index 00000000..7a119ccf--- /dev/null+++ b/scripts/acceptance/field-issues-control.py@@ -0,0 +1,43 @@+"""Read-only scope guard for the 2026-09-30 field fixes."""+import hashlib+import json+from pathlib import Path+import subprocess+import sys+ROOT = Path('E:/项目/Veyra/worktrees/p0-p1-r53-20260927')+ARCHIVE = Path('E:/项目/Veyra/archives/field-issues-20260930-start')+BASELINE_SHA = '9914a06b381fb6d5b90247d4169065b0c9503f84c48dd2272f571b771a18d354'+def guard():+ raw = (ARCHIVE / 'scope-baseline.json').read_bytes()+ if hashlib.sha256(raw).hexdigest() != BASELINE_SHA:+ raise RuntimeError('immutable field baseline changed')+ baseline = json.loads(raw)+ allow = set(baseline['allow'])+ # New batches list additional paths separately, never replacing start hashes.+ for amendment in sorted(ARCHIVE.glob('scope-amendment-*.json')):+ data = json.loads(amendment.read_text(encoding='utf-8-sig'))+ if data['baseline_sha256'] != BASELINE_SHA:+ raise RuntimeError('scope amendment has wrong parent')+ allow.update(data['allow'])+ # Windows checkout paths are case insensitive; git may report the existing+ # directory spelling (licenses) instead of a notice's spelling (LICENSES).+ allowed_paths = {name.casefold() for name in allow}+ names = set(filter(None, subprocess.check_output(['git', 'ls-files', '-c', '-o', '--exclude-standard', '-z'], cwd=ROOT).decode('utf8').split('\0')))+ problems = []+ for name in names | set(baseline['hashes']):+ if name.casefold() in allowed_paths:+ continue+ path = ROOT / name+ actual = hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None+ if actual != baseline['hashes'].get(name):+ problems.append(name)+ for ref in ('HEAD', 'main'):+ actual = subprocess.check_output(['git', 'rev-parse', ref], cwd=ROOT, text=True).strip()+ if actual != baseline[ref.lower()]:+ problems.append('Git ' + ref)+ if subprocess.check_output(['git', 'branch', '--show-current'], cwd=ROOT, text=True).strip() != baseline['branch']:+ problems.append('Git branch')+ print('FIELD_SCOPE', 'FAIL' if problems else 'PASS', 'files', len(names), problems)+ return not problems+if __name__ == '__main__':+ sys.exit(0 if guard() else 3)diff --git a/scripts/acceptance/field-issues-display.qml b/scripts/acceptance/field-issues-display.qmlnew file mode 100644index 00000000..bbdf0d3f--- /dev/null+++ b/scripts/acceptance/field-issues-display.qml@@ -0,0 +1,48 @@+ Timer {+ interval: 250; running: true; repeat: true+ property int step: 0+ property int ticks: 0+ property int total: 0+ property double positionBefore: 0+ function check(value,label) { if(!value)throw new Error(label) }+ function next(n,label) { step=n;ticks=0;positionBefore=veyra.position;veyra.logUi("display-test",label) }+ onTriggered: { try {+ ++ticks;++total;if(total>280)throw new Error("bounded step="+step)+ if(step===0) {+ if(ticks<8)return+ root.page="pro";veyra.muted=true+ veyra.nrEnabled=false;veyra.srEnabled=false;veyra.fgEnabled=false+ veyra.videoHdr=false;veyra.colorEnabled=false;veyra.outputRateMode=0+ check(veyra.displaySync===2,"fresh default Automatic")+ veyra.openPath("E:/项目/Veyra/tests/nr-sfv2-lecram-20260930/media/gta6-native-4k30-silent-90s.mp4")+ next(1,"DISPLAY_WINDOW_AUTO_BEGIN");return+ }+ if(ticks<24||veyra.applying||!veyra.running)return+ check(!veyra.nrActive&&!veyra.srActive&&!veyra.fgActive,"all effects remain inactive")+ check(veyra.position>positionBefore+0.5,"playback advances")+ if(step===1) {+ check(!root.fullscreen&&veyra.presentationStatus.indexOf("低延迟队列已关闭")>=0,"queue disabled")+ root.toggleFullscreen();next(2,"DISPLAY_FULLSCREEN_AUTO_BEGIN");return+ }+ if(step===2) {+ check(root.fullscreen&&veyra.presentationStatus.indexOf("防撕裂")>=0,"Automatic fullscreen: no vsync, no tearing")+ veyra.displaySync=0;next(3,"DISPLAY_FULLSCREEN_TEARING_BEGIN");return+ }+ if(step===3) {+ check(root.fullscreen&&veyra.presentationStatus.indexOf("允许撕裂")>=0,"explicit tearing preserved")+ veyra.displaySync=1;next(4,"DISPLAY_FULLSCREEN_VSYNC_BEGIN");return+ }+ if(step===4) {+ check(root.fullscreen&&veyra.presentationStatus.indexOf("垂直同步")>=0,"explicit VSync with queue disabled")+ root.toggleFullscreen();next(5,"DISPLAY_WINDOW_VSYNC_BEGIN");return+ }+ if(step===5) {+ check(!root.fullscreen&&veyra.presentationStatus.indexOf("垂直同步")>=0,"window VSync preserved")+ veyra.displaySync=2;next(6,"DISPLAY_WINDOW_AUTO_RETURN_BEGIN");return+ }+ if(step===6) {+ check(!root.fullscreen&&veyra.presentationStatus.indexOf("防撕裂")>=0,"Automatic window restored")+ veyra.logUi("display-test","DISPLAY_UI_PASS");Qt.quit()+ }+ } catch(e) {veyra.logUi("display-test","DISPLAY_UI_FAIL "+e.message);Qt.quit()} }+ }diff --git a/scripts/acceptance/field-issues-export.qml b/scripts/acceptance/field-issues-export.qmlnew file mode 100644index 00000000..644b4f42--- /dev/null+++ b/scripts/acceptance/field-issues-export.qml@@ -0,0 +1,33 @@+ Timer {+ interval: 500; running: true; repeat: true+ property int step: 0+ property int ticks: 0+ property int total: 0+ onTriggered: { try {+ ++ticks;++total;if(total>480)throw new Error("bounded export step="+step)+ if(step===0) {+ if(ticks<4)return+ root.page="pro";veyra.muted=true;veyra.nrEnabled=false;veyra.srEnabled=false;veyra.fgEnabled=false+ veyra.openPath("E:/项目/Veyra/tests/nr-sfv2-lecram-20260930/media/gta6-native-4k30-silent-90s.mp4")+ step=1;ticks=0;return+ }+ if(step===1) {+ if(ticks<6||!veyra.running)return+ // Exclude the exact 4.000 endpoint: the export trim includes it.+ veyra.exportTrimStart=0;veyra.exportTrimEnd=3.98+ veyra.stopPlayback();step=2;ticks=0;return+ }+ if(step===2) {+ if(ticks<4||veyra.running)return+ veyra.nrEnabled=Qt.application.arguments.indexOf("--without-nr")<0+ veyra.srEnabled=true;veyra.srTargetIndex=3;veyra.exportSrTargetIndex=3;veyra.exportHevc=true+ veyra.exportRateControl=2;veyra.startExport();step=3;ticks=0;return+ }+ if(step===3) {+ if(ticks<4)return+ if(veyra.exportRunning)return+ if(veyra.exportEncoded!==120)throw new Error("encoded="+veyra.exportEncoded+" status="+veyra.exportStatus+" failures="+veyra.exportQueueFailure)+ running=false;veyra.logUi("export-repro","EXPORT_8K_120_PASS "+veyra.exportStatus);Qt.quit()+ }+ } catch(e) {running=false;veyra.cancelExport();veyra.logUi("export-repro","EXPORT_8K_FAIL "+e.message);Qt.quit()} }+ }diff --git a/scripts/acceptance/field-issues-nr-reject.qml b/scripts/acceptance/field-issues-nr-reject.qmlnew file mode 100644index 00000000..aff476bc--- /dev/null+++ b/scripts/acceptance/field-issues-nr-reject.qml@@ -0,0 +1,32 @@+ Timer {+ interval: 250; running: true; repeat: true+ property int step: 0+ property int ticks: 0+ property int total: 0+ property double positionBefore: 0+ function check(value,label) { if(!value)throw new Error(label) }+ onTriggered: { try {+ ++ticks;++total;if(total>240)throw new Error("bounded step="+step)+ if(step===0) {+ if(ticks<8)return+ root.page="pro";veyra.muted=true+ veyra.srEnabled=false;veyra.fgEnabled=false;veyra.nrEnabled=true+ check(veyra.nrLayers[0].runtime===0,"initial Lecram")+ veyra.openPath("E:/项目/Veyra/tests/nr-sfv2-lecram-20260930/media/gta6-native-4k30-silent-90s.mp4")+ step=1;ticks=0;return+ }+ if(step===1) {+ if(ticks<20||!veyra.running||veyra.applying)return+ check(veyra.nrActive,"Lecram active")+ positionBefore=veyra.position+ check(veyra.setNrLayerParameter(veyra.nrLayers[0].index,"runtime",2),"enqueue SF-v2 request")+ step=2;ticks=0;return+ }+ if(step===2) {+ if(ticks<24||veyra.applying)return+ check(veyra.running&&veyra.nrActive&&veyra.position>positionBefore+0.5,"working Lecram playback restored")+ check(veyra.nrLayers.every(n=>n.runtime===0),"selector restored to actual Lecram")+ veyra.logUi("nr-reject-test","NR_UI_REJECT_PASS");Qt.quit()+ }+ } catch(e) {veyra.logUi("nr-reject-test","NR_UI_REJECT_FAIL "+e.message);Qt.quit()} }+ }diff --git a/scripts/acceptance/field-issues-nr.qml b/scripts/acceptance/field-issues-nr.qmlnew file mode 100644index 00000000..2d236fad--- /dev/null+++ b/scripts/acceptance/field-issues-nr.qml@@ -0,0 +1,91 @@+ Timer {+ interval: 250; running: true; repeat: true+ property int step: 0+ property int ticks: 0+ property int total: 0+ property double beforePosition: 0+ property bool restore: Qt.application.arguments.indexOf("--nr-restore") >= 0+ function check(value,label) { if(!value) throw new Error(label) }+ function next(value) { step=value; ticks=0 }+ function preset(name) { for(var i=0;i<veyra.presets.length;++i)if(veyra.presets[i].name===name)return i;return -1 }+ function choose(id) {+ beforePosition=veyra.position+ check(veyra.setNrLayerParameter(veyra.nrLayers[0].index,"runtime",id),"select runtime "+id)+ check(veyra.nrLayers.every(n=>n.runtime===id),"whole chain runtime "+id)+ }+ onTriggered: { try {+ ++ticks;++total;if(total>520)throw new Error("bounded step="+step)+ if(step===0) {+ if(ticks<8)return+ if(restore) {+ check(veyra.nodeMode===0&&veyra.nrLayers.every(n=>n.runtime===2),"list SF-v2 restored")+ veyra.nodeMode=1+ check(veyra.nrLayers.every(n=>n.runtime===2),"node SF-v2 restored")+ check(veyra.applyPresetIndex(preset("NR Node Lecram")),"restore Lecram preset")+ check(veyra.nrLayers.every(n=>n.runtime===0),"manual Lecram preserved")+ console.log("NR_UI_RESTORE_PASS");Qt.quit();return+ }+ root.page="pro";veyra.muted=true;veyra.srEnabled=false;veyra.fgEnabled=false+ veyra.nrEnabled=true+ check(veyra.nrLayers[0].runtime===0,"5070 fresh Lecram default")+ veyra.openPath("E:/项目/Veyra/tests/nr-sfv2-lecram-20260930/media/gta6-native-4k30-silent-90s.mp4")+ next(1);return+ }+ if(step===1) {+ if(ticks<20||!veyra.running||veyra.applying)return+ check(veyra.nrActive,"Lecram NR active "+veyra.statusText)+ check(veyra.duplicateNrLayer(veyra.nrLayers[0].index)>=0,"second NR layer")+ choose(2);next(2);return+ }+ if(step===2) {+ if(ticks<20||veyra.applying)return+ check(veyra.running&&veyra.nrActive&&veyra.position>beforePosition+0.5,"SF-v2 playback")+ check(veyra.nrLayers.length===2&&veyra.nrLayers.every(n=>n.runtime===2),"two NRs SF-v2")+ console.log("NR_UI_SF_ACTIVE position="+veyra.position)+ check(veyra.savePresetAs("NR List SF-v2",15,false),"save list SF-v2")+ choose(0);next(3);return+ }+ if(step===3) {+ if(ticks<20||veyra.applying)return+ check(veyra.running&&veyra.nrActive&&veyra.position>beforePosition+0.5,"Lecram hot switch")+ check(!veyra.setNrLayerParameter(veyra.nrLayers[0].index,"runtime",1),"retired option rejected")+ veyra.togglePlayPause();next(4);return+ }+ if(step===4) {+ if(!veyra.paused)return+ veyra.seekTo(20);root.width=1140;root.height=720;next(5);return+ }+ if(step===5) {+ if(ticks<12)return+ veyra.togglePlayPause();next(6);return+ }+ if(step===6) {+ if(ticks<16||veyra.applying)return+ check(veyra.running&&!veyra.paused&&veyra.nrActive&&veyra.position>20.5,"NR pause seek resize resume")+ veyra.nodeMode=1;root.page="node";next(7);return+ }+ if(step===7) {+ if(ticks<10||veyra.applying)return+ check(veyra.addEffect("nr")>=0,"add NR node")+ choose(0);next(8);return+ }+ if(step===8) {+ if(ticks<16||veyra.applying)return+ check(veyra.nrActive&&veyra.chainValid,"node Lecram active")+ check(veyra.savePresetAs("NR Node Lecram",15,true),"save node Lecram")+ choose(2);next(9);return+ }+ if(step===9) {+ if(ticks<16||veyra.applying)return+ check(veyra.nrActive&&veyra.running&&veyra.position>beforePosition+0.5,"node SF-v2 active")+ veyra.nodeMode=0;root.page="pro"+ check(veyra.applyPresetIndex(preset("NR List SF-v2")),"list SF-v2 preset")+ next(10);return+ }+ if(step===10) {+ if(ticks<16||veyra.applying)return+ check(veyra.nrActive&&veyra.nrLayers.every(n=>n.runtime===2),"final list SF-v2")+ console.log("NR_UI_PASS");Qt.quit()+ }+ } catch(e) {console.warn("NR_UI_FAIL "+e.message);Qt.quit()} }+ }diff --git a/scripts/acceptance/field-issues-options.qml b/scripts/acceptance/field-issues-options.qmlnew file mode 100644index 00000000..23dd3cd9--- /dev/null+++ b/scripts/acceptance/field-issues-options.qml@@ -0,0 +1,80 @@+ Timer {+ interval: 250; running: true; repeat: true+ property int step: 0+ property int ticks: 0+ property int total: 0+ property bool restore: Qt.application.arguments.indexOf("--options-restore") >= 0+ function check(ok, label) { if(!ok) throw new Error(label) }+ function next(n) { step=n; ticks=0 }+ function preset(name) { for(var i=0;i<veyra.presets.length;++i)if(veyra.presets[i].name===name)return i;return -1 }+ onTriggered: { try {+ ++ticks;++total;if(total>650)throw new Error("bounded step="+step)+ if(step===0) {+ if(ticks<8)return+ if(restore) {+ check(veyra.hdrOutputMode===1&&veyra.srTargetIndex===5&&veyra.srMotionSource===0&&veyra.nrMotionSource===0&&veyra.fgMotionSource===0,"saved common choices restored")+ check(veyra.aspectMode===6,"saved preview ratio restored")+ veyra.nodeMode=1+ check(veyra.hdrOutputMode===1&&veyra.srTargetIndex===5&&veyra.nrMotionSource===0,"node session common choices")+ running=false;console.log("OPTIONS_UI_RESTORE_PASS");Qt.quit();return+ }+ root.page="pro";veyra.muted=true;veyra.nrEnabled=false;veyra.srEnabled=false;veyra.fgEnabled=false+ check(veyra.hdrOutputMode===0,"fresh HDR10 default")+ veyra.fgBackendName="xess";check(veyra.fgMotionSource===0,"XeSS fresh zero motion")+ veyra.fgBackendName="dlss";check(veyra.fgMotionSource===1,"DLSS preserves prior flow default")+ veyra.openPath("E:/项目/Veyra/tests/field-issues-20260930/media/gta6-1080p30-45s.mp4")+ next(1);return+ }+ if(ticks<16||veyra.applying||!veyra.running)return+ if(step>=1&&step<=7) {+ veyra.aspectMode=step-1+ check(veyra.aspectMode===step-1,"geometry selection")+ if(step===5)check(Math.abs(veyra.previewAspect-16/9)<.001,"forced 16:9")+ if(step===6)check(Math.abs(veyra.previewAspect-4/3)<.001,"forced 4:3")+ if(step===7)check(Math.abs(veyra.previewAspect-21/9)<.001,"forced 21:9")+ if(step<7){next(step+1);return}+ veyra.aspectMode=0;veyra.seekTo(0);veyra.srTargetIndex=2;veyra.srMotionSource=0;veyra.srEnabled=true;next(8);return+ }+ if(step===8) {+ check(veyra.srActive&&veyra.srMotionSource===0,"SR zero motion initializes")+ veyra.videoSrQuality=5;next(14);return+ }+ if(step===14) {+ check(veyra.srActive&&veyra.videoSrQuality===5&&veyra.srMotionSource===0,"FSR SR zero motion initializes")+ veyra.srMotionSource=1;next(15);return+ }+ if(step===15) {+ check(veyra.srActive&&veyra.srMotionSource===1,"FSR SR flow initializes")+ veyra.srMotionSource=0;next(16);return+ }+ if(step===16) {+ check(veyra.srActive&&veyra.srMotionSource===0,"FSR SR returns to zero")+ veyra.seekTo(0);veyra.videoSrQuality=0;veyra.nrMotionSource=0;veyra.nrEnabled=true;next(9);return+ }+ if(step===9) {+ check(veyra.nrActive&&veyra.nrMotionSource===0&&veyra.srActive,"NR zero motion initializes")+ veyra.fgBackendName="xess";veyra.fgMultiplier=4;veyra.fgEnabled=true;next(10);return+ }+ if(step===10) {+ check(veyra.fgActive&&veyra.fgMotionSource===0,"XeSS zero motion 4X active "+veyra.statusText)+ veyra.fgMotionSource=1;next(11);return+ }+ if(step===11) {+ check(veyra.fgActive&&veyra.fgMotionSource===1,"XeSS external flow active")+ veyra.fgEnabled=false;veyra.srEnabled=false;veyra.nrEnabled=false;next(12);return+ }+ if(step===12) {+ veyra.hdrOutputMode=1;veyra.srTargetIndex=5;veyra.fgMotionSource=0;veyra.srMotionSource=0;veyra.nrMotionSource=0+ check(veyra.savePresetAs("Field Rendering Choices",15,false),"save list common choices")+ veyra.hdrOutputMode=0;veyra.srTargetIndex=2;veyra.srMotionSource=1+ check(veyra.applyPresetIndex(preset("Field Rendering Choices")),"apply list common choices")+ check(veyra.hdrOutputMode===1&&veyra.srTargetIndex===5&&veyra.srMotionSource===0,"list common choices restored")+ veyra.nodeMode=1;root.page="node";next(13);return+ }+ if(step===13) {+ check(veyra.hdrOutputMode===1&&veyra.srTargetIndex===5&&veyra.nrMotionSource===0,"node common choices")+ check(veyra.savePresetAs("Field Node Rendering Choices",15,true),"save node common choices")+ veyra.nodeMode=0;veyra.aspectMode=6;running=false;console.log("OPTIONS_UI_PASS");Qt.quit()+ }+ } catch(e) {running=false;console.log("OPTIONS_UI_FAIL "+e.message);Qt.quit()} }+ }diff --git a/scripts/acceptance/field-issues-resolution.qml b/scripts/acceptance/field-issues-resolution.qmlnew file mode 100644index 00000000..27c0dbe9--- /dev/null+++ b/scripts/acceptance/field-issues-resolution.qml@@ -0,0 +1,34 @@+ Timer {+ interval: 500; running: true; repeat: true+ property int step: 0+ property int ticks: 0+ property int total: 0+ property double began: 0+ property double before: 0+ function check(ok,label) { if(!ok)throw new Error(label) }+ function next(n) { step=n;ticks=0 }+ onTriggered: { try {+ ++ticks;++total;if(total>440)throw new Error("bounded step="+step)+ if(step===0) {+ if(ticks<4)return+ root.page="pro";veyra.muted=true;veyra.nrEnabled=true;veyra.srEnabled=true;veyra.fgEnabled=false+ veyra.srTargetIndex=4+ veyra.openPath("E:/项目/Veyra/tests/field-issues-20260930/media/gta6-1080p30-45s.mp4")+ next(1);return+ }+ if(step===1||step===3||step===5) {+ if(ticks<6||veyra.applying||!veyra.running)return+ check(veyra.srActive&&veyra.nrActive,"NR+SR active "+veyra.statusText)+ before=veyra.position;began=Date.now()+ veyra.logUi("resolution-test","RESOLUTION_BEGIN "+veyra.srTargetLabel+" "+veyra.outputSummary)+ next(step+1);return+ }+ if(step===2||step===4||step===6) {+ if(Date.now()-began<30000)return+ check(veyra.running&&veyra.srActive&&veyra.nrActive&&veyra.position>before+20,"30s high resolution playback "+veyra.srTargetLabel+" "+veyra.statusText)+ veyra.logUi("resolution-test","RESOLUTION_30S_PASS "+veyra.srTargetLabel+" "+veyra.outputSummary)+ if(step===6){veyra.logUi("resolution-test","RESOLUTION_UI_PASS");Qt.quit();return}+ veyra.seekTo(0);veyra.srTargetIndex=step===2?5:6;next(step+1);return+ }+ } catch(e) {veyra.logUi("resolution-test","RESOLUTION_UI_FAIL "+e.message);Qt.quit()} }+ }diff --git a/scripts/acceptance/p0-p1-r53-control.py b/scripts/acceptance/p0-p1-r53-control.pynew file mode 100644index 00000000..f16bd677--- /dev/null+++ b/scripts/acceptance/p0-p1-r53-control.py@@ -0,0 +1,158 @@+"""P0/P1-only guard and bounded command runner; never rewrites its baseline."""+import argparse+import hashlib+import json+import os+from pathlib import Path+import subprocess+import sys+import time+++def sha(path):+ return hashlib.file_digest(Path(path).open('rb'), 'sha256').hexdigest()+++def git(root, *args):+ return subprocess.check_output(['git', '-C', str(root), *args], stderr=subprocess.PIPE).decode('utf-8').strip()+++def files(root):+ names = git(root, 'ls-files', '-c', '-o', '--exclude-standard', '-z').split(chr(0))+ return {n: sha(root / n) for n in sorted(set(names)) if n and (root / n).is_file()}+++def differences(before, after, allowed=()):+ return [n for n in sorted(before.keys() | after.keys())+ if n not in allowed and before.get(n) != after.get(n)]+++def identity_differences(expected, actual):+ return [key for key in expected if expected[key] != actual.get(key)]+++def guard(manifest, manifest_sha):+ if sha(manifest) != manifest_sha.lower():+ raise RuntimeError('Immutable baseline SHA mismatch; do not regenerate it to pass.')+ b = json.loads(Path(manifest).read_text(encoding='utf-8'))+ root, original = Path(b['root']), Path(b['original_root'])+ actual = {+ 'root': str(Path(git(root, 'rev-parse', '--show-toplevel')).resolve()),+ 'branch': git(root, 'branch', '--show-current'),+ 'head': git(root, 'rev-parse', 'HEAD'),+ 'main': git(root, 'rev-parse', 'main'),+ 'original_branch': git(original, 'branch', '--show-current'),+ 'original_head': git(original, 'rev-parse', 'HEAD'),+ }+ errors = ['identity:' + x for x in identity_differences(b['identity'], actual)]+ errors += ['original:' + x for x in differences(b['original_files'], files(original))]+ errors += ['frozen:' + x for x in differences(b['files'], files(root), b['allow'])]+ if errors:+ raise RuntimeError('Scope guard FAIL: ' + json.dumps(errors, ensure_ascii=False))+ return b, {'status': 'pass', 'identity': actual, 'original_files_checked': len(b['original_files']),+ 'isolated_files_checked': len(b['files']), 'mutable_paths': b['allow']}+++def self_test():+ before = {'engine': 'a', 'test': 'b', 'guard': 'c'}+ cases = {+ 'unchanged': not differences(before, dict(before)),+ 'allowed_edit': not differences(before, {**before, 'test': 'd'}, ['test']),+ 'frozen_edit_rejected': differences(before, {**before, 'engine': 'd'}, ['test']) == ['engine'],+ 'deletion_rejected': differences(before, {'engine': 'a', 'test': 'b'}) == ['guard'],+ 'new_file_rejected': differences(before, {**before, 'source/new': 'x'}) == ['source/new'],+ 'original_even_allowed_rejected': differences(before, {**before, 'test': 'x'}) == ['test'],+ 'branch_rejected': identity_differences({'branch': 'isolated'}, {'branch': 'main'}) == ['branch'],+ 'main_rejected': identity_differences({'main': 'a'}, {'main': 'b'}) == ['main'],+ 'wrong_root_rejected': identity_differences({'root': 'E'}, {'root': 'C'}) == ['root'],+ }+ print(json.dumps(cases, indent=2))+ return 0 if all(cases.values()) else 1+++def run(args, b):+ limit = 900 if args.kind == 'build' else 300+ if not 0 < args.seconds <= limit:+ raise RuntimeError(f'{args.kind} timeout must be 1..{limit} seconds')+ output = Path(args.output).resolve()+ artifact_root = Path('E:/项目/Veyra').resolve()+ if not output.is_relative_to(artifact_root) or output.is_relative_to(Path(b['root'])):+ raise RuntimeError('Output must stay under E:/项目/Veyra and outside source workspace')+ output.mkdir(parents=True, exist_ok=True)+ ledger_path = output / 'commands.json'+ ledger = json.loads(ledger_path.read_text(encoding='utf-8')) if ledger_path.exists() else []+ attempts = [x for x in ledger if x['case'] == args.case and x['exit_code'] != 0]+ if len(attempts) >= 3:+ raise RuntimeError('Same-cause stop: initial diagnosis plus two failed attempts exhausted')+ if any(x['revision'] == args.revision for x in attempts):+ raise RuntimeError('No unchanged retry: provide a distinct evidence-backed revision or stop')+ command = list(args.command)+ if command and command[0] == '--':+ command.pop(0)+ if not command:+ raise RuntimeError('Missing child command')+ index = len(ledger) + 1+ prefix = output / f'{index:03d}-{args.case}'+ if any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_' for c in args.case):+ raise RuntimeError('Unsafe case identifier')+ temp = artifact_root / 'tmp' / 'p0-p1-r53-20260927' / f'{index:03d}-{args.case}'+ temp.mkdir(parents=True, exist_ok=True)+ env = {**os.environ, 'TEMP': str(temp), 'TMP': str(temp)}+ env['QT_PLUGIN_PATH'] = 'E:/项目/Veyra/deps/qt/6.8.3/msvc2022_64/plugins'+ started = time.time()+ timed_out = False+ with Path(str(prefix) + '.stdout.log').open('wb') as out, Path(str(prefix) + '.stderr.log').open('wb') as err:+ child = subprocess.Popen(command, cwd=args.cwd or b['root'], env=env, stdout=out, stderr=err)+ try:+ code = child.wait(timeout=args.seconds)+ except subprocess.TimeoutExpired:+ timed_out = True+ # Terminate only the PID we created and its descendants, never by image name.+ subprocess.run(['taskkill', '/PID', str(child.pid), '/T', '/F'], stdout=err, stderr=err, timeout=15)+ child.wait(timeout=15)+ code = 124+ record = {'case': args.case, 'revision': args.revision, 'command': command,+ 'cwd': args.cwd or b['root'], 'pid': child.pid, 'timeout_seconds': args.seconds,+ 'elapsed_seconds': round(time.time() - started, 3), 'exit_code': code,+ 'timed_out': timed_out, 'started_epoch': started, 'log_prefix': str(prefix)}+ ledger.append(record)+ ledger_path.write_text(json.dumps(ledger, ensure_ascii=False, indent=2), encoding='utf-8')+ _, after = guard(args.baseline, args.sha256)+ record['post_guard'] = after['status']+ Path(str(prefix) + '.result.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')+ print(json.dumps(record, ensure_ascii=False, indent=2))+ return code+++def main():+ p = argparse.ArgumentParser(description=__doc__)+ p.add_argument('mode', choices=['guard', 'self-test', 'run'])+ p.add_argument('--baseline')+ p.add_argument('--sha256')+ p.add_argument('--kind', choices=['test', 'build'], default='test')+ p.add_argument('--seconds', type=int, default=300)+ p.add_argument('--case')+ p.add_argument('--revision')+ p.add_argument('--output')+ p.add_argument('--cwd')+ args, command = p.parse_known_args()+ args.command = command+ if args.mode == 'self-test':+ return self_test()+ if not args.baseline or not args.sha256:+ p.error('--baseline and independently recorded --sha256 are required')+ b, result = guard(args.baseline, args.sha256)+ if args.mode == 'guard':+ print(json.dumps(result, ensure_ascii=False, indent=2))+ return 0+ if not args.case or not args.revision or not args.output:+ p.error('run requires --case, --revision, --output')+ return run(args, b)+++if __name__ == '__main__':+ try:+ sys.exit(main())+ except Exception as exc:+ print(str(exc), file=sys.stderr)+ sys.exit(2)diff --git a/scripts/acceptance/qml-ui-smoke.ps1 b/scripts/acceptance/qml-ui-smoke.ps1new file mode 100644index 00000000..72ae3559--- /dev/null+++ b/scripts/acceptance/qml-ui-smoke.ps1@@ -0,0 +1,155 @@+[CmdletBinding()]+param(+ [Parameter(Mandatory = $true)][string]$Root,+ [Parameter(Mandatory = $true)][ValidateSet('qml')][string]$UiTarget,+ [Parameter(Mandatory = $true)][string]$PlayerExe,+ [Parameter(Mandatory = $true)][string]$BuildDirectory,+ [Parameter(Mandatory = $true)][string]$StagingDirectory,+ [string]$OutputDirectory = '',+ [string]$TempDirectory = '',+ [string]$FixtureRoot = '',+ [ValidateRange(1, 270000)][int]$ExitAfterMs = 1800,+ [switch]$AllowMissingPlaybackFixture+)++# QML has a different command-line contract from the Win32 shell. This smoke+# test deliberately uses only options implemented by apps/veyra-qml/main.cpp.+$ErrorActionPreference = 'Stop'+$rootPath = (Resolve-Path -LiteralPath $Root).Path+$projectDirectoryName = [string]([char]0x9879) + [string]([char]0x76ee)+$artifactRoot = [IO.Path]::GetFullPath((Join-Path (Join-Path 'E:\' $projectDirectoryName) 'Veyra')).TrimEnd('\') + '\'+if ([string]::IsNullOrWhiteSpace($OutputDirectory)) {+ $OutputDirectory = Join-Path $artifactRoot 'logs\ui-qml-migration-20260927\qml-smoke'+}+if ([string]::IsNullOrWhiteSpace($TempDirectory)) {+ $TempDirectory = Join-Path $artifactRoot 'tmp\ui-qml-migration-20260927\qml-smoke'+}+$outputRoot = [IO.Path]::GetFullPath($OutputDirectory)+$tempRoot = [IO.Path]::GetFullPath($TempDirectory)+foreach ($path in @($outputRoot, $tempRoot)) {+ if (-not $path.StartsWith($artifactRoot, [StringComparison]::OrdinalIgnoreCase)) {+ throw "Smoke output and TEMP must be under E:\项目\Veyra: $path"+ }+}+$runId = [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssfffZ') + '-' + ([Guid]::NewGuid().ToString('N').Substring(0, 8))+$outPath = Join-Path $outputRoot ('run-' + $runId)+$tempPath = Join-Path $tempRoot ('run-' + $runId)+foreach ($path in @($outPath, $tempPath)) {+ if (Test-Path -LiteralPath $path) {+ throw "Smoke run directory already exists; refusing to reuse: $path"+ }+ [IO.Directory]::CreateDirectory($path) | Out-Null+}+$env:TEMP = $tempPath+$env:TMP = $tempPath+$env:QT_FORCE_STDERR_LOGGING = '1'+$env:QML_DISK_CACHE_PATH = Join-Path $tempPath 'qmlcache'+$entryScript = Join-Path $PSScriptRoot 'resolve-ui-migration-entry.ps1'+$entryArgs = @{+ Root = $rootPath; UiTarget = $UiTarget; PlayerExe = $PlayerExe+ BuildDirectory = $BuildDirectory; StagingDirectory = $StagingDirectory+ ArtifactDirectory = $outPath; OutputFile = (Join-Path $outPath 'entry.json')+}+$null = & $entryScript @entryArgs+if ($UiTarget -ne 'qml') {+ throw 'qml-ui-smoke.ps1 requires -UiTarget qml and veyra_qml_ui.exe.'+}++$exePath = (Resolve-Path -LiteralPath $PlayerExe).Path+$workingDirectory = Split-Path -Parent $exePath+$dataPath = Join-Path $outPath 'data'+[IO.Directory]::CreateDirectory($dataPath) | Out-Null+$cases = @(+ [pscustomobject]@{ name = 'home'; args = @('--page', 'home') },+ [pscustomobject]@{ name = 'minimal'; args = @('--page', 'minimal') },+ [pscustomobject]@{ name = 'professional'; args = @('--page', 'pro', '--tab', 'quality') },+ [pscustomobject]@{ name = 'node'; args = @('--page', 'node') },+ [pscustomobject]@{ name = 'export'; args = @('--page', 'export') },+ [pscustomobject]@{ name = 'settings'; args = @('--page', 'settings') },+ [pscustomobject]@{ name = 'dialog-capture'; args = @('--page', 'home', '--dialog', 'capture') }+)+$clip = if ([string]::IsNullOrWhiteSpace($FixtureRoot)) { $null } else { Join-Path ([IO.Path]::GetFullPath($FixtureRoot)) 'test_av_1080p.mp4' }+if ($clip -and (Test-Path -LiteralPath $clip -PathType Leaf)) {+ $cases += [pscustomobject]@{ name = 'playback-professional'; args = @('--page', 'pro', '--tab', 'quality', $clip) }+} elseif (-not $AllowMissingPlaybackFixture) {+ $fixtureDescription = if ($clip) { $clip } else { 'FixtureRoot was not provided' }+ throw "Missing required QML playback fixture: $fixtureDescription. Pass -AllowMissingPlaybackFixture only for an explicit UI-only run that records the playback case as skipped."+} else {+ $fixtureDescription = if ($clip) { $clip } else { 'FixtureRoot was not provided' }+ $cases += [pscustomobject]@{ name = 'playback-professional'; args = @(); skipped = $true; skipReason = "missing fixture: $fixtureDescription" }+}++$results = [Collections.Generic.List[object]]::new()+foreach ($case in $cases) {+ if ($case.PSObject.Properties['skipped'] -and $case.skipped) {+ # A skipped playback case is explicit evidence that U4 is incomplete. It+ # must never be serialized as passed or let unattended mode advance.+ $results.Add([ordered]@{ name = $case.name; status = 'skipped'; passed = $false; detail = [string]$case.skipReason; exit = $null })+ continue+ }+ $stdout = Join-Path $outPath ($case.name + '.stdout.log')+ $stderr = Join-Path $outPath ($case.name + '.stderr.log')+ $qmlLog = Join-Path $outPath ($case.name + '.qml.log')+ $savedLog = $env:VEYRA_LOG_FILE+ try {+ $env:VEYRA_LOG_FILE = $qmlLog+ $arguments = @($case.args | ForEach-Object { $_ }) + @('--data-dir', $dataPath, '--reduced-motion', '--exit-after', $ExitAfterMs)+ $psi = [Diagnostics.ProcessStartInfo]::new()+ $psi.FileName = $exePath+ $psi.WorkingDirectory = $workingDirectory+ $psi.UseShellExecute = $false+ $psi.CreateNoWindow = $true+ $psi.RedirectStandardOutput = $true+ $psi.RedirectStandardError = $true+ if ($psi.PSObject.Properties.Name -contains 'ArgumentList') {+ foreach ($argument in $arguments) { [void]$psi.ArgumentList.Add([string]$argument) }+ } else {+ $quote = { param([string]$value) '"' + $value.Replace('"', '\"') + '"' }+ $psi.Arguments = (($arguments | ForEach-Object { & $quote ([string]$_) }) -join ' ')+ }+ $p = [Diagnostics.Process]::Start($psi)+ $stdoutTask = $p.StandardOutput.ReadToEndAsync()+ $stderrTask = $p.StandardError.ReadToEndAsync()+ $finished = $p.WaitForExit(($ExitAfterMs + 30000))+ if (-not $finished) {+ try { $p.Kill() } catch { }+ $stdoutTask.GetAwaiter().GetResult() | Set-Content -LiteralPath $stdout -Encoding UTF8+ $stderrTask.GetAwaiter().GetResult() | Set-Content -LiteralPath $stderr -Encoding UTF8+ $results.Add([ordered]@{ name = $case.name; status = 'fail'; passed = $false; detail = 'timeout'; exit = $null })+ continue+ }+ $p.WaitForExit()+ $stdoutTask.GetAwaiter().GetResult() | Set-Content -LiteralPath $stdout -Encoding UTF8+ $stderrTask.GetAwaiter().GetResult() | Set-Content -LiteralPath $stderr -Encoding UTF8+ $text = if (Test-Path -LiteralPath $qmlLog) { Get-Content -LiteralPath $qmlLog -Raw } else { '' }+ $ok = ($p.ExitCode -eq 0) -and ($text -match 'Veyra QML session started') -and+ ($text -notmatch 'no root object|objectCreationFailed|QML Error|invalid video probe')+ $detail = "exit=$($p.ExitCode) log=$qmlLog"+ if (-not $ok -and [string]::IsNullOrWhiteSpace($text)) { $detail += '; qml log is empty' }+ $results.Add([ordered]@{ name = $case.name; status = if ($ok) { 'pass' } else { 'fail' }; passed = $ok; detail = $detail; exit = $p.ExitCode })+ } finally {+ if ($null -eq $savedLog) { Remove-Item Env:VEYRA_LOG_FILE -ErrorAction SilentlyContinue }+ else { $env:VEYRA_LOG_FILE = $savedLog }+ }+}++$record = [ordered]@{+ schema = 'veyra.qml-ui-smoke.v2'+ runDirectory = $outPath+ tempDirectory = $tempPath+ uiTarget = $UiTarget+ playbackFixture = $clip+ allowMissingPlaybackFixture = [bool]$AllowMissingPlaybackFixture+ cases = $results+ failures = @($results | Where-Object { $_.status -eq 'fail' }).Count+ skipped = @($results | Where-Object { $_.status -eq 'skipped' }).Count+ requiredFailures = @($results | Where-Object { $_.status -in @('fail', 'skipped') }).Count+ passed = (@($results | Where-Object { $_.status -in @('fail', 'skipped') }).Count -eq 0)+}+$record | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath (Join-Path $outPath 'result.json') -Encoding UTF8+if ($record.requiredFailures -gt 0) {+ Write-Host "QML UI SMOKE INCOMPLETE: $outPath (failures=$($record.failures), skipped=$($record.skipped))"+ exit 1+}+Write-Host "QML UI SMOKE PASS: $outPath"+exit 0diff --git a/scripts/acceptance/resolve-ui-migration-entry.ps1 b/scripts/acceptance/resolve-ui-migration-entry.ps1new file mode 100644index 00000000..15cac9a9--- /dev/null+++ b/scripts/acceptance/resolve-ui-migration-entry.ps1@@ -0,0 +1,209 @@+[CmdletBinding()]+param(+ [Parameter(Mandatory = $true)][string]$Root,+ [Parameter(Mandatory = $true)][ValidateSet('qml')][string]$UiTarget,+ [Parameter(Mandatory = $true)][string]$PlayerExe,+ [Parameter(Mandatory = $true)][string]$BuildDirectory,+ [Parameter(Mandatory = $true)][string]$StagingDirectory,+ [string]$ArtifactDirectory = '',+ [string]$OutputFile = ''+)++$ErrorActionPreference = 'Stop'+$projectDirectoryName = [string]([char]0x9879) + [string]([char]0x76ee)+$artifactRoot = [IO.Path]::GetFullPath((Join-Path (Join-Path 'E:\' $projectDirectoryName) 'Veyra')).TrimEnd('\')+if ([string]::IsNullOrWhiteSpace($ArtifactDirectory)) {+ $ArtifactDirectory = Join-Path $artifactRoot 'logs\ui-qml-migration-20260927\entry'+}++function FullPath([string]$Path) {+ return [IO.Path]::GetFullPath($Path)+}++function Resolve-Directory([string]$Path, [string]$Name) {+ $full = FullPath $Path+ if (-not (Test-Path -LiteralPath $full -PathType Container)) { throw "$Name is not a directory: $full" }+ return (Resolve-Path -LiteralPath $full -ErrorAction Stop).Path+}++function Resolve-File([string]$Path, [string]$Name) {+ $full = FullPath $Path+ if (-not (Test-Path -LiteralPath $full -PathType Leaf)) { throw "$Name is not a file: $full" }+ return (Resolve-Path -LiteralPath $full -ErrorAction Stop).Path+}++function Assert-Under([string]$Path, [string]$Directory, [string]$Name) {+ $fullPath = FullPath $Path+ $fullDirectory = (FullPath $Directory).TrimEnd('\', '/')+ $prefix = $fullDirectory + '\'+ if (-not $fullPath.Equals($fullDirectory, [StringComparison]::OrdinalIgnoreCase) -and+ -not $fullPath.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) {+ throw "$Name must be inside ${fullDirectory}: $fullPath"+ }+}++function Assert-ArtifactPath([string]$Path, [string]$Name) {+ $full = FullPath $Path+ Assert-Under $full $artifactRoot $Name+ return $full+}++$rootPath = Resolve-Directory $Root 'Root'+$playerPath = Resolve-File $PlayerExe 'PlayerExe'+$buildPath = Resolve-Directory $BuildDirectory 'BuildDirectory'+$stagingPath = Resolve-Directory $StagingDirectory 'StagingDirectory'+Assert-Under $buildPath $artifactRoot 'BuildDirectory'+Assert-Under $stagingPath $artifactRoot 'StagingDirectory'+$actualName = [IO.Path]::GetFileName($playerPath)+$expectedName = 'veyra_qml_ui.exe'+if (-not $actualName.Equals($expectedName, [StringComparison]::OrdinalIgnoreCase)) {+ throw "UI entry mismatch: target=$UiTarget requires $expectedName but PlayerExe=$playerPath"+}+Assert-Under $playerPath $stagingPath 'PlayerExe'++# A staging directory is one QML product plus its three QML-only test tools.+# The legacy entry or an unlisted executable makes later smoke/unit results+# ambiguous even when PlayerExe is explicit.+$requiredExecutables = @(+ 'veyra_qml_ui.exe',+ 'veyra_qml_data_tests.exe',+ 'veyra_qml_easing_tests.exe',+ 'veyra_qml_quick_tests.exe'+)+$allStagedExecutables = @(Get-ChildItem -LiteralPath $stagingPath -File -Filter '*.exe' -Recurse -Force |+ ForEach-Object { $_.Name } | Sort-Object)+$expectedExecutableNames = @($requiredExecutables | Sort-Object)+$exeDifferences = @(Compare-Object -ReferenceObject $expectedExecutableNames -DifferenceObject $allStagedExecutables)+if ($exeDifferences.Count -gt 0) {+ throw "StagingDirectory executable set mismatch; expected=$($expectedExecutableNames -join ', ') found=$($allStagedExecutables -join ', ')"+}+$legacyExecutables = @(Get-ChildItem -LiteralPath $stagingPath -Filter 'veyra.exe' -File -Recurse -Force)+if ($legacyExecutables.Count -gt 0) { throw "StagingDirectory contains the legacy UI executable: $($legacyExecutables[0].FullName)" }++$cachePath = Resolve-File (Join-Path $buildPath 'CMakeCache.txt') 'CMakeCache.txt'+$line = Select-String -LiteralPath $cachePath -Pattern '^VEYRA_BUILD_QML_UI:BOOL=(ON|OFF)$' | Select-Object -First 1+if (-not $line) { throw "CMakeCache.txt has no VEYRA_BUILD_QML_UI entry: $cachePath" }+$cmakeQml = $line.Matches[0].Groups[1].Value+$expectedSwitch = if ($UiTarget -eq 'qml') { 'ON' } else { 'OFF' }+if ($cmakeQml -ne $expectedSwitch) {+ throw "UI target $UiTarget requires VEYRA_BUILD_QML_UI=$expectedSwitch in $cachePath (found $cmakeQml)"+}++$buildMatches = @(Get-ChildItem -LiteralPath $buildPath -Filter $expectedName -File -Recurse -Force | Sort-Object FullName)+if ($buildMatches.Count -ne 1) {+ throw "BuildDirectory must contain exactly one $expectedName; found $($buildMatches.Count): $buildPath"+}+$buildExePath = $buildMatches[0].FullName+$buildHash = (Get-FileHash -LiteralPath $buildExePath -Algorithm SHA256).Hash+$playerHash = (Get-FileHash -LiteralPath $playerPath -Algorithm SHA256).Hash+if (-not $buildHash.Equals($playerHash, [StringComparison]::OrdinalIgnoreCase)) {+ throw "Build/staging executable mismatch: build=$buildExePath ($buildHash), staging=$playerPath ($playerHash)"+}++$testExecutables = [Collections.Generic.List[object]]::new()+foreach ($name in @('veyra_qml_data_tests.exe', 'veyra_qml_easing_tests.exe', 'veyra_qml_quick_tests.exe')) {+ $buildTestMatches = @(Get-ChildItem -LiteralPath $buildPath -Filter $name -File -Recurse -Force | Sort-Object FullName)+ if ($buildTestMatches.Count -ne 1) {+ throw "BuildDirectory must contain exactly one $name; found $($buildTestMatches.Count): $buildPath"+ }+ $stagedTestPath = Join-Path $stagingPath $name+ if (-not (Test-Path -LiteralPath $stagedTestPath -PathType Leaf)) { throw "staging is missing QML test executable: $stagedTestPath" }+ $testHash = (Get-FileHash -LiteralPath $stagedTestPath -Algorithm SHA256).Hash+ $buildTestHash = (Get-FileHash -LiteralPath $buildTestMatches[0].FullName -Algorithm SHA256).Hash+ if (-not $buildTestHash.Equals($testHash, [StringComparison]::OrdinalIgnoreCase)) {+ throw "Build/staging executable mismatch: build=$($buildTestMatches[0].FullName) ($buildTestHash), staging=$stagedTestPath ($testHash)"+ }+ $testExecutables.Add([ordered]@{+ name = $name+ stagingPath = $stagedTestPath+ stagingSha256 = $testHash+ buildPath = $buildTestMatches[0].FullName+ buildSha256 = $buildTestHash+ })+}++if ($UiTarget -eq 'qml') {+ $qmldir = Join-Path $stagingPath 'qml\Veyra\qmldir'+ if (-not (Test-Path -LiteralPath $qmldir -PathType Leaf)) {+ throw "QML staging is incomplete; missing $qmldir"+ }+}+$qmlTestSource = Join-Path $stagingPath 'qml-tests\tst_components.qml'+if (-not (Test-Path -LiteralPath $qmlTestSource -PathType Leaf)) {+ throw "QML staging is incomplete; missing $qmlTestSource"+}+$requiredQtDlls = @(+ 'Qt6Core.dll', 'Qt6Gui.dll', 'Qt6Qml.dll', 'Qt6QmlModels.dll',+ 'Qt6Quick.dll', 'Qt6QuickControls2.dll', 'Qt6QuickTemplates2.dll',+ 'Qt6Widgets.dll', 'Qt6QuickTest.dll'+)+$qtRuntimeFiles = [Collections.Generic.List[object]]::new()+foreach ($name in $requiredQtDlls) {+ $path = Join-Path $stagingPath $name+ if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { throw "QML staging is missing Qt runtime DLL: $path" }+ $qtRuntimeFiles.Add([ordered]@{ name = $name; path = $path; sha256 = (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash })+}+$platformPlugin = Join-Path $stagingPath 'platforms\qwindows.dll'+if (-not (Test-Path -LiteralPath $platformPlugin -PathType Leaf)) { throw "QML staging is missing Qt platform plugin: $platformPlugin" }+$offscreenPlugin = Join-Path $stagingPath 'platforms\qoffscreen.dll'+if (-not (Test-Path -LiteralPath $offscreenPlugin -PathType Leaf)) { throw "QML staging is missing Qt offscreen plugin: $offscreenPlugin" }+$qtTestModule = Join-Path $stagingPath 'qml\QtTest\qmldir'+if (-not (Test-Path -LiteralPath $qtTestModule -PathType Leaf)) { throw "QML staging is missing QtTest module: $qtTestModule" }+$runtimeDirectories = @('runtime', 'runtime_local\amd', 'runtime_local\intel')+foreach ($relative in $runtimeDirectories) {+ $path = Join-Path $stagingPath $relative+ if (-not (Test-Path -LiteralPath $path -PathType Container)) { throw "QML staging is missing runtime directory: $path" }+}++$artifactPath = Assert-ArtifactPath $ArtifactDirectory 'ArtifactDirectory'+[IO.Directory]::CreateDirectory($artifactPath) | Out-Null+$outputPath = $null+if (-not [string]::IsNullOrWhiteSpace($OutputFile)) {+ $outputPath = Assert-ArtifactPath $OutputFile 'OutputFile'+ Assert-Under $outputPath $artifactPath 'OutputFile'+ [IO.Directory]::CreateDirectory((Split-Path -Parent $outputPath)) | Out-Null+}++$branch = (& git -C $rootPath rev-parse --abbrev-ref HEAD 2>$null)+$commit = (& git -C $rootPath rev-parse HEAD 2>$null)+if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($commit)) { throw "Could not resolve Git identity for $rootPath" }++$record = [ordered]@{+ schema = 'veyra.ui-migration-entry.v3'+ timestampUtc = [DateTime]::UtcNow.ToString('o')+ root = $rootPath+ branch = [string]$branch+ commit = [string]$commit+ uiTarget = $UiTarget+ entryContract = 'qml-smoke'+ playerExe = $playerPath+ playerExeName = $actualName+ playerExeSha256 = $playerHash+ buildDirectory = $buildPath+ buildExe = $buildExePath+ buildExeSha256 = $buildHash+ buildStagingHashMatch = $true+ testExecutables = @($testExecutables)+ cmakeCache = $cachePath+ cmakeQmlSwitch = $cmakeQml+ stagingDirectory = $stagingPath+ qmlModule = Join-Path $stagingPath 'qml\Veyra\qmldir'+ qmlQuickTestSource = $qmlTestSource+ qtRuntime = [ordered]@{+ dlls = @($qtRuntimeFiles)+ platformPlugin = [ordered]@{+ path = $platformPlugin+ sha256 = (Get-FileHash -LiteralPath $platformPlugin -Algorithm SHA256).Hash+ }+ offscreenPlugin = [ordered]@{+ path = $offscreenPlugin+ sha256 = (Get-FileHash -LiteralPath $offscreenPlugin -Algorithm SHA256).Hash+ }+ qtTestModule = $qtTestModule+ }+ runtimeDirectories = @($runtimeDirectories | ForEach-Object { Join-Path $stagingPath $_ })+ artifactDirectory = $artifactPath+}+$json = $record | ConvertTo-Json -Depth 10+if ($outputPath) { $json | Set-Content -LiteralPath $outputPath -Encoding UTF8 }+Write-Output $jsondiff --git a/scripts/acceptance/test-ui-migration-entry-contract.ps1 b/scripts/acceptance/test-ui-migration-entry-contract.ps1new file mode 100644index 00000000..a0afd378--- /dev/null+++ b/scripts/acceptance/test-ui-migration-entry-contract.ps1@@ -0,0 +1,140 @@+[CmdletBinding()]+param(+ [string]$Root = 'C:\Users\123\Desktop\Veyra DLSS Video Player',+ [Parameter(Mandatory = $true)][string]$QmlBuild,+ [string]$OutputDirectory = ''+)++# Read-only contract test over copied executable names. It intentionally makes+# no source/build changes; each case receives a fresh staging directory and+# only the resolver decides whether that combination is valid.+$ErrorActionPreference = 'Stop'+$rootPath = (Resolve-Path -LiteralPath $Root -ErrorAction Stop).Path+$qmlBuildPath = (Resolve-Path -LiteralPath $QmlBuild -ErrorAction Stop).Path+$projectDirectoryName = [string]([char]0x9879) + [string]([char]0x76ee)+$artifactRoot = [IO.Path]::GetFullPath((Join-Path (Join-Path 'E:\' $projectDirectoryName) 'Veyra')).TrimEnd('\') + '\'+if ([string]::IsNullOrWhiteSpace($OutputDirectory)) {+ $OutputDirectory = Join-Path $artifactRoot 'tests\ui-migration-entry-contract-20260927'+}+[string]$outputRoot = [IO.Path]::GetFullPath($OutputDirectory)+if (-not $qmlBuildPath.StartsWith($artifactRoot, [StringComparison]::OrdinalIgnoreCase)) {+ throw "QmlBuild must be under E:\项目\Veyra: $qmlBuildPath"+}+if ($qmlBuildPath -match '\\qt-probe(?:-|\\|$)') {+ throw "QmlBuild cannot use a legacy qt-probe directory: $qmlBuildPath"+}+if (-not $outputRoot.StartsWith($artifactRoot, [StringComparison]::OrdinalIgnoreCase)) {+ throw "OutputDirectory must be under E:\项目\Veyra: $outputRoot"+}+$runId = [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssfffZ') + '-' + ([Guid]::NewGuid().ToString('N').Substring(0, 8))+$outRoot = Join-Path $outputRoot ('run-' + $runId)+[IO.Directory]::CreateDirectory($outRoot) | Out-Null+$resolver = Join-Path $rootPath 'scripts\acceptance\resolve-ui-migration-entry.ps1'+$qtRoot = Join-Path $artifactRoot 'deps\qt\6.8.3\msvc2022_64'+$requiredExecutables = @(+ 'veyra_qml_ui.exe',+ 'veyra_qml_data_tests.exe',+ 'veyra_qml_easing_tests.exe',+ 'veyra_qml_quick_tests.exe'+)+$requiredQtDlls = @(+ 'Qt6Core.dll', 'Qt6Gui.dll', 'Qt6Qml.dll', 'Qt6QmlModels.dll',+ 'Qt6Quick.dll', 'Qt6QuickControls2.dll', 'Qt6QuickTemplates2.dll',+ 'Qt6Widgets.dll', 'Qt6QuickTest.dll'+)+foreach ($name in $requiredExecutables) {+ if (-not (Test-Path -LiteralPath (Join-Path $qmlBuildPath $name) -PathType Leaf)) { throw "missing QML fixture: $(Join-Path $qmlBuildPath $name)" }+}+foreach ($name in $requiredQtDlls) {+ if (-not (Test-Path -LiteralPath (Join-Path $qtRoot "bin\$name") -PathType Leaf)) { throw "missing Qt fixture: $(Join-Path $qtRoot "bin\$name")" }+}+if (-not (Test-Path -LiteralPath (Join-Path $qtRoot 'plugins\platforms\qwindows.dll') -PathType Leaf)) {+ throw "missing Qt fixture platform plugin: $(Join-Path $qtRoot 'plugins\platforms\qwindows.dll')"+}+if (-not (Test-Path -LiteralPath (Join-Path $rootPath 'tests\qml\quick\tst_components.qml') -PathType Leaf)) {+ throw "missing QML Quick Test source fixture"+}++function Copy-Tree([string]$Source, [string]$Destination) {+ if (-not (Test-Path -LiteralPath $Source -PathType Container)) { throw "fixture source directory is missing: $Source" }+ [IO.Directory]::CreateDirectory($Destination) | Out-Null+ Get-ChildItem -LiteralPath $Source -Force | ForEach-Object {+ Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $Destination $_.Name) -Recurse -Force+ }+}++function New-Stage([string]$Name, [string]$SourceExe, [string]$TargetExe, [bool]$IncludeQml) {+ $stage = Join-Path $outRoot ("stage-" + $Name)+ [IO.Directory]::CreateDirectory($stage) | Out-Null+ Copy-Item -LiteralPath $SourceExe -Destination (Join-Path $stage $TargetExe) -Force+ foreach ($name in $requiredExecutables | Where-Object { $_ -ne 'veyra_qml_ui.exe' }) {+ Copy-Item -LiteralPath (Join-Path $qmlBuildPath $name) -Destination (Join-Path $stage $name) -Force+ }+ if ($IncludeQml) {+ Copy-Tree (Join-Path $qmlBuildPath 'qml') (Join-Path $stage 'qml')+ }+ Copy-Tree (Join-Path $qtRoot 'qml\QtTest') (Join-Path $stage 'qml\QtTest')+ Copy-Tree (Join-Path $rootPath 'tests\qml\quick') (Join-Path $stage 'qml-tests')+ foreach ($name in $requiredQtDlls) {+ Copy-Item -LiteralPath (Join-Path $qtRoot "bin\$name") -Destination (Join-Path $stage $name) -Force+ }+ [IO.Directory]::CreateDirectory((Join-Path $stage 'platforms')) | Out-Null+ Copy-Item -LiteralPath (Join-Path $qtRoot 'plugins\platforms\qwindows.dll') -Destination (Join-Path $stage 'platforms\qwindows.dll') -Force+ Copy-Item -LiteralPath (Join-Path $qtRoot 'plugins\platforms\qoffscreen.dll') -Destination (Join-Path $stage 'platforms\qoffscreen.dll') -Force+ foreach ($relative in @('runtime', 'runtime_local\amd', 'runtime_local\intel')) {+ [IO.Directory]::CreateDirectory((Join-Path $stage $relative)) | Out-Null+ }+ return $stage+}++$qmlSource = Join-Path $qmlBuildPath 'veyra_qml_ui.exe'++$qmlStage = New-Stage 'qml-valid' $qmlSource 'veyra_qml_ui.exe' $true+$qmlNamedLegacyStage = New-Stage 'qml-with-legacy-entry' $qmlSource 'veyra.exe' $true+$hashMismatchStage = New-Stage 'qml-hash-mismatch' $qmlSource 'veyra_qml_ui.exe' $true+$missingModuleStage = New-Stage 'qml-missing-module' $qmlSource 'veyra_qml_ui.exe' $false+$missingQtStage = New-Stage 'qml-missing-qt-runtime' $qmlSource 'veyra_qml_ui.exe' $true+$missingOffscreenStage = New-Stage 'qml-missing-offscreen' $qmlSource 'veyra_qml_ui.exe' $true+$missingQtTestStage = New-Stage 'qml-missing-qttest' $qmlSource 'veyra_qml_ui.exe' $true+[IO.File]::AppendAllText((Join-Path $hashMismatchStage 'veyra_qml_ui.exe'), 'entry-contract-hash-mismatch')+Remove-Item -LiteralPath (Join-Path $missingQtStage 'Qt6Quick.dll') -Force+Remove-Item -LiteralPath (Join-Path $missingOffscreenStage 'platforms\qoffscreen.dll') -Force+Remove-Item -LiteralPath (Join-Path $missingQtTestStage 'qml\QtTest\qmldir') -Force++$cases = @(+ [ordered]@{ name = 'qml-valid'; target = 'qml'; build = $qmlBuildPath; stage = $qmlStage; exe = (Join-Path $qmlStage 'veyra_qml_ui.exe'); expected = $true },+ [ordered]@{ name = 'qml-rejects-legacy-entry'; target = 'qml'; build = $qmlBuildPath; stage = $qmlNamedLegacyStage; exe = (Join-Path $qmlNamedLegacyStage 'veyra.exe'); expected = $false },+ [ordered]@{ name = 'qml-rejects-hash-mismatch'; target = 'qml'; build = $qmlBuildPath; stage = $hashMismatchStage; exe = (Join-Path $hashMismatchStage 'veyra_qml_ui.exe'); expected = $false },+ [ordered]@{ name = 'qml-rejects-missing-module'; target = 'qml'; build = $qmlBuildPath; stage = $missingModuleStage; exe = (Join-Path $missingModuleStage 'veyra_qml_ui.exe'); expected = $false },+ [ordered]@{ name = 'qml-rejects-missing-qt-runtime'; target = 'qml'; build = $qmlBuildPath; stage = $missingQtStage; exe = (Join-Path $missingQtStage 'veyra_qml_ui.exe'); expected = $false },+ [ordered]@{ name = 'qml-rejects-missing-offscreen'; target = 'qml'; build = $qmlBuildPath; stage = $missingOffscreenStage; exe = (Join-Path $missingOffscreenStage 'veyra_qml_ui.exe'); expected = $false },+ [ordered]@{ name = 'qml-rejects-missing-qttest'; target = 'qml'; build = $qmlBuildPath; stage = $missingQtTestStage; exe = (Join-Path $missingQtTestStage 'veyra_qml_ui.exe'); expected = $false }+)++$results = [Collections.Generic.List[object]]::new()+foreach ($case in $cases) {+ $artifact = Join-Path $outRoot ("evidence-" + $case.name)+ $output = Join-Path $artifact 'entry.json'+ $actual = $false+ $detail = ''+ try {+ [IO.Directory]::CreateDirectory($artifact) | Out-Null+ $null = & $resolver -Root $rootPath -UiTarget $case.target -PlayerExe $case.exe -BuildDirectory $case.build -StagingDirectory $case.stage -ArtifactDirectory $artifact -OutputFile $output+ $actual = $true+ } catch {+ $detail = $_.Exception.Message+ }+ $passed = ($actual -eq [bool]$case.expected)+ $results.Add([ordered]@{ name = $case.name; expectedPass = [bool]$case.expected; actualPass = $actual; passed = $passed; detail = $detail })+}+$record = [ordered]@{+ schema = 'veyra.ui-migration-entry-contract.v3'+ timestampUtc = [DateTime]::UtcNow.ToString('o')+ outputRoot = $outputRoot+ runDirectory = $outRoot+ cases = $results+ failures = @($results | Where-Object { -not $_.passed }).Count+}+$record | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath (Join-Path $outRoot 'result.json') -Encoding UTF8+if ($record.failures -gt 0) { Write-Host "ENTRY CONTRACT FAIL: $outRoot"; exit 1 }+Write-Host "ENTRY CONTRACT PASS: $outRoot"; exit 0diff --git a/scripts/build-ui-migration.cmd b/scripts/build-ui-migration.cmdindex 6c537c59..32741547 100644--- a/scripts/build-ui-migration.cmd+++ b/scripts/build-ui-migration.cmd@@ -1,24 +1,35 @@@echo off-rem Build for the QML UI migration branch with the 1.4.4 release configuration.-rem The caller sets VEYRA_OUT (build dir) and VEYRA_TMP (process TEMP): a .cmd file-rem is parsed in the ANSI code page, so non-ASCII paths must come from the environment.-rem Use scripts/build-ui-migration.ps1. Usage: build-ui-migration.cmd [target...]+rem Target-explicit build wrapper. Use scripts/build-ui-migration.ps1.call "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvars64.bat" >nul 2>&1if errorlevel 1 exit /b 4set "ROOT=%~dp0.."if "%VEYRA_OUT%"=="" exit /b 3+if /I "%VEYRA_UI_TARGET%"=="qml" (+ set "QML_SWITCH=ON"+) else (+ echo VEYRA_UI_TARGET must be qml for the active UI migration 1>&2+ exit /b 7+)set "OUT=%VEYRA_OUT%"if not "%VEYRA_TMP%"=="" set "TEMP=%VEYRA_TMP%"if not "%VEYRA_TMP%"=="" set "TMP=%VEYRA_TMP%"set "CMAKE=C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe"if not exist "%OUT%\CMakeCache.txt" (- "%CMAKE%" --preset x64-release -S "%ROOT%" -B "%OUT%" -DVEYRA_ENABLE_EXPERIMENTAL_DLSSNR=ON -DVEYRA_DLSS_SDK_ROOT="%ROOT%\third_party_local\nvidia\DLSS_SDK_310.7.0" -DVEYRA_NVOF_SDK_ROOT="%ROOT%\third_party_local\nvidia\Optical_Flow_SDK_5.0.7" -DVEYRA_NVENC_HEADERS_ROOT="%ROOT%\third_party_local\nvidia\nv-codec-headers-13.0" -DVEYRA_XESS_ROOT="%ROOT%\third_party_local\intel\xess-3.0.2" -DVEYRA_FIDELITYFX_ROOT="%ROOT%\third_party_local\amd\FidelityFX-SDK\sdk" -DVEYRA_FIDELITYFX2_ROOT="%ROOT%\third_party_local\amd\FidelityFX-SDK-2.3.0\Kits\FidelityFX" -DVEYRA_FFMPEG_ROOT="C:\veyra-deps\ffmpeg-ps5-dav1d-installed" -DVEYRA_CLIP_TOOLS_ROOT="C:\veyra-deps\tools-installed\x64-windows" -DVEYRA_ENABLE_REMOTEPLAY=ON -DVEYRA_RP_CHIAKI_VERIFY_DIR="C:/veyra-deps/chiaki-source" -DVEYRA_RP_CHIAKI_SOURCE_DIR="%ROOT%\out\remoteplay\chiaki-msvc-stage" -DCMAKE_PREFIX_PATH="C:/veyra-deps/remoteplay-installed/x64-windows-static" -DPROTOC="C:/veyra-deps/remoteplay-installed/x64-windows/tools/protobuf/protoc.exe" -DPKG_CONFIG_EXECUTABLE="C:/veyra-deps/vcpkg/downloads/tools/msys2/3e71d1f8e22ab23f/mingw64/bin/pkg-config.exe"+ "%CMAKE%" --preset x64-release -S "%ROOT%" -B "%OUT%" -DVEYRA_BUILD_QML_UI=ON -DCMAKE_PREFIX_PATH="%VEYRA_QT_DIR%;C:/veyra-deps/remoteplay-installed/x64-windows-static" -DVEYRA_ENABLE_EXPERIMENTAL_DLSSNR=ON -DVEYRA_DLSS_SDK_ROOT="%ROOT%\third_party_local\nvidia\DLSS_SDK_310.7.0" -DVEYRA_NVOF_SDK_ROOT="%ROOT%\third_party_local\nvidia\Optical_Flow_SDK_5.0.7" -DVEYRA_NVENC_HEADERS_ROOT="%ROOT%\third_party_local\nvidia\nv-codec-headers-13.0" -DVEYRA_XESS_ROOT="%ROOT%\third_party_local\intel\xess-3.0.2" -DVEYRA_FIDELITYFX_ROOT="%ROOT%\third_party_local\amd\FidelityFX-SDK\sdk" -DVEYRA_FIDELITYFX2_ROOT="%ROOT%\third_party_local\amd\FidelityFX-SDK-2.3.0\Kits\FidelityFX" -DVEYRA_FFMPEG_ROOT="C:\veyra-deps\ffmpeg-ps5-dav1d-installed" -DVEYRA_CLIP_TOOLS_ROOT="C:\veyra-deps\tools-installed\x64-windows" -DVEYRA_ENABLE_REMOTEPLAY=ON -DVEYRA_RP_CHIAKI_VERIFY_DIR="C:/veyra-deps/chiaki-source" -DVEYRA_RP_CHIAKI_SOURCE_DIR="%ROOT%\out\remoteplay\chiaki-msvc-stage" -DPROTOC="C:/veyra-deps/remoteplay-installed/x64-windows/tools/protobuf/protoc.exe" -DPKG_CONFIG_EXECUTABLE="C:/veyra-deps/vcpkg/downloads/tools/msys2/3e71d1f8e22ab23f/mingw64/bin/pkg-config.exe"if errorlevel 1 exit /b 5-)-if "%~1"=="" (- "%CMAKE%" --build "%OUT%") else (- "%CMAKE%" --build "%OUT%" --target %*+ findstr /R /C:"^VEYRA_BUILD_QML_UI:BOOL=%QML_SWITCH%$" "%OUT%\CMakeCache.txt" >nul+ if errorlevel 1 (+ echo Existing CMakeCache.txt does not match target %VEYRA_UI_TARGET% 1>&2+ exit /b 8+ ))+set "PRIMARY_TARGETS=veyra_qml_ui veyra_qml_data_tests veyra_qml_easing_tests veyra_qml_quick_tests"+rem The UI contract always builds all four targets. Do not forward arbitrary+rem command-line targets/options into a backend build from this UI wrapper.+"%CMAKE%" --build "%OUT%" --target %PRIMARY_TARGETS%if errorlevel 1 exit /b 6+for %%T in (veyra_qml_ui veyra_qml_data_tests veyra_qml_easing_tests veyra_qml_quick_tests) do (+ if not exist "%OUT%\%%T.exe" exit /b 9+)exit /b 0diff --git a/scripts/build-ui-migration.ps1 b/scripts/build-ui-migration.ps1index a6766299..7bc9f549 100644--- a/scripts/build-ui-migration.ps1+++ b/scripts/build-ui-migration.ps1@@ -1,13 +1,62 @@-# Wrapper that sets the non-ASCII output paths and runs build-ui-migration.cmd.-# Build output goes to the log file through cmd's own redirection, so compiler-# warnings on stderr never become PowerShell errors.-param([string[]]$Targets = @(), [string]$Log = 'E:\项目\Veyra\logs\ui-qml-migration-20260925\build.log')-$env:VEYRA_OUT = 'E:\项目\Veyra\build\ui-qml-migration-20260925'-$env:VEYRA_TMP = 'E:\项目\Veyra\tmp\ui-qml-migration-20260925'-$env:VEYRA_LOG = $Log+[CmdletBinding()]+param(+ [Parameter(Mandatory = $true)][ValidateSet('qml')][string]$UiTarget,+ [ValidateSet('veyra_qml_ui', 'veyra_qml_data_tests', 'veyra_qml_easing_tests', 'veyra_qml_quick_tests')][string[]]$Targets = @(),+ [string]$Out = '',+ [string]$Log = '',+ [string]$Temp = ''+)++# A migration build is explicitly one UI contract. Reusing a cache configured+# for the other contract can produce a valid executable with the wrong entry.+$projectDirectoryName = [string]([char]0x9879) + [string]([char]0x76ee)+$artifactRoot = Join-Path (Join-Path 'E:\' $projectDirectoryName) 'Veyra'+$runId = [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssfffZ') + '-' + ([Guid]::NewGuid().ToString('N').Substring(0, 8))+if ([string]::IsNullOrWhiteSpace($Out)) {+ $Out = Join-Path $artifactRoot ("build\ui-qml-migration-20260927\" + $runId + "\" + $UiTarget)+}+if ([string]::IsNullOrWhiteSpace($Log)) {+ $Log = Join-Path $artifactRoot ("logs\ui-qml-migration-20260927\" + $runId + "\build-" + $UiTarget + '.log')+}+if ([string]::IsNullOrWhiteSpace($Temp)) {+ $Temp = Join-Path $artifactRoot ("tmp\ui-qml-migration-20260927\" + $runId + "\" + $UiTarget)+}+$outFull = [IO.Path]::GetFullPath($Out)+$logFull = [IO.Path]::GetFullPath($Log)+$tempFull = [IO.Path]::GetFullPath($Temp)+$rootPrefix = [IO.Path]::GetFullPath($artifactRoot).TrimEnd('\') + '\'+foreach ($path in @($outFull, $logFull, $tempFull)) {+ if (-not $path.StartsWith($rootPrefix, [StringComparison]::OrdinalIgnoreCase)) {+ throw "Build output, logs and TEMP must be under ${artifactRoot}: $path"+ }+}++function Assert-NewDirectory([string]$Path, [string]$Label) {+ if (Test-Path -LiteralPath $Path) {+ if (-not (Test-Path -LiteralPath $Path -PathType Container)) { throw "$Label is not a directory: $Path" }+ $existing = @(Get-ChildItem -LiteralPath $Path -Force)+ if ($existing.Count -gt 0) { throw "$Label must be a new empty directory; refusing to reuse: $Path" }+ } else {+ [IO.Directory]::CreateDirectory($Path) | Out-Null+ }+}++Assert-NewDirectory $outFull 'Build output'+[IO.Directory]::CreateDirectory((Split-Path -Parent $logFull)) | Out-Null+if (Test-Path -LiteralPath $logFull) { throw "Build log already exists; refusing to overwrite: $logFull" }+[IO.Directory]::CreateDirectory((Split-Path -Parent $tempFull)) | Out-Null+Assert-NewDirectory $tempFull 'Build TEMP'+[IO.Directory]::CreateDirectory((Split-Path -Parent $logFull)) | Out-Null+$env:VEYRA_OUT = $outFull+$env:VEYRA_TMP = $tempFull+$env:TEMP = $tempFull+$env:TMP = $tempFull+$env:VEYRA_UI_TARGET = $UiTarget+$env:VEYRA_QT_DIR = Join-Path $artifactRoot 'deps\qt\6.8.3\msvc2022_64'$cmd = Join-Path $PSScriptRoot 'build-ui-migration.cmd'-& cmd.exe /c "`"$cmd`" $($Targets -join ' ') > `"%VEYRA_LOG%`" 2>&1"+$targetArgs = if ($Targets.Count -gt 0) { ' ' + ($Targets -join ' ') } else { '' }+& cmd.exe /d /c "`"$cmd`"$targetArgs > `"$logFull`" 2>&1"$code = $LASTEXITCODE-Get-Content -LiteralPath $Log -Tail 25 -Encoding utf8+if (Test-Path -LiteralPath $logFull) { Get-Content -LiteralPath $logFull -Tail 25 -Encoding utf8 }"exit=$code"exit $codediff --git a/scripts/compare-ui-migration-perf.ps1 b/scripts/compare-ui-migration-perf.ps1new file mode 100644index 00000000..5df34a9c--- /dev/null+++ b/scripts/compare-ui-migration-perf.ps1@@ -0,0 +1,54 @@+# Read-only comparison against the frozen UI migration performance baseline.+# Do not overwrite/re-record the baseline or relax limits to make a run pass.+param([Parameter(Mandatory=$true)][string]$Results,+ [Parameter(Mandatory=$true)][string]$Baseline,+ [Parameter(Mandatory=$true)][string]$Report)+$ErrorActionPreference = 'Stop'+$cases = 'nr-1080','nr-fg-1080','nr-fg-4k','plain-1080'+$limits = [ordered]@{ graphSubmitP95Ms = 10.0; gpuReadyP95Ms = 5.0 }+function IsNumber($value) {+ return ($null -ne $value -and $value -is [ValueType] -and $value -isnot [bool] -and+ -not [double]::IsNaN([double]$value) -and -not [double]::IsInfinity([double]$value))+}+try {+ $resultsPath = (Resolve-Path -LiteralPath $Results).Path+ $baselinePath = (Resolve-Path -LiteralPath $Baseline).Path+ $reportPath = [IO.Path]::GetFullPath($Report)+ if ($reportPath -eq $baselinePath -or $reportPath -eq $resultsPath) { throw 'Report must not overwrite input evidence' }+ $now = Get-Content -LiteralPath $resultsPath -Raw | ConvertFrom-Json+ $base = Get-Content -LiteralPath $baselinePath -Raw | ConvertFrom-Json+ $rows = @()+ foreach ($case in $cases) {+ $current = $now.$case; $previous = $base.$case+ $errors = @(); $metrics = @()+ foreach ($pair in @(@('current',$current),@('baseline',$previous))) {+ $label = $pair[0]; $row = $pair[1]+ if ($null -eq $row -or $row -is [string]) { $errors += "$label missing or failed case"; continue }+ if (-not (IsNumber $row.exit) -or $row.exit -ne 0) { $errors += "$label process did not exit successfully" }+ if (-not (IsNumber $row.samples) -or $row.samples -lt 1) { $errors += "$label has no timing samples" }+ if (-not (IsNumber $row.realPresented) -or $row.realPresented -lt 1) { $errors += "$label has no presented source frames" }+ }+ foreach ($field in $limits.Keys) {+ $a = $current.$field; $b = $previous.$field+ if (-not (IsNumber $a) -or -not (IsNumber $b) -or $a -le 0 -or $b -le 0) {+ $errors += "$field missing or invalid timing"; continue+ }+ $pct = 100.0 * ([double]$a / [double]$b - 1.0)+ $pass = [double]$a -le ([double]$b * (1.0 + $limits[$field] / 100.0) + 1e-12)+ $metrics += [pscustomobject]@{ field=$field; baseline=$b; current=$a; changePct=$pct; limitPct=$limits[$field]; passed=$pass }+ }+ $passed = $errors.Count -eq 0 -and @($metrics | Where-Object { -not $_.passed }).Count -eq 0+ $rows += [pscustomobject]@{ name=$case; passed=$passed; errors=$errors; metrics=$metrics }+ $status = if ($passed) { 'PASS' } else { 'FAIL' }+ Write-Output ("$status $case : " + (($metrics | ForEach-Object { '{0} {1:F2}% (limit {2:F0}%)' -f $_.field,$_.changePct,$_.limitPct }) -join ' | '))+ foreach ($message in $errors) { Write-Output " $message" }+ }+ $passed = @($rows | Where-Object { -not $_.passed }).Count -eq 0+ [ordered]@{ passed=$passed; results=$resultsPath; baseline=$baselinePath; cases=$rows } |+ ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $reportPath -Encoding utf8+ if (-not $passed) { exit 1 }+} catch {+ [Console]::Error.WriteLine($_.Exception.Message)+ exit 2+}+exit 0diff --git a/scripts/gates/delivery.ps1 b/scripts/gates/delivery.ps1index f39c7d18..01949174 100644--- a/scripts/gates/delivery.ps1+++ b/scripts/gates/delivery.ps1@@ -1,5 +1,7 @@[CmdletBinding()]-param([Parameter(Mandatory=$true)][string]$Root,[switch]$VisiblePlayer,[string]$BuildDirectory,[string]$PlayerExe,[switch]$PortablePlayer,+param([Parameter(Mandatory=$true)][string]$Root,[switch]$VisiblePlayer,[Parameter(Mandatory=$true)][string]$BuildDirectory,+ [Parameter(Mandatory=$true)][string]$PlayerExe,+ [Parameter(Mandatory=$true)][ValidateSet('legacy')][string]$UiTarget,[switch]$PortablePlayer,[Parameter(Mandatory=$true)][string]$OutputDirectory,[Parameter(Mandatory=$true)][string]$FixtureRoot)# User-authorized local software acceptance, <=300s for this entire suite.@@ -15,13 +17,15 @@ $timer=[Diagnostics.Stopwatch]::StartNew()$run=[Guid]::NewGuid().ToString('N')$dir=Join-Path ([IO.Path]::GetFullPath($OutputDirectory)) $run[IO.Directory]::CreateDirectory($dir)|Out-Null+$entryScript=Join-Path $Root 'scripts/acceptance/resolve-ui-migration-entry.ps1'+$null=& $entryScript -Root $Root -UiTarget $UiTarget -PlayerExe $PlayerExe -BuildDirectory $BuildDirectory -StagingDirectory (Split-Path -Parent $PlayerExe) -ArtifactDirectory $dir -OutputFile (Join-Path $dir 'entry.json')+if($UiTarget -ne 'legacy'){throw 'delivery.ps1 is legacy-only. QML uses the separate qml-ui-smoke contract.'}# The quality probe reads its arguments from the UTF-16 command line, so the# absolute output directory works even when it is on another drive or has# Unicode names (a relative path cannot cross from the repo drive to E:).$qualityDir=$dir$bin=Join-Path $Root 'out/build/x64-release'if($BuildDirectory){$bin=(Resolve-Path -LiteralPath $BuildDirectory).Path}-if(-not $PlayerExe){$PlayerExe=Join-Path $bin 'veyra.exe'}$PlayerExe=(Resolve-Path -LiteralPath $PlayerExe).Path$checks=[Collections.Generic.List[object]]::new()function Check([string]$Name,[bool]$Passed,[string]$Detail){$checks.Add([pscustomobject]@{name=$Name;passed=$Passed;detail=$Detail});if(-not $Passed){throw "$Name : $Detail"}}diff --git a/scripts/package-portable.ps1 b/scripts/package-portable.ps1index c27fd5f6..2641f0a0 100644--- a/scripts/package-portable.ps1+++ b/scripts/package-portable.ps1@@ -44,14 +44,19 @@ if (-not $appVersion.ProductVersion.StartsWith($Version)) { throw "EXE version $# Publisher audit only. The application permits users to replace these DLLs.$runtimeFiles = @(@{ Name='nvngx_dlss.dll'; Folder='runtime/experimental'; Source='runtime_local/nvidia/nvngx_dlss.dll'; Hash='BE6E434A94CA32499515EB62CA0E6C274526055D568D0426E4C652DCDFB6EE6E'; Category='official-dlss-sdk-310.7.0-rel'; Experimental=$false },- @{ Name='nvngx_dlssg.dll'; Folder='runtime/experimental'; Source='runtime_local/nvidia/nvngx_dlssg.dll'; Hash='135EAF0733C1E37381A8C28ABCF7A862404A54132B81787C04E35D09EFC5E36F'; Category='pinned-dlss-sdk-310.7.0-rel'; Experimental=$true },- @{ Name='nvngx_dlssnr.dll'; Folder='runtime/experimental'; Source='runtime_local/nvidia/nvngx_dlssnr.dll'; Hash='E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E'; Category='user-provided-pinned-experimental-runtime'; Experimental=$true },+ @{ Name='nvngx_dlssg.dll'; Folder='runtime/experimental'; Source='runtime_local/nvidia/nvngx_dlssg.dll'; Hash='FF6E90EB78B827927DFF5B4ECC6B1C870C2E9BCA29ED9F48C7D348CC9E170B82'; Signature='Valid'; Size=7460976; Version='310.9.1.0'; Category='official-dlss-sdk-310.9.1-rel'; Experimental=$true },+ @{ Name='nvngx_dlssnr.dll'; Folder='runtime/experimental'; Source='runtime_local/nvidia/nvngx_dlssnr.dll'; Hash='F95FEB54137EA11979F9B4EC4F00AFD84B5C98A5624D3388FBF6A87714A39FCC'; Signature='HashMismatch'; Size=165840496; Version='310.8.3.0'; Category='user-approved-community-Lecram-310.8.3-RTX50-runtime'; Experimental=$true },@{ Name='nvngx_dlssnr.dll'; Folder='runtime/experimental/nr-community'; Source='runtime_local/nvidia/nr-community/nvngx_dlssnr.dll'; Hash='984BEE0F775C277D5829B8FD6775D53A7B0F75396C852B3AAF06A18375F81014'; Signature='HashMismatch'; Size=165840496; Version='310.8.0.0'; Category='user-provided-community-modified-RTX40-RTX50-runtime'; Experimental=$true },@{ Name='nvngx_vsr.dll'; Folder='runtime/experimental'; Source='runtime_local/nvidia/nvngx_vsr.dll'; Hash='C3D88EEA5FF7A548EDEFA66414CF6E77464D0947277C904F324DD23ABF58A1ED'; Category='official-rtx-video-sdk-1.1.0'; Experimental=$false },@{ Name='libxell.dll'; Folder='runtime_local/intel/experimental'; Source='runtime_local/intel/experimental/libxell.dll'; Hash='D2030DCD694FDA8F2EC7E044B13E6DB8F0B56D4BA9113A5EFAD334E3F3DED8C7'; Category='official-intel-xess-sdk-3.0.2'; Experimental=$true },@{ Name='libxess_fg.dll'; Folder='runtime_local/intel/experimental'; Source='runtime_local/intel/experimental/libxess_fg.dll'; Hash='EC5E0C65E075570C6EDE72618BB666D0BE0C2E10B2EA9762C0FE8CB8E375AB27'; Category='official-intel-xess-sdk-3.0.2'; Experimental=$true })if ([version]$Version -ge [version]'1.3.1') {+ if ([version]$Version -ge [version]'2.0.0') {+ # New candidates ship exactly two NR versions. Historical 1.x manifests+ # keep their original identities; the retired40 binary is not recopied.+ $runtimeFiles = @($runtimeFiles | Where-Object { $_.Folder -ne 'runtime/experimental/nr-community' })+ }# AMD FidelityFX SDK 2.3.0 runtime (MIT licensed, AMD-signed). Needed for the# FSR frame-generation and FSR upscaling paths; loaded from runtime_local/amd/fidelityfx.$runtimeFiles += @(@@ -61,7 +66,12 @@ if ([version]$Version -ge [version]'1.3.1') {)}if ([version]$Version -ge [version]'1.1.1') {- $runtimeFiles += @{ Name='nvngx_dlssnr.dll'; Folder='runtime/experimental/nr-ampere'; Source='runtime_local/nvidia/nr-ampere/nvngx_dlssnr.dll'; Hash='DCC0DC2414AEDEC4A8E084647070383BE068554042587180C20C784D4772D36F'; Signature='HashMismatch'; Size=165840496; Version='310.8.0.0'; Category='user-provided-NeuralScreen-1.8.2-modified-RTX30-experimental-runtime'; Experimental=$true }+ if ([version]$Version -ge [version]'2.0.0') {+ # SF-v2 is the RTX20-50 compatible choice; the disk slot name is historical.+ $runtimeFiles += @{ Name='nvngx_dlssnr.dll'; Folder='runtime/experimental/nr-ampere'; Source='runtime_local/nvidia/nr-ampere/nvngx_dlssnr.dll'; Hash='6EB209E764F39872625DEBD6ABAF45E2BB6322F6F270F781F70C059AE30B3927'; Signature='NotSigned'; Size=165830144; Version='310.8.2.0'; Category='user-approved-community-SF-v2-310.8.2-RTX20-RTX50-compatible-runtime'; Experimental=$true }+ } else {+ $runtimeFiles += @{ Name='nvngx_dlssnr.dll'; Folder='runtime/experimental/nr-ampere'; Source='runtime_local/nvidia/nr-ampere/nvngx_dlssnr.dll'; Hash='DCC0DC2414AEDEC4A8E084647070383BE068554042587180C20C784D4772D36F'; Signature='HashMismatch'; Size=165840496; Version='310.8.0.0'; Category='user-provided-NeuralScreen-1.8.2-modified-RTX30-experimental-runtime'; Experimental=$true }+ }}if ($LocalVideoHdr -or [version]$Version -ge [version]'1.4.2') {if ($LocalVideoHdr -and -not $Label) { throw 'Local HDR package requires an explicit test label.' }@@ -71,6 +81,22 @@ function Runtime-Source($Item) {if ([IO.Path]::IsPathRooted($Item.Source)) { return $Item.Source }return Join-Path $resolvedDependencies $Item.Source}+if ([version]$Version -ge [version]'2.0.0') {+ # DLSS-G 310.9.1 optimized network kernels (DLSSG-Transfusion 1.4.5.3, see+ # THIRD_PARTY_NOTICES.md). Runtime data loaded from disk, not linked in.+ $kernelSource = Join-Path $resolvedDependencies 'third_party_local/nvidia/dlssg-transfusion-kernels-1.4.5.3'+ if (-not (Test-Path -LiteralPath $kernelSource -PathType Container)) { throw "DLSS-G optimized kernel set missing: $kernelSource" }+ foreach ($kernel in (Get-ChildItem -LiteralPath $kernelSource -Filter *.ptx | Sort-Object Name)) {+ $runtimeFiles += @{+ Name = $kernel.Name; Folder = 'runtime/experimental/dlssg-kernels'+ Source = "third_party_local/nvidia/dlssg-transfusion-kernels-1.4.5.3/$($kernel.Name)"+ Hash = (Get-FileHash -LiteralPath $kernel.FullName -Algorithm SHA256).Hash+ Signature = 'NotSigned'+ Category = 'community-DLSSG-Transfusion-1.4.5.3-sm86-optimized-kernels'+ Experimental = $true+ }+ }+}$records = foreach ($item in $runtimeFiles) {$source = Runtime-Source $item$file = Get-Item -LiteralPath $sourcediff --git a/scripts/perf-ui-migration.ps1 b/scripts/perf-ui-migration.ps1index 2277281e..c54c0d7a 100644--- a/scripts/perf-ui-migration.ps1+++ b/scripts/perf-ui-migration.ps1@@ -1,15 +1,43 @@-# Performance / latency baseline for the UI migration (S0.4 and every engine step).-# Runs the real player headless on fixed clips and averages the [player-timing]-# P95 fields plus the final [frame-flow] counters. Compare two runs with -Compare.-param([string]$App = 'E:\项目\Veyra\tests\ui-qml-migration-20260925\app',- [string]$Fixtures = 'C:\Users\123\Desktop\Veyra DLSS Video Player\loop\local\fixed_clips',- [string]$Out = 'E:\项目\Veyra\logs\ui-qml-migration-20260925\perf',- [string]$Save = '',- [string]$Compare = '',- [int]$Seconds = 8)-$env:TEMP = 'E:\项目\Veyra\tmp\ui-qml-migration-20260925'; $env:TMP = $env:TEMP-New-Item -ItemType Directory -Force $Out | Out-Null-$exe = Join-Path $App 'veyra.exe'+# Performance / latency baseline for the shared legacy engine path. The old+# command-line switches below are not implemented by the QML executable.+# Callers must name the executable and UI contract explicitly; a staging folder+# containing both front ends is otherwise ambiguous.+[CmdletBinding()]+param(+ [Parameter(Mandatory = $true)][ValidateSet('legacy')][string]$UiTarget,+ [Parameter(Mandatory = $true)][string]$PlayerExe,+ [string]$App = '',+ [Parameter(Mandatory = $true)][string]$BuildDirectory,+ [Parameter(Mandatory = $true)][string]$StagingDirectory,+ [string]$Fixtures = 'C:\Users\123\Desktop\Veyra DLSS Video Player\loop\local\fixed_clips',+ [string]$Out = 'E:\项目\Veyra\logs\ui-qml-migration-20260925\perf',+ [string]$Save = '',+ [string]$Compare = '',+ [int]$Seconds = 8+)+$ErrorActionPreference = 'Stop'+$env:TEMP = 'E:\项目\Veyra\tmp\ui-qml-migration-20260925'+$env:TMP = $env:TEMP+$root = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..\..')).Path+$outPath = [IO.Path]::GetFullPath($Out)+$entryScript = Join-Path $PSScriptRoot 'acceptance\resolve-ui-migration-entry.ps1'+$entryArgs = @(+ '-Root', $root, '-UiTarget', $UiTarget, '-PlayerExe', $PlayerExe,+ '-ArtifactDirectory', $outPath,+ '-OutputFile', (Join-Path $outPath 'entry.json')+)+$entryArgs += @('-BuildDirectory', $BuildDirectory, '-StagingDirectory', $StagingDirectory)+$null = & $entryScript @entryArgs+New-Item -ItemType Directory -Force $outPath | Out-Null+$exe = (Resolve-Path -LiteralPath $PlayerExe).Path+$workingDirectory = if ($App) { (Resolve-Path -LiteralPath $App).Path } else { Split-Path -Parent $exe }+$fixturePaths = @(+ (Join-Path $Fixtures 'test_av_1080p.mp4'),+ (Join-Path $Fixtures 'test_av_4k.mp4')+)+foreach ($fixture in $fixturePaths) {+ if (-not (Test-Path -LiteralPath $fixture -PathType Leaf)) { throw "Missing performance fixture: $fixture" }+}$cases = [ordered]@{'nr-1080' = @((Join-Path $Fixtures 'test_av_1080p.mp4'), '--nr', '--realtime')'nr-fg-1080' = @((Join-Path $Fixtures 'test_av_1080p.mp4'), '--nr', '--realtime', '--fg')@@ -18,14 +46,41 @@ $cases = [ordered]@{}$fields = 'decodeP95Ms','graphSubmitP95Ms','gpuReadyP95Ms','presentP95Ms','gpuColorP95Ms','gpuSrP95Ms','gpuFlowP95Ms','gpuNrP95Ms','gpuResidualP95Ms','gpuFgBatchP95Ms','gpuBlitP95Ms'$summary = [ordered]@{}+$failures = [Collections.Generic.List[string]]::new()foreach ($name in $cases.Keys) {- $log = Join-Path $Out "$name.log"- $argv = @($cases[$name] | ForEach-Object { if ($_ -like '*\*') { "`"$_`"" } else { $_ } }) + @('--smoke-seconds', $Seconds)- $p = Start-Process -FilePath $exe -ArgumentList $argv -WorkingDirectory $App -PassThru -WindowStyle Minimized -RedirectStandardOutput $log -RedirectStandardError "$log.err"- $null = $p.Handle- if (-not $p.WaitForExit(($Seconds + 40) * 1000)) { $p.Kill(); $summary[$name] = 'timeout'; continue }- $lines = Get-Content -LiteralPath $log | Where-Object { $_ -match '\[player-timing\]' } | Select-Object -Skip 1+ $log = Join-Path $outPath "$name.log"+ $argv = @($cases[$name]) + @('--smoke-seconds', $Seconds)+ $psi = [Diagnostics.ProcessStartInfo]::new()+ $psi.FileName = $exe+ $psi.WorkingDirectory = $workingDirectory+ $psi.UseShellExecute = $false+ $psi.CreateNoWindow = $true+ $psi.RedirectStandardOutput = $true+ $psi.RedirectStandardError = $true+ if ($psi.PSObject.Properties.Name -contains 'ArgumentList') {+ foreach ($argument in $argv) { [void]$psi.ArgumentList.Add([string]$argument) }+ } else {+ $quote = { param([string]$value) '"' + $value.Replace('"', '\"') + '"' }+ $psi.Arguments = (($argv | ForEach-Object { & $quote ([string]$_) }) -join ' ')+ }+ $p = [Diagnostics.Process]::Start($psi)+ $stdoutTask = $p.StandardOutput.ReadToEndAsync()+ $stderrTask = $p.StandardError.ReadToEndAsync()+ $finished = $p.WaitForExit(($Seconds + 40) * 1000)+ if (-not $finished) {+ try { $p.Kill() } catch { }+ $stdoutTask.GetAwaiter().GetResult() | Set-Content -LiteralPath $log -Encoding UTF8+ $stderrTask.GetAwaiter().GetResult() | Set-Content -LiteralPath "$log.err" -Encoding UTF8+ $summary[$name] = 'timeout'+ $failures.Add($name)+ continue+ }+ $p.WaitForExit()+ $stdoutTask.GetAwaiter().GetResult() | Set-Content -LiteralPath $log -Encoding UTF8+ $stderrTask.GetAwaiter().GetResult() | Set-Content -LiteralPath "$log.err" -Encoding UTF8+ $lines = @(Get-Content -LiteralPath $log | Where-Object { $_ -match '\[player-timing\]' } | Select-Object -Skip 1)$row = [ordered]@{ exit = $p.ExitCode; samples = @($lines).Count }+ if ($p.ExitCode -ne 0 -or $row.samples -eq 0) { $failures.Add($name) }foreach ($f in $fields) {$vals = @($lines | ForEach-Object { if ($_ -match "$f=([0-9.]+)") { [double]$Matches[1] } })$row[$f] = if ($vals.Count) { [math]::Round(($vals | Measure-Object -Average).Average, 3) } else { $null }@@ -37,6 +92,8 @@ foreach ($name in $cases.Keys) {$summary[$name] = $row}$json = $summary | ConvertTo-Json -Depth 4+$resultsPath = Join-Path $outPath 'results.json'+$json | Set-Content -LiteralPath $resultsPath -Encoding utf8if ($Save) { $json | Set-Content -LiteralPath $Save -Encoding utf8; "saved $Save" }if ($Compare) {$base = Get-Content -LiteralPath $Compare -Raw | ConvertFrom-Json@@ -48,4 +105,8 @@ if ($Compare) {}"$name : " + ($parts -join ' | ')}+ & (Join-Path $PSScriptRoot 'compare-ui-migration-perf.ps1') -Results $resultsPath -Baseline $Compare -Report (Join-Path $outPath 'gate.json')+ if ($failures.Count -gt 0) { exit 1 }+ exit $LASTEXITCODE} else { $json }+if ($failures.Count -gt 0) { Write-Error ("Performance run failed: " + ($failures -join ', ')); exit 1 }diff --git a/scripts/run-unit-ui-migration.ps1 b/scripts/run-unit-ui-migration.ps1index 014bf3b5..0a6b3466 100644--- a/scripts/run-unit-ui-migration.ps1+++ b/scripts/run-unit-ui-migration.ps1@@ -1,39 +1,138 @@-# Runs the unit/contract test executables of the staged app and writes a JSON summary.-# Tests that need hardware or media (capture, remote play, endpoint audio) are skipped:-# they are listed in $skip with the reason, never reported as passed.-param([string]$App = 'E:\项目\Veyra\tests\ui-qml-migration-20260925\app',- [string]$Out = 'E:\项目\Veyra\logs\ui-qml-migration-20260925\unit',- [int]$TimeoutSeconds = 120)-$ErrorActionPreference = 'Continue'-New-Item -ItemType Directory -Force $Out | Out-Null-$env:TEMP = 'E:\项目\Veyra\tmp\ui-qml-migration-20260925'; $env:TMP = $env:TEMP-# Several contract tests open a fixture through a path relative to the CWD-# (loop/local/fixed_clips/corpus/...). They run from the staged app directory,-# so stage the fixture tree beside the executables first; otherwise they report-# "corpus missing" and look like a regression they are not.-$fixtureRoot = Join-Path $App 'loop'-if (-not (Test-Path -LiteralPath (Join-Path $fixtureRoot 'localixed_clips\corpus'))) {- $sourceRoot = Join-Path (Split-Path -Parent $PSScriptRoot) 'loop'- if (Test-Path -LiteralPath $sourceRoot) { Copy-Item -LiteralPath $sourceRoot -Destination $fixtureRoot -Recurse -Force }-}-# name -> reason. Anything not listed and matching *_tests.exe runs with no arguments.-$skip = @{- 'veyra_capture_tests.exe' = 'needs a capture device'- 'veyra_wasapi_input_tests.exe' = 'needs an explicit recording endpoint'- 'veyra_capture_latency_tests.exe' = 'needs a capture device'-}-$results = @()-Get-ChildItem -LiteralPath $App -Filter 'veyra_*_tests.exe' | Sort-Object Name | ForEach-Object {- $name = $_.Name- if ($skip.ContainsKey($name)) { $results += [pscustomobject]@{ name = $name; status = 'skipped'; exit = $null; seconds = 0; reason = $skip[$name] }; return }- $log = Join-Path $Out ($_.BaseName + '.log')+[CmdletBinding()]+param(+ [Parameter(Mandatory = $true)][string]$Root,+ [Parameter(Mandatory = $true)][ValidateSet('qml')][string]$UiTarget,+ [Parameter(Mandatory = $true)][string]$PlayerExe,+ [Parameter(Mandatory = $true)][string]$BuildDirectory,+ [Parameter(Mandatory = $true)][string]$StagingDirectory,+ [string]$App = '',+ [string]$Out = '',+ [string]$TempDirectory = '',+ [ValidateRange(1, 300)][int]$TimeoutSeconds = 120+)++# Unit/contract results are real process results. Hardware-dependent tests are+# explicitly skipped and never counted as passes; any executable failure makes+# this script fail so unattended mode cannot advance on a partial run.+$ErrorActionPreference = 'Stop'+$rootPath = (Resolve-Path -LiteralPath $Root -ErrorAction Stop).Path+$projectDirectoryName = [string]([char]0x9879) + [string]([char]0x76ee)+$artifactRoot = [IO.Path]::GetFullPath((Join-Path (Join-Path 'E:\' $projectDirectoryName) 'Veyra')).TrimEnd('\') + '\'+$runId = [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssfffZ') + '-' + ([Guid]::NewGuid().ToString('N').Substring(0, 8))+if ([string]::IsNullOrWhiteSpace($Out)) {+ $Out = Join-Path $artifactRoot ("logs\ui-qml-migration-20260927\" + $runId + '\unit')+}+if ([string]::IsNullOrWhiteSpace($TempDirectory)) {+ $TempDirectory = Join-Path $artifactRoot ("tmp\ui-qml-migration-20260927\" + $runId + '\unit')+}+$outPath = [IO.Path]::GetFullPath($Out)+foreach ($path in @($outPath, [IO.Path]::GetFullPath($TempDirectory))) {+ if (-not $path.StartsWith($artifactRoot, [StringComparison]::OrdinalIgnoreCase)) {+ throw "Unit output and TEMP must be under E:\项目\Veyra: $path"+ }+}+[IO.Directory]::CreateDirectory((Split-Path -Parent $outPath)) | Out-Null+if (Test-Path -LiteralPath $outPath) {+ if (-not (Test-Path -LiteralPath $outPath -PathType Container)) { throw "Unit output is not a directory: $outPath" }+ if (@(Get-ChildItem -LiteralPath $outPath -Force).Count -gt 0) { throw "Unit output must be a new empty directory; refusing to reuse: $outPath" }+} else {+ [IO.Directory]::CreateDirectory($outPath) | Out-Null+}+[IO.Directory]::CreateDirectory($outPath) | Out-Null+$tempPath = [IO.Path]::GetFullPath($TempDirectory)+if (Test-Path -LiteralPath $tempPath) {+ if (-not (Test-Path -LiteralPath $tempPath -PathType Container)) { throw "Unit TEMP is not a directory: $tempPath" }+ if (@(Get-ChildItem -LiteralPath $tempPath -Force).Count -gt 0) { throw "Unit TEMP must be a new empty directory; refusing to reuse: $tempPath" }+} else {+ [IO.Directory]::CreateDirectory($tempPath) | Out-Null+}+$env:TEMP = $tempPath+$env:TMP = $env:TEMP+# Unit tests run unattended and must not depend on an interactive desktop. The+# QML test binaries still use the staged Qt platform/plugin and fail normally+# if that deployment is incomplete.+$env:QT_QPA_PLATFORM = 'offscreen'+$env:QT_FORCE_STDERR_LOGGING = '1'+$env:QML_DISK_CACHE_PATH = Join-Path $tempPath 'qmlcache'++$entryScript = Join-Path $rootPath 'scripts\acceptance\resolve-ui-migration-entry.ps1'+$entryArgs = @{+ Root = $rootPath; UiTarget = $UiTarget; PlayerExe = $PlayerExe+ BuildDirectory = $BuildDirectory; StagingDirectory = $StagingDirectory+ ArtifactDirectory = $outPath; OutputFile = (Join-Path $outPath 'entry.json')+}+$null = & $entryScript @entryArgs+$stagingPath = (Resolve-Path -LiteralPath $StagingDirectory -ErrorAction Stop).Path+$appPath = if ([string]::IsNullOrWhiteSpace($App)) { $stagingPath } else { (Resolve-Path -LiteralPath $App -ErrorAction Stop).Path }+if (-not (Test-Path -LiteralPath $appPath -PathType Container)) { throw "App is not a directory: $appPath" }+if (-not $appPath.Equals($stagingPath, [StringComparison]::OrdinalIgnoreCase)) {+ throw "QML unit tests must run from the QML staging directory passed to -StagingDirectory: staging=$stagingPath app=$appPath"+}+if (Test-Path -LiteralPath (Join-Path $appPath 'veyra.exe') -PathType Leaf) {+ throw "QML staging contains the legacy entry veyra.exe: $appPath"+}++$requiredTests = @('veyra_qml_data_tests.exe', 'veyra_qml_easing_tests.exe', 'veyra_qml_quick_tests.exe')+$testExecutables = foreach ($name in $requiredTests) {+ $candidate = Join-Path $appPath $name+ if (-not (Test-Path -LiteralPath $candidate -PathType Leaf)) { throw "Missing QML-only test executable: $candidate" }+ Get-Item -LiteralPath $candidate+}+$results = [Collections.Generic.List[object]]::new()++function Quote-Argument([string]$Value) { return '"' + $Value.Replace('"', '\"') + '"' }+foreach ($test in $testExecutables) {+ $name = $test.Name+ $log = Join-Path $outPath ($test.BaseName + '.log')+ $errLog = $log + '.err'+ $arguments = @()+ if ($name -eq 'veyra_qml_data_tests.exe') {+ $scratch = Join-Path $outPath 'qml-data-scratch'+ # The test creates this directory itself and rejects an existing one.+ $arguments = @($scratch)+ }+ $psi = [Diagnostics.ProcessStartInfo]::new()+ $psi.FileName = $test.FullName+ $psi.WorkingDirectory = $appPath+ $psi.UseShellExecute = $false+ $psi.CreateNoWindow = $true+ $psi.RedirectStandardOutput = $true+ $psi.RedirectStandardError = $true+ if ($psi.PSObject.Properties.Name -contains 'ArgumentList') {+ foreach ($argument in $arguments) { [void]$psi.ArgumentList.Add([string]$argument) }+ } elseif ($arguments.Count -gt 0) {+ $psi.Arguments = ($arguments | ForEach-Object { Quote-Argument ([string]$_) }) -join ' '+ }$sw = [Diagnostics.Stopwatch]::StartNew()- $p = Start-Process -FilePath $_.FullName -WorkingDirectory $App -PassThru -WindowStyle Hidden -RedirectStandardOutput $log -RedirectStandardError ($log + '.err')- $null = $p.Handle # cache the handle so ExitCode is readable after exit- if (-not $p.WaitForExit($TimeoutSeconds * 1000)) { $p.Kill(); $status = 'timeout'; $code = $null }- else { $p.WaitForExit(); $code = $p.ExitCode; $status = if ($code -eq 0) { 'pass' } else { 'fail' } }- $results += [pscustomobject]@{ name = $name; status = $status; exit = $code; seconds = [math]::Round($sw.Elapsed.TotalSeconds, 1); reason = '' }+ $process = [Diagnostics.Process]::Start($psi)+ $stdoutTask = $process.StandardOutput.ReadToEndAsync()+ $stderrTask = $process.StandardError.ReadToEndAsync()+ $finished = $process.WaitForExit($TimeoutSeconds * 1000)+ if (-not $finished) {+ try { $process.Kill() } catch { }+ $stdoutTask.GetAwaiter().GetResult() | Set-Content -LiteralPath $log -Encoding UTF8+ $stderrTask.GetAwaiter().GetResult() | Set-Content -LiteralPath $errLog -Encoding UTF8+ $results.Add([ordered]@{ name = $name; status = 'timeout'; exit = $null; seconds = [math]::Round($sw.Elapsed.TotalSeconds, 1); reason = 'timeout' })+ continue+ }+ $process.WaitForExit()+ $stdoutTask.GetAwaiter().GetResult() | Set-Content -LiteralPath $log -Encoding UTF8+ $stderrTask.GetAwaiter().GetResult() | Set-Content -LiteralPath $errLog -Encoding UTF8+ $code = $process.ExitCode+ $results.Add([ordered]@{ name = $name; status = if ($code -eq 0) { 'pass' } else { 'fail' }; exit = $code; seconds = [math]::Round($sw.Elapsed.TotalSeconds, 1); reason = '' })+}++$summaryPath = Join-Path $outPath 'summary.json'+$summary = [ordered]@{+ schema = 'veyra.qml-only-unit-run.v1'+ uiTarget = $UiTarget+ stagingDirectory = $appPath+ results = $results+ failures = @($results | Where-Object { $_.status -in @('fail', 'timeout') }).Count}-$results | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $Out 'summary.json') -Encoding utf8+$summary | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $summaryPath -Encoding UTF8$results | Group-Object status | ForEach-Object { "{0}={1}" -f $_.Name, $_.Count }-$results | Where-Object { $_.status -in 'fail', 'timeout' } | ForEach-Object { "{0} {1} exit={2}" -f $_.status, $_.name, $_.exit }+$failed = @($results | Where-Object { $_.status -in @('fail', 'timeout') })+$failed | ForEach-Object { "{0} {1} exit={2}" -f $_.status, $_.name, $_.exit }+if ($failed.Count -gt 0) { exit 1 }+exit 0diff --git a/scripts/stage-runtime.ps1 b/scripts/stage-runtime.ps1index b2d42692..d6312d78 100644--- a/scripts/stage-runtime.ps1+++ b/scripts/stage-runtime.ps1@@ -3,9 +3,13 @@ param([Parameter(Mandatory = $true)][string]$Root)-# Stage the local NVIDIA DLSSNR runtime for Phase 0+ probes (Playbook 4.3/4.4).-# - Copies (never moves) the workspace-root nvngx_dlssnr.dll into-# runtime_local/nvidia/ after verifying its pinned identity.+# Stage the local DLSSNR runtime for Phase 0+ probes (Playbook 4.3/4.4).+# - Copies (never moves) the pinned default NR runtime into runtime_local/nvidia/+# after verifying its identity. Since 2026-09-29 (user decision) the default+# slot holds the community Lecram build 310.8.3.0 (RankFTW/rhi-repo+# dlssnr-310.8.Lecram): kernels rebuilt, weights unchanged, output measured+# byte-identical to NVIDIA 310.8.0.0 on RTX 5070 and ~2% cheaper. It carries+# NVIDIA's certificate over modified content, so Authenticode is HashMismatch.# - Writes runtime-manifest.json with the real size/hash and local-experimental# mode markers.# - Creates a persistent runtime_local/config/ngx-local.json identity exactly@@ -15,9 +19,9 @@ Set-StrictMode -Version Latest$ErrorActionPreference = "Stop"$expectedSize = [long]165840496-$expectedSha256 = "E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E"+$expectedSha256 = "F95FEB54137EA11979F9B4EC4F00AFD84B5C98A5624D3388FBF6A87714A39FCC"-$sourceDll = Join-Path $Root "nvngx_dlssnr.dll"+$sourceDll = Join-Path $Root "third_party_local\nvidia\dlssnr-310.8.Lecram\nvngx_dlssnr.dll"if (-not (Test-Path -LiteralPath $sourceDll -PathType Leaf)) {Write-Host "stage-runtime.ps1: source DLL missing: $sourceDll"exit 2@@ -34,7 +38,7 @@ if ($hash -ne $expectedSha256) {exit 3}$signature = Get-AuthenticodeSignature -LiteralPath $sourceDll-if ([string]$signature.Status -ne "Valid") {+if ([string]$signature.Status -ne "HashMismatch") {Write-Host ("stage-runtime.ps1: signature status {0}" -f [string]$signature.Status)exit 3}@@ -50,7 +54,7 @@ if (-not (Test-Path -LiteralPath $targetDll -PathType Leaf)) {else {$stagedHash = (Get-FileHash -LiteralPath $targetDll -Algorithm SHA256).Hash.ToUpperInvariant()if ($stagedHash -ne $expectedSha256) {- Write-Host "stage-runtime.ps1: staged DLL identity drifted; replacing from workspace root"+ Write-Host "stage-runtime.ps1: staged DLL identity drifted; replacing from the pinned Lecram source"Copy-Item -LiteralPath $sourceDll -Destination $targetDll -Force}else {@@ -77,12 +81,15 @@ if (Test-Path -LiteralPath $sdkRel -PathType Leaf) {}# Stage the official DLSSG runtime DLL from the SDK (Playbook section 14/3.2).-# Pinned identity from the Playbook lock: 7,519,856 bytes, 310.7.0.0,-# SHA256 135EAF0733C1E37381A8C28ABCF7A862404A54132B81787C04E35D09EFC5E36F,-# Authenticode Valid / NVIDIA Corporation. Only this known SDK path may be used.-$dlssgExpectedSize = [long]7519856-$dlssgExpectedSha256 = "135EAF0733C1E37381A8C28ABCF7A862404A54132B81787C04E35D09EFC5E36F"-$dlssgRel = Join-Path $Root "third_party_local\nvidia\DLSS_SDK_310.7.0\lib\Windows_x86_64\rel\nvngx_dlssg.dll"+# 2026-09-30 user decision: the frame-generation provider moves to the official+# NVIDIA DLSS SDK 310.9.1 build so the community 310.9.1 provider patches and+# their optimized kernels can be used. Identity is still pinned and verified:+# 7,460,976 bytes, 310.9.1.0, SHA256+# FF6E90EB78B827927DFF5B4ECC6B1C870C2E9BCA29ED9F48C7D348CC9E170B82, Authenticode+# Valid / NVIDIA Corporation. Only this SDK path may be used.+$dlssgExpectedSize = [long]7460976+$dlssgExpectedSha256 = "FF6E90EB78B827927DFF5B4ECC6B1C870C2E9BCA29ED9F48C7D348CC9E170B82"+$dlssgRel = Join-Path $Root "third_party_local\nvidia\DLSS_SDK_310.9.1\lib\Windows_x86_64\rel\nvngx_dlssg.dll"$dlssgDll = Join-Path $runtimeDir "nvngx_dlssg.dll"$dlssgPinned = $trueif (Test-Path -LiteralPath $dlssgRel -PathType Leaf) {@@ -109,6 +116,23 @@ else {Write-Host "stage-runtime.ps1: SDK nvngx_dlssg.dll not found; skipped (Phase 6 requires it)"}+# DLSS-G 310.9.1 optimized network kernels (DLSSG-Transfusion 1.4.5.3). They+# are user-replaceable runtime data loaded from disk at session start, never+# compiled into the executable. See THIRD_PARTY_NOTICES.md for provenance.+$kernelSource = Join-Path $Root "third_party_local\nvidia\dlssg-transfusion-kernels-1.4.5.3"+$kernelDir = Join-Path $runtimeDir "dlssg-kernels"+if (Test-Path -LiteralPath $kernelSource -PathType Container) {+ [IO.Directory]::CreateDirectory($kernelDir) | Out-Null+ $kernels = @(Get-ChildItem -LiteralPath $kernelSource -Filter *.ptx | Sort-Object Name)+ foreach ($kernel in $kernels) {+ Copy-Item -LiteralPath $kernel.FullName -Destination (Join-Path $kernelDir $kernel.Name) -Force+ }+ Write-Host ("stage-runtime.ps1: staged {0} DLSS-G optimized kernel file(s) into runtime_local/nvidia/dlssg-kernels" -f $kernels.Count)+}+else {+ Write-Host "stage-runtime.ps1: DLSSG-Transfusion kernel set not found; the provider optimization stays off"+}+$manifestPath = Join-Path $runtimeDir "runtime-manifest.json"$srManifestEntry = ""if (Test-Path -LiteralPath $srDll -PathType Leaf) {@@ -121,9 +145,9 @@ if (Test-Path -LiteralPath $srDll -PathType Leaf) {$dlssgManifestEntry = ""if (Test-Path -LiteralPath $dlssgDll -PathType Leaf) {$dlssgVersion = [string](Get-Item -LiteralPath $dlssgDll).VersionInfo.FileVersion- $dlssgManifestEntry = ",`n {`n `"name`": `"nvngx_dlssg.dll`",`n `"size`": $dlssgExpectedSize,`n `"sha256`": `"$dlssgExpectedSha256`",`n `"fileVersion`": `"$dlssgVersion`",`n `"authenticode`": `"Valid`",`n `"source`": `"official DLSS SDK 310.7.0 rel (pinned)`",`n `"redistributable`": false`n }"+ $dlssgManifestEntry = ",`n {`n `"name`": `"nvngx_dlssg.dll`",`n `"size`": $dlssgExpectedSize,`n `"sha256`": `"$dlssgExpectedSha256`",`n `"fileVersion`": `"$dlssgVersion`",`n `"authenticode`": `"Valid`",`n `"source`": `"official DLSS SDK 310.9.1 rel (pinned, 2026-09-30 user decision)`",`n `"redistributable`": false`n }"}-$manifestJson = "{`n `"schema`": 1,`n `"mode`": `"local-experimental-only`",`n `"files`": [`n {`n `"name`": `"nvngx_dlssnr.dll`",`n `"size`": 165840496,`n `"sha256`": `"E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E`",`n `"fileVersion`": `"310.8.0.0`",`n `"authenticode`": `"Valid`",`n `"source`": `"user-provided workspace file`",`n `"redistributable`": false`n }$srManifestEntry$dlssgManifestEntry`n ]`n}"+$manifestJson = "{`n `"schema`": 1,`n `"mode`": `"local-experimental-only`",`n `"files`": [`n {`n `"name`": `"nvngx_dlssnr.dll`",`n `"size`": 165840496,`n `"sha256`": `"F95FEB54137EA11979F9B4EC4F00AFD84B5C98A5624D3388FBF6A87714A39FCC`",`n `"fileVersion`": `"310.8.3.0`",`n `"authenticode`": `"HashMismatch`",`n `"source`": `"community Lecram 310.8.3 (RankFTW/rhi-repo dlssnr-310.8.Lecram), user-approved 2026-09-29`",`n `"redistributable`": false`n }$srManifestEntry$dlssgManifestEntry`n ]`n}"Set-Content -LiteralPath $manifestPath -Value $manifestJson -Encoding utf8Write-Host "stage-runtime.ps1: runtime-manifest.json written"diff --git a/scripts/stage-ui-migration.ps1 b/scripts/stage-ui-migration.ps1index b3ae6072..43964008 100644--- a/scripts/stage-ui-migration.ps1+++ b/scripts/stage-ui-migration.ps1@@ -1,29 +1,225 @@-# Stage the current branch build into a runnable app directory for tests.-# Runtime components come from the verified 1.4.4 release (junctions, never copied-# or modified); settings under runtime_local are fresh test-only files, so running-# tests never touches the user's real configuration.-param([string]$Build = 'E:\项目\Veyra\build\ui-qml-migration-20260925',- [string]$App = 'E:\项目\Veyra\tests\ui-qml-migration-20260925\app',- [string]$Release = 'E:\项目\Veyra\releases\1.4.4\final\Veyra-1.4.4-win64-portable')+[CmdletBinding()]+param(+ [Parameter(Mandatory = $true)][ValidateSet('qml')][string]$UiTarget,+ [Parameter(Mandatory = $true)][string]$Build,+ [Parameter(Mandatory = $true)][string]$App,+ [Parameter(Mandatory = $true)][string]$Release,+ # Optional default-slot NR runtime (2026-09-29 user decision: Lecram 310.8.3).+ # When given, runtime/ is copied instead of linked so the release stays untouched.+ [string]$NrDefaultRuntime = '',+ # Shared RTX20-50 compatible slot (legacy parameter/path name retained).+ [string]$NrAmpereRuntime = ''+)++# Stage one runnable UI contract per directory. The resolver later checks the+# same cache switch and executable hash before any smoke test starts.$ErrorActionPreference = 'Stop'-New-Item -ItemType Directory -Force $App | Out-Null-foreach ($name in 'runtime') {- $link = Join-Path $App $name- if (-not (Test-Path -LiteralPath $link)) { New-Item -ItemType Junction -Path $link -Target (Join-Path $Release $name) | Out-Null }+$projectDirectoryName = [string]([char]0x9879) + [string]([char]0x76ee)+$artifactRoot = Join-Path (Join-Path 'E:\' $projectDirectoryName) 'Veyra'+$rootPath = (Resolve-Path (Join-Path $PSScriptRoot '..') -ErrorAction Stop).Path+$buildPath = (Resolve-Path -LiteralPath $Build -ErrorAction Stop).Path+$releasePath = (Resolve-Path -LiteralPath $Release -ErrorAction Stop).Path+$appPath = [IO.Path]::GetFullPath($App)+$artifactRootFull = [IO.Path]::GetFullPath($artifactRoot).TrimEnd('\') + '\'+foreach ($path in @($buildPath, $releasePath, $appPath)) {+ if (-not $path.StartsWith($artifactRootFull, [StringComparison]::OrdinalIgnoreCase)) {+ throw "Build, release and staging paths must be under ${artifactRoot}: $path"+ }}-$local = Join-Path $App 'runtime_local'-New-Item -ItemType Directory -Force $local | Out-Null+if (Test-Path -LiteralPath $appPath) {+ if (-not (Test-Path -LiteralPath $appPath -PathType Container)) { throw "Staging path is not a directory: $appPath" }+ $existing = @(Get-ChildItem -LiteralPath $appPath -Force)+ if ($existing.Count -gt 0) { throw "Staging directory must be new and empty; refusing to reuse: $appPath" }+} else {+ [IO.Directory]::CreateDirectory($appPath) | Out-Null+}+$cache = Join-Path $buildPath 'CMakeCache.txt'+if (-not (Test-Path -LiteralPath $cache -PathType Leaf)) { throw "missing CMakeCache.txt: $cache" }+$switch = (Select-String -LiteralPath $cache -Pattern '^VEYRA_BUILD_QML_UI:BOOL=(ON|OFF)$' | Select-Object -First 1).Matches[0].Groups[1].Value+$expectedSwitch = if ($UiTarget -eq 'qml') { 'ON' } else { 'OFF' }+if ($switch -ne $expectedSwitch) { throw "Build cache target mismatch: requested=$UiTarget expected=$expectedSwitch found=$switch" }++$expectedExe = 'veyra_qml_ui.exe'+$requiredExecutables = @(+ 'veyra_qml_ui.exe',+ 'veyra_qml_data_tests.exe',+ 'veyra_qml_easing_tests.exe',+ 'veyra_qml_quick_tests.exe'+)+$buildExecutables = @{}+foreach ($name in $requiredExecutables) {+ $found = @(Get-ChildItem -LiteralPath $buildPath -Filter $name -File -Recurse -Force)+ if ($found.Count -ne 1) { throw "expected exactly one $name in $buildPath, found $($found.Count)" }+ $buildExecutables[$name] = $found[0].FullName+}+$opposite = 'veyra.exe'+$existingOpposite = @(Get-ChildItem -LiteralPath $appPath -Filter $opposite -File -Recurse -ErrorAction SilentlyContinue)+if ($existingOpposite.Count -gt 0) { throw "staging directory contains the legacy UI executable: $($existingOpposite[0].FullName)" }++$qtRoot = Join-Path $artifactRoot 'deps\qt\6.8.3\msvc2022_64'+$windeployqt = Join-Path $qtRoot 'bin\windeployqt.exe'+if (-not (Test-Path -LiteralPath $windeployqt -PathType Leaf)) { throw "missing Qt deployment tool: $windeployqt" }+$qmlSource = Join-Path $buildPath 'qml'+if (-not (Test-Path -LiteralPath (Join-Path $qmlSource 'Veyra\qmldir') -PathType Leaf)) {+ throw "QML build output is missing qml/Veyra/qmldir: $qmlSource"+}+$qmlTestSource = Join-Path $rootPath 'tests\qml\quick'+if (-not (Test-Path -LiteralPath (Join-Path $qmlTestSource 'tst_components.qml') -PathType Leaf)) {+ throw "QML Quick Test source is missing tests/qml/quick/tst_components.qml: $qmlTestSource"+}++$runtimeTargets = @{+ runtime = Join-Path $releasePath 'runtime'+ 'runtime_local\amd' = Join-Path $releasePath 'runtime_local\amd'+ 'runtime_local\intel' = Join-Path $releasePath 'runtime_local\intel'+}+foreach ($entry in $runtimeTargets.GetEnumerator()) {+ if (-not (Test-Path -LiteralPath $entry.Value -PathType Container)) {+ throw "release runtime directory is missing: $($entry.Value)"+ }+}++# Always copy the NR runtime tree: retiring the old40 DLL must never follow a+# junction into the protected beta. Audit both approved files in every staging.+if (-not $NrDefaultRuntime) { $NrDefaultRuntime = Join-Path $runtimeTargets['runtime'] 'experimental\nvngx_dlssnr.dll' }+if (-not $NrAmpereRuntime) { $NrAmpereRuntime = Join-Path $runtimeTargets['runtime'] 'experimental\nr-ampere\nvngx_dlssnr.dll' }+# Approved slot replacements, pinned by identity for publisher staging only.+$nrSlots = @(+ @{ Given = $NrDefaultRuntime; Folder = 'experimental'; Path = 'runtime/experimental/nvngx_dlssnr.dll'+ Sha = 'F95FEB54137EA11979F9B4EC4F00AFD84B5C98A5624D3388FBF6A87714A39FCC'; Size = 165840496; Sig = 'HashMismatch'+ Class = 'user-approved-community-Lecram-310.8.3-RTX50-runtime'; Source = 'community Lecram 310.8.3 (RankFTW/rhi-repo dlssnr-310.8.Lecram)' },+ @{ Given = $NrAmpereRuntime; Folder = 'experimental\nr-ampere'; Path = 'runtime/experimental/nr-ampere/nvngx_dlssnr.dll'+ Sha = '6EB209E764F39872625DEBD6ABAF45E2BB6322F6F270F781F70C059AE30B3927'; Size = 165830144; Sig = 'NotSigned'+ Class = 'user-approved-community-SF-v2-310.8.2-RTX20-RTX50-compatible-runtime'; Source = 'community SF-v2 310.8.2 (RankFTW/rhi-repo dlssnr-310.8.SF-v2)' }+) | Where-Object { $_.Given }+if ($nrSlots) {+ # A copied runtime keeps the release untouched while one slot is replaced.+ $runtimeCopy = Join-Path $appPath 'runtime'+ & robocopy $runtimeTargets['runtime'] $runtimeCopy /E /NJH /NJS /NP /NFL /NDL | Out-Null+ if ($LASTEXITCODE -gt 7) { throw "robocopy failed ($LASTEXITCODE): runtime" }+ $manifestFile = Join-Path $runtimeCopy 'experimental\release-runtime-manifest.json'+ $manifest = Get-Content -LiteralPath $manifestFile -Raw -Encoding UTF8 | ConvertFrom-Json+ foreach ($slot in $nrSlots) {+ $nrSource = (Resolve-Path -LiteralPath $slot.Given -ErrorAction Stop).Path+ $nrItem = Get-Item -LiteralPath $nrSource+ $nrHash = (Get-FileHash -LiteralPath $nrSource -Algorithm SHA256).Hash+ $nrSig = [string](Get-AuthenticodeSignature -LiteralPath $nrSource).Status+ if ($nrHash -ne $slot.Sha -or $nrItem.Length -ne $slot.Size -or $nrSig -ne $slot.Sig) {+ throw "NR runtime identity rejected for $($slot.Path): sha=$nrHash size=$($nrItem.Length) sig=$nrSig"+ }+ Copy-Item -LiteralPath $nrSource -Destination (Join-Path (Join-Path $runtimeCopy $slot.Folder) 'nvngx_dlssnr.dll') -Force+ $entry = @($manifest.files | Where-Object { $_.path -eq $slot.Path })+ if ($entry.Count -ne 1) { throw "manifest has $($entry.Count) entries for $($slot.Path)" }+ # Numeric parts, as package-portable.ps1 writes them (these DLLs' strings vary).+ $nrVersion = $nrItem.VersionInfo+ $entry[0].sha256 = $nrHash+ $entry[0].size = $nrItem.Length+ $entry[0].fileVersion = "$($nrVersion.FileMajorPart).$($nrVersion.FileMinorPart).$($nrVersion.FileBuildPart).$($nrVersion.FilePrivatePart)"+ $entry[0].authenticode = $nrSig+ $entry[0].classification = $slot.Class+ $entry[0].source = $slot.Source+ $entry[0].experimental = $true+ Write-Host "NR slot $($slot.Path) staged from $nrSource (sha $nrHash)"+ }+ $retired = [IO.Path]::GetFullPath((Join-Path $runtimeCopy 'experimental\nr-community\nvngx_dlssnr.dll'))+ if (-not $retired.StartsWith(([IO.Path]::GetFullPath($appPath).TrimEnd('\') + '\'), [StringComparison]::OrdinalIgnoreCase)) { throw 'Retired runtime escaped fresh staging' }+ foreach ($parent in @($runtimeCopy, (Split-Path -Parent $retired))) {+ if ((Test-Path -LiteralPath $parent) -and ((Get-Item -LiteralPath $parent).Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw "Refusing to delete through runtime junction: $parent" }+ }+ if (Test-Path -LiteralPath $retired) { Remove-Item -LiteralPath $retired -Force }+ $manifest.files = @($manifest.files | Where-Object { $_.path -ne 'runtime/experimental/nr-community/nvngx_dlssnr.dll' })+ [IO.File]::WriteAllText($manifestFile, ($manifest | ConvertTo-Json -Depth 6), (New-Object Text.UTF8Encoding $false))+} else {+ foreach ($name in 'runtime') {+ $link = Join-Path $appPath $name+ if (-not (Test-Path -LiteralPath $link)) { New-Item -ItemType Junction -Path $link -Target $runtimeTargets[$name] | Out-Null }+ }+}+$local = Join-Path $appPath 'runtime_local'+[IO.Directory]::CreateDirectory($local) | Out-Nullforeach ($name in 'amd', 'intel') {- $link = Join-Path $local $name- if (-not (Test-Path -LiteralPath $link)) { New-Item -ItemType Junction -Path $link -Target (Join-Path (Join-Path $Release 'runtime_local') $name) | Out-Null }+ $link = Join-Path $local $name+ $target = $runtimeTargets[(Join-Path 'runtime_local' $name)]+ if (-not (Test-Path -LiteralPath $link)) { New-Item -ItemType Junction -Path $link -Target $target | Out-Null }}-# Application binaries, test executables, FFmpeg DLLs and shaders from the build.-Get-ChildItem -LiteralPath $Build -File | Where-Object { $_.Extension -in '.exe', '.dll' } | ForEach-Object {- Copy-Item -LiteralPath $_.FullName -Destination $App -Force++# Application binaries, QML-only test executables, FFmpeg DLLs and shaders come+# from the selected build. Backend tests and probes never enter this staging.+Get-ChildItem -LiteralPath $buildPath -File | Where-Object {+ $_.Extension -eq '.dll' -or $_.Name -eq $expectedExe -or $_.Name -in @('veyra_qml_data_tests.exe', 'veyra_qml_easing_tests.exe', 'veyra_qml_quick_tests.exe')+} | ForEach-Object {+ Copy-Item -LiteralPath $_.FullName -Destination $appPath -Force+}+foreach ($name in $requiredExecutables) {+ Copy-Item -LiteralPath $buildExecutables[$name] -Destination (Join-Path $appPath $name) -Force}foreach ($dll in 'avcodec-63.dll','avformat-63.dll','avutil-61.dll','dav1d.dll','swresample-7.dll','swscale-10.dll','msvcp140.dll','vcruntime140.dll','vcruntime140_1.dll') {- $target = Join-Path $App $dll- if (-not (Test-Path -LiteralPath $target)) { Copy-Item -LiteralPath (Join-Path $Release $dll) -Destination $target }+ $target = Join-Path $appPath $dll+ $source = Join-Path $releasePath $dll+ if (-not (Test-Path -LiteralPath $source -PathType Leaf)) { throw "release dependency is missing: $source" }+ if (-not (Test-Path -LiteralPath $target)) { Copy-Item -LiteralPath $source -Destination $target }+}+function Invoke-Robocopy([string]$Source, [string]$Destination) {+ # The destination is a fresh staging tree. /E copies the selected build+ # without deleting anything from a directory that might belong to another run.+ & robocopy $Source $Destination /E /NJH /NJS /NP /NFL /NDL | Out-Null+ if ($LASTEXITCODE -gt 7) { throw "robocopy failed ($LASTEXITCODE): $Source -> $Destination" }+}+if (Test-Path -LiteralPath (Join-Path $buildPath 'shaders')) {+ Invoke-Robocopy (Join-Path $buildPath 'shaders') (Join-Path $appPath 'shaders')+}+Invoke-Robocopy $qmlSource (Join-Path $appPath 'qml')+Invoke-Robocopy $qmlTestSource (Join-Path $appPath 'qml-tests')++# Deploy Qt beside the same executable and test binaries that will be run. The+# QML UI alone does not pull in Qt Quick Test, so deploying only from it would+# leave veyra_qml_quick_tests un-runnable in a fresh staging directory.+ $stageTemp = Join-Path $artifactRoot ('tmp\ui-migration-stage\' + [IO.Path]::GetFileName($appPath))+ New-Item -ItemType Directory -Path $stageTemp -Force | Out-Null+ $previousTemp = $env:TEMP; $previousTmp = $env:TMP+ try {+ $env:TEMP = $stageTemp; $env:TMP = $stageTemp+ foreach ($name in @('veyra_qml_ui.exe', 'veyra_qml_easing_tests.exe', 'veyra_qml_quick_tests.exe')) {+ # QtTest is imported by the test sources, not by the application QML.+ $scanSource = if ($name -eq 'veyra_qml_quick_tests.exe') { $qmlTestSource } else { $qmlSource }+ & $windeployqt '--release' '--no-translations' '--qmldir' $scanSource '--qmlimport' $qmlSource '--dir' $appPath (Join-Path $appPath $name) | Out-Null+ if ($LASTEXITCODE -ne 0) { throw "windeployqt failed for $name with exit $LASTEXITCODE" }+}+ } finally { $env:TEMP = $previousTemp; $env:TMP = $previousTmp }++# windeployqt deploys qwindows by default, but both QML tests run offscreen.+$offscreenSource = Join-Path $qtRoot 'plugins\platforms\qoffscreen.dll'+if (-not (Test-Path -LiteralPath $offscreenSource -PathType Leaf)) { throw "missing Qt offscreen platform plugin: $offscreenSource" }+Copy-Item -LiteralPath $offscreenSource -Destination (Join-Path $appPath 'platforms\qoffscreen.dll')+if (-not (Test-Path -LiteralPath (Join-Path $appPath 'qml\QtTest\qmldir') -PathType Leaf)) {+ throw 'Qt deployment is incomplete; missing qml/QtTest/qmldir'+}++$requiredQtDlls = @(+ 'Qt6Core.dll', 'Qt6Gui.dll', 'Qt6Qml.dll', 'Qt6QmlModels.dll',+ 'Qt6Quick.dll', 'Qt6QuickControls2.dll', 'Qt6QuickTemplates2.dll',+ 'Qt6Widgets.dll', 'Qt6QuickTest.dll'+)+foreach ($name in $requiredQtDlls) {+ $path = Join-Path $appPath $name+ if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { throw "Qt deployment is incomplete; missing $path" }+}+$platformPlugin = Join-Path $appPath 'platforms\qwindows.dll'+if (-not (Test-Path -LiteralPath $platformPlugin -PathType Leaf)) { throw "Qt deployment is incomplete; missing $platformPlugin" }+if (-not (Test-Path -LiteralPath (Join-Path $appPath 'qml\Veyra\qmldir') -PathType Leaf)) {+ throw "staging is missing qml/Veyra/qmldir after Qt deployment"+}+if (-not (Test-Path -LiteralPath (Join-Path $appPath 'qml-tests\tst_components.qml') -PathType Leaf)) {+ throw "staging is missing qml-tests/tst_components.qml"+}+$stagedUi = @(Get-ChildItem -LiteralPath $appPath -File -Force | Where-Object { $_.Name -in @('veyra.exe', 'veyra_qml_ui.exe') })+if ($stagedUi.Count -ne 1 -or -not $stagedUi[0].Name.Equals($expectedExe, [StringComparison]::OrdinalIgnoreCase)) {+ $names = ($stagedUi | ForEach-Object Name) -join ', '+ throw "staging must contain exactly $expectedExe and no other UI executable; found: $names"+}+$stagedExecutables = @(Get-ChildItem -LiteralPath $appPath -File -Filter '*.exe' -Force | ForEach-Object Name | Sort-Object)+$expectedStagedExecutables = @($requiredExecutables | Sort-Object)+if (@(Compare-Object -ReferenceObject $expectedStagedExecutables -DifferenceObject $stagedExecutables).Count -gt 0) {+ throw "staging executable set mismatch; expected=$($expectedStagedExecutables -join ',') found=$($stagedExecutables -join ',')"}-robocopy (Join-Path $Build 'shaders') (Join-Path $App 'shaders') /MIR /NJH /NJS /NP /NFL /NDL | Out-Null-"staged $App"+"staged $UiTarget $appPath"diff --git a/shaders/ColorGrade.hlsli b/shaders/ColorGrade.hlsliindex 5f25c29e..8b2bcca2 100644--- a/shaders/ColorGrade.hlsli+++ b/shaders/ColorGrade.hlsli@@ -233,3 +233,13 @@ float3 ColorGradeApply(float3 lin, ColorGradeParams p)}return rgb;}++// Keep the fused ingress path bit-for-bit aligned with ColorGradePass for a+// pure exposure grade. The independent pass uses the same fast path because+// neutral log/HSV/LUT work can otherwise move HDR scRGB values by a visible+// amount before the FP16 store.+float3 ColorGradeApplyWithFlags(float3 lin, ColorGradeParams p)+{+ if (p.flags.w > 0.5) return lin * exp2(p.controls.x);+ return ColorGradeApply(lin, p);+}diff --git a/shaders/ColorGradePass.hlsl b/shaders/ColorGradePass.hlslnew file mode 100644index 00000000..4b2314e2--- /dev/null+++ b/shaders/ColorGradePass.hlsl@@ -0,0 +1,26 @@+// R5.3 standalone RGBA16F grade. Reuse the same colour algorithm/tables as+// fused ingress; only the working-domain scale and resource binding differ.+#include "ColorGrade.hlsli"+cbuffer Params : register(b0) {+ uint width; uint height; float workingToScene; float exposureOnly;+ float4 row0; float4 row1; float4 row2; float4 controls; float4 flags;+};+Texture2D<float4> source : register(t0);+RWTexture2D<float4> target : register(u0);+[numthreads(16,16,1)]+void main(uint3 p : SV_DispatchThreadID) {+ if(p.x>=width||p.y>=height)return;+ float4 color=source[p.xy];+ if(flags.x>0.5){+ if(exposureOnly>0.5){+ // Pure exposure is a linear gain in both scene and scRGB units.+ // Avoid otherwise-neutral table/gamma and working-scale round trips.+ // The legacy fused ingress shader is deliberately unchanged.+ color.rgb*=exp2(controls.x);+ }else{+ ColorGradeParams grade={row0,row1,row2,controls,flags};+ color.rgb=ColorGradeApply(color.rgb*workingToScene,grade)/workingToScene;+ }+ }+ target[p.xy]=color;+}diff --git a/shaders/NrHold.hlsl b/shaders/NrHold.hlslnew file mode 100644index 00000000..1e1bfaf1--- /dev/null+++ b/shaders/NrHold.hlsl@@ -0,0 +1,83 @@+// Output stabiliser (anti-flicker), stage 5 of+// docs/NR_FG_OPTIMIZATION_PLAN_2026-09-29.md.+//+// Independent implementation of the behaviour publicly described by+// DLSS5-Feeder 1.17/1.18's "Output stabiliser": hold the previous output where+// the source has not visibly changed. No code was taken from that project; only+// the described behaviour. See THIRD_PARTY_NOTICES.md.+//+// Deliberate differences from that description, and why:+// * No reprojection. The plan explicitly excludes it: a wrong motion vector+// would drag the previous output into a region that did move, which is the+// ghosting this pass exists to avoid. Regions that moved simply stop+// holding.+// * The change test compares the *source* (the image going into NR) against+// the previous source, not against our own output. Comparing the output+// with itself would feed the hold back into its own decision and let a held+// region stay held forever, which is a smear.+Texture2D<float4> Current : register(t0); // this frame's NR result+Texture2D<float4> PreviousOutput : register(t1); // what we emitted last frame+Texture2D<float4> Base : register(t2); // this frame's NR input+Texture2D<float4> PreviousBase : register(t3); // that input one frame ago+RWTexture2D<float4> Output : register(u0);+RWTexture2D<float4> NextBase : register(u1);+cbuffer Settings : register(b0) {+ uint2 Size; // NR output extent (the dispatch grid)+ uint2 BaseSize; // source extent; may differ under the realtime NR policy+ float HoldStrength; // 0 is refused by the host, which skips the dispatch+ float Tolerance; // relative box-luma delta that still counts as unchanged+ uint UseHistory; // 0 on reset: publish current, seed history, hold nothing+};+// Perceptual luminance, matching the guide distance in NrTemporal.hlsl, so a+// given tolerance means the same thing in shadows as in highlights. The stored+// value is always linear, never mapped.+float Luma(float3 c) { return dot(c, float3(0.2126, 0.7152, 0.0722)); }+int2 ClampBase(int2 p) { return clamp(p, int2(0, 0), int2(BaseSize) - int2(1, 1)); }+// Mean luminance of the 3x3 neighbourhood, clamped at the frame edge. A mean+// rather than a max: one hot pixel should not veto the hold for its neighbours,+// and one dead pixel should not let it through. Base is sampled at its own+// extent, so a downscaled NR extent still sees the same neighbourhood shape.+float BoxLumaBase(int2 p, float2 scale) {+ const int2 c = int2(float2(p) * scale);+ float sum = 0;+ [unroll] for (int y = -1; y <= 1; ++y)+ [unroll] for (int x = -1; x <= 1; ++x)+ sum += Luma(Base[ClampBase(c + int2(x, y))].rgb);+ return sum / 9.0;+}+float BoxLumaPreviousBase(int2 p, float2 scale) {+ const int2 c = int2(float2(p) * scale);+ float sum = 0;+ [unroll] for (int y = -1; y <= 1; ++y)+ [unroll] for (int x = -1; x <= 1; ++x)+ sum += Luma(PreviousBase[ClampBase(c + int2(x, y))].rgb);+ return sum / 9.0;+}+[numthreads(8, 8, 1)]+void main(uint3 id : SV_DispatchThreadID) {+ const int2 p = int2(id.xy);+ if (any(p >= int2(Size))) return;+ const float4 current = Current.Load(int3(p, 0));+ // Publish this frame's source unconditionally as the next anchor: the anchor+ // must describe the source as it is now, whatever we decide about the hold.+ const float2 scale = float2(BaseSize) / float2(Size);+ const int2 baseTexel = ClampBase(int2((float2(p) + .5) * scale));+ NextBase[p] = Base.Load(int3(baseTexel, 0));+ // A non-finite sample must not be held: publish it and let the next frame+ // decide, rather than freezing corruption in place.+ if (!all(isfinite(current))) { Output[p] = current; return; }+ if (UseHistory == 0) { Output[p] = current; return; }+ const float4 previous = PreviousOutput.Load(int3(p, 0));+ if (!all(isfinite(previous)) || previous.a < .999) { Output[p] = current; return; }+ const float currentLuma = BoxLumaBase(p, scale);+ const float previousLuma = BoxLumaPreviousBase(p, scale);+ // Relative difference, so one tolerance holds in both shadows and+ // highlights. The epsilon keeps a near-black anchor from turning the+ // smallest representable change into a large relative one.+ const float delta = abs(currentLuma - previousLuma) / max(max(currentLuma, previousLuma), 1e-4);+ // Moved (or visibly changed) beyond tolerance: publish the new value and+ // hold nothing. This is what keeps motion from smearing.+ if (delta > Tolerance) { Output[p] = current; return; }+ // Unchanged: blend toward the previous output.+ Output[p] = float4(lerp(current.rgb, previous.rgb, HoldStrength), current.a);+}diff --git a/shaders/NrProtection.hlsli b/shaders/NrProtection.hlsliindex 7859d679..94785caf 100644--- a/shaders/NrProtection.hlsli+++ b/shaders/NrProtection.hlsli@@ -1,12 +1,26 @@#ifndef VEYRA_NR_PROTECTION#define VEYRA_NR_PROTECTION+// regions: normalized (left, top, right, bottom). A region sent with left and+// right swapped (engine::protectionConstants) is the ellipse inscribed in the+// box; an ordinary rectangle is unchanged.float NrProtection(float2 pixel, uint2 size, float enabled, float feather, float4 regions[4]) {float protection=0;if(enabled>0) {for(uint i=0;i<4;++i) {float4 r=regions[i]*float4(size,size);+ const bool ellipse=r.z<r.x;+ if(ellipse)r=float4(r.z,r.y,r.x,r.w);if(r.z<=r.x||r.w<=r.y)continue;- float edge=min(min(pixel.x-r.x,r.z-pixel.x),min(pixel.y-r.y,r.w-pixel.y));+ float edge;+ if(ellipse) {+ // Distance inside the ellipse, approximated along the normalized+ // radius and scaled by the shorter semi-axis (exact on circles).+ const float2 centre=(r.xy+r.zw)*0.5;+ const float2 axis=max((r.zw-r.xy)*0.5,1e-3);+ edge=(1.0-length((pixel-centre)/axis))*min(axis.x,axis.y);+ } else {+ edge=min(min(pixel.x-r.x,r.z-pixel.x),min(pixel.y-r.y,r.w-pixel.y));+ }protection=max(protection,feather>0?smoothstep(0,feather,edge):(edge>=0?1:0));}}diff --git a/shaders/NrTemporal.hlsl b/shaders/NrTemporal.hlslindex 82db1a4d..af88f179 100644--- a/shaders/NrTemporal.hlsl+++ b/shaders/NrTemporal.hlsl@@ -2,18 +2,56 @@// 3841698348bfb246623d4acf791984c8b68a577b// src/Magpie.Core/DLSSNRTemporalShader.h (motion route 2).// Veyra: D3D12 Load-based bilinear sampling, source-flow extent conversion,-// linear signed HDR guide, reset via zero weight, post-protection residual.+// bounded signed perceptual guide, reset via zero weight, post-protection residual.+//+// Anti-flicker tiers (Route, stage 6 of+// docs/NR_FG_OPTIMIZATION_PLAN_2026-09-29.md). Route numbers follow the upstream+// shader's own meaning so the two stay comparable:+// 1 Static accumulate only where the patch is not moving+// 2 Flow the original 80 ms motion-reprojected EMA (unchanged path)+// 3 FlowPlus 60 ms attack / 180 ms release memory + direction-reversal+// rejection, plus an explicit support channel in history alpha+// 4 LowFrequency route 2 on a half-resolution residual; this frame's high+// frequency rides through untouched+// Route 2 is byte-for-byte the behaviour that existed before the tiers, so a+// preset that only ever knew "temporal on" keeps producing what it produced.#include "NrProtection.hlsli"Texture2D<float4> Base:register(t0);Texture2D<float4> Raw:register(t1);Texture2D<float4> History:register(t2);Texture2D<float4> PreviousGuide:register(t3);Texture2D<float2> Motion:register(t4);+Texture2D<float4> LowResidual:register(t5);+Texture2D<float4> LowGuide:register(t6);RWTexture2D<float4> Output:register(u0);RWTexture2D<float4> NextHistory:register(u1);RWTexture2D<float4> NextGuide:register(u2);-cbuffer Settings:register(b0){uint2 Size;float HistoryWeight;float Total;float ProtectionEnabled;float Feather;float2 reserved;float4 Regions[4];}-float3 Guide(float3 c){return c/(1+abs(c));}+cbuffer Settings:register(b0){+ uint2 Size;float HistoryWeight;float Total;float ProtectionEnabled;float Feather;float2 reserved;float4 Regions[4];+ uint Route;float2 LowSize;float RoutePad;+}+float GuideChannel(float c){+ // The matching tolerance must distinguish visible changes in shadows,+ // not treat a several-fold linear-light change as the same observation.+ // Retain the bounded signed HDR mapping, then use the sRGB transfer for+ // guide distance only. Residuals and the output remain signed linear.+ float mapped=abs(c)/(1+abs(c));+ return sign(c)*(mapped<=.0031308?12.92*mapped:1.055*pow(mapped,1.0/2.4)-.055);+}+float3 Guide(float3 c){return float3(GuideChannel(c.r),GuideChannel(c.g),GuideChannel(c.b));}+float RebaseResidual(float base,float raw,float correction){+ // A valid old residual can exceed a darker current base. As in+ // NrResidualComposite::shadowSafe, compress extra darkening smoothly+ // instead of manufacturing a negative channel or hard-clipping detail.+ // Only nonnegative inputs have this constraint: signed HDR/gamut data+ // must retain its sign. At a zero anchor there is no darker valid value.+ float anchorDelta=min(raw-base,0.0);+ if(base>=0&&raw>=0&&correction<anchorDelta){+ float anchor=min(base,raw);+ return anchor>0?anchor/(1.0+(anchorDelta-correction)/anchor):0;+ }+ return base+correction;+}bool Inside(int2 p){return all(p>=0)&&all(p<int2(Size));}float4 Bilinear(Texture2D<float4> tex,float2 p){int2 a=int2(floor(p));float2 f=frac(p);int2 b=min(a+1,int2(Size)-1);@@ -28,6 +66,55 @@ bool PreviousPosition(int2 p,out float2 previous){if(!all(isfinite(mv)))return false;previous+=mv;return all(previous>=0)&&all(previous<=float2(Size)-1);}+// Route 4: rebuild a low-frequency observation at this pixel from the half-res+// pair, accepting only blocks whose guide still matches this pixel's colour.+// Returning false means "no usable low-frequency support", which must publish+// no history rather than a fabricated zero.+bool Reconstruct(int2 p,float3 color,out float3 residual){+ int2 a=clamp(int2(floor(float2(p)*.5-.25)),0,int2(LowSize)-1);+ int2 b=clamp(int2(floor(float2(p)*.5-.25))+1,0,int2(LowSize)-1);+ float2 ca=min(float2(a)*2+.5,float2(Size)-1);+ float2 cb=min(float2(b)*2+.5,float2(Size)-1);+ float2 f=saturate((float2(p)-ca)/max(cb-ca,float2(1,1)));+ residual=0;float mass=0;+ [unroll]for(int y=0;y<2;++y){+ [unroll]for(int x=0;x<2;++x){+ int2 n=int2(x?b.x:a.x,y?b.y:a.y);+ float4 r=LowResidual[n];float4 g=LowGuide[n];+ if(!all(isfinite(r))||!all(isfinite(g))||r.a<.999||g.a<.999)continue;+ float3 delta=abs(color-g.rgb);+ float accept=1-smoothstep(.02,.10,max(delta.r,max(delta.g,delta.b)));+ float w=(x?f.x:1-f.x)*(y?f.y:1-f.y)*accept;+ if(w<=0)continue;+ residual+=w*r.rgb;mass+=w;+ }+ }+ if(mass<.05)return false;+ residual/=mass;+ return true;+}+// Route 4's history read: validate each tap against the guide before blending,+// so a half-res block straddling an edge cannot leak across it.+bool GatherHistory(float2 previous,float3 color,out float4 result){+ int2 a=int2(floor(previous));float2 f=frac(previous);+ result=0;float mass=0;+ [unroll]for(int y=0;y<2;++y){+ [unroll]for(int x=0;x<2;++x){+ int2 n=a+int2(x,y);+ float w=(x?f.x:1-f.x)*(y?f.y:1-f.y);+ if(w<=0||!Inside(n))continue;+ float4 g=PreviousGuide[n];float4 h=History[n];+ if(!all(isfinite(g))||!all(isfinite(h))||g.a<.999||h.a<.999)continue;+ float3 delta=abs(color-g.rgb);+ w*=1-smoothstep(.025,.10,max(delta.r,max(delta.g,delta.b)));+ if(w<=0)continue;+ result+=w*h;mass+=w;+ }+ }+ if(mass<.25)return false;+ result/=mass;+ return true;+}groupshared float4 TileResidual[100];groupshared float4 TilePosition[100];groupshared float TileError[100];@@ -55,13 +142,39 @@ groupshared float TileError[100];float4 base=Base[p],raw=Raw[p];bool finite=all(isfinite(base))&&all(isfinite(raw));NextGuide[p]=all(isfinite(base))?float4(Guide(base.rgb),1):0;if(!finite){NextHistory[p]=0;Output[p]=all(isfinite(base))?base:float4(0,0,0,1);return;}- float3 current=raw.rgb-base.rgb,result=current;float2 previous;- // A zero correction is a valid observation, not a protection mask. Keep- // protected/feathered pixels exact and exclude them from future history.- bool protectedPixel=Total==0||NrProtection(float2(p)+.5,Size,ProtectionEnabled,Feather,Regions)>0;- if(protectedPixel){NextHistory[p]=0;Output[p]=raw;return;}+ // Route 4 splits the observation: the accumulated signal is the+ // low-frequency component and `detail` carries this frame's exact+ // high-frequency complement through untouched.+ float3 detail=0;+ if(Route==4){+ float3 low;+ if(!Reconstruct(p,Guide(base.rgb),low)){NextHistory[p]=0;Output[p]=raw;return;}+ detail=(raw.rgb-base.rgb)-low;+ // `result` below now accumulates the low-frequency observation, so the+ // residual used for the guide/box comparison must be the same signal.+ // The tile cache above holds the full-band residual for route 2/3; for+ // route 4 the per-pixel comparison is replaced below.+ }+ // Protected/feathered pixels are excluded from history entirely: the caller+ // composites the original image there, so nothing this pass emits should be+ // remembered. This is a protection decision, not an observation.+ if(NrProtection(float2(p)+.5,Size,ProtectionEnabled,Feather,Regions)>0){NextHistory[p]=0;Output[p]=raw;return;}+ // A zero requested correction is a valid observation, not a protection mask.+ // It publishes the raw value, but must still record that as history: wiping+ // the chain here would drop the accumulated correction the moment a layer's+ // total reached zero, and the next frame would restart from nothing. The+ // temporal blend itself is gated on Total below.+ const bool observesCorrection=Total!=0;+ float3 current=raw.rgb-base.rgb;+ if(Route==4)current=current-detail; // accumulate the low-frequency part only+ float3 result=current;float2 previous;+ // Route 3 carries a support channel in history alpha: the residual is only+ // applied in proportion to how strongly the source is currently observed.+ float support=saturate(smoothstep(.005,.02,max(abs(Guide(raw.rgb)-Guide(base.rgb)).r,+ max(abs(Guide(raw.rgb)-Guide(base.rgb)).g,+ abs(Guide(raw.rgb)-Guide(base.rgb)).b))));uint center=(local.y+1)*10+local.x+1;- if(HistoryWeight>0&&TilePosition[center].z>0){+ if(observesCorrection&&HistoryWeight>0&&TilePosition[center].z>0){previous=TilePosition[center].xy;float error=0,maximumError=0;bool valid=true;float3 lo=current,hi=current;[unroll]for(int y=-1;y<=1;++y)[unroll]for(int x=-1;x<=1;++x){@@ -71,12 +184,55 @@ groupshared float TileError[100];if(any(abs((previousN-n)-(previous-p))>2)){valid=false;continue;}float3 residualN=TileResidual[tap].rgb;if(TileResidual[tap].a==0){valid=false;continue;}+ // Route 4 accumulates a half-resolution signal, so the full-band tile+ // residual is not the quantity being filtered. Its spatial agreement+ // still gates motion validity, but the box must come from the+ // reconstructed low-frequency observation instead.+ if(Route==4){float3 lowN;if(!Reconstruct(n,Guide(Base[n].rgb),lowN)){valid=false;continue;}residualN=lowN;}float e=TileError[tap];error+=e/9;maximumError=max(maximumError,e);lo=min(lo,residualN);hi=max(hi,residualN);}float q=(1-smoothstep(.008,.04,error))*(1-smoothstep(.025,.10,maximumError));- if(valid&&q>0){float4 old=Bilinear(History,previous);if(all(isfinite(old))&&old.a>=.999){float3 margin=.02+q*abs(old.rgb);result=lerp(current,clamp(old.rgb,lo-margin,hi+margin),HistoryWeight*q);}}+ // Route 1 (static): accumulate only where the patch is essentially+ // still. No smooth falloff: any real motion publishes immediately, which+ // is what makes this the tier with the least ghosting risk.+ if(Route==1)q=maximumError<.008?1:0;+ if(valid&&q>0){+ float4 old=0;bool historyValid=true;+ if(Route==4)historyValid=GatherHistory(previous,Guide(base.rgb),old);+ else old=Bilinear(History,previous);+ if(historyValid&&all(isfinite(old))&&old.a>=.999){+ float3 margin=.02+q*abs(old.rgb);+ float3 safe=clamp(old.rgb,lo-margin,hi+margin);+ if(Route==3){+ // 60 ms attack / 180 ms release, derived from the same+ // capture interval as the 80 ms amplitude EMA. q applies once.+ float oldSupport=saturate(old.a-1);+ float memory=pow(abs(HistoryWeight),.08/(support>oldSupport?.06:.18))*q;+ support=lerp(support,oldSupport,memory);+ if(oldSupport<=.001)result=current;+ else if(support>0&&dot(current,old.rgb)<0){+ // An opposite-direction correction starts a new episode+ // instead of being averaged into the old one.+ support=support*(1-pow(abs(HistoryWeight),.08/.06)*q);+ result=current;+ }else{+ float update=(1-HistoryWeight*q)*support;+ result=lerp(safe,current,update);+ }+ }else result=lerp(current,safe,HistoryWeight*q);+ }+ }}- NextHistory[p]=float4(clamp(result,-65504,65504),1);+ float3 resolved=float3(RebaseResidual(base.r,raw.r,result.r),+ RebaseResidual(base.g,raw.g,result.g),+ RebaseResidual(base.b,raw.b,result.b));+ // History must describe what was actually emitted, not the rejected+ // correction; otherwise the next frame reuses the same invalid shadow.+ // Route 3 stores 1+support in alpha: the support channel rides along with+ // the observation rather than in a separate texture.+ NextHistory[p]=float4(clamp(resolved-base.rgb,-65504,65504),Route==3?1+support:1);+ // Route 4 restores this frame's high frequency after the temporal filter.+ float3 composited=resolved+detail;// Preserve signed wide-gamut/HDR working components (no SDR saturate).- Output[p]=float4(clamp(base.rgb+result,-65504,65504),raw.a);+ Output[p]=float4(clamp(composited,-65504,65504),raw.a);}diff --git a/shaders/NrTemporalReduce.hlsl b/shaders/NrTemporalReduce.hlslnew file mode 100644index 00000000..59849b8e--- /dev/null+++ b/shaders/NrTemporalReduce.hlsl@@ -0,0 +1,50 @@+// Half-resolution observation pass for the low-frequency anti-flicker route.+//+// Ported from SAOG0721/Magpie, GPL-3.0, commit+// 3841698348bfb246623d4acf791984c8b68a577b+// src/Magpie.Core/DLSSNRTemporalShader.h (DLSSNR_TEMPORAL_REDUCE_SHADER).+// Veyra: D3D12 Load-based reads, reset via zero weight, post-protection limit.+//+// Only the "low-frequency temporal reconstruction" route uses this. It folds a+// 2x2 block of the exact post-chain difference into one signed observation plus+// one guide value, so the temporal filter can work on a signal that is already+// narrow-band; the carrier keeps this frame's high frequency untouched.+Texture2D<float4> Input : register(t0); // NR base (the image NR consumed)+Texture2D<float4> Base : register(t1); // alias of Input in this graph+Texture2D<float4> Raw : register(t2); // NR result+RWTexture2D<float4> Residual : register(u0);+RWTexture2D<float4> Guide : register(u1);+cbuffer Settings : register(b0) {+ uint2 Size; // full extent+ uint2 LowSize; // half extent (ceil)+ uint Hdr;+ uint Protected;+};+[numthreads(8, 8, 1)]+void main(uint3 id : SV_DispatchThreadID) {+ if (any(id.xy >= LowSize)) return;+ float3 residual = 0, guide = 0;+ float count = 0;+ bool valid = true;+ [unroll] for (uint y = 0; y < 2; ++y) {+ [unroll] for (uint x = 0; x < 2; ++x) {+ const uint2 p = id.xy * 2 + uint2(x, y);+ // Odd dimensions keep their last sample rather than dropping it.+ if (any(p >= Size)) continue;+ const float4 i = Input.Load(int3(p, 0));+ const float4 b = Base.Load(int3(p, 0));+ const float4 o = Raw.Load(int3(p, 0));+ if (!all(isfinite(i)) || !all(isfinite(b)) || !all(isfinite(o))) { valid = false; continue; }+ residual += o.rgb - b.rgb;+ // The guide is the bounded signed mapping, so a low-frequency guide+ // comparison means the same thing in shadows as in highlights.+ guide += Hdr ? i.rgb / (1 + abs(i.rgb)) : i.rgb;+ count += 1;+ }+ }+ // A protected pixel must not publish an observation at all; a partial block+ // would otherwise smuggle the protected value into the temporal filter.+ if (!valid || count == 0 || Protected) { Residual[id.xy] = 0; Guide[id.xy] = 0; return; }+ Residual[id.xy] = float4(clamp(residual / count, -65504, 65504), 1);+ Guide[id.xy] = float4(guide / count, 1);+}diff --git a/shaders/PackedCaptureToLinear.hlsl b/shaders/PackedCaptureToLinear.hlslindex d5fae305..79d4b283 100644--- a/shaders/PackedCaptureToLinear.hlsl+++ b/shaders/PackedCaptureToLinear.hlsl@@ -49,6 +49,6 @@ void main(uint3 p : SV_DispatchThreadID) {if (limitedU != 0 && packing <= 3) rgb = saturate((rgb - 16.0 / 255.0) * (255.0 / 219.0));float3 decoded = float3(decode(rgb.r), decode(rgb.g), decode(rgb.b));if (primaries2020 > 0.5) decoded = HdrTo709(decoded);- if (colorFlags.x > 0.5) { ColorGradeParams grade = { colorRow0, colorRow1, colorRow2, colorControls, colorFlags }; decoded = ColorGradeApply(decoded, grade); }+ if (colorFlags.x > 0.5) { ColorGradeParams grade = { colorRow0, colorRow1, colorRow2, colorControls, colorFlags }; decoded = ColorGradeApplyWithFlags(decoded, grade); }linearRgb[p.xy] = float4(decoded, 1);}diff --git a/shaders/PresentMotion.hlsl b/shaders/PresentMotion.hlslindex a62768b4..7e628125 100644--- a/shaders/PresentMotion.hlsl+++ b/shaders/PresentMotion.hlsl@@ -3,25 +3,23 @@ Texture2D<float2> sourceMotion : register(t0);RWTexture2D<float2> outputMotion : register(u0);cbuffer Mapping : register(b0) {float4 extent; // source extent, current client extent- float4 currentView; // zoom, center x/y, reset- float4 previousView; // zoom, center x/y, unused- float4 previousClient; // width/height, unused+ float4 currentView; // current rendered width, center x/y, reset+ float4 previousView; // current rendered height, previous center x/y, unused+ float4 previousClient; // previous client width/height, rendered width/height};[numthreads(8,8,1)]void main(uint3 tid : SV_DispatchThreadID) {uint2 size; outputMotion.GetDimensions(size.x,size.y);if(any(tid.xy>=size))return;float2 displayUv=(float2(tid.xy)+.5)/float2(size);- float fit=min(extent.z/extent.x,extent.w/extent.y)*currentView.x;- float2 sourceUv=(displayUv-.5)*extent.zw/(extent.xy*fit)+currentView.yz;+ float2 sourceUv=(displayUv-.5)*extent.zw/float2(currentView.x,previousView.x)+currentView.yz;if(currentView.w!=0||any(sourceUv<0)||any(sourceUv>=1)) {outputMotion[tid.xy]=0;return;}uint2 motionSize;sourceMotion.GetDimensions(motionSize.x,motionSize.y);int2 samplePixel=min(int2(sourceUv*motionSize),int2(motionSize)-1);float2 previousUv=sourceUv+sourceMotion.Load(int3(samplePixel,0))/extent.xy;- float previousFit=min(previousClient.x/extent.x,previousClient.y/extent.y)*previousView.x;- float2 previousDisplay=.5+(previousUv-previousView.yz)*extent.xy*previousFit/previousClient.xy;+ float2 previousDisplay=.5+(previousUv-previousView.yz)*previousClient.zw/previousClient.xy;outputMotion[tid.xy]=(any(previousUv<0)||any(previousUv>=1)||any(previousDisplay<0)||any(previousDisplay>=1))?float2(0,0):(previousDisplay-displayUv)*float2(size);}diff --git a/shaders/RgbToLinear.hlsl b/shaders/RgbToLinear.hlslindex 949647ec..75c718ef 100644--- a/shaders/RgbToLinear.hlsl+++ b/shaders/RgbToLinear.hlsl@@ -20,7 +20,7 @@ void main(uint3 p : SV_DispatchThreadID) {float3 decoded=float3(decode(c.r),decode(c.g),decode(c.b));if(primaries2020>0.5)decoded=HdrTo709(decoded);const bool scRgb=transfer==0&&reserved.x>0.5;- if(colorFlags.x>0.5){ColorGradeParams grade={colorRow0,colorRow1,colorRow2,colorControls,colorFlags};decoded=scRgb?ColorGradeApply(decoded*(80.0/203.0),grade)*(203.0/80.0):ColorGradeApply(decoded,grade);}+ if(colorFlags.x>0.5){ColorGradeParams grade={colorRow0,colorRow1,colorRow2,colorControls,colorFlags};decoded=scRgb?ColorGradeApplyWithFlags(decoded*(80.0/203.0),grade)*(203.0/80.0):ColorGradeApplyWithFlags(decoded,grade);}if(scRgb&&reserved.x>1.5)decoded=HdrToSdr(decoded*80.0,reserved.y,203.0);linearRgb[p.xy]=float4(decoded*c.a,1);}diff --git a/shaders/YuvToLinearRgb.hlsl b/shaders/YuvToLinearRgb.hlslindex 7de8ac84..5f14d749 100644--- a/shaders/YuvToLinearRgb.hlsl+++ b/shaders/YuvToLinearRgb.hlsl@@ -114,7 +114,7 @@ void main(uint3 dispatchThreadId : SV_DispatchThreadID)float3 linear709=mul(float3x3(1.660491,-0.587641,-0.072850,-0.124550,1.132900,-0.008349,-0.018151,-0.100579,1.118730),nits);// Grade in the normalised domain: HDR is referenced to the BT.2408// 203 cd/m2 SDR reference white; SDR paths below are already 0..1.- if(colorFlags.x>0.5){ColorGradeParams grade={colorRow0,colorRow1,colorRow2,colorControls,colorFlags};linear709=ColorGradeApply(linear709/203.0,grade)*203.0;}+ if(colorFlags.x>0.5){ColorGradeParams grade={colorRow0,colorRow1,colorRow2,colorControls,colorFlags};linear709=ColorGradeApplyWithFlags(linear709/203.0,grade)*203.0;}if((yuvDimensions.z&1)!=0)rgb=linear709/80.0; // scRGB: 1.0 = 80 nits.else{rgb=HdrToSdr(linear709,toneMapParams.x,toneMapParams.y);@@ -131,6 +131,6 @@ void main(uint3 dispatchThreadId : SV_DispatchThreadID)if(colorParams0.z<3.5&&(yuvDimensions.z&2)!=0)rgb=HdrTo709(rgb);// SDR paths carry normalised scene-linear RGB here (after any primaries// conversion), which is exactly the domain ColorGradeApply expects.- if(colorParams0.z<3.5&&colorFlags.x>0.5){ColorGradeParams grade={colorRow0,colorRow1,colorRow2,colorControls,colorFlags};rgb=ColorGradeApply(rgb,grade);}+ if(colorParams0.z<3.5&&colorFlags.x>0.5){ColorGradeParams grade={colorRow0,colorRow1,colorRow2,colorControls,colorFlags};rgb=ColorGradeApplyWithFlags(rgb,grade);}linearRgb[dispatchThreadId.xy] = float4(rgb, 1.0);}diff --git a/shaders/Yuy2ToLinear.hlsl b/shaders/Yuy2ToLinear.hlslindex e77191e3..ad7dfc80 100644--- a/shaders/Yuy2ToLinear.hlsl+++ b/shaders/Yuy2ToLinear.hlsl@@ -30,6 +30,6 @@ void main(uint3 p : SV_DispatchThreadID) {rgb=saturate(rgb);float3 decoded=float3(decode(rgb.r),decode(rgb.g),decode(rgb.b));if(primaries2020>0.5)decoded=HdrTo709(decoded);- if(colorFlags.x>0.5){ColorGradeParams grade={colorRow0,colorRow1,colorRow2,colorControls,colorFlags};decoded=ColorGradeApply(decoded,grade);}+ if(colorFlags.x>0.5){ColorGradeParams grade={colorRow0,colorRow1,colorRow2,colorControls,colorFlags};decoded=ColorGradeApplyWithFlags(decoded,grade);}linearRgb[p.xy]=float4(decoded,1);}diff --git a/src/engine/EffectChain.cpp b/src/engine/EffectChain.cppindex cbc0474d..89df9dae 100644--- a/src/engine/EffectChain.cpp+++ b/src/engine/EffectChain.cpp@@ -1,6 +1,9 @@#include "veyra/engine/EffectChain.h"#include <algorithm>+#include <cmath>+#include <limits>+#include <memory>namespace veyra::engine {namespace {@@ -20,6 +23,210 @@ const EffectInfo& effectInfo(EffectType type) {}const std::array<EffectInfo, effectTypeCount>& effectCatalog() { return kCatalog; }+int NodeGraphLayout::indexOf(const EffectChain& chain, uint32_t id) const {+ if (id < 2 || chain.nodeCount > kMaxChainNodes) return -1;+ for (uint32_t i = 0; i < chain.nodeCount; ++i)+ if (ids[i] == id) return int(i);+ return -1;+}++ChainValidation NodeGraphLayout::initialize(const EffectChain& chain) {+ if (chain.mode != ChainMode::Node) return {false, "只有节点模式使用编辑连接"};+ if (auto v = validateChain(chain); !v.accepted) return v;+ NodeGraphLayout candidate;+ for (uint32_t i = 0; i < chain.nodeCount; ++i) {+ candidate.ids[i] = candidate.nextId++;+ candidate.next[i] = i + 1 < chain.nodeCount ? candidate.nextId : Output;+ }+ candidate.inputNext = chain.nodeCount ? candidate.ids[0] : Output;+ if (auto v = candidate.validate(chain); !v.accepted) return v;+ *this = candidate;+ return {};+}++ChainValidation NodeGraphLayout::validate(const EffectChain& chain) const {+ if (chain.mode != ChainMode::Node || chain.nodeCount > kMaxChainNodes)+ return {false, "节点编辑文档类型或容量无效"};+ if (nextId < 2) return {false, "节点标识计数器无效"};+ std::array<uint32_t, effectTypeCount> counts{};+ for (uint32_t i = 0; i < chain.nodeCount; ++i) {+ const auto& n = chain.nodes[i];+ if (ids[i] < 2 || ids[i] >= nextId) return {false, "节点标识无效"};+ for (uint32_t j = 0; j < i; ++j)+ if (ids[i] == ids[j]) return {false, "节点标识重复"};+ if (size_t(n.type) >= effectTypeCount || n.type == EffectType::Protection)+ return {false, "节点模式不支持该效果类型"};+ if (++counts[size_t(n.type)] > effectInfo(n.type).maxInstances)+ return {false, "已存在节点(含未连接节点)超过数量上限"};+ if (!std::isfinite(n.viewX) || !std::isfinite(n.viewY) ||+ std::abs(n.viewX) > 1000000 || std::abs(n.viewY) > 1000000)+ return {false, "节点坐标无效"};+ if (n.type == EffectType::NrEnhance && !pipeline::validNrSizePolicy(n.nr.sizePolicy))+ return {false, "NR 内部处理分辨率非法"};+ }+ const auto validTarget = [&](uint32_t id) { return id <= Output || indexOf(chain, id) >= 0; };+ if (!validTarget(inputNext)) return {false, "输入节点连接目标不存在"};+ std::array<uint32_t, kMaxChainNodes> incoming{};+ uint32_t outputIncoming = 0;+ const auto admit = [&](uint32_t target) {+ if (target == Input) return true;+ if (target == Output) return ++outputIncoming <= 1;+ return ++incoming[size_t(indexOf(chain, target))] <= 1;+ };+ if (!admit(inputNext)) return {false, "输出只允许一个输入"};+ for (uint32_t i = 0; i < chain.nodeCount; ++i) {+ if (!validTarget(next[i])) return {false, "节点连接目标不存在"};+ if (!admit(next[i])) return {false, "节点只允许一个输入,不支持合流"};+ }+ // Include detached components. Traversal is bounded even for corrupt files.+ for (uint32_t i = 0; i < chain.nodeCount; ++i) {+ uint32_t id = ids[i], visits = 0;+ while (id > Output) {+ if (++visits > chain.nodeCount) return {false, "节点连接不能形成环"};+ id = next[size_t(indexOf(chain, id))];+ }+ }+ return {};+}++ChainValidation NodeGraphLayout::project(const EffectChain& chain, EffectChain& output) const {+ if (auto v = validate(chain); !v.accepted) return v;+ auto candidate = std::make_unique<EffectChain>();+ candidate->mode = ChainMode::Node;+ candidate->fgMultiplier = chain.fgMultiplier;+ candidate->fgStrictAdmission = chain.fgStrictAdmission;+ uint32_t id = inputNext;+ while (id > Output) {+ const auto i = size_t(indexOf(chain, id));+ candidate->nodes[candidate->nodeCount++] = chain.nodes[i];+ id = next[i];+ }+ if (id != Output) return {false, "输入至输出尚未连接完整,保留上个运行链"};+ if (auto v = validateChain(*candidate); !v.accepted) return v;+ for (uint32_t i = 0; i + 1 < candidate->nodeCount; ++i)+ if (candidate->nodes[i].type == EffectType::FrameGeneration)+ return {false, "补帧节点固定在输出前,禁用时也不能移到链路中间"};+ output = *candidate;+ return {};+}++ChainValidation NodeGraphLayout::connect(const EffectChain& chain, uint32_t from, uint32_t to) {+ if (auto v = validate(chain); !v.accepted) return v;+ const int index = indexOf(chain, from);+ if (from == Output || (from != Input && index < 0) || to == Input ||+ (to != Output && indexOf(chain, to) < 0)) return {false, "连接端点无效"};+ auto candidate = *this;+ if (from == Input) candidate.inputNext = to;+ else candidate.next[size_t(index)] = to;+ if (auto v = candidate.validate(chain); !v.accepted) return v;+ *this = candidate;+ return {};+}++ChainValidation NodeGraphLayout::disconnect(const EffectChain& chain, uint32_t from) {+ if (auto v = validate(chain); !v.accepted) return v;+ if (from == Input) { inputNext = Input; return {}; }+ const int index = indexOf(chain, from);+ if (index < 0) return {false, "固定输出或不存在节点不能断开"};+ next[size_t(index)] = Input;+ return {};+}++ChainValidation NodeGraphLayout::duplicate(EffectChain& chain, uint32_t id, uint32_t& createdId) {+ if (auto v = validate(chain); !v.accepted) return v;+ const int index = indexOf(chain, id);+ if (index < 0) return {false, "固定节点不能复制"};+ const auto type = chain.nodes[size_t(index)].type;+ if (effectInfo(type).maxInstances <= 1 || chain.countOf(type) >= effectInfo(type).maxInstances ||+ chain.nodeCount == kMaxChainNodes) return {false, "单例节点或数量已达上限,不能复制"};+ if (nextId == std::numeric_limits<uint32_t>::max()) return {false, "节点标识已耗尽"};+ auto candidate = std::make_unique<EffectChain>(chain);+ auto layout = *this;+ auto& copy = candidate->nodes[candidate->nodeCount];+ copy = chain.nodes[size_t(index)];+ bool placed = false;+ for (uint32_t attempt = 1; attempt <= kMaxChainNodes + 1; ++attempt) {+ copy.viewX = chain.nodes[size_t(index)].viewX + 280.0f;+ copy.viewY = chain.nodes[size_t(index)].viewY + 300.0f * float(attempt - 1);+ placed = true;+ for (uint32_t i = 0; i < chain.nodeCount; ++i)+ if (std::abs(chain.nodes[i].viewX - copy.viewX) < 260 &&+ std::abs(chain.nodes[i].viewY - copy.viewY) < 300) placed = false;+ if (placed) break;+ }+ if (!placed) return {false, "副本附近没有可用位置"};+ const uint32_t newId = layout.nextId++;+ layout.ids[candidate->nodeCount] = newId;+ layout.next[candidate->nodeCount++] = Input; // detached, with enabled state preserved+ if (auto v = layout.validate(*candidate); !v.accepted) return v;+ chain = *candidate; *this = layout; createdId = newId;+ return {};+}++ChainValidation NodeGraphLayout::remove(EffectChain& chain, uint32_t id) {+ if (auto v = validate(chain); !v.accepted) return v;+ const int index = indexOf(chain, id);+ if (index < 0) return {false, "固定节点或不存在节点不能删除"};+ auto candidate = std::make_unique<EffectChain>(chain);+ auto layout = *this;+ const uint32_t successor = layout.next[size_t(index)];+ if (layout.inputNext == id) layout.inputNext = successor;+ for (uint32_t i = 0; i < chain.nodeCount; ++i)+ if (layout.next[i] == id) layout.next[i] = successor;+ for (uint32_t i = uint32_t(index); i + 1 < chain.nodeCount; ++i) {+ candidate->nodes[i] = candidate->nodes[i + 1];+ layout.ids[i] = layout.ids[i + 1]; layout.next[i] = layout.next[i + 1];+ }+ const uint32_t tail = --candidate->nodeCount;+ candidate->nodes[tail] = ChainNode{}; layout.ids[tail] = layout.next[tail] = 0;+ if (auto v = layout.validate(*candidate); !v.accepted) return v;+ chain = *candidate; *this = layout;+ return {};+}++ChainValidation NodeGraphLayout::insertAfter(const EffectChain& chain, uint32_t id, uint32_t after) {+ if (auto v = validate(chain); !v.accepted) return v;+ const int index = indexOf(chain, id), anchor = indexOf(chain, after);+ if (index < 0 || id == after || after == Output || (after != Input && anchor < 0))+ return {false, "插入端点无效"};+ if (chain.nodes[size_t(index)].type == EffectType::FrameGeneration ||+ (anchor >= 0 && chain.nodes[size_t(anchor)].type == EffectType::FrameGeneration))+ return {false, "补帧固定末位,不能在其后插入"};+ auto candidate = *this;+ const uint32_t oldNext = candidate.next[size_t(index)];+ if (candidate.inputNext == id) candidate.inputNext = oldNext;+ for (uint32_t i = 0; i < chain.nodeCount; ++i)+ if (candidate.next[i] == id) candidate.next[i] = oldNext;+ auto& edge = after == Input ? candidate.inputNext : candidate.next[size_t(anchor)];+ candidate.next[size_t(index)] = edge; edge = id;+ if (auto v = candidate.validate(chain); !v.accepted) return v;+ auto projected = std::make_unique<EffectChain>();+ if (auto v = candidate.project(chain, *projected); !v.accepted) return v;+ *this = candidate;+ return {};+}++uint32_t removeLegacyNodeProtection(EffectChain& chain, int* selectedNr, int* selectedColour) {+ if (chain.mode != ChainMode::Node || chain.nodeCount > kMaxChainNodes) return 0;+ const int oldNr = selectedNr ? *selectedNr : -1;+ const int oldColour = selectedColour ? *selectedColour : -1;+ uint32_t count = 0;+ for (uint32_t i = 0; i < chain.nodeCount; ++i) {+ if (chain.nodes[i].type == EffectType::Protection) {+ if (selectedNr && oldNr == int(i)) *selectedNr = -1;+ if (selectedColour && oldColour == int(i)) *selectedColour = -1;+ continue;+ }+ if (selectedNr && oldNr == int(i)) *selectedNr = int(count);+ if (selectedColour && oldColour == int(i)) *selectedColour = int(count);+ chain.nodes[count++] = chain.nodes[i];+ }+ const auto removed = chain.nodeCount - count;+ for (uint32_t i = count; i < chain.nodeCount; ++i) chain.nodes[i] = {};+ chain.nodeCount = count;+ return removed;+}+ChainValidation validateChain(const EffectChain& chain) {if (chain.nodeCount > kMaxChainNodes) return {false, "链路节点过多"};std::array<uint32_t, effectTypeCount> seen{};@@ -28,6 +235,10 @@ ChainValidation validateChain(const EffectChain& chain) {const auto& node = chain.nodes[i];const auto index = size_t(node.type);if (index >= effectTypeCount) return {false, "未知效果类型"};+ if (chain.mode == ChainMode::Node && node.type == EffectType::Protection)+ return {false, "节点模式已取消 NR 保护区域,请迁移旧节点配置"};+ if(node.type==EffectType::NrEnhance&&!pipeline::validNrSizePolicy(node.nr.sizePolicy))+ return {false, "NR 内部处理分辨率非法"};++seen[index];if (node.enabled) lastEnabled = i;}@@ -63,6 +274,14 @@ ChainValidation validateChain(const EffectChain& chain) {}}}+ const ChainNrParams* firstNr=nullptr;+ for(uint32_t i=0;i<chain.nodeCount;++i){+ const auto& node=chain.nodes[i];+ if(node.type!=EffectType::NrEnhance||!node.enabled)continue;+ if(firstNr&&(node.nr.runtime!=firstNr->runtime||node.nr.lowLatencyPairing!=firstNr->lowLatencyPairing))+ return {false, "启用的 NR 层必须使用同一运行时和 NR/SR 顺序"};+ firstNr=&node.nr;+ }return {};}@@ -82,19 +301,23 @@ EffectChain toChain(const EnhancementSettings& settings) {// List order is the product order: colour (fused into the ingest shader),// SR, NR layers, protection, Video HDR, frame generation.append(EffectType::Color, settings.color.enabled).color = settings.color;+ for(uint32_t i=0;i<std::min(settings.additionalColorCount,kMaxColorInstances-1);++i)+ append(EffectType::Color,settings.additionalColors[i].enabled).color=settings.additionalColors[i];{ChainNode& sr = append(EffectType::SuperResolution, settings.sr);// SR has no payload of its own yet: its inputs live in the settings// fields videoSrQuality / srTarget, which fromChain() fills back.(void)sr;}- {- ChainNode& nr = append(EffectType::NrEnhance, settings.nr);- nr.nr.model = settings.model;- nr.nr.residual = settings.residual;- nr.nr.runtime = settings.nrRuntime;- nr.nr.temporal = settings.nrTemporal;- nr.nr.lowLatencyPairing = settings.lowLatency;+ for(uint32_t i=0;i<std::min(settings.nrLayerCount?settings.nrLayerCount:1u,kMaxNrInstances);++i){+ const auto layer=settings.nrLayer(i);+ ChainNode& nr = append(EffectType::NrEnhance, layer.enabled);+ nr.nr.model = layer.model;+ nr.nr.residual = layer.residual;+ nr.nr.runtime = layer.runtime;+ nr.nr.temporal = layer.temporal;+ nr.nr.lowLatencyPairing = layer.lowLatencyPairing;+ nr.nr.sizePolicy = layer.sizePolicy;}append(EffectType::Protection, settings.protection.enabled).protection = settings.protection;append(EffectType::VideoHdr, settings.videoHdr.enabled).videoHdr = settings.videoHdr;@@ -102,46 +325,107 @@ EffectChain toChain(const EnhancementSettings& settings) {return chain;}+std::optional<ChainRuntimeOrder> runtimeOrder(const EffectChain& chain) {+ if (chain.mode == ChainMode::List) return std::nullopt;+ ChainRuntimeOrder order;+ order.nodeCount = chain.nodeCount;+ for (uint32_t i = 0; i < std::min(chain.nodeCount, kMaxChainNodes); ++i)+ order.types[i] = chain.nodes[i].type;+ return order;+}++ChainValidation restoreRuntimeOrder(const EnhancementSettings& settings, const ChainRuntimeOrder& order,+ EffectChain& output) {+ if (order.nodeCount > kMaxChainNodes || settings.nrLayerCount > kMaxNrInstances ||+ settings.additionalColorCount >= kMaxColorInstances)+ return {false, "运行节点顺序或实例数量无效"};+ const auto source = toChain(settings);+ EffectChain restored;+ restored.mode = ChainMode::Node;+ restored.nodeCount = order.nodeCount;+ restored.fgMultiplier = source.fgMultiplier;+ restored.fgStrictAdmission = source.fgStrictAdmission;+ std::array<bool, kMaxChainNodes> used{};+ for (uint32_t i = 0; i < order.nodeCount; ++i) {+ if (uint32_t(order.types[i]) >= effectTypeCount) return {false, "运行节点类型无效"};+ uint32_t index = 0;+ while (index < source.nodeCount && (used[index] || source.nodes[index].type != order.types[i])) ++index;+ if (index == source.nodeCount) return {false, "运行节点顺序与实例参数数量不匹配"};+ used[index] = true;+ restored.nodes[i] = source.nodes[index];+ }+ for (uint32_t i = 0; i < source.nodeCount; ++i) {+ if (used[i]) continue;+ const auto& node = source.nodes[i];+ if (node.enabled || (node.type == EffectType::NrEnhance && settings.nrLayerCount) ||+ (node.type == EffectType::Color && settings.additionalColorCount))+ return {false, "运行节点顺序遗漏实例参数"};+ }+ const auto valid = validateChain(restored);+ if (!valid.accepted) return valid;+ output = restored;+ return {};+}+void fromChain(const EffectChain& chain, EnhancementSettings& settings) {// Start from the values the chain does not carry, so callers can pass a// settings struct that already has capture/audio/export fields filled in.settings.color = {};+ settings.additionalColors = {};+ settings.additionalColorCount = 0;+ bool firstColor = true;settings.sr = false;settings.nr = false;+ settings.nrLayers = {};+ settings.nrLayerCount = 0;settings.model = NrSettings{};settings.residual = ResidualSettings{};- settings.nrRuntime = NrRuntime::Original;+ // An empty node graph must retain the shared runtime choice. Otherwise a+ // fresh RTX40 SF-v2 default becomes Lecram when its first NR is added.settings.nrTemporal = false;settings.lowLatency = false;settings.protection = ProtectionSettings{};settings.videoHdr = VideoHdrSettings{};settings.multiplier = 1;settings.fgStrictAdmission = chain.fgStrictAdmission;- for (uint32_t i = 0; i < chain.nodeCount; ++i) {+ for (uint32_t i = 0; i < std::min(chain.nodeCount,kMaxChainNodes); ++i) {const auto& node = chain.nodes[i];switch (node.type) {case EffectType::Color:- settings.color = node.color;- settings.color.enabled = node.enabled;+ if(firstColor){+ settings.color=node.color;+ settings.color.enabled=node.enabled;+ firstColor=false;+ }else if(settings.additionalColorCount<settings.additionalColors.size()){+ auto& color=settings.additionalColors[settings.additionalColorCount++];+ color=node.color;+ color.enabled=node.enabled;+ }break;case EffectType::SuperResolution:settings.sr = node.enabled;break;case EffectType::NrEnhance:- // Only the first NR instance maps back into today's single-NR- // settings; extra layers need the multi-instance engine work.- if (!settings.nr) {+ if(settings.nrLayerCount>=kMaxNrInstances)break;+ settings.nrLayers[settings.nrLayerCount]={node.nr.model,node.nr.residual,+ node.nr.runtime,node.nr.temporal,node.nr.lowLatencyPairing,node.enabled,+ node.nr.antiFlicker,node.nr.sizePolicy};+ if (settings.nrLayerCount==0||(!settings.nr&&node.enabled)) {settings.model = node.nr.model;settings.residual = node.nr.residual;settings.nrRuntime = node.nr.runtime;settings.nrTemporal = node.nr.temporal;settings.lowLatency = node.nr.lowLatencyPairing;+ settings.nrPolicy = node.nr.sizePolicy;}settings.nr = settings.nr || node.enabled;+ ++settings.nrLayerCount;break;case EffectType::Protection:- settings.protection = node.protection;- settings.protection.enabled = node.enabled;+ if (chain.mode == ChainMode::List) {+ settings.protection = node.protection;+ settings.protection.enabled = node.enabled;+ }break;case EffectType::VideoHdr:settings.videoHdr = node.videoHdr;@@ -154,9 +438,174 @@ void fromChain(const EffectChain& chain, EnhancementSettings& settings) {break;}}+ if(settings.nrLayerCount<=1){settings.nrLayers={};settings.nrLayerCount=0;}+}++ChainValidation compileChainExecutionPlan(const EffectChain& chain, const ChainExecutionRequest& request,+ ChainExecutionPlan& result) {+ if (chain.mode != ChainMode::List && chain.mode != ChainMode::Node) return {false, "未知链路模式"};+ const auto validation = validateChain(chain);+ if (!validation.accepted) return validation;+ if (!request.source.valid() || !pipeline::validSrTarget(request.srTarget))+ return {false, "执行计划尺寸或超分目标非法"};++ // Retain storage ordinals even when an earlier instance is disabled. This+ // is how the existing settings arrays address parameters; GPU resources+ // instead use compact active ordinals. Confusing them grades the wrong+ // Color or applies the wrong NR model after bypassing the first instance.+ std::array<uint32_t, kMaxChainNodes> parameterIndices{};+ std::array<uint32_t, effectTypeCount> parameters{};+ bool nrFirst = false;+ for (uint32_t i = 0; i < chain.nodeCount; ++i) {+ const auto& node = chain.nodes[i];+ parameterIndices[i] = parameters[size_t(node.type)]++;+ if (node.enabled && node.type == EffectType::NrEnhance) nrFirst = node.nr.lowLatencyPairing;+ }+ nrFirst = nrFirst && !request.stillImage && !request.exportJob;+ const auto srExtent = pipeline::ResolutionPlan::make(request.source, true,+ pipeline::NrSizePolicy::Native, true, 0, request.srTarget).base;+ ChainExecutionPlan plan;+ auto cursor = request.source;+ const auto append = [&](uint32_t index) {+ const auto& node = chain.nodes[index];+ if (!node.enabled) return;+ if (node.type == EffectType::SuperResolution && cursor == srExtent) return;+ ChainExecutionStep step;+ step.type = node.type; step.nodeIndex = index;+ step.parameterIndex = parameterIndices[index];+ step.resourceIndex = plan.resourceCounts[size_t(node.type)]++;+ step.input = step.processing = step.output = cursor;+ if (node.type == EffectType::SuperResolution) step.processing = step.output = srExtent;+ if (node.type == EffectType::NrEnhance) {+ const auto policy = request.exportJob ? pipeline::NrSizePolicy::Native : node.nr.sizePolicy;+ step.processing = pipeline::ResolutionPlan::make(cursor, false, policy,+ request.stillImage || request.exportJob, 0, request.srTarget).nr;+ }+ plan.steps[plan.stepCount++] = step;+ cursor = step.output;+ };+ if (chain.mode == ChainMode::Node) {+ for (uint32_t i = 0; i < chain.nodeCount; ++i) append(i);+ } else {+ const std::array<EffectType, effectTypeCount> order = nrFirst+ ? std::array{EffectType::Color, EffectType::NrEnhance, EffectType::Protection,+ EffectType::SuperResolution, EffectType::VideoHdr, EffectType::FrameGeneration}+ : std::array{EffectType::Color, EffectType::SuperResolution, EffectType::NrEnhance,+ EffectType::Protection, EffectType::VideoHdr, EffectType::FrameGeneration};+ for (const auto type : order)+ for (uint32_t i = 0; i < chain.nodeCount; ++i)+ if (chain.nodes[i].type == type) append(i);+ }+ plan.output = cursor;+ result = plan;+ return {};+}++ChainGlobalSettings ChainGlobalSettings::capture(const EnhancementSettings& s) {+ ChainGlobalSettings c;+ c.srTarget = s.srTarget; c.videoSrQuality = s.videoSrQuality;+ c.fgBackend = s.frameGenerationBackend; c.flow = s.flow;+ c.opticalFlowBackend = s.opticalFlowBackend; c.amdFlowHalfResolution = s.amdFlowHalfResolution;+ c.nrPolicy = s.nrPolicy;+ c.hdrOutputMode=s.hdrOutputMode;c.fgMotion=s.fgMotion;c.srMotion=s.srMotion;c.nrMotion=s.nrMotion;+ return c;+}++void ChainGlobalSettings::apply(EnhancementSettings& s) const {+ s.nrPolicy = nrPolicy;+ s.hdrOutputMode=hdrOutputMode;s.fgMotion=fgMotion;s.srMotion=srMotion;s.nrMotion=nrMotion;+ s.srTarget = srTarget; s.videoSrQuality = videoSrQuality;+ s.frameGenerationBackend = fgBackend; s.flow = flow;+ s.opticalFlowBackend = opticalFlowBackend; s.amdFlowHalfResolution = amdFlowHalfResolution;+}++ChainConfiguration ChainConfiguration::capture(const EffectChain& chain, const EnhancementSettings& s, int nr, int colour) {+ ChainConfiguration c;+ static_cast<ChainGlobalSettings&>(c) = ChainGlobalSettings::capture(s);+ c.chain = chain; c.selectedNr = nr; c.selectedColour = colour;+ return c;+}++void ChainConfiguration::apply(EnhancementSettings& s) const {+ s.nrPolicy = nrPolicy;+ fromChain(chain, s);+ ChainGlobalSettings::apply(s);+}++bool ChainConfiguration::operator==(const ChainConfiguration& other) const {+ return chain == other.chain && srTarget == other.srTarget && videoSrQuality == other.videoSrQuality &&+ fgBackend == other.fgBackend && flow == other.flow && opticalFlowBackend == other.opticalFlowBackend &&+ amdFlowHalfResolution == other.amdFlowHalfResolution && nrPolicy == other.nrPolicy &&+ selectedNr == other.selectedNr && selectedColour == other.selectedColour &&+ ((!editor && !other.editor) || (editor && other.editor && *editor == *other.editor));+}++bool ChainConfiguration::valid() const {+ if (chain.mode != ChainMode::List && chain.mode != ChainMode::Node) return false;+ if (editor) {+ if (chain.mode != ChainMode::Node || !editor->layout.validate(editor->nodes).accepted) return false;+ const auto globals = editor->globals.value_or(static_cast<const ChainGlobalSettings&>(*this));+ EnhancementSettings globalCheck;+ globals.apply(globalCheck);+ if (!globalCheck.validate().empty()) return false;+ // Detached parameters must still be valid. Validate them independently+ // of ordering and without mutating enabled flags in the document.+ for (uint32_t i = 0; i < editor->nodes.nodeCount; ++i) {+ auto single = std::make_unique<EffectChain>();+ single->mode = ChainMode::Node; single->nodeCount = 1;+ single->nodes[0] = editor->nodes.nodes[i]; single->fgMultiplier = editor->nodes.fgMultiplier;+ if (!validateChain(*single).accepted) return false;+ auto parameters = std::make_unique<EnhancementSettings>();+ fromChain(*single, *parameters);+ globals.apply(*parameters);+ if (!parameters->validate().empty()) return false;+ }+ }+ if (!validateChain(chain).accepted || chain.fgMultiplier < 2 || chain.fgMultiplier > 6 ||+ !pipeline::validNrSizePolicy(nrPolicy)) return false;+ const auto& selectable = editor ? editor->nodes : chain;+ const auto selectionOk = [&](int index, EffectType type) {+ return index == -1 || (index >= 0 && uint32_t(index) < selectable.nodeCount && selectable.nodes[index].type == type);+ };+ if (!selectionOk(selectedNr, EffectType::NrEnhance) || !selectionOk(selectedColour, EffectType::Color)) return false;+ for (uint32_t i = 0; i < chain.nodeCount; ++i)+ if (!std::isfinite(chain.nodes[i].viewX) || !std::isfinite(chain.nodes[i].viewY)) return false;+ EnhancementSettings s;+ apply(s);+ return s.validate().empty();+}++ChainSession ChainSession::initial(const EnhancementSettings& settings) {+ ChainSession result;+ result.configurations[0] = ChainConfiguration::capture(toChain(settings), settings);+ result.configurations[1].chain.mode = ChainMode::Node;+ return result;+}++bool ChainSession::valid() const {+ if (active != ChainMode::List && active != ChainMode::Node) return false;+ if (!initialized[size_t(active)] || !initialized[0]) return false;+ for (size_t i = 0; i < configurations.size(); ++i)+ if (configurations[i].chain.mode != ChainMode(i) || !configurations[i].valid()) return false;+ return true;+}++bool ChainSession::select(ChainMode mode) {+ if ((mode != ChainMode::List && mode != ChainMode::Node) || !valid()) return false;+ const auto target = size_t(mode);+ if (!initialized[target]) {+ configurations[target] = configurations[size_t(active)];+ configurations[target].chain.mode = mode;+ removeLegacyNodeProtection(configurations[target].chain,+ &configurations[target].selectedNr, &configurations[target].selectedColour);+ initialized[target] = true;+ }+ active = mode;+ return true;}bool requiresGraphRebuild(const EnhancementSettings& previous, const EnhancementSettings& next) {+ if(!previous.sameNrTopology(next))return true;// Everything the graph allocates or branches on. Live uniform parameters// (NR model/residual sliders, colour values, protection rectangles, audio,// export bitrate) are deliberately absent: applySettings() handles them.@@ -179,12 +628,18 @@ bool requiresGraphRebuild(const EnhancementSettings& previous, const Enhancementif (previous.flow != next.flow) return true;if (previous.captureCompatible != next.captureCompatible) return true;if (previous.forceSdrPreview != next.forceSdrPreview) return true;+ if (previous.hdrOutputMode != next.hdrOutputMode || previous.fgMotion != next.fgMotion ||+ previous.srMotion != next.srMotion || previous.nrMotion != next.nrMotion) return true;if (previous.color.lutNameString() != next.color.lutNameString()) return true;// The LUT's input space changes which table the colour stage binds.if (previous.color.lutInputSpace != next.color.lutInputSpace) return true;- // Deeper chain edits (an extra NR layer, a reordered node) need the engine- // work that lands with the ordered executor; until then the chain's shape- // is fully determined by the fields above.+ if(previous.additionalColorCount!=next.additionalColorCount)return true;+ for(uint32_t i=0;i<std::min(next.additionalColorCount,kMaxColorInstances-1);++i){+ const auto& a=previous.additionalColors[i];+ const auto& b=next.additionalColors[i];+ if(a.enabled!=b.enabled||a.lutName!=b.lutName||a.lutInputSpace!=b.lutInputSpace)return true;+ }+ // Arbitrary inter-effect node ordering remains the separate P3 executor.return false;}}diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex c24a93a3..c02c1515 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -27,6 +27,7 @@#include "veyra/pipeline/ResetCoordinator.h"#include "veyra/gfx/XessMfgUnlock.h"#include "veyra/ngx/AmpereMfgUnlock.h"+#include "veyra/ngx/DlssgTransfusion.h"#include "veyra/diagnostics/ResetCause.h"#include "veyra/diagnostics/CpuStallTrace.h"#include "veyra/sink/WasapiAudioSink.h"@@ -77,15 +78,17 @@ void EngineController::open(HWND video,const std::wstring& path,PlayerOptions op// Diagnostics-only PlayerOptions fields never enter EnhancementSettings;// keep them across the snapshot round-trip below.const bool captureCpuUnpack=opts.captureCpuUnpack;- {std::lock_guard lock(mutex_);snapshot_={};activeFlow_.reset();previewView_={};fgMultiFrameMaxCap_=0;xessMaxInterpolatedFramesCap_=0;fsrMaxGeneratedFramesCap_=0;snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;savePath_.clear();desired_=opts.snapshot();desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_);}+ const bool softwareDecode=opts.softwareDecode;const bool hardwareDecodeOnly=opts.hardwareDecodeOnly;+ {std::lock_guard lock(mutex_);snapshot_={};activeFlow_.reset();previewView_={};fgMultiFrameMaxCap_=0;xessMaxInterpolatedFramesCap_=0;fsrMaxGeneratedFramesCap_=0;snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;savePath_.clear();desired_=opts.snapshot();desiredNodeOrder_=opts.nodeOrder;desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_,desiredNodeOrder_);}opts.captureReplayForTest=captureReplay;opts.captureCpuUnpack=captureCpuUnpack;+ opts.softwareDecode=softwareDecode;opts.hardwareDecodeOnly=hardwareDecodeOnly;post([this,video,path,opts]{paused_=false;seekSeconds_=-1;run(video,path,opts);});}#ifdef VEYRA_ENABLE_REMOTEPLAYvoid EngineController::openRemotePlay(HWND window,source::RemotePlayConnectDesc desc,PlayerOptions opts){auto request=std::make_shared<source::RemotePlayConnectDesc>(std::move(desc));- {std::lock_guard lock(mutex_);snapshot_={};activeFlow_.reset();previewView_={};fgMultiFrameMaxCap_=0;xessMaxInterpolatedFramesCap_=0;fsrMaxGeneratedFramesCap_=0;snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;snapshot_.remotePlay=true;snapshot_.capture=true;savePath_.clear();desired_=opts.snapshot();desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_);}+ {std::lock_guard lock(mutex_);snapshot_={};activeFlow_.reset();previewView_={};fgMultiFrameMaxCap_=0;xessMaxInterpolatedFramesCap_=0;fsrMaxGeneratedFramesCap_=0;snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;snapshot_.remotePlay=true;snapshot_.capture=true;savePath_.clear();desired_=opts.snapshot();desiredNodeOrder_=opts.nodeOrder;desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_,desiredNodeOrder_);}post([this,window,request,opts]{paused_=false;seekSeconds_=-1;run(window,L"remoteplay:",opts,request);});}remoteplay::ControllerFeedback EngineController::remotePlayFeedback(){std::lock_guard lock(mutex_);return activeRemote_?activeRemote_->takeFeedback():remoteplay::ControllerFeedback{};}@@ -101,8 +104,19 @@ bool EngineController::selectAudioTrack(uint64_t session,int streamIndex){if(std::none_of(snapshot_.audioTracks.begin(),snapshot_.audioTracks.end(),[&](const auto& t){return t.streamIndex==streamIndex;}))return false;pendingAudioSession_=session;pendingAudioTrack_=streamIndex;return true;}-bool EngineController::requestSettings(EnhancementSettings s){+bool EngineController::requestSettings(EnhancementSettings s,std::optional<ChainRuntimeOrder> order,uint64_t* acceptedRevision){if(!s.validate().empty()){veyra::log::warn("settings","invalid whole settings transaction rejected");status(L"整套设置无效,未应用任何字段",false);return false;}+ if(order){+ // Fail before changing desired state. This is a shape admission check,+ // not a GPU test; actual dimensions are compiled again at graph creation.+ StageRequest r;r.width=64;r.height=64;r.nr=s.nr;r.sr=s.sr;+ r.fg=s.multiplier>1;r.fgMultiplier=s.multiplier;r.nodeOrder=&*order;+ pipeline::EnhanceGraphDesc desc;describeStages(r,s,desc);+ if(const auto error=desc.validateFixedExecutionPlan();!error.empty()){+ veyra::log::warn("settings",std::format("node order rejected before commit: {}",error));+ status(L"当前执行器尚不支持此节点顺序,原配置保持不变",false);return false;+ }+ }std::lock_guard lock(mutex_);if(snapshot_.image)s.multiplier=1;// Capability gate: refuse a multiplier the active GPU/runtime cannot honour// instead of letting the graph fail and silently turning frame generation@@ -121,7 +135,7 @@ bool EngineController::requestSettings(EnhancementSettings s){// frame per presented frame; the probe (tools/fsr_probe) measured this on// every requested count, so anything above 2X is refused instead of// silently presenting 2X under a 4X label.- if(s.multiplier>2&&s.frameGenerationBackend==FrameGenerationBackend::Fsr){+ if(s.multiplier>2&&fsrFrameGeneration(s.frameGenerationBackend)){snapshot_.status=L"AMD FSR 帧生成上限为 2X;请求未应用";snapshot_.failed=false;veyra::log::info("settings",std::format("fsr multiplier gate: requested={} maxGeneratedFrames=1 applied=unchanged",s.multiplier));@@ -129,12 +143,17 @@ bool EngineController::requestSettings(EnhancementSettings s){}// Revision partitions GPU history and measurements. Audio-only edits must// not invalidate in-flight video, and identical notifications are no-ops.- s.revision=desired_.revision;if(s==desired_)return true;- if(!s.sameVideoConfiguration(desired_))s.revision=++nextRevision_;- desired_=s;snapshot_.desired=s;snapshot_.applying=snapshot_.applied!=desired_;return true;+ s.revision=desired_.revision;if(s==desired_&&order==desiredNodeOrder_){if(acceptedRevision)*acceptedRevision=desired_.revision;return true;}+ if(!s.sameVideoConfiguration(desired_)||order!=desiredNodeOrder_)s.revision=++nextRevision_;+ desiredNodeOrder_=order;desired_=s;snapshot_.desired=s;snapshot_.applying=snapshot_.applied!=desired_;+ if(acceptedRevision)*acceptedRevision=s.revision;return true;}void EngineController::saveFrame(const std::wstring& path){std::lock_guard lock(mutex_);savePath_=path;}void EngineController::startExport(const std::wstring& input,const std::wstring& output,PlayerOptions opts,bool hevc){+ if(opts.nodeOrder){+ veyra::log::warn("node-order","export has no runtime node-order transport; request rejected before posting");+ status(L"节点链尚未接入导出执行器,请切换列表模式后导出",false);return;+ }const auto frozen=opts.snapshot();const int audioStream=opts.audioStreamIndex;post([this,input,output,frozen,audioStream,hevc]{CoInitializeEx(nullptr,COINIT_MULTITHREADED);auto options=PlayerOptions::from(frozen);options.audioStreamIndex=audioStream;bool ok=exportVideo(input,output,options,hevc,stop_,[this](double p,const std::wstring& s){std::lock_guard lock(mutex_);snapshot_.status=s;snapshot_.position=p;snapshot_.duration=1;snapshot_.running=true;});{std::lock_guard lock(mutex_);snapshot_.running=false;snapshot_.failed=!ok&&!stop_;}CoUninitialize();});}@@ -231,6 +250,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(isImage){if(!sink::loadImage(path,image)){status(L"无法解码PNG/JPEG",true);break;}if(!pipeline::Extent{image.width,image.height}.valid()||uint64_t(image.width)*image.height>16777216){+ if(options.nodeOrder){+ veyra::log::warn("node-order","large-image tiling has no runtime node-order transport; request rejected");+ status(L"节点模式尚未接入大图分块处理,请切换列表模式后打开",true);break;+ }runLargeImage(window,image,options,ctx,ring);break;}imageFrame=av_frame_alloc();imageFrame->format=AV_PIX_FMT_RGBA;imageFrame->width=image.width;imageFrame->height=image.height;imageFrame->pts=0;imageFrame->color_range=AVCOL_RANGE_JPEG;imageFrame->colorspace=AVCOL_SPC_RGB;imageFrame->color_trc=AVCOL_TRC_IEC61966_2_1;@@ -248,9 +271,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// VP9 through D3D12VA; MJPEG stays on the software path inside// CaptureCompressedDecoder). Each source performs its own// capability check and records its fallback.- od.preferHardwareDecode=true;+ od.preferHardwareDecode=!(options.softwareDecode&&!isCapture);+ od.requireHardwareDecode=options.hardwareDecodeOnly&&!options.softwareDecode&&!isCapture&&!isImage; // stills have no hardware decoderod.d3d12Device=ctx.device();od.d3d12Queue=ctx.directQueue();od.d3d12AdapterLuid=ctx.adapter().luid;+ if(!isCapture)veyra::log::info("decode",std::format("file decode preference={}",options.softwareDecode?"software":options.hardwareDecodeOnly?"hardware-only":"hardware-first"));// Diagnostic uses the production graph/presenter to validate// D3D12VA imports without needing a paired PS5 or credentials.if(!isCapture&&GetEnvironmentVariableW(L"VEYRA_TEST_FILE_HW_DECODE",nullptr,0)){@@ -310,6 +335,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst auto& si=activeSource->info();snapshot_.sourceWidth=si.width;snapshot_.sourceHeight=si.height;snapshot_.sourceDisplayAspect=si.displayAspect;+ if(si.width&&si.height&&std::isfinite(si.displayAspect)&&si.displayAspect>0&&std::abs(si.displayAspect-double(si.width)/si.height)>.001)+ previewView_.displayAspect=si.displayAspect;snapshot_.sourceRotationDegrees=si.rotationDegrees;// Poster for the minimal-mode bar. Built once, from the frame// we already decoded; failure leaves it empty on purpose.@@ -341,21 +368,22 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst bool nvidiaAdapter=ctx.adapter().isNvidia;auto stageRequest=[&](const PlayerOptions& o){StageRequest r;r.nr=o.nr;r.sr=o.sr;r.fg=o.fg;r.fgMultiplier=o.fgMultiplier;- r.width=width;r.height=height;r.stillImage=isImage;r.nvidiaAdapter=nvidiaAdapter;return r;+ r.width=width;r.height=height;r.stillImage=isImage;r.nvidiaAdapter=nvidiaAdapter;+ r.nodeOrder=o.nodeOrder?&*o.nodeOrder:nullptr;return r;};describeStages(stageRequest(options),options.snapshot(),gd);- const bool xessFg=presentSinkFrameGeneration(options.settings.frameGenerationBackend);+ const bool xessFg=crossVendorFrameGeneration(options.settings.frameGenerationBackend);gd.noFeatures=false;gd.hdrOutput=options.settings.useHdrPreview(gd.hdrInput,displayHdrActive());veyra::log::info("display-color",std::format("hdrInput={} hdrOutput={} forceSdrPreview={}",gd.hdrInput,gd.hdrOutput,options.settings.forceSdrPreview));gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();gd.compatibilityPreflight=[this](const auto& desc,const auto& device){return checkFgCompatibility(desc,device,stop_);};std::wstring backendRecoveryWarning;- auto initializePreview=[&](pipeline::EnhanceGraphDesc& desc,PlayerOptions& selected,bool preserveWorkingFg=false){+ auto initializePreview=[&](pipeline::EnhanceGraphDesc& desc,PlayerOptions& selected,bool preserveWorkingFg=false,bool preserveWorkingNr=false){backendRecoveryWarning.clear();auto supported=selected.snapshot();if(disableUnsupportedNvidiaEffects(supported,nvidiaAdapter)){- selected=PlayerOptions::from(supported);+ selected=PlayerOptions::from(supported,selected.nodeOrder);// Same stage rules as every other build: AMD FSR upscaling// survives the normalization, it used to be dropped here.describeStages(stageRequest(selected),selected.snapshot(),desc);@@ -371,7 +399,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sopened=presenter.open(ctx,window,graph,selected.settings.captureCompatible,!isCapture&&!isImage)&&graph.createViews();failure=FailedBackend::Infrastructure;if(opened&&graph.xessEnabled()&&!presenter.xessActive()){opened=false;failure=FailedBackend::Fg;}- if(opened&&graph.fsrEnabled()&&!presenter.fsrActive()){opened=false;failure=FailedBackend::Fg;}+ if(opened&&graph.fsrEnabled()&&!graph.fsrActive()){opened=false;failure=FailedBackend::Fg;}// Requested AMD FSR upscaling that could not be created// (missing local runtime, unsupported layout) degrades// to the plain scale path with a visible warning.@@ -381,6 +409,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// A live backend/multiplier switch must not turn a working FG// session into effects-off playback when the new provider fails.if(preserveWorkingFg&&failure==FailedBackend::Fg)return false;+ if(preserveWorkingNr&&failure==FailedBackend::Nr)return false;auto reduced=selected.snapshot();// Requested multiplier above this GPU's capability: clamp to what// the runtime supports and say so, instead of dropping frame@@ -394,8 +423,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst auto xessState=gfx::XessMfgUnlock::snapshot();if(xessState.applied)capabilityGeneratedFrames=int(xessState.maxInterpolations);}- else if(reduced.frameGenerationBackend==FrameGenerationBackend::Fsr){- capabilityGeneratedFrames=int(presenter.fsrMaxGeneratedFrames());+ else if(fsrFrameGeneration(reduced.frameGenerationBackend)){+ capabilityGeneratedFrames=int((graph.fsrActive()?1u:0u));}}if(capabilityGeneratedFrames>0&&int(reduced.multiplier)-1>capabilityGeneratedFrames){@@ -410,17 +439,18 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(!clampedOverCapability&&!disableFailedBackend(reduced,failure))return false;veyra::log::warn("backend-recovery",std::format("initialization failed component={} attempt={} revision={} -> nr={} sr={} multiplier={}; original SDK error above",unsigned(failure),attempt+1,reduced.revision,reduced.nr,reduced.sr,reduced.multiplier));if(!backendRecoveryWarning.empty())backendRecoveryWarning+=L";";- backendRecoveryWarning+=std::wstring(backendFailureName(failure))+L"初始化失败,已关闭依赖效果(错误码见日志)";- if(failure==FailedBackend::Fg&&ngx::AmpereMfgUnlock::applied())backendRecoveryWarning+=L";RTX 30 系补帧解锁已应用,但当前驱动/运行库组合下运行时不开放补帧,可改用 AMD FSR 补帧";- if(failure==FailedBackend::Fg&&reduced.frameGenerationBackend==FrameGenerationBackend::XeSS&&presenter.fsrActive()){- // The FidelityFX proxy owns the window's only flip-model- // swapchain slot; it cannot be released without leaving- // the window unable to host any later swapchain (verified- // locally), so switching FSR -> XeSS needs a restart.- backendRecoveryWarning+=L";AMD FSR 的代理交换链仍占用窗口,切到 XeSS 需要重启软件";- }+ const uint32_t ngxResult=uint32_t(graph.failedNgxResult());+ if(selected.settings.frameGenerationBackend==FrameGenerationBackend::Fsr4&&failure==FailedBackend::Fg)+ backendRecoveryWarning+=L"FSR 4 ML 提供方不可用(需要支持的 RX 9000 和驱动),已关闭补帧;原因见日志";+ else if((ngxResult&0xFFF00000u)==0xBAD00000u)+ backendRecoveryWarning+=std::wstring(backendFailureName(failure))+L":"+ngxFailureHint(ngxResult)+std::format(L"(NGX 0x{:08X},驱动 {}),已关闭依赖效果",ngxResult,ctx.adapter().driverVersion);+ else if(!clampedOverCapability)+ backendRecoveryWarning+=std::wstring(backendFailureName(failure))+L" 初始化失败,已关闭依赖效果;原因见诊断日志";+ if(!graph.driverRequirementNotice().empty())backendRecoveryWarning+=L";"+graph.driverRequirementNotice();+ if(failure==FailedBackend::Fg&&(ngx::AmpereMfgUnlock::applied()||(ngx::DlssgTransfusion::applied()&&ngx::DlssgTransfusion::snapshot().target==ngx::DlssgTransfusion::Target::Ampere)))backendRecoveryWarning+=L";RTX 30 系补帧解锁已应用,但当前驱动/运行库组合下运行时不开放补帧,可改用 AMD FSR 补帧";+if(!ring.drainQueue()||!ring.discardRecording())return false;- presenter.close();graph.shutdown();selected=PlayerOptions::from(reduced);+ presenter.close();graph.shutdown();selected=PlayerOptions::from(reduced,selected.nodeOrder);describeStages(stageRequest(selected),selected.snapshot(),desc);}return false;@@ -437,10 +467,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// session must not restrict the XeSS choices in the UI.xessMaxInterpolatedFramesCap_=presenter.xessActive()?int(std::max(1u,xessState.maxInterpolations)):0;snapshot_.xessMaxInterpolatedFrames=xessMaxInterpolatedFramesCap_;- // AMD FSR ceiling comes from the running presenter; 0 keeps the+ // AMD FSR ceiling comes from the active graph provider; 0 keeps the// settings UI on its static 2X fallback until a session ran.- fsrMaxGeneratedFramesCap_=graph.fsrEnabled()&&presenter.fsrActive()?int(presenter.fsrMaxGeneratedFrames()):0;+ fsrMaxGeneratedFramesCap_=graph.fsrEnabled()&&graph.fsrActive()?int((graph.fsrActive()?1u:0u)):0;snapshot_.fsrMaxGeneratedFrames=fsrMaxGeneratedFramesCap_;+ snapshot_.fsrProviderVersion=graph.fsrProviderVersion();if(fgMultiFrameMaxCap_>0)veyra::log::info("settings",std::format("frame-generation capability: maxGeneratedFrames={} maxMultiplier={}",fgMultiFrameMaxCap_,fgMultiFrameMaxCap_+1));veyra::log::info("settings",std::format("xess capability: active={} maxInterpolatedFrames={} unlockApplied={} (active context only)",presenter.xessActive(),xessMaxInterpolatedFramesCap_,xessState.applied));if(fsrMaxGeneratedFramesCap_>0)veyra::log::info("settings",std::format("fsr capability: generatedPerPresent={} => maxMultiplier={}",fsrMaxGeneratedFramesCap_,fsrMaxGeneratedFramesCap_+1));@@ -503,6 +534,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s};PresentationScheduler liveTimeline;uint64_t submitted=0,expired=0;std::deque<int64_t> submissionTimes;DeadlineWait deadlineWait;+ // Live capture: the GPU fence of a submitted frame wakes this thread+ // directly. The 0.2 ms ready poll alone left a finished frame waiting+ // up to one timer slice (plus timer jitter) before its Present.+ struct EventHandle{HANDLE handle=CreateEventW(nullptr,FALSE,FALSE,nullptr);~EventHandle(){if(handle)CloseHandle(handle);}} gpuReadyEvent;// Realtime file preview scheduling (P2/P3): expired decoded// candidates lose their enhancement opportunity against the audio// master clock; FG admission predicts pair completion; XeSS-FG@@ -519,7 +554,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// so per-call deltas systematically miss updates that land just// after a submission; feeding the cumulative difference at the// next submission cannot lose them. Reset with the presenter.- uint64_t fedXessPresented=0,fedXessGenerated=0,fedFsrPresented=0,fedFsrGenerated=0;+ uint64_t fedXessPresented=0,fedXessGenerated=0;double playbackSpeedLastPts=0;Clock::time_point playbackSpeedLastWall{};CaptureHalfRate captureSampler;FrameLineageTracker lineageTracker;@@ -694,7 +729,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s};auto drainLivePresentation=[&]{cadence.reset();if(liveScheduler){++presentationDrains;liveScheduler->cancel();pollCompletions();pendingCompletions.clear();}pairLatency.reset();};auto advanceLive=[&]{applyPresentation();if(liveScheduler){pollCompletions();if(stop_||(paused_&&!seekPreviewPending)||seekSeconds_>=0){liveScheduler->cancel();cadence.reset();}else liveScheduler->advance(host100ns());}};- auto waitLive=[&]{const auto due=liveScheduler?liveScheduler->wakeAt():0;deadlineWait.slice(due>host100ns()?std::min(1.0,double(due-host100ns())/10000):1.0,physicalCapture?captureSource.frameEvent():nullptr);};+ auto waitLive=[&]{const auto due=liveScheduler?liveScheduler->wakeAt():0;deadlineWait.slice(due>host100ns()?std::min(1.0,double(due-host100ns())/10000):1.0,physicalCapture?captureSource.frameEvent():nullptr,physicalCapture?gpuReadyEvent.handle:nullptr);};uint64_t metricsRevision=options.settings.revision,metricsEpoch=0,metricsWindowEpoch=0,statsSourceBase=0;uint64_t slotWaitBase=ring.cpuWaitCount(),submitBase=ring.submitCount();double slotWaitMsBase=ring.cpuWaitMilliseconds();std::shared_ptr<FrameCompletionRates> completionRates;@@ -723,11 +758,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sbool captureRecovering=false;unsigned captureRetries=0;Clock::time_point captureRetryAt{};bool xessPresentationRecovery=false;- bool fsrPresentationRecovery=false;- bool fsrDegradedReported=false;auto recoverXessPresentation=[&]{- const bool fsrFailed=presenter.fsrFailed();- if((!presenter.xessFailed()&&!fsrFailed)||FAILED(ctx.device()->GetDeviceRemovedReason()))return false;+ if(!presenter.xessFailed()||FAILED(ctx.device()->GetDeviceRemovedReason()))return false;auto reduced=options.snapshot();if(!disableFailedBackend(reduced,FailedBackend::Fg))return false;holdFileAudio();fileAudioAlignPending=true;@@ -741,11 +773,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sstd::lock_guard lock(mutex_);desired_.rejectVideoRequest(options.snapshot(),reduced);desired_.revision=++nextRevision_;snapshot_.desired=desired_;snapshot_.applying=true;- snapshot_.backendWarning=fsrFailed?L"AMD FSR 帧生成呈现失败,正在恢复基础播放;错误码见日志":L"XeSS 呈现失败,正在恢复基础播放;错误码见日志";+ snapshot_.backendWarning=L"XeSS 呈现失败,正在恢复基础播放;错误码见日志";}- veyra::log::warn("backend-recovery",std::format("{} presentation failed; drained commands, requesting swapchain rebuild without FG",fsrFailed?"AMD FSR":"XeSS"));- xessPresentationRecovery=!fsrFailed;- fsrPresentationRecovery=fsrFailed;+ veyra::log::warn("backend-recovery",std::format("{} presentation failed; drained commands, requesting swapchain rebuild without FG","XeSS"));+ xessPresentationRecovery=true;reset=true;pendingResetCause=pipeline::ResetReason::Settings;return true;};@@ -785,7 +816,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(audioStarted)publishAudioStatus();if(audioStarted&&injectFileEndpointLoss&&!fileEndpointLossInjected&&frames>=20){audioPipe.requestEndpointLossForTest();fileEndpointLossInjected=true;}advanceLive();- if(liveScheduler&&liveScheduler->failed()){if(recoverXessPresentation())continue;status(L"视频呈现失败,请查看诊断",true);break;}+ if(liveScheduler&&liveScheduler->failed()){+ if(recoverXessPresentation())continue;+ const bool alive=ctx.reportDeviceFailure("live-presentation-failed");+ status(alive?L"视频队列或呈现失败;GPU 未报告设备移除,请查看诊断":L"GPU 设备已移除或驱动已重置;请稍后重新连接,可切换 NR 运行库后重试",true);break;+ }const float gain=muted_?0.0f:volume_.load();audio.setGain(gain);if(physicalCapture)captureSource.recoverAudio(gain,unsigned(options.settings.audioSync),options.settings.audioOffsetMs);captureSource.setAudioSync(unsigned(options.settings.audioSync),options.settings.audioOffsetMs);@@ -798,7 +833,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s#endif// Save the latest processed real frame before a settings transaction// invalidates it (live rendering can be one batch behind processing).- std::wstring save;EnhancementSettings requested;{std::lock_guard lock(mutex_);requested=desired_;if(hasOutput)save.swap(savePath_);}+ std::wstring save;EnhancementSettings requested;std::optional<ChainRuntimeOrder> requestedOrder;+ {std::lock_guard lock(mutex_);requested=desired_;requestedOrder=desiredNodeOrder_;if(hasOutput)save.swap(savePath_);}if(!save.empty()){try{sink::RgbaImage result;const auto e=std::filesystem::path(save).extension().wstring();drainLivePresentation();if(graph.hdrOutput()){auto hdrPath=std::filesystem::path(save);hdrPath.replace_extension(L".jxr");if(sink::saveHdrScreenshot(hdrPath.wstring(),ctx,ring,graph.videoFrameResource(out.videoSlot)))status(L"HDR截图已保存:"+hdrPath.wstring());else status(L"HDR截图保存失败,请查看日志",false);}else if(!sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),result)||!sink::saveImage(save,result,e==L".jpg"||e==L".jpeg"))status(L"保存失败(目标文件可能已存在),播放已保留",false);else{status(L"图片已保存:"+save);veyra::log::info("image-save",std::format("saved extent={}x{} revision={}",gd.workWidth,gd.workHeight,options.settings.revision));}}@@ -833,7 +869,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sstd::lock_guard lock(mutex_);snapshot_.applied=options.snapshot();snapshot_.applying=desired_!=snapshot_.applied;veyra::log::info("settings",std::format("Audio applied videoRevision={} mode={} offsetMs={} (video history retained)",requested.revision,unsigned(requested.audioSync),requested.audioOffsetMs));}- const auto previous=options.snapshot();const auto previousDesc=gd;bool transaction=false;+ const auto previous=options.snapshot();const auto previousDesc=gd;const auto previousOrder=options.nodeOrder;bool transaction=false;if(requested.revision!=previous.revision){holdFileAudio();finishReset(diagnostics::ResetOutcome::Cancelled);@@ -854,12 +890,12 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// A drain may outlive several slider notifications. Build// only the latest pending configuration at this boundary.- {std::lock_guard lock(mutex_);requested=desired_;}+ {std::lock_guard lock(mutex_);requested=desired_;requestedOrder=desiredNodeOrder_;}if(requested.revision==previous.revision){finishReset(diagnostics::ResetOutcome::Cancelled);continue;}resetRecord->settingsRevision=requested.revision;- auto next=PlayerOptions::from(requested);auto nextDesc=gd;+ auto next=PlayerOptions::from(requested,requestedOrder);auto nextDesc=gd;const bool nvidiaAdapter=ctx.adapter().isNvidia;- const bool xessFg=presentSinkFrameGeneration(next.settings.frameGenerationBackend);+ const bool xessFg=crossVendorFrameGeneration(next.settings.frameGenerationBackend);describeStages(stageRequest(next),next.snapshot(),nextDesc);nextDesc.hdrOutput=requested.useHdrPreview(nextDesc.hdrInput,displayHdrActive());// Rebuild decision.@@ -875,7 +911,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// extents come from the resolution plan, and a non-NVIDIA// adapter resolves requested effects differently than the// settings record.- bool rebuild=engine::requiresGraphRebuild(previous,requested);+ bool rebuild=engine::requiresGraphRebuild(previous,requested)||previousOrder!=requestedOrder;if(gd.hdrOutput!=nextDesc.hdrOutput||(!nvidiaAdapter&&(next.nr||next.sr||(next.fg&&!xessFg)))||gd.enableNr!=nextDesc.enableNr||gd.enableFg!=nextDesc.enableFg||@@ -890,14 +926,14 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sbackendRecoveryWarning.clear();const bool preserveWorkingFg=previous.multiplier>1&&requested.multiplier>1&&(previous.frameGenerationBackend!=requested.frameGenerationBackend||previous.multiplier!=requested.multiplier);- if(accepted&&rebuild){presenter.close();graph.shutdown();markResetStage(diagnostics::ResetStage::Destroy);accepted=initializePreview(nextDesc,next,preserveWorkingFg);+ const bool preserveWorkingNr=previous.nr&&requested.nr&&previous.nrRuntime!=requested.nrRuntime;+ if(accepted&&rebuild){presenter.close();graph.shutdown();markResetStage(diagnostics::ResetStage::Destroy);accepted=initializePreview(nextDesc,next,preserveWorkingFg,preserveWorkingNr);markResetStage(diagnostics::ResetStage::Create);if(!accepted){presenter.close();graph.shutdown();if(!graph.initialize(gd)||!presenter.open(ctx,window,graph,options.settings.captureCompatible,!isCapture&&!isImage)||!graph.createViews()){status(L"设置失败且旧资源恢复失败,已停止",true);break;}}}else if(accepted)accepted=graph.applySettings(requested);if(rebuild)publishFrameGenerationCapabilities();if(accepted){if(xessPresentationRecovery){backendRecoveryWarning=L"XeSS 呈现失败,已关闭补帧并恢复播放;错误码见日志";xessPresentationRecovery=false;}- if(fsrPresentationRecovery){backendRecoveryWarning=L"AMD FSR 帧生成呈现失败,已关闭补帧并恢复播放;错误码见日志";fsrPresentationRecovery=false;}if(!backendRecoveryWarning.empty()){std::lock_guard lock(mutex_);desired_.rejectVideoRequest(requested,next.snapshot());snapshot_.desired=desired_;snapshot_.backendWarning=backendRecoveryWarning;}@@ -907,7 +943,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s}else {finishReset(diagnostics::ResetOutcome::RolledBack);- std::lock_guard lock(mutex_);desired_.rejectVideoRequest(requested,previous);snapshot_.desired=desired_;snapshot_.rejectedRevision=requested.revision;snapshot_.applying=desired_!=previous;snapshot_.status=L"设置应用失败,已恢复上一套参数";snapshot_.backendWarning=requested.nrRuntime!=previous.nrRuntime?L"NR运行版本切换失败,已恢复上一套参数":requested.frameGenerationBackend==FrameGenerationBackend::XeSS?L"XeSS 未能启用,已恢复上一套参数":requested.frameGenerationBackend==FrameGenerationBackend::Fsr?L"AMD FSR 帧生成未能启用,已恢复上一套参数":L"后端切换失败,已恢复上一套参数";}+ std::lock_guard lock(mutex_);if(desired_.revision==requested.revision)desiredNodeOrder_=previousOrder;desired_.rejectVideoRequest(requested,previous);snapshot_.desired=desired_;snapshot_.rejectedRevision=requested.revision;snapshot_.applying=desired_!=previous;snapshot_.status=L"设置应用失败,已恢复上一套参数";snapshot_.backendWarning=requested.nrRuntime!=previous.nrRuntime?L"NR运行版本切换失败,已恢复上一套参数":requested.frameGenerationBackend==FrameGenerationBackend::XeSS?L"XeSS 未能启用,已恢复上一套参数":requested.frameGenerationBackend==FrameGenerationBackend::Fsr4?L"FSR 4 ML 未能启用(需要支持的 RX 9000 和驱动),已恢复上一套参数":fsrFrameGeneration(requested.frameGenerationBackend)?L"FSR 3.1 帧生成未能启用,已恢复上一套参数":L"后端切换失败,已恢复上一套参数";}}// Live uniform update. The revision identifies the graph *shape*// (NR/SR/FG/resolution and the colour master switch); colour@@ -917,7 +953,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// unrelated rebuild (toggling NR): the "sliders do nothing" report.if(requested.revision==previous.revision&&!(requested==previous)){if(graph.applySettings(requested)){- options=PlayerOptions::from(requested);+ options=PlayerOptions::from(requested,requestedOrder);{std::lock_guard lock(mutex_);snapshot_.applied=options.snapshot();snapshot_.applying=desired_!=snapshot_.applied;}veyra::log::info("settings",std::format("live parameter update revision={} colourEnabled={} exposure={:.2f} contrast={:.2f} temperature={:.2f}",requested.revision,requested.color.enabled?1:0,requested.color.exposure,requested.color.contrast,requested.color.temperature));// Colour lives inside the ingest dispatch, so a paused@@ -926,7 +962,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// be re-rendered before the next present.if(paused_||isImage)refreshPausedFrame_=true;}else{- std::lock_guard lock(mutex_);desired_.rejectVideoRequest(requested,previous);snapshot_.desired=desired_;snapshot_.applying=desired_!=previous;snapshot_.status=L"这套参数需要重建管线,已回到上一套数值";+ std::lock_guard lock(mutex_);if(desired_.revision==requested.revision)desiredNodeOrder_=previousOrder;desired_.rejectVideoRequest(requested,previous);snapshot_.desired=desired_;snapshot_.applying=desired_!=previous;snapshot_.status=L"这套参数需要重建管线,已回到上一套数值";}}if(stop_)break;@@ -995,7 +1031,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(liveScheduler&&!transaction){const auto enhancementPending=[&]{if(presentationEffective.enabled&&!options.fg&&(isCapture||!fileAwaitingVideo)&&liveScheduler->occupancy()>=1)return true;- return isCapture&&options.fg&&!presentSinkFrameGeneration(options.settings.frameGenerationBackend)&&!pendingCompletions.empty();+ // Live sources: never stack a second frame behind one the GPU+ // is still enhancing. When NR/SR cost more than one source+ // interval, a second queued frame doubled capture-to-present+ // latency (3 NR layers at 1440p60: 49 ms for 20 ms of GPU+ // work); waiting and then taking the newest mailbox sample+ // keeps it at one GPU pass. No effect while the GPU keeps up.+ return isCapture&&!(options.fg&&presentSinkFrameGeneration(options.settings.frameGenerationBackend))&&!pendingCompletions.empty();};const auto leaseWaitStart=Clock::now();while((liveScheduler->occupancy()>=2||!graph.nextFrameSlotAvailable()||enhancementPending())&&!stop_&&(!paused_||seekPreviewPending)&&!liveScheduler->failed()){@@ -1332,7 +1374,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(!ring.drainQueue()||!ring.discardRecording()){status(L"增强故障恢复排空失败",true);break;}out={};hasOutput=false;presenter.close();graph.shutdown();{std::lock_guard lock(mutex_);reduced.revision=++nextRevision_;}- options=PlayerOptions::from(reduced);+ options=PlayerOptions::from(reduced,options.nodeOrder);describeStages(stageRequest(options),options.snapshot(),gd);if(!initializePreview(gd,options)){status(L"增强故障后的基础图重建失败",true);break;}publishFrameGenerationCapabilities();@@ -1345,12 +1387,12 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s}}if(transaction){- ring.drainQueue();out={};presenter.close();graph.shutdown();options=PlayerOptions::from(previous);+ ring.drainQueue();out={};presenter.close();graph.shutdown();options=PlayerOptions::from(previous,previousOrder);gd=previousDesc;if(graph.initialize(gd)&&presenter.open(ctx,window,graph,options.settings.captureCompatible,!isCapture&&!isImage)&&graph.createViews()&&graph.process(frame,pts,true,out,pkt.sequence,&pkt.colorInfo,&pkt.hardwareSurface,comparisonMode_!=0)){publishFrameGenerationCapabilities();finishReset(diagnostics::ResetOutcome::RolledBack);- std::lock_guard lock(mutex_);desired_.rejectVideoRequest(requested,previous);snapshot_.desired=desired_;snapshot_.rejectedRevision=requested.revision;snapshot_.applying=desired_!=previous;snapshot_.status=L"参数执行失败,已整套回滚";transaction=false;+ std::lock_guard lock(mutex_);if(desired_.revision==requested.revision)desiredNodeOrder_=previousOrder;desired_.rejectVideoRequest(requested,previous);snapshot_.desired=desired_;snapshot_.rejectedRevision=requested.revision;snapshot_.applying=desired_!=previous;snapshot_.status=L"参数执行失败,已整套回滚";transaction=false;}else{status(L"参数回滚失败,已停止",true);break;}}else{status(std::wstring(backendFailureName(failedComponent))+L"执行失败;请查看日志",true);break;}}@@ -1381,7 +1423,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// Admission predictions and the XeSS gate must not carry// samples across a settings revision (new backend/dimensions);// soft preview-skip history breaks do NOT reopen them.- if(settingsChanged){fedXessPresented=fedXessGenerated=fedFsrPresented=fedFsrGenerated=0;}+ if(settingsChanged){fedXessPresented=fedXessGenerated=0;}playbackSpeedLastWall={};if(liveScheduler){liveStats={};liveSubmissions.clear();liveAges.clear();liveWaits.clear();livePresent.clear();livePresentGpu.clear();liveReady.clear();}if(settingsChanged||!completionRates)completionRates=std::make_shared<FrameCompletionRates>(host100ns());@@ -1434,6 +1476,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,swatch->captureArrival=captureArrival;watch->presentationGeneration=jobGeneration;watch->reflexFrame=currentReflexFrame;pendingCompletions.push_back(watch);+ if(physicalCapture&&gpuReadyEvent.handle)for(unsigned i=0;i<out.batch.count;++i){+ const auto& lease=out.batch.frames[i].lease;+ if(lease&&lease->readyFenceObject&&lease->readyFence)lease->readyFenceObject->SetEventOnCompletion(lease->readyFence,gpuReadyEvent.handle);+ }struct LiveStepState {unsigned next=0,handled=0,remaining=0;bool readyReported=false;Clock::time_point readyStart=Clock::now();std::optional<Clock::time_point> deadlineStart;@@ -1452,7 +1498,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// loop, so all of these are declared above it. Adding a reference to a// local declared after that guard is now a compile error instead of a// silent dangling reference.- if(!liveScheduler->push([this,&anchor,&anchorMs,&captureSource,&fedFsrGenerated,&fedFsrPresented,&fedXessGenerated,&fedXessPresented,&lastFilePresentLateness,&lastFilePresentedMs,&liveSubmissions,&presentationCompletedReal,+ if(!liveScheduler->push([this,&anchor,&anchorMs,&captureSource,&fedXessGenerated,&fedXessPresented,&lastFilePresentLateness,&lastFilePresentedMs,&liveSubmissions,&presentationCompletedReal,#ifdef VEYRA_ENABLE_REMOTEPLAY&remote,#endif@@ -1480,7 +1526,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(traceSubframes&&generated&&(readiness==PreviewFrameReadiness::Expired||readiness==PreviewFrameReadiness::Suppressed))traceFrame(diagnostics::TraceKind::Discarded,item.identity,batch.batch.batchId,item.lease->readyFence,item.pts100ns,item.subframe,unsigned(readiness),isCapture?double(decisionTime-timeline.deadline(item.pts100ns))/10000:nowMs()-itemPtsMs);if(readiness==PreviewFrameReadiness::Pending){- if(elapsedMs(s.readyStart)>2000){veyra::log::error("capture-present","GPU frame ready timeout");return {State::Failed};}+ if(elapsedMs(s.readyStart)>2000){+ ctx.reportDeviceFailure("GPU-frame-ready-timeout",item.lease?item.lease->readyFence:0);+ veyra::log::error("capture-present",std::format("GPU frame ready timeout nr={} nrRuntime={} source={} epoch={} revision={} subframe={} dimensions={}x{} nrDimensions={}x{} flowBackend={}",graph.nrEnabled(),nrRuntimeName(options.settings.nrRuntime),item.identity.sourceFrameId,item.identity.epoch,item.identity.settingsRevision,item.subframe,graph.workWidth(),graph.workHeight(),graph.nrWidth(),graph.nrHeight(),opticalFlowBackendName(options.settings.opticalFlowBackend)));+ return {State::Failed};+ }return {State::Pending,host100ns()+2000};}if(readiness==PreviewFrameReadiness::Invalid){++s.handled;++s.next;s.deadlineStart.reset();continue;}@@ -1565,11 +1615,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst auto xessPresentedTotal=presenter.xessPresentedCount(),xessGeneratedTotal=presenter.xessGeneratedCount();const uint64_t xessPresented=xessPresentedTotal-fedXessPresented,xessGenerated=xessGeneratedTotal-fedXessGenerated;if(xessPresented){flow->xessSubmitted(xessPresented,xessGenerated,host100ns());fedXessPresented=xessPresentedTotal;fedXessGenerated=xessGeneratedTotal;}- const auto fsrPresentedTotal=presenter.fsrPresentedCount(),fsrGeneratedTotal=presenter.fsrGeneratedCount();- const uint64_t fsrPresented=fsrPresentedTotal-fedFsrPresented,fsrGenerated=fsrGeneratedTotal-fedFsrGenerated;- // Same metric shape for the AMD provider: frames it actually- // submitted to the display, real and generated.- if(fsrPresented){flow->xessSubmitted(fsrPresented,fsrGenerated,host100ns());fedFsrPresented=fsrPresentedTotal;fedFsrGenerated=fsrGeneratedTotal;}+}if(didPresent&&!isCapture){lastFilePresentedMs=itemPtsMs;lastFilePresentLateness=returnDeviation;@@ -1672,7 +1718,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// Present-sink FG backends record their application-side work on// the presenter's list; surface that sample instead of leaving// the stage unmeasured. The in-graph DLSS FG keeps its own.- if(graph.xessEnabled()||graph.fsrEnabled())measured.gpu[size_t(diagnostics::GpuStage::FgBatch)]=presenter.fgTiming(ctx.fence(),options.settings.revision,out.batch.identity.epoch);+ if(graph.xessEnabled())measured.gpu[size_t(diagnostics::GpuStage::FgBatch)]=presenter.fgTiming(ctx.fence(),options.settings.revision,out.batch.identity.epoch);slotWaitCount=ring.cpuWaitCount()-slotWaitBase;slotWaitMilliseconds=ring.cpuWaitMilliseconds()-slotWaitMsBase;commandSubmits=ring.submitCount()-submitBase;slotsInFlight=ring.inFlightCount();loopTrace.mark("gpuStats");collectTimings();@@ -1682,15 +1728,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(graph.xessEnabled()){graphStats.fgGeneratedFrames=presenter.xessGeneratedCount();}- if(graph.fsrEnabled()){- graphStats.fgGeneratedFrames=presenter.fsrGeneratedCount();- }- if(graph.fsrEnabled()&&presenter.fsrFailed()&&!fsrDegradedReported){- fsrDegradedReported=true;- std::lock_guard lock(mutex_);- snapshot_.backendWarning=L"AMD FSR 帧生成已停用(原因见日志),继续基础播放";- veyra::log::warn("backend-recovery","AMD FSR frame generation degraded to plain presentation inside the provider");- }++for(size_t stage=0;stage<measured.gpu.size();++stage){const auto& sample=measured.gpu[stage];if(sample.state==diagnostics::SampleState::Measured&&sample.milliseconds&&sample.end&&sample.end!=lastGpuSampleEnd[stage]){gpuStageTimes[stage].add(*sample.milliseconds);lastGpuSampleEnd[stage]=sample.end;}}measured.resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.snapshot().nrPolicy,isImage,options.settings.revision,options.settings.srTarget,options.settings.lowLatency&&options.nr);measured.decodeCpuMs=decodeMs;measured.submitCpuMs=std::chrono::duration<double,std::milli>(processDone-processStart).count();measured.gpuWaitCpuMs=gpuWaitMs;measured.deadlineWaitCpuMs=frameWaitMs;measured.presentCpuMs=framePresentMs;measured.queueWatermark=out.batch.count;LiveStats completed;if(liveScheduler)completed=liveStats;@@ -1704,6 +1743,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,smeasured.sourceFrames=measured.flow.counters.sourceAccepted;measured.validGenerated=measured.flow.counters.fgReadyValid;measured.submitted=measured.flow.counters.realPresented+measured.flow.counters.generatedPresented;measured.expired=measured.flow.counters.generatedExpiredAfterEval;const double ageP95=liveScheduler?completed.ageP95:captureAges.p95(),waitP95=liveScheduler?completed.waitP95:scheduleWaits.p95(),presentP95=liveScheduler?completed.presentP95:presentTimes.p95();++frames;{std::lock_guard lock(mutex_);snapshot_.metrics=measured;snapshot_.colorStatus=graph.videoHdrActive()?L"SDR → RTX Video HDR":options.settings.videoHdr.enabled&&!gd.hdrInput?L"SDR → SDR(HDR显示未启用)":gd.hdrOutput?(graph.hdr10Output()?L"HDR → HDR10 / PQ":L"HDR → scRGB / 浮点"):gd.hdrInput?L"HDR → SDR色调映射":L"SDR → SDR";snapshot_.position=(isCapture||isImage?pts:lastFilePresentedMs)/1000;snapshot_.frames=sourceFrames;snapshot_.generated=graphStats.fgGeneratedFrames;snapshot_.lateMs=lateness;snapshot_.lateP95Ms=presentReturnDeviation.p95();+ snapshot_.videoHdrActive=graph.videoHdrActive();snapshot_.videoHdrStatus=graph.videoHdrActive()?L"预览:SDR 转 HDR 已运行":!options.settings.videoHdr.enabled?L"RTX Video HDR 已关闭":gd.hdrInput?L"原生 HDR 输入,无需 SDR 转 HDR":@@ -1739,6 +1779,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst auto gpuP95=[&](diagnostics::GpuStage stage){return gpuStageTimes[size_t(stage)].p95();};if(veyra::log::verboseFrameLogs()&&Clock::now()>=nextTimingLog){const auto [retained,overwritten]=Logger::instance().frameTraceSize();veyra::log::info("frame-trace",std::format("retained={} capacity=8192 overwritten={} (records available in diagnostic preview)",retained,overwritten));}+ if(options.settings.multiplier>1&&Clock::now()>=nextTimingLog)+ veyra::log::info("fg-validity",std::format("revision={} candidate={} valid={} invalid={} providerDisabled={} contentDuplicate={} both={} contentPolicy={} sourceTransportFps={} backend={} (invalid union=provider+duplicate-both; no automatic content-rate/multiplier rewrite)",options.settings.revision,graphStats.fgSubmittedCandidates,graphStats.fgGeneratedFrames,graphStats.fgDisabledFrames,graphStats.fgProviderDisabled,graphStats.fgDuplicateSuppressed,graphStats.fgBothDisabled,int(options.settings.content),activeSource->info().averageFps,frameGenerationBackendName(options.settings.frameGenerationBackend)));if(!isCapture&&Clock::now()>=nextTimingLog){const double playbackSpeedNow=[&]{std::lock_guard lock(mutex_);return snapshot_.playbackSpeed;}();// present-deviation / output-queue are folded into the// player-timing line below (sweep E5); the separate lines stay@@ -1764,7 +1806,14 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s{std::lock_guard lock(mutex_);activeRemote_.reset();}if(remote)remote->close();#endif- audioPipe.stopThread();audio.shutdown();ring.drainQueue();presenter.close();graph.shutdown();captureSource.close();screenSource.close();source.close();av_frame_free(&cachedFrame);av_frame_free(&imageFrame);ring.shutdown();ctx.shutdown();+ // Each step is logged: a session that stopped responding after a remote+ // play failure left "graph shutdown complete" as its last line.+ audioPipe.stopThread();audio.shutdown();veyra::log::info("engine","teardown: audio stopped");+ ring.drainQueue();presenter.close();graph.shutdown();+ veyra::log::info("engine","teardown: closing sources");+ captureSource.close();screenSource.close();source.close();av_frame_free(&cachedFrame);av_frame_free(&imageFrame);+ veyra::log::info("engine","teardown: sources closed");+ ring.shutdown();ctx.shutdown();{std::lock_guard lock(mutex_);snapshot_.running=false;snapshot_.audioEndpointRecovering=false;snapshot_.audioRebuffering=false;}CoUninitialize();}diff --git a/src/engine/EngineControllerImage.cpp b/src/engine/EngineControllerImage.cppindex 34243563..911ced76 100644--- a/src/engine/EngineControllerImage.cpp+++ b/src/engine/EngineControllerImage.cpp@@ -66,6 +66,7 @@ void EngineController::runLargeImage(HWND window,const sink::RgbaImage& originalif(requested.revision!=applied.revision){pipeline::EnhanceGraphDesc desc;desc.enableNr=requested.nr;desc.nrRuntime=requested.nrRuntime;desc.noFeatures=!requested.nr;desc.model=requested.model;desc.nrTemporal=requested.nrTemporal;desc.residual=requested.residual;desc.protection=requested.protection;desc.color=requested.color;desc.settingsRevision=requested.revision;+ desc.additionalColors=requested.additionalColors;desc.additionalColorCount=requested.additionalColorCount;desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();sink::RgbaImage candidate;TiledImageProcessor::Stats stats;status(L"正在分块增强大图,保留完整输出尺寸…");diff --git a/src/engine/ExportJobManager.cpp b/src/engine/ExportJobManager.cppindex 11945b02..f7b154f1 100644--- a/src/engine/ExportJobManager.cpp+++ b/src/engine/ExportJobManager.cpp@@ -23,7 +23,7 @@ struct Shared {// chain is fixed-capacity and trivially copyable, so it can cross the// process boundary; a worker that sees another version refuses the job// instead of reading a mismatched layout.- DWORD signature=magic,version=4,bytes=sizeof(Shared);+ DWORD signature=magic,version=5,bytes=sizeof(Shared); // R5.3 independent colour settingsEnhancementSettings settings;EffectChain chain;wchar_t input[32768]{},output[32768]{};@@ -44,6 +44,21 @@ struct ExportJobManager::Impl {ExportJobSnapshot snapshot;ULONGLONG cancelAt=0,startTick=0;struct Request { std::wstring input,output; EnhancementSettings settings; bool hevc=false; unsigned maxFrames=0; int audioStreamIndex=-1; double trimStart=0,trimEnd=0; sink::ExportRateControl rateControl=sink::ExportRateControl::Cq; };std::deque<Request> queue;+ uint64_t queueFailures=0;std::wstring lastQueueFailure;bool launchingQueued=false;+ // Starts queued items in order until one launches; each refusal is recorded.+ bool startNext(ExportJobManager& owner){+ while(!queue.empty()){+ auto next=std::move(queue.front());queue.pop_front();+ launchingQueued=true;+ const bool started=owner.start(next.input,next.output,next.settings,next.hevc,next.maxFrames,next.audioStreamIndex,next.trimStart,next.trimEnd,next.rateControl);+ launchingQueued=false;+ if(started)return true;+ ++queueFailures;+ lastQueueFailure=std::filesystem::path(next.output).filename().wstring()+L":"+snapshot.message;+ log::warn("export-queue",std::format("queued item refused output={} reason={} failures={}",utf8(next.output),utf8(snapshot.message),queueFailures));+ }+ return false;+ }void clear(){if(shared){UnmapViewOfFile(shared);shared=nullptr;}close(process);close(job);close(mapping);cancelAt=0;}~Impl(){clear();}};@@ -53,7 +68,13 @@ ExportJobManager::ExportJobManager():p_(std::make_unique<Impl>()){}// stalling process exit for up to five seconds.ExportJobManager::~ExportJobManager(){cancel();clearQueue();if(p_->process)WaitForSingleObject(p_->process,1000);p_->clear();}bool ExportJobManager::start(const std::wstring& input,const std::wstring& output,EnhancementSettings settings,bool hevc,unsigned maxFrames,int audioStreamIndex,double trimStartSeconds,double trimEndSeconds,sink::ExportRateControl rateControl){- if(poll().active())return false;p_->clear();p_->snapshot={};+ // Busy means a launched worker not yet collected. Not poll(): polling here+ // starts the next queued item, which made a queued conflict look "busy"+ // and dropped it without a failure.+ if(p_->shared)return false;p_->clear();+ if(!p_->launchingQueued){p_->queueFailures=0;p_->lastQueueFailure.clear();}+ const auto failures=p_->queueFailures;const auto lastFailure=p_->lastQueueFailure;+ p_->snapshot={};p_->snapshot.queueFailures=failures;p_->snapshot.lastQueueFailure=lastFailure;auto fail=[&](const wchar_t* message){const DWORD error=GetLastError();p_->clear();p_->snapshot.state=ExportState::Failed;p_->snapshot.message=message;log::error("export-worker",std::format("launch failed error={}",error));return false;};if(input.empty()||output.empty()||input.size()>=32768||output.size()>=32768||!settings.validate().empty()||input.starts_with(L"capture:")||input.starts_with(L"capture2:"))return fail(L"请选择本地视频与有效导出设置");if(rateControl!=sink::ExportRateControl::Cq&&settings.exportBitrateMbps==0)return fail(L"CBR/VBR 需要指定码率;CQ 不使用码率");@@ -85,7 +106,9 @@ bool ExportJobManager::start(const std::wstring& input,const std::wstring& outpulog::info("export-worker",std::format("started jobId={} pid={} frozenRevision={} nativeNR=true independentPlayback=true log={}",p_->snapshot.jobId,pi.dwProcessId,settings.revision,std::filesystem::path(p_->snapshot.workerLog).string()));return true;}bool ExportJobManager::enqueue(const std::wstring& input,const std::wstring& output,EnhancementSettings settings,bool hevc,unsigned maxFrames,int audioStreamIndex,double trimStartSeconds,double trimEndSeconds,sink::ExportRateControl rateControl){- if(poll().active()){p_->queue.push_back({input,output,settings,hevc,maxFrames,audioStreamIndex,trimStartSeconds,trimEndSeconds,rateControl});return true;}+ if(poll().active()||!p_->queue.empty()){p_->queue.push_back({input,output,settings,hevc,maxFrames,audioStreamIndex,trimStartSeconds,trimEndSeconds,rateControl});return true;}+ // A new batch from idle starts with a clean failure record.+ p_->queueFailures=0;p_->lastQueueFailure.clear();return start(input,output,settings,hevc,maxFrames,audioStreamIndex,trimStartSeconds,trimEndSeconds,rateControl);}void ExportJobManager::clearQueue(){p_->queue.clear();}@@ -94,13 +117,9 @@ void ExportJobManager::cancel(){if(p_->shared&&p_->snapshot.active()){Interlockevoid ExportJobManager::pause(bool v){if(p_->shared)InterlockedExchange(&p_->shared->pause,v);}void ExportJobManager::watching(bool v){if(p_->shared)InterlockedExchange(&p_->shared->watching,v);}ExportJobSnapshot ExportJobManager::poll(){- if(!p_->shared&&!p_->queue.empty()){- auto next=std::move(p_->queue.front());p_->queue.pop_front();- if(!start(next.input,next.output,next.settings,next.hevc,next.maxFrames,next.audioStreamIndex,next.trimStart,next.trimEnd,next.rateControl)){- p_->snapshot.queuePosition=0;p_->snapshot.queued=p_->queue.size();return p_->snapshot;- }- }- if(!p_->shared){p_->snapshot.queued=p_->queue.size();return p_->snapshot;}+ if(!p_->shared&&!p_->queue.empty())p_->startNext(*this);+ p_->snapshot.queueFailures=p_->queueFailures;p_->snapshot.lastQueueFailure=p_->lastQueueFailure;+ if(!p_->shared){p_->snapshot.queuePosition=0;p_->snapshot.queued=p_->queue.size();return p_->snapshot;}auto& s=*p_->shared;p_->snapshot.sourceFrames=InterlockedCompareExchange64(&s.sourceFrames,0,0);p_->snapshot.generated=InterlockedCompareExchange64(&s.generated,0,0);p_->snapshot.holds=InterlockedCompareExchange64(&s.holds,0,0);p_->snapshot.encoded=InterlockedCompareExchange64(&s.encoded,0,0);p_->snapshot.state=static_cast<ExportState>(InterlockedCompareExchange(&s.state,0,0));p_->snapshot.progress=InterlockedCompareExchange(&s.progress,0,0)/10000.0;p_->snapshot.queued=p_->queue.size();p_->snapshot.queuePosition=p_->queue.empty()?0:1;if(p_->snapshot.progress>0.001&&p_->startTick){const double elapsed=double(GetTickCount64()-p_->startTick)/1000.0;p_->snapshot.etaSeconds=std::max(0.0,elapsed*(1.0-p_->snapshot.progress)/p_->snapshot.progress);}else p_->snapshot.etaSeconds=0;if(p_->cancelAt&&GetTickCount64()-p_->cancelAt>5000&&WaitForSingleObject(p_->process,0)==WAIT_TIMEOUT)TerminateJobObject(p_->job,3);@@ -114,15 +133,17 @@ ExportJobSnapshot ExportJobManager::poll(){if(final.state==ExportState::Failed)p_->snapshot.message+=L"\n日志:"+final.workerLog;p_->clear();if(!p_->queue.empty()){- auto next=std::move(p_->queue.front());p_->queue.pop_front();- if(!start(next.input,next.output,next.settings,next.hevc,next.maxFrames,next.audioStreamIndex,next.trimStart,next.trimEnd,next.rateControl))p_->snapshot.queued=p_->queue.size();+ // The finished job's outcome is reported by this poll; the next one+ // is launched on the following poll so the UI sees both states.+ p_->snapshot.queued=p_->queue.size();p_->snapshot.queuePosition=0;+ return p_->snapshot;}}if(p_->shared&&InterlockedCompareExchange(&p_->shared->messageLock,1,0)==0){if(p_->shared->message[0])p_->snapshot.message=p_->shared->message;InterlockedExchange(&p_->shared->messageLock,0);}if(p_->snapshot.message.empty()||p_->snapshot.state==ExportState::Paused||p_->snapshot.state==ExportState::Cancelled)p_->snapshot.message=label(p_->snapshot.state);return p_->snapshot;}int runExportWorker(HANDLE mapping){auto s=static_cast<Shared*>(MapViewOfFile(mapping,FILE_MAP_ALL_ACCESS,0,0,sizeof(Shared)));if(!s)return 1;- if(s->signature!=magic||s->version!=4||s->bytes!=sizeof(Shared)||s->audioStreamIndex< -1||s->rateControl>uint32_t(sink::ExportRateControl::Cq)||!std::isfinite(s->trimStartSeconds)||!std::isfinite(s->trimEndSeconds)||s->trimStartSeconds<0||s->trimEndSeconds<0||(s->trimEndSeconds>0&&s->trimEndSeconds<=s->trimStartSeconds)||!s->settings.validate().empty()||s->input[32767]||s->output[32767]){UnmapViewOfFile(s);CloseHandle(mapping);return 1;}+ if(s->signature!=magic||s->version!=5||s->bytes!=sizeof(Shared)||s->audioStreamIndex< -1||s->rateControl>uint32_t(sink::ExportRateControl::Cq)||!std::isfinite(s->trimStartSeconds)||!std::isfinite(s->trimEndSeconds)||s->trimStartSeconds<0||s->trimEndSeconds<0||(s->trimEndSeconds>0&&s->trimEndSeconds<=s->trimStartSeconds)||!s->settings.validate().empty()||s->input[32767]||s->output[32767]){UnmapViewOfFile(s);CloseHandle(mapping);return 1;}Logger::instance().openFile((runtime::logsDirectory()/std::format("export-worker-{}.log",GetCurrentProcessId())).wstring());// The chain is the description of record for this job; the settings struct// stays the runtime input until the executor consumes chains directly.diff --git a/src/engine/PresetLibrary.cpp b/src/engine/PresetLibrary.cppindex 66b6adbc..1da1b7e1 100644--- a/src/engine/PresetLibrary.cpp+++ b/src/engine/PresetLibrary.cpp@@ -10,6 +10,18 @@namespace veyra::engine {namespace {+// Six full grades per entry (plus the legacy first-grade field), up to 64+// entries. Never remove the file-size guard as LUT names are external input.+constexpr size_t kMaxPresetBytes = 2u * 1024u * 1024u;+void writeRendering(std::ostream& out,const ChainGlobalSettings& g){out<<' '<<int(g.hdrOutputMode)<<' '<<int(g.fgMotion)<<' '<<int(g.srMotion)<<' '<<int(g.nrMotion);}+bool readRendering(std::istream& in,ChainGlobalSettings& g){int hdr,fg,sr,nr;if(!(in>>hdr>>fg>>sr>>nr))return false;g.hdrOutputMode=HdrOutputMode(hdr);g.fgMotion=MotionSource(fg);g.srMotion=MotionSource(sr);g.nrMotion=MotionSource(nr);EnhancementSettings s;g.apply(s);return s.validate().empty();}+void applyRenderingPreset(const PresetEntry& e,EnhancementSettings& s){+ if(!e.globals)return;+ const auto fg=s.frameGenerationBackend;const auto fgMotion=s.fgMotion;+ if(e.contents&presetContentMask(PresetContent::Chain))e.globals->apply(s);+ if(e.contents&presetContentMask(PresetContent::FrameGeneration))s.fgMotion=e.globals->fgMotion;+ else{s.frameGenerationBackend=fg;s.fgMotion=fgMotion;}+}std::string utf8(const std::wstring& s) {if (s.empty()) return {};const int n = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, s.data(), int(s.size()), nullptr, 0, nullptr, nullptr);@@ -31,6 +43,7 @@ bool nameOk(const std::wstring& s) {} // namespacevoid PresetLibrary::addBuiltins() {+ if (!includeBuiltins_) return;auto add = [this](const wchar_t* name, const wchar_t* note, ChainMode kind, bool nr, bool sr,uint32_t multiplier, bool hdr, bool color) {PresetEntry entry;@@ -55,16 +68,28 @@ void PresetLibrary::addBuiltins() {bool PresetLibrary::load() {error_.clear();addBuiltins();+ const auto rootRendering=std::filesystem::path(path_).concat(L".field-render");+ if(std::filesystem::exists(rootRendering))path_=rootRendering;+ const auto migratedPath = std::filesystem::path(path_).concat(L".p3-node");+ if (std::filesystem::exists(migratedPath)) path_ = migratedPath;+ const auto editorPath = std::filesystem::path(path_).concat(L".p3-editor");+ if (std::filesystem::exists(editorPath) ||+ std::filesystem::exists(std::filesystem::path(editorPath).concat(L".p3-globals"))) path_ = editorPath;+ const auto globalsPath = std::filesystem::path(path_).concat(L".p3-globals");+ if (std::filesystem::exists(globalsPath)) path_ = globalsPath;+ const auto renderingPath=std::filesystem::path(path_).concat(L".field-render");+ if(std::filesystem::exists(renderingPath))path_=renderingPath;if (!std::filesystem::exists(path_)) return true;std::error_code ec;const auto size = std::filesystem::file_size(path_, ec);- if (ec || size > 262144) { corrupt_ = true; error_ = L"预设库文件过大,原文件保留"; return false; }+ if (ec || size > kMaxPresetBytes) { corrupt_ = true; error_ = L"预设库文件过大,原文件保留"; return false; }std::ifstream f(path_, std::ios::binary);if (!f) { corrupt_ = true; error_ = L"预设库无法读取,原文件保留"; return false; }const std::string data((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());std::vector<PresetEntry> loaded;std::wstring def, parseError;- if (!parse(data, loaded, def, parseError)) {+ bool migrated = false;+ if (!parse(data, loaded, def, parseError, &migrated)) {corrupt_ = true;error_ = parseError.empty() ? L"预设库损坏或版本不支持;原文件已保留,禁止覆盖" : parseError;return false;@@ -73,17 +98,92 @@ bool PresetLibrary::load() {// user who deleted nothing always sees them.entries_ = std::move(loaded);defaultName_ = def;+ if (migrated) {+ path_ = std::filesystem::path(path_).concat(L".p3-node");+ error_ = L"旧节点预设的 NR 保护区域已移除;其余参数保留,后续保存到 .p3-node 文件,原文件不覆盖";+ }addBuiltins();for (auto& entry : entries_) entry.builtin = entry.builtin || (entry.name == L"原画" || entry.name == L"流畅" || entry.name == L"均衡" || entry.name == L"极致");+ if (!includeBuiltins_) {+ const bool defaultWasBuiltin = std::any_of(entries_.begin(), entries_.end(), [this](const auto& e) {+ return e.builtin && e.name == defaultName_;+ });+ std::erase_if(entries_, [](const auto& e) { return e.builtin; });+ if (defaultWasBuiltin) defaultName_.clear();+ }+ return true;+}++bool PresetLibrary::exportEntry(size_t index, const std::filesystem::path& target) {+ error_.clear();+ if (index >= entries_.size()) { error_ = L"预设不存在"; return false; }+ auto entry = entries_[index];+ entry.builtin = false;+ const auto data = encodeEntries({entry}, L"");+ std::vector<PresetEntry> checked;+ std::wstring def;+ if (!parse(data, checked, def, error_) || checked.size() != 1) {+ if (error_.empty()) error_ = L"预设无法编码";+ return false;+ }+ std::error_code ec;+ const auto temp = std::filesystem::path(target).concat(L".tmp");+ {+ std::ofstream f(temp, std::ios::binary | std::ios::trunc);+ if (!f || !(f << data) || !f.flush()) { error_ = L"导出文件无法写入"; return false; }+ }+ std::filesystem::rename(temp, target, ec);+ if (ec) { std::filesystem::remove(temp, ec); error_ = L"导出文件无法替换"; return false; }+ return true;+}++bool PresetLibrary::importFile(const std::filesystem::path& source, std::wstring& nameOut) {+ error_.clear();+ if (corrupt_) { error_ = L"预设库损坏,已拒绝导入"; return false; }+ std::error_code ec;+ const auto size = std::filesystem::file_size(source, ec);+ if (ec || size == 0 || size > kMaxPresetBytes) { error_ = L"预设文件为空或过大"; return false; }+ std::ifstream f(source, std::ios::binary);+ if (!f) { error_ = L"预设文件无法读取"; return false; }+ const std::string data((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());+ std::vector<PresetEntry> loaded;+ std::wstring def, parseError;+ if (!parse(data, loaded, def, parseError) || loaded.empty()) {+ error_ = parseError.empty() ? L"不是 Veyra 预设文件" : parseError;+ return false;+ }+ auto entry = loaded.front();+ entry.builtin = false;+ const std::wstring base = entry.name.empty() ? std::wstring(L"导入的预设") : entry.name;+ auto taken = [this](const std::wstring& n) {+ return std::any_of(entries_.begin(), entries_.end(), [&n](const auto& e) { return e.name == n; });+ };+ entry.name = base;+ for (int n = 2; taken(entry.name) && n < 1000; ++n) entry.name = base.substr(0, 40) + L" " + std::to_wstring(n);+ if (!put(entry, false)) return false;+ nameOut = entry.name;return true;}bool PresetLibrary::save() {if (corrupt_) { error_ = L"预设库损坏,已拒绝覆盖原文件"; return false; }+ const auto data = serialize();+ std::vector<PresetEntry> checked;+ std::wstring checkedDefault;+ // Match PresetStore: never replace a valid file with one our reader rejects.+ if (!parse(data, checked, checkedDefault, error_)) return false;+ if(data.starts_with("VEYRA_PRESET_LIBRARY 6")&&!path_.wstring().ends_with(L".field-render"))path_=std::filesystem::path(path_).concat(L".field-render");+ if (std::any_of(entries_.begin(), entries_.end(), [](const auto& e) { return e.nodeConfiguration.has_value(); }) &&+ !path_.wstring().ends_with(L".field-render")&&!path_.wstring().ends_with(L".p3-editor") && !path_.wstring().ends_with(L".p3-globals"))+ path_ = std::filesystem::path(path_).concat(L".p3-editor");+ if (std::any_of(entries_.begin(), entries_.end(), [](const auto& e) {+ return e.nodeConfiguration && e.nodeConfiguration->editor && e.nodeConfiguration->editor->globals;+ }) && !path_.wstring().ends_with(L".field-render")&&!path_.wstring().ends_with(L".p3-globals"))+ path_ = std::filesystem::path(path_).concat(L".p3-globals");std::error_code ec;std::filesystem::create_directories(path_.parent_path(), ec);const auto temporary = std::filesystem::path(path_).concat(L".tmp");- { std::ofstream f(temporary, std::ios::binary | std::ios::trunc); if (!f) { error_ = L"预设库写入失败"; return false; } f << serialize(); if (!f) { error_ = L"预设库写入失败"; return false; } }+ { std::ofstream f(temporary, std::ios::binary | std::ios::trunc); if (!f) { error_ = L"预设库写入失败"; return false; } f << data; if (!f) { error_ = L"预设库写入失败"; return false; } }if (!MoveFileExW(temporary.c_str(), path_.c_str(), MOVEFILE_REPLACE_EXISTING)) {std::filesystem::remove(temporary, ec);error_ = L"预设库替换失败";@@ -98,21 +198,28 @@ bool PresetLibrary::put(const PresetEntry& entry, bool replace) {if (found != entries_.end()) {if (!replace) { error_ = L"同名预设已存在"; return false; }if (found->builtin) { error_ = L"内置预设不能覆盖,请换一个名称"; return false; }- *found = entry;- return save();+ const auto before = *found; *found = entry;+ if (save()) return true;+ *found = before; return false;}if (entries_.size() >= 64) { error_ = L"预设数量已达上限"; return false; }entries_.push_back(entry);- return save();+ if (save()) return true;+ entries_.pop_back(); return false;}bool PresetLibrary::rename(size_t index, std::wstring name) {if (index >= entries_.size() || entries_[index].builtin) { error_ = L"内置预设不能改名"; return false; }if (!nameOk(name)) { error_ = L"预设名称非法"; return false; }if (std::any_of(entries_.begin(), entries_.end(), [&](const PresetEntry& e) { return e.name == name; })) { error_ = L"同名预设已存在"; return false; }- if (defaultName_ == entries_[index].name) defaultName_ = name;+ const auto oldDefault = defaultName_;+ const auto oldName = entries_[index].name;+ if (defaultName_ == oldName) defaultName_ = name;entries_[index].name = std::move(name);- return save();+ if (save()) return true;+ entries_[index].name = oldName;+ defaultName_ = oldDefault;+ return false;}bool PresetLibrary::duplicate(size_t index) {@@ -125,21 +232,39 @@ bool PresetLibrary::duplicate(size_t index) {if (std::none_of(entries_.begin(), entries_.end(), [&](const PresetEntry& e) { return e.name == candidate; })) { copy.name = std::move(candidate); break; }}entries_.insert(entries_.begin() + std::ptrdiff_t(index) + 1, std::move(copy));- return save();+ if (save()) return true;+ entries_.erase(entries_.begin() + std::ptrdiff_t(index) + 1);+ return false;}bool PresetLibrary::erase(size_t index) {if (index >= entries_.size()) return false;if (entries_[index].builtin) { error_ = L"内置预设不能删除;可以复制后修改"; return false; }+ const auto oldDefault = defaultName_;+ const auto removed = entries_[index];if (defaultName_ == entries_[index].name) defaultName_.clear();entries_.erase(entries_.begin() + std::ptrdiff_t(index));- return save();+ if (save()) return true;+ entries_.insert(entries_.begin() + std::ptrdiff_t(index), removed);+ defaultName_ = oldDefault;+ return false;}bool PresetLibrary::setDefault(size_t index) {if (index >= entries_.size()) return false;+ const auto oldDefault = defaultName_;defaultName_ = entries_[index].name;- return save();+ if (save()) return true;+ defaultName_ = oldDefault;+ return false;+}++bool PresetLibrary::clearDefault() {+ const auto oldDefault = defaultName_;+ defaultName_.clear();+ if (save()) return true;+ defaultName_ = oldDefault;+ return false;}const std::optional<size_t> PresetLibrary::defaultIndex() const {@@ -154,13 +279,25 @@ void PresetLibrary::apply(const PresetEntry& entry, EnhancementSettings& setting// colour stage is part of it). Keep the unclaimed parts exactly as the// caller had them, so "chain only" never silently resets a colour look.const auto keepColor = settings.color;+ const auto keepAdditionalColors = settings.additionalColors;+ const auto keepAdditionalColorCount = settings.additionalColorCount;const auto keepMultiplier = settings.multiplier;const auto keepBackend = settings.frameGenerationBackend;+ applyRenderingPreset(entry,settings);const auto keepAudioSync = settings.audioSync;const auto keepAudioOffset = settings.audioOffsetMs;if (entry.contents & presetContentMask(PresetContent::Chain)) fromChain(entry.chain, settings);- if (entry.contents & presetContentMask(PresetContent::Color)) settings.color = entry.color;- else settings.color = keepColor;+ if (entry.contents & presetContentMask(PresetContent::Color)) {+ auto colors = settings;+ fromChain(entry.chain, colors);+ settings.color = entry.color; // legacy single-grade compatibility field+ settings.additionalColors = colors.additionalColors;+ settings.additionalColorCount = colors.additionalColorCount;+ } else {+ settings.color = keepColor;+ settings.additionalColors = keepAdditionalColors;+ settings.additionalColorCount = keepAdditionalColorCount;+ }if (entry.contents & presetContentMask(PresetContent::FrameGeneration)) {settings.multiplier = std::max(1u, entry.fg.multiplier);settings.frameGenerationBackend = entry.fg.backend;@@ -177,6 +314,221 @@ void PresetLibrary::apply(const PresetEntry& entry, EnhancementSettings& setting}}+ChainValidation PresetLibrary::applyToChain(const PresetEntry& entry, EffectChain& chain,+ EnhancementSettings& settings) {+ if (entry.kind != chain.mode) return {false, "预设编辑模式不匹配"};+ if (entry.contents & ~kPresetAllContent) return {false, "预设内容类型无效"};+ if (const auto v = validateChain(chain); !v.accepted) return v;+ if (const auto v = validateChain(entry.chain); !v.accepted) return v;+ const bool hasChain = (entry.contents & presetContentMask(PresetContent::Chain)) != 0;+ const bool hasColor = (entry.contents & presetContentMask(PresetContent::Color)) != 0;+ const bool hasFg = (entry.contents & presetContentMask(PresetContent::FrameGeneration)) != 0;+ auto nextSettings = settings;+ apply(entry, nextSettings);+ auto next = hasChain ? entry.chain : chain;+ next.mode = chain.mode;++ if (hasChain || hasColor) {+ // Do not round-trip through toChain(): that canonicalises node order+ // and erases positions, even for presets that only carry audio.+ const auto& source = hasColor ? entry.chain : chain;+ std::vector<ChainNode> colors;+ for (uint32_t i = 0; i < source.nodeCount; ++i)+ if (source.nodes[i].type == EffectType::Color) colors.push_back(source.nodes[i]);+ if (hasColor) {+ // Legacy colour-only entries can carry the grade outside the chain.+ if (colors.empty() && (!hasChain || entry.color.enabled)) {+ ChainNode color; color.type = EffectType::Color; colors.push_back(color);+ }+ if (!colors.empty()) {+ colors.front().color = entry.color;+ colors.front().enabled = entry.color.enabled;+ }+ }+ const auto needed = next.nodeCount - next.countOf(EffectType::Color) + colors.size();+ if (needed > kMaxChainNodes) return {false, "合并后的节点数量超出上限"};+ auto arranged = next;+ arranged.nodes = {}; arranged.nodeCount = 0;+ size_t colorIndex = 0;+ uint32_t insertAt = 0;+ for (uint32_t i = 0; i < next.nodeCount; ++i) {+ auto node = next.nodes[i];+ if (node.type == EffectType::Color) {+ if (colorIndex == colors.size()) continue;+ node.color = colors[colorIndex].color;+ node.enabled = colors[colorIndex++].enabled;+ arranged.nodes[arranged.nodeCount++] = node;+ insertAt = arranged.nodeCount;+ } else arranged.nodes[arranged.nodeCount++] = node;+ }+ // New instances have the saved positions; existing slots keep theirs.+ while (colorIndex < colors.size()) {+ for (uint32_t i = arranged.nodeCount; i > insertAt; --i)+ arranged.nodes[i] = arranged.nodes[i - 1];+ arranged.nodes[insertAt++] = colors[colorIndex++];+ ++arranged.nodeCount;+ }+ next = arranged;+ }+ if (hasChain || hasFg) {+ if (!hasFg) next.fgMultiplier = chain.fgMultiplier;+ auto* fg = next.firstOf(EffectType::FrameGeneration);+ if (!fg && nextSettings.multiplier > 1) {+ if (next.nodeCount == kMaxChainNodes) return {false, "合并后无法添加补帧节点"};+ fg = &next.nodes[next.nodeCount++];+ *fg = {}; fg->type = EffectType::FrameGeneration;+ }+ if (fg) fg->enabled = nextSettings.multiplier > 1;+ if (nextSettings.multiplier > 1) next.fgMultiplier = nextSettings.multiplier;+ }+ if (const auto v = validateChain(next); !v.accepted) return v;+ if (hasChain || hasColor) fromChain(next, nextSettings);+ if (!nextSettings.validate().empty()) return {false, "预设参数无效"};+ chain = next; settings = nextSettings;+ return {};+}++ChainValidation PresetLibrary::applyToEditor(const PresetEntry& entry, NodeEditorDocument& document,+ EnhancementSettings& settings) {+ if (entry.kind != ChainMode::Node || document.nodes.mode != ChainMode::Node)+ return {false, "预设编辑模式不匹配"};+ if (entry.contents & ~kPresetAllContent) return {false, "预设内容类型无效"};+ if (auto v = document.layout.validate(document.nodes); !v.accepted) return v;+ if (auto v = validateChain(entry.chain); !v.accepted) return v;+ if (entry.nodeConfiguration && (!entry.nodeConfiguration->valid() || entry.nodeConfiguration->chain != entry.chain))+ return {false, "预设编辑快照无效"};+ auto next = std::make_unique<NodeEditorDocument>(document);+ auto& nodes = next->nodes; auto& layout = next->layout;+ auto values = settings;+ if (document.globals) document.globals->apply(values);+ if ((entry.contents & presetContentMask(PresetContent::Chain)) && entry.nodeConfiguration) {+ const auto& saved = *entry.nodeConfiguration;+ if (saved.editor) *next = *saved.editor;+ else { nodes = saved.chain; if (auto v = layout.initialize(nodes); !v.accepted) return v; }+ saved.apply(values);+ if (saved.editor && saved.editor->globals) saved.editor->globals->apply(values);+ if (!(entry.contents & presetContentMask(PresetContent::Color))) {+ PresetEntry keep; keep.kind = ChainMode::Node; keep.chain.mode = ChainMode::Node;+ keep.contents = presetContentMask(PresetContent::Color);+ for (uint32_t i = 0; i < document.nodes.nodeCount; ++i)+ if (document.nodes.nodes[i].type == EffectType::Color)+ keep.chain.nodes[keep.chain.nodeCount++] = document.nodes.nodes[i];+ if (keep.chain.nodeCount) {+ keep.color = keep.chain.nodes[0].color; keep.color.enabled = keep.chain.nodes[0].enabled;+ if (auto v = applyToEditor(keep, *next, values); !v.accepted) return v;+ } else {+ for (uint32_t i = nodes.nodeCount; i > 0; --i)+ if (nodes.nodes[i-1].type == EffectType::Color)+ if (auto v = layout.remove(nodes, layout.ids[i-1]); !v.accepted) return v;+ }+ }+ if (!(entry.contents & presetContentMask(PresetContent::FrameGeneration))) {+ PresetEntry keep; keep.kind = ChainMode::Node; keep.chain.mode = ChainMode::Node;+ keep.contents = presetContentMask(PresetContent::FrameGeneration);+ const auto* old = document.nodes.firstOf(EffectType::FrameGeneration);+ keep.fg = {old && old->enabled ? document.nodes.fgMultiplier : 1, settings.frameGenerationBackend};+ if (auto v = applyToEditor(keep, *next, values); !v.accepted) return v;+ nodes.fgStrictAdmission = document.nodes.fgStrictAdmission;+ }+ if (entry.contents & presetContentMask(PresetContent::Audio)) {+ values.audioSync = entry.audioSync; values.audioOffsetMs = entry.audioOffsetMs;+ }+ } else if (entry.contents & presetContentMask(PresetContent::Chain)) {+ // Whole-chain replacement discards the old order, not saved colours.+ // Sort only the helper INPUT, so detached tail nodes do not reject it.+ const auto rank = [](const ChainNode& n) {+ switch (n.type) {+ case EffectType::Color: return 0;+ case EffectType::SuperResolution: return 1;+ case EffectType::NrEnhance: return 2;+ case EffectType::VideoHdr: return 3;+ default: return 4;+ }+ };+ std::stable_sort(nodes.nodes.begin(), nodes.nodes.begin() + nodes.nodeCount,+ [&](const auto& a, const auto& b) { return rank(a) < rank(b); });+ if (auto v = applyToChain(entry, nodes, values); !v.accepted) return v;+ if (auto v = layout.initialize(nodes); !v.accepted) return v;+ } else {+ const auto append = [&](ChainNode node, uint32_t after, bool attach) -> ChainValidation {+ if (nodes.nodeCount >= kMaxChainNodes || layout.nextId == (std::numeric_limits<uint32_t>::max)())+ return {false, "节点容量或标识已耗尽"};+ const uint32_t index = nodes.nodeCount++, id = layout.nextId++;+ // New slots are placed below existing cards, not on top of them.+ for (uint32_t i = 0; i < index; ++i)+ node.viewY = (std::max)(node.viewY, nodes.nodes[i].viewY + 300);+ nodes.nodes[index] = node; layout.ids[index] = id; layout.next[index] = 0;+ if (attach) {+ auto& edge = after == NodeGraphLayout::Input ? layout.inputNext :+ layout.next[size_t(layout.indexOf(nodes, after))];+ layout.next[index] = edge; edge = id;+ }+ return layout.validate(nodes);+ };+ if (entry.contents & presetContentMask(PresetContent::Color)) {+ std::vector<ChainNode> incoming; std::vector<uint32_t> existing;+ const auto& source = entry.nodeConfiguration && entry.nodeConfiguration->editor ?+ entry.nodeConfiguration->editor->nodes : entry.chain;+ for (uint32_t i = 0; i < source.nodeCount; ++i)+ if (source.nodes[i].type == EffectType::Color) incoming.push_back(source.nodes[i]);+ if (incoming.empty()) { ChainNode n; n.type = EffectType::Color; incoming.push_back(n); }+ incoming.front().color = entry.color; incoming.front().enabled = entry.color.enabled;+ for (uint32_t i = 0; i < nodes.nodeCount; ++i)+ if (nodes.nodes[i].type == EffectType::Color) existing.push_back(layout.ids[i]);+ const size_t kept = (std::min)(incoming.size(), existing.size());+ for (size_t i = 0; i < kept; ++i) {+ auto& node = nodes.nodes[size_t(layout.indexOf(nodes, existing[i]))];+ node.color = incoming[i].color; node.enabled = incoming[i].enabled;+ }+ for (size_t i = existing.size(); i > kept; --i)+ if (auto v = layout.remove(nodes, existing[i - 1]); !v.accepted) return v;+ uint32_t after = kept ? existing[kept - 1] : NodeGraphLayout::Input;+ for (size_t i = kept; i < incoming.size(); ++i) {+ if (auto v = append(incoming[i], after, true); !v.accepted) return v;+ after = layout.ids[nodes.nodeCount - 1];+ }+ }+ if (entry.contents & presetContentMask(PresetContent::FrameGeneration)) {+ auto* node = nodes.firstOf(EffectType::FrameGeneration);+ if (!node && entry.fg.multiplier > 1) {+ uint32_t after = NodeGraphLayout::Input, end = layout.inputNext;+ while (end > NodeGraphLayout::Output) {+ after = end; end = layout.next[size_t(layout.indexOf(nodes, end))];+ }+ ChainNode added; added.type = EffectType::FrameGeneration;+ if (auto v = append(added, after, end == NodeGraphLayout::Output); !v.accepted) return v;+ node = nodes.firstOf(EffectType::FrameGeneration);+ }+ if (node) node->enabled = entry.fg.multiplier > 1;+ if (entry.fg.multiplier > 1) nodes.fgMultiplier = entry.fg.multiplier;+ values.frameGenerationBackend = entry.fg.backend;+ }+ if (entry.contents & presetContentMask(PresetContent::Audio)) {+ values.audioSync = entry.audioSync; values.audioOffsetMs = entry.audioOffsetMs;+ }+ }+ if (auto v = layout.validate(nodes); !v.accepted) return v;+ auto runtime = std::make_unique<EffectChain>(); runtime->mode = ChainMode::Node;+ const auto projected = layout.project(nodes, *runtime);+ if (projected.accepted) fromChain(*runtime, values);+ else {+ uint32_t end = layout.inputNext;+ while (end > NodeGraphLayout::Output) end = layout.next[size_t(layout.indexOf(nodes, end))];+ if (end != NodeGraphLayout::Input) return projected;+ }+ applyRenderingPreset(entry,values);+ if (next->globals || ChainGlobalSettings::capture(values) != ChainGlobalSettings::capture(settings))+ next->globals = ChainGlobalSettings::capture(values);+ auto contract = std::make_unique<ChainConfiguration>(ChainConfiguration::capture(*runtime, values));+ contract->editor = std::make_shared<NodeEditorDocument>(*next);+ // An incomplete draft may choose XeSS 2X while the accepted runtime is+ // still DLSS 6X. Never validate that accidental flat-settings combination.+ // The document contract checks every detached node against draft globals.+ auto projectedValues = values; fromChain(*runtime, projectedValues);+ if (!contract->valid() || !projectedValues.validate().empty()) return {false, "预设节点参数无效"};+ document = *next; settings = values; return {};+}+bool PresetLibrary::importLegacy(const std::vector<PresetEntry>& incoming) {bool changed = false;for (const auto& entry : incoming) {@@ -191,10 +543,29 @@ bool PresetLibrary::importLegacy(const std::vector<PresetEntry>& incoming) {}std::string PresetLibrary::serialize() const {+ return encodeEntries(entries_, defaultName_);+}++std::string PresetLibrary::encodeEntries(const std::vector<PresetEntry>& entries_, const std::wstring& defaultName_, int minimumVersion) {std::ostringstream o;o.imbue(std::locale::classic());o << std::setprecision(std::numeric_limits<float>::max_digits10);- o << "VEYRA_PRESET_LIBRARY 1\n" << std::quoted(utf8(defaultName_)) << ' ' << entries_.size() << '\n';+ const bool multi = std::any_of(entries_.begin(), entries_.end(), [](const auto& e) {+ return std::count_if(e.chain.nodes.begin(), e.chain.nodes.begin() + e.chain.nodeCount,+ [](const auto& n) { return n.type == EffectType::Color; }) > 1;+ });+ const bool layerSizes=std::any_of(entries_.begin(),entries_.end(),[](const auto& e){+ return std::any_of(e.chain.nodes.begin(),e.chain.nodes.begin()+e.chain.nodeCount,[](const auto& n){+ return n.type==EffectType::NrEnhance&&n.nr.sizePolicy!=pipeline::NrSizePolicy::Realtime;+ });+ });+ const bool editor = std::any_of(entries_.begin(), entries_.end(), [](const auto& e) { return e.nodeConfiguration.has_value(); });+ const bool globals = std::any_of(entries_.begin(), entries_.end(), [](const auto& e) {+ return e.nodeConfiguration && e.nodeConfiguration->editor && e.nodeConfiguration->editor->globals;+ });+ const bool rendering=std::any_of(entries_.begin(),entries_.end(),[](const auto& e){return e.globals.has_value();});+ const int version=std::max(minimumVersion, rendering?6:globals?5:editor?4:layerSizes?3:multi?2:1);+ o << "VEYRA_PRESET_LIBRARY " << version << '\n' << std::quoted(utf8(defaultName_)) << ' ' << entries_.size() << '\n';for (const auto& e : entries_) {o << std::quoted(utf8(e.name)) << ' ' << std::quoted(utf8(e.note)) << ' '<< int(e.kind) << ' ' << (e.builtin ? 1 : 0) << ' ' << e.contents << ' '@@ -210,25 +581,48 @@ std::string PresetLibrary::serialize() const {<< n.nr.residual.color << ' ' << n.nr.residual.luminance << ' '<< int(n.nr.runtime) << ' ' << (n.nr.temporal ? 1 : 0) << ' ' << (n.nr.lowLatencyPairing ? 1 : 0) << ' '<< (n.protection.enabled ? 1 : 0) << ' ' << n.protection.featherPixels;- for (const auto& r : n.protection.regions) o << ' ' << r.left << ' ' << r.top << ' ' << r.right << ' ' << r.bottom;+ // An ellipse is stored with left and right swapped (no format change;+ // earlier files never hold an inverted box).+ for (const auto& r : n.protection.regions)+ o << ' ' << (r.ellipse ? r.right : r.left) << ' ' << r.top << ' ' << (r.ellipse ? r.left : r.right) << ' ' << r.bottom;o << ' ' << (n.videoHdr.enabled ? 1 : 0) << ' ' << n.videoHdr.contrast << ' ' << n.videoHdr.saturation << ' '<< n.videoHdr.middleGray << ' ' << n.videoHdr.peakNits << ' ';+ if(version>=3)o<<int(n.nr.sizePolicy)<<' ';+ if (version>=2 && n.type == EffectType::Color) {+ writeColorSettings(o, n.color, utf8(n.color.lutNameString()));+ o << ' ';+ }}o << ' ';writeColorSettings(o, e.color, utf8(e.color.lutNameString()));+ if (version >= 4) {+ o << ' ' << e.nodeConfiguration.has_value();+ if (e.nodeConfiguration) {+ auto session = std::make_unique<ChainSession>(ChainSession::initial({}));+ session->active = ChainMode::Node; session->initialized[1] = true;+ session->configurations[1] = *e.nodeConfiguration;+ o << ' ' << std::quoted(ChainSessionStore::encode(*session));+ }+ }+ if(version>=6){+ o<<' '<<e.globals.has_value();+ if(e.globals){const auto& g=*e.globals;o<<' '<<int(g.srTarget)<<' '<<g.videoSrQuality<<' '<<int(g.fgBackend)<<' '<<int(g.flow)<<' '<<int(g.opticalFlowBackend)<<' '<<g.amdFlowHalfResolution<<' '<<int(g.nrPolicy);writeRendering(o,g);}+ }o << '\n';}return o.str();}-bool PresetLibrary::parse(const std::string& data, std::vector<PresetEntry>& out, std::wstring& def, std::wstring& error) {- if (data.size() > 262144) { error = L"预设库超过 256 KiB"; return false; }+bool PresetLibrary::parse(const std::string& data, std::vector<PresetEntry>& out, std::wstring& def, std::wstring& error,+ bool* migrated, bool preserveLegacy) {+ if (migrated) *migrated = false;+ if (data.size() > kMaxPresetBytes) { error = L"预设库超过 2 MiB"; return false; }std::istringstream in(data);in.imbue(std::locale::classic());std::string magic, quoted;int version = 0;size_t count = 0;- if (!(in >> magic >> version) || magic != "VEYRA_PRESET_LIBRARY" || version < 1 || version > 1) { error = L"预设库格式或版本不支持"; return false; }+ if (!(in >> magic >> version) || magic != "VEYRA_PRESET_LIBRARY" || version < 1 || version > (preserveLegacy ? 3 : 6)) { error = L"预设库格式或版本不支持"; return false; }if (!(in >> std::quoted(quoted) >> count) || count > 64) { error = L"预设库条目数非法"; return false; }def = wide(quoted);for (size_t i = 0; i < count; ++i) {@@ -237,12 +631,16 @@ bool PresetLibrary::parse(const std::string& data, std::vector<PresetEntry>& outint kind = 0, builtin = 0, fgBackend = 0, audioSync = 0, chainMode = 0, strict = 0;uint32_t nodeCount = 0;if (!(in >> std::quoted(name) >> std::quoted(note) >> kind >> builtin >> e.contents >> e.fg.multiplier >> fgBackend >> audioSync >> e.audioOffsetMs >> nodeCount >> chainMode >> e.chain.fgMultiplier >> strict)) { error = L"预设库头部字段损坏"; return false; }- if (kind < 0 || kind > 1 || nodeCount > kMaxChainNodes || e.fg.multiplier < 1 || e.fg.multiplier > 6) { error = L"预设库字段超出范围"; return false; }+ if (kind < 0 || kind > 1 || chainMode < 0 || chainMode > 1 || strict < 0 || strict > 1 ||+ nodeCount > kMaxChainNodes || e.fg.multiplier < 1 || e.fg.multiplier > 6) { error = L"预设库字段超出范围"; return false; }e.name = wide(name);e.note = wide(note);e.kind = static_cast<ChainMode>(kind);e.builtin = builtin != 0;e.fg.backend = static_cast<FrameGenerationBackend>(fgBackend);+ EnhancementSettings fgContract;+ fgContract.multiplier=e.fg.multiplier;fgContract.frameGenerationBackend=e.fg.backend;+ if(!fgContract.validate().empty()){error=L"预设库补帧后端或倍率无效";return false;}e.audioSync = static_cast<AudioSyncMode>(audioSync);e.chain.nodeCount = nodeCount;e.chain.mode = static_cast<ChainMode>(chainMode);@@ -258,7 +656,10 @@ bool PresetLibrary::parse(const std::string& data, std::vector<PresetEntry>& out>> node.nr.residual.total >> node.nr.residual.darken >> node.nr.residual.brighten>> node.nr.residual.color >> node.nr.residual.luminance>> runtime >> temporal >> lowLatency >> protEnabled >> node.protection.featherPixels)) { error = L"预设库节点字段损坏"; return false; }- for (auto& r : node.protection.regions) if (!(in >> r.left >> r.top >> r.right >> r.bottom)) { error = L"预设库保护区域损坏"; return false; }+ for (auto& r : node.protection.regions) {+ if (!(in >> r.left >> r.top >> r.right >> r.bottom)) { error = L"预设库保护区域损坏"; return false; }+ if (r.left > r.right) { std::swap(r.left, r.right); r.ellipse = true; }+ }if (!(in >> hdrEnabled >> node.videoHdr.contrast >> node.videoHdr.saturation >> node.videoHdr.middleGray >> node.videoHdr.peakNits)) { error = L"预设库 HDR 字段损坏"; return false; }if (type < 0 || type >= int(EffectType::Count) || enabled < 0 || enabled > 1 || runtime < 0 || runtime > 2 ||temporal < 0 || temporal > 1 || lowLatency < 0 || lowLatency > 1 || protEnabled < 0 || protEnabled > 1 || hdrEnabled < 0 || hdrEnabled > 1) {@@ -266,11 +667,22 @@ bool PresetLibrary::parse(const std::string& data, std::vector<PresetEntry>& out}node.type = static_cast<EffectType>(type);node.enabled = enabled != 0;- node.nr.runtime = static_cast<NrRuntime>(runtime);+ node.nr.runtime = currentNrRuntime(static_cast<NrRuntime>(runtime));node.nr.temporal = temporal != 0;node.nr.lowLatencyPairing = lowLatency != 0;node.protection.enabled = protEnabled != 0;node.videoHdr.enabled = hdrEnabled != 0;+ if(version>=3){int size;+ if(!(in>>size)||!pipeline::validNrSizePolicy(static_cast<pipeline::NrSizePolicy>(size))){error=L"预设库 NR 分辨率非法";return false;}+ node.nr.sizePolicy=static_cast<pipeline::NrSizePolicy>(size);+ }+ if (version >= 2 && node.type == EffectType::Color) {+ std::string lut;+ if (!readColorSettings(in, node.color, lut, 19) ||+ (!lut.empty() && !node.color.setLutName(wide(lut))) || !node.color.validate().empty()) {+ error = L"预设库节点调色参数损坏"; return false;+ }+ }}in >> std::ws;std::string lut;@@ -279,11 +691,232 @@ bool PresetLibrary::parse(const std::string& data, std::vector<PresetEntry>& outif (!readColorSettings(in, e.color, lut, 19)) { error = L"预设库调色字段损坏"; return false; }if (!lut.empty() && !e.color.setLutName(wide(lut))) { error = L"预设库 LUT 名称非法"; return false; }if (auto problem = e.color.validate(); !problem.empty()) { error = L"预设库调色参数超出范围"; return false; }- if (auto verdict = validateChain(e.chain); !verdict.accepted) { error = L"预设库链路违反顺序规则"; return false; }+ // v1 stores its only grade after the chain, not in the Color node.+ // Restore that payload before a node-mode caller uses the chain itself.+ if (version == 1) {+ if (auto* color = e.chain.firstOf(EffectType::Color)) color->color = e.color;+ }+ auto compatible = e.chain;+ if (removeLegacyNodeProtection(compatible) && migrated) *migrated = true;+ if (auto verdict = validateChain(compatible); !verdict.accepted) { error = L"预设库链路违反顺序规则"; return false; }+ if (!preserveLegacy) e.chain = compatible;+ if (version >= 4) {+ int hasEditor = 0;+ if (!(in >> hasEditor) || hasEditor < 0 || hasEditor > 1) return false;+ if (hasEditor) {+ std::string body; auto session = std::make_unique<ChainSession>();+ if (!(in >> std::quoted(body)) || e.kind != ChainMode::Node ||+ !ChainSessionStore::decode(body, *session) || !session->valid() ||+ session->active != ChainMode::Node || session->configurations[1].chain != e.chain) {+ error = L"预设编辑文档无效,原状态保留"; return false;+ }+ e.nodeConfiguration = session->configurations[1];+ }+ }+ if(version>=6){+ int present;if(!(in>>present)||present<0||present>1)return false;+ if(present){ChainGlobalSettings g;int target,backend,flow,optical,half,policy;+ if(!(in>>target>>g.videoSrQuality>>backend>>flow>>optical>>half>>policy)||half<0||half>1)return false;+ g.srTarget=pipeline::SrTarget(target);g.fgBackend=FrameGenerationBackend(backend);g.flow=FlowQuality(flow);g.opticalFlowBackend=OpticalFlowBackend(optical);g.amdFlowHalfResolution=half!=0;g.nrPolicy=pipeline::NrSizePolicy(policy);+ if(!readRendering(in,g))return false;e.globals=g;+ }+ }out.push_back(std::move(e));}in >> std::ws;if (!in.eof()) { error = L"预设库尾部有多余数据"; return false; }return true;}++std::string ChainSessionStore::encode(const ChainSession& session) {+ std::ostringstream out;+ out.imbue(std::locale::classic());+ const auto& editor = session.configurations[1].editor;+ const auto extended=[](const ChainGlobalSettings& g){return g.srTarget>pipeline::SrTarget::Uhd8K||g.hdrOutputMode!=HdrOutputMode::Hdr10||g.fgMotion!=MotionSource::Automatic||g.srMotion!=MotionSource::OpticalFlow||g.nrMotion!=MotionSource::OpticalFlow;};+ const bool rendering=std::any_of(session.configurations.begin(),session.configurations.end(),[&](const auto& c){return extended(c)||(c.editor&&c.editor->globals&&extended(*c.editor->globals));});+ const int version = rendering?4:editor ? (editor->globals ? 3 : 2) : 1;+ out << "VEYRA_CHAIN_SESSION " << version << '\n' << int(session.active) << ' ' << session.initialized[0] << ' ' << session.initialized[1];+ if(version>=4)out<<' '<<bool(editor);out<<'\n';+ std::vector<PresetEntry> entries;+ for (size_t i = 0; i < session.configurations.size(); ++i) {+ const auto& c = session.configurations[i];+ out << int(c.srTarget) << ' ' << c.videoSrQuality << ' ' << int(c.fgBackend) << ' '+ << int(c.flow) << ' ' << int(c.opticalFlowBackend) << ' ' << c.amdFlowHalfResolution << ' '+ << int(c.nrPolicy) << ' ' << c.selectedNr << ' ' << c.selectedColour;+ if(version>=4)writeRendering(out,c);out<<'\n';+ PresetEntry entry;+ entry.name = i == 0 ? L"list" : L"node";+ entry.kind = ChainMode(i); entry.chain = c.chain;+ entry.fg = {c.chain.fgMultiplier, c.fgBackend};+ if (const auto color = c.chain.firstOf(EffectType::Color)) entry.color = color->color;+ entries.push_back(std::move(entry));+ }+ // v3 always carries full per-node colours, even with just one Color node.+ out << std::quoted(PresetLibrary::encodeEntries(entries, {}, 3)) << '\n';+ if (editor) {+ const auto& document = *session.configurations[1].editor;+ const auto& graph = document.layout;+ if(version>=4)out<<bool(document.globals)<<'\n';+ if (version>=3&&document.globals) {+ const auto& g = *document.globals;+ out << int(g.srTarget) << ' ' << g.videoSrQuality << ' ' << int(g.fgBackend) << ' '+ << int(g.flow) << ' ' << int(g.opticalFlowBackend) << ' ' << g.amdFlowHalfResolution << ' '+ << int(g.nrPolicy);if(version>=4)writeRendering(out,g);out<<'\n';+ }+ out << graph.nextId << ' ' << graph.inputNext << ' ' << document.nodes.nodeCount << '\n';+ // The ordinary preset codec validates a linear runtime chain. Use a+ // disabled envelope for the editor-only unordered payload, with the+ // exact enabled flags stored alongside IDs/edges and restored below.+ // This does not weaken ordinary preset import or runtime validation.+ auto entry = std::make_unique<PresetEntry>();+ entry->name = L"editor"; entry->kind = ChainMode::Node; entry->chain = document.nodes;+ entry->fg = {document.nodes.fgMultiplier, session.configurations[1].fgBackend};+ for (uint32_t i = 0; i < document.nodes.nodeCount; ++i) {+ out << graph.ids[i] << ' ' << graph.next[i] << ' ' << document.nodes.nodes[i].enabled << '\n';+ entry->chain.nodes[i].enabled = false;+ }+ std::vector<PresetEntry> payload; payload.push_back(std::move(*entry));+ out << std::quoted(PresetLibrary::encodeEntries(payload, {}, 3)) << '\n';+ }+ return out.str();+}++bool ChainSessionStore::decode(const std::string& data, ChainSession& session, bool* migrated) {+ if (migrated) *migrated = false;+ if (data.size() > kMaxPresetBytes) return false;+ std::istringstream in(data); in.imbue(std::locale::classic());+ std::string magic, body; int version = 0, active = 0, list = 0, node = 0;+ if (!(in >> magic >> version >> active >> list >> node) || magic != "VEYRA_CHAIN_SESSION" ||+ (version < 1 || version > 4) || active < 0 || active > 1 || list != 1 || node < 0 || node > 1) return false;+ int hasEditor=version>=2?1:0;+ if(version>=4&&(!(in>>hasEditor)||hasEditor<0||hasEditor>1))return false;+ ChainSession parsed; parsed.active = ChainMode(active); parsed.initialized = {true, node != 0};+ for (auto& c : parsed.configurations) {+ int target, backend, flow, optical, half, policy;+ if (!(in >> target >> c.videoSrQuality >> backend >> flow >> optical >> half >> policy >> c.selectedNr >> c.selectedColour) ||+ half < 0 || half > 1) return false;+ c.srTarget = pipeline::SrTarget(target); c.fgBackend = FrameGenerationBackend(backend);+ c.flow = FlowQuality(flow); c.opticalFlowBackend = OpticalFlowBackend(optical);+ c.amdFlowHalfResolution = half != 0; c.nrPolicy = pipeline::NrSizePolicy(policy);+ if(version>=4&&!readRendering(in,c))return false;+ }+ if (!(in >> std::quoted(body))) return false;+ std::vector<PresetEntry> entries; std::wstring def, error;+ if (!PresetLibrary::parse(body, entries, def, error, nullptr, true) || entries.size() != 2 || !def.empty()) return false;+ for (size_t i = 0; i < entries.size(); ++i) {+ if (entries[i].kind != ChainMode(i)) return false;+ parsed.configurations[i].chain = entries[i].chain;+ auto& configuration = parsed.configurations[i];+ if (removeLegacyNodeProtection(configuration.chain, &configuration.selectedNr, &configuration.selectedColour) && migrated)+ *migrated = true;+ }+ if (hasEditor) {+ if (!parsed.initialized[1]) return false;+ auto editor = std::make_shared<NodeEditorDocument>();+ int hasGlobals=version>=3?1:0;+ if(version>=4&&(!(in>>hasGlobals)||hasGlobals<0||hasGlobals>1))return false;+ if (hasGlobals) {+ ChainGlobalSettings g;+ int target, backend, flow, optical, half, policy;+ if (!(in >> target >> g.videoSrQuality >> backend >> flow >> optical >> half >> policy) ||+ half < 0 || half > 1) return false;+ g.srTarget = pipeline::SrTarget(target); g.fgBackend = FrameGenerationBackend(backend);+ g.flow = FlowQuality(flow); g.opticalFlowBackend = OpticalFlowBackend(optical);+ g.amdFlowHalfResolution = half != 0; g.nrPolicy = pipeline::NrSizePolicy(policy);+ if(version>=4&&!readRendering(in,g))return false;+ editor->globals = g;+ }+ uint32_t count = 0;+ if (!(in >> editor->layout.nextId >> editor->layout.inputNext >> count) || count > kMaxChainNodes) return false;+ std::array<bool, kMaxChainNodes> enabled{};+ for (uint32_t i = 0; i < count; ++i) {+ int flag = 0;+ if (!(in >> editor->layout.ids[i] >> editor->layout.next[i] >> flag) || flag < 0 || flag > 1) return false;+ enabled[i] = flag != 0;+ }+ if (!(in >> std::quoted(body))) return false;+ entries.clear(); def.clear(); error.clear();+ if (!PresetLibrary::parse(body, entries, def, error, nullptr, true) || entries.size() != 1 ||+ !def.empty() || entries[0].kind != ChainMode::Node || entries[0].chain.nodeCount != count) return false;+ editor->nodes = std::move(entries[0].chain);+ for (uint32_t i = 0; i < count; ++i) {+ if (editor->nodes.nodes[i].enabled) return false;+ editor->nodes.nodes[i].enabled = enabled[i];+ }+ if (!editor->layout.validate(editor->nodes).accepted) return false;+ parsed.configurations[1].editor = std::move(editor);+ }+ in >> std::ws; if (!in.eof()) return false;+ if (!parsed.valid()) return false;+ session = std::move(parsed);+ return true;+}++bool ChainSessionStore::load(ChainSession& session) {+ error_.clear();+ std::error_code ec;+ const auto rootRendering=std::filesystem::path(path_).concat(L".field-render");+ if(std::filesystem::exists(rootRendering,ec))path_=rootRendering;+ const auto migratedPath = std::filesystem::path(path_).concat(L".p3-node");+ if (std::filesystem::exists(migratedPath, ec)) path_ = migratedPath;+ const auto editorPath = std::filesystem::path(path_).concat(L".p3-editor");+ if (std::filesystem::exists(editorPath, ec) ||+ std::filesystem::exists(std::filesystem::path(editorPath).concat(L".p3-globals"), ec)) path_ = editorPath;+ const auto globalsPath = std::filesystem::path(path_).concat(L".p3-globals");+ if (std::filesystem::exists(globalsPath, ec)) path_ = globalsPath;+ const auto renderingPath=std::filesystem::path(path_).concat(L".field-render");+ if(std::filesystem::exists(renderingPath,ec))path_=renderingPath;+ const bool exists = std::filesystem::exists(path_, ec);+ if (!exists && !ec) return true;+ const auto size = std::filesystem::file_size(path_, ec);+ if (!ec && size <= kMaxPresetBytes) {+ std::ifstream file(path_, std::ios::binary);+ if (file) {+ const std::string data((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());+ bool migrated = false;+ if (!file.bad() && decode(data, session, &migrated)) {+ if (migrated) {+ path_ = std::filesystem::path(path_).concat(L".p3-node");+ error_ = L"旧节点配置的 NR 保护区域已移除;列表保护及其他节点参数保留,后续保存到 .p3-node 文件,原文件不覆盖";+ }+ return true;+ }+ }+ }+ corrupt_ = true;+ error_ = L"模式会话损坏、无法读取或版本不支持;原文件保留,禁止覆盖";+ return false;+}++bool ChainSessionStore::save(const ChainSession& session) {+ error_.clear();+ if (corrupt_) { error_ = L"模式会话损坏,已拒绝覆盖原文件"; return false; }+ if (!session.valid()) { error_ = L"模式会话包含无效链或参数,未保存"; return false; }+ const auto data = encode(session);+ ChainSession checked;+ if (!decode(data, checked)) { error_ = L"模式会话编码校验失败,未保存"; return false; }+ if(data.starts_with("VEYRA_CHAIN_SESSION 4")&&!path_.wstring().ends_with(L".field-render"))path_=std::filesystem::path(path_).concat(L".field-render");+ // A v1 reader must never reinterpret or overwrite the new editor graph.+ // Preserve the original session as a rollback point during this opt-in.+ if (session.configurations[1].editor && !path_.wstring().ends_with(L".field-render")&&!path_.wstring().ends_with(L".p3-editor") &&+ !path_.wstring().ends_with(L".field-render")&&!path_.wstring().ends_with(L".p3-globals"))+ path_ = std::filesystem::path(path_).concat(L".p3-editor");+ if (session.configurations[1].editor && session.configurations[1].editor->globals &&+ !path_.wstring().ends_with(L".field-render")&&!path_.wstring().ends_with(L".p3-globals"))+ path_ = std::filesystem::path(path_).concat(L".p3-globals");+ std::error_code ec;+ if (!path_.parent_path().empty()) std::filesystem::create_directories(path_.parent_path(), ec);+ if (ec) { error_ = L"模式会话目录无法创建"; return false; }+ const auto temporary = std::filesystem::path(path_).concat(L".tmp");+ bool written = false;+ {+ std::ofstream file(temporary, std::ios::binary | std::ios::trunc);+ if (file) { file << data; file.flush(); written = bool(file); file.close(); written = written && !file.fail(); }+ }+ if (!written || !MoveFileExW(temporary.c_str(), path_.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {+ std::filesystem::remove(temporary, ec);+ error_ = L"模式会话写入或替换失败,原存档保留"; return false;+ }+ return true;+}}diff --git a/src/engine/PresetStore.cpp b/src/engine/PresetStore.cppindex e558769d..042582cb 100644--- a/src/engine/PresetStore.cpp+++ b/src/engine/PresetStore.cpp@@ -7,18 +7,61 @@#include <limits>namespace veyra::engine {namespace {+// 64 presets may each contain six full-precision grades and UTF-8 LUT names.+// This is metadata only; retain a finite bound before allocating/parsing it.+constexpr size_t kMaxPresetBytes=2u*1024u*1024u;std::string utf8(const std::wstring& s){int n=WideCharToMultiByte(CP_UTF8,WC_ERR_INVALID_CHARS,s.data(),int(s.size()),nullptr,0,nullptr,nullptr);std::string r(n,0);if(n)WideCharToMultiByte(CP_UTF8,WC_ERR_INVALID_CHARS,s.data(),int(s.size()),r.data(),n,nullptr,nullptr);return r;}std::wstring wide(const std::string& s){int n=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,s.data(),int(s.size()),nullptr,0);std::wstring r(n,0);if(n)MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,s.data(),int(s.size()),r.data(),n);return r;}bool nameOk(const std::wstring& s){return !s.empty()&&s.size()<=48&&s.front()!=L' '&&s.back()!=L' '&&std::none_of(s.begin(),s.end(),[](wchar_t c){return c<32;});}std::wstring trim(std::wstring s){auto a=s.find_first_not_of(L" \t\r\n");if(a==s.npos)return {};auto b=s.find_last_not_of(L" \t\r\n");return s.substr(a,b-a+1);}}std::string PresetStore::serialize()const{- std::ostringstream o;o.imbue(std::locale::classic());o<<std::setprecision(std::numeric_limits<float>::max_digits10)<<"VEYRA_PRESETS 21\n"<<std::quoted(utf8(default_))<<' '<<entries_.size()<<'\n';- for(auto& p:entries_){const auto& s=p.settings;const auto& m=s.model;const auto& r=s.residual;o<<std::quoted(utf8(p.name))<<' '<<m.intensity<<' '<<m.tone<<' '<<m.structure<<' '<<m.skin<<' '<<m.style<<' '<<m.autoMask<<' '<<m.uiCorrection<<' '<<r.total<<' '<<r.darken<<' '<<r.brighten<<' '<<r.color<<' '<<r.luminance<<' '<<s.nr<<' '<<s.sr<<' '<<s.multiplier<<' '<<int(s.nrPolicy)<<' '<<int(s.flow)<<' '<<int(s.content)<<' '<<s.protection.enabled<<' '<<s.protection.featherPixels;for(auto q:s.protection.regions)o<<' '<<q.left<<' '<<q.top<<' '<<q.right<<' '<<q.bottom;o<<' '<<s.videoSrQuality<<' '<<int(s.frameGenerationBackend)<<' '<<int(s.srTarget)<<' '<<int(s.opticalFlowBackend)<<' '<<s.amdFlowHalfResolution<<' '<<int(s.audioSync)<<' '<<s.audioOffsetMs<<' '<<int(s.nrRuntime)<<' '<<s.captureCompatible<<' '<<s.lowLatency<<' '<<s.forceSdrPreview<<' '<<int(s.captureAudio)<<' '<<s.exportBitrateMbps<<' '<<s.captureFlipVertical<<' '<<int(s.captureBuffer)<<' ';writeColorSettings(o,s.color,utf8(s.color.lutNameString()));o<<' '<<s.videoHdr.enabled<<' '<<s.videoHdr.contrast<<' '<<s.videoHdr.saturation<<' '<<s.videoHdr.middleGray<<' '<<s.videoHdr.peakNits<<' '<<s.nrTemporal<<'\n';}return o.str();+ // Leave single-instance files readable by 1.4.4. A multi-grade preset+ // explicitly opts into v22; older readers reject rather than lose nodes.+ const bool stack=std::any_of(entries_.begin(),entries_.end(),[](const auto& p){return p.settings.nrLayerCount!=0;});+ const bool multi=stack||std::any_of(entries_.begin(),entries_.end(),[](const auto& p){return p.settings.additionalColorCount!=0;});+ // v24 appends the stage-5 output-stabiliser pair and the stage-6 per-layer+ // anti-flicker tier, and follows the same rule as v22/v23: write the LOWEST+ // version that still describes the store, so a store that never touched+ // either stays readable by older builds. The tier alone does not need v24:+ // its default (Flow) is exactly what `temporal=true` meant before the tiers+ // existed, so only a non-default tier forces the version up.+ const bool hold=std::any_of(entries_.begin(),entries_.end(),[](const auto& p){+ if(p.settings.nrHoldStrength!=0.0f)return true;+ for(uint32_t i=0;i<p.settings.nrLayerCount&&i<kMaxNrInstances;++i)+ if(p.settings.nrLayer(i).antiFlicker!=NrAntiFlicker::Flow)return true;+ return p.settings.nrAntiFlicker!=NrAntiFlicker::Flow;});+ const bool fsr4=std::any_of(entries_.begin(),entries_.end(),[](const auto& p){return p.settings.frameGenerationBackend==FrameGenerationBackend::Fsr4;});+ const bool higher=std::any_of(entries_.begin(),entries_.end(),[](const auto& p){return p.settings.srTarget>pipeline::SrTarget::Uhd8K;});+ const bool rendering=std::any_of(entries_.begin(),entries_.end(),[](const auto& p){const auto& s=p.settings;return s.hdrOutputMode!=HdrOutputMode::Hdr10||s.fgMotion!=MotionSource::Automatic||s.srMotion!=MotionSource::OpticalFlow||s.nrMotion!=MotionSource::OpticalFlow;});+ const bool fullSchema=fsr4||higher||rendering;+ // v26 introduces appended resolution IDs; old readers reject this schema.+ std::ostringstream o;o.imbue(std::locale::classic());o<<std::setprecision(std::numeric_limits<float>::max_digits10)<<"VEYRA_PRESETS "<<(rendering?27:higher?26:fsr4?25:hold?24:stack?23:multi?22:21)<<'\n'<<std::quoted(utf8(default_))<<' '<<entries_.size()<<'\n';+ for(auto& p:entries_){const auto& s=p.settings;const auto& m=s.model;const auto& r=s.residual;o<<std::quoted(utf8(p.name))<<' '<<m.intensity<<' '<<m.tone<<' '<<m.structure<<' '<<m.skin<<' '<<m.style<<' '<<m.autoMask<<' '<<m.uiCorrection<<' '<<r.total<<' '<<r.darken<<' '<<r.brighten<<' '<<r.color<<' '<<r.luminance<<' '<<s.nr<<' '<<s.sr<<' '<<s.multiplier<<' '<<int(s.nrPolicy)<<' '<<int(s.flow)<<' '<<int(s.content)<<' '<<s.protection.enabled<<' '<<s.protection.featherPixels;for(auto q:s.protection.regions)o<<' '<<q.left<<' '<<q.top<<' '<<q.right<<' '<<q.bottom;o<<' '<<s.videoSrQuality<<' '<<int(s.frameGenerationBackend)<<' '<<int(s.srTarget)<<' '<<int(s.opticalFlowBackend)<<' '<<s.amdFlowHalfResolution<<' '<<int(s.audioSync)<<' '<<s.audioOffsetMs<<' '<<int(s.nrRuntime)<<' '<<s.captureCompatible<<' '<<s.lowLatency<<' '<<s.forceSdrPreview<<' '<<int(s.captureAudio)<<' '<<s.exportBitrateMbps<<' '<<s.captureFlipVertical<<' '<<int(s.captureBuffer)<<' ';writeColorSettings(o,s.color,utf8(s.color.lutNameString()));o<<' '<<s.videoHdr.enabled<<' '<<s.videoHdr.contrast<<' '<<s.videoHdr.saturation<<' '<<s.videoHdr.middleGray<<' '<<s.videoHdr.peakNits<<' '<<s.nrTemporal;+ if(multi||fullSchema){o<<' '<<s.additionalColorCount;for(unsigned i=0;i<s.additionalColorCount;++i){o<<' ';writeColorSettings(o,s.additionalColors[i],utf8(s.additionalColors[i].lutNameString()));}}+ if(stack||fullSchema){+ o<<' '<<s.nrLayerCount;+ for(unsigned i=0;i<s.nrLayerCount;++i){const auto& n=s.nrLayers[i];+ o<<' '<<n.model.intensity<<' '<<n.model.tone<<' '<<n.model.structure<<' '<<n.model.skin+ <<' '<<n.model.style<<' '<<n.model.autoMask<<' '<<n.model.uiCorrection+ <<' '<<n.residual.total<<' '<<n.residual.darken<<' '<<n.residual.brighten<<' '<<n.residual.color<<' '<<n.residual.luminance+ <<' '<<int(n.runtime)<<' '<<n.temporal<<' '<<n.lowLatencyPairing<<' '<<n.enabled<<' '<<int(n.sizePolicy);+ // The tier is a v24 field: the reader only takes it at version>=24,+ // so writing it on a v23 line would misalign the rest of the row.+ if(hold||fullSchema)o<<' '<<int(n.antiFlicker);+ }+ }+ // v24: the hold flag is store-level, so every entry writes the pair once+ // any entry needs it. Otherwise entries in the same file would parse+ // differently.+ if(hold||fullSchema)o<<' '<<s.nrHoldStrength<<' '<<s.nrHoldTolerance;+ if(rendering)o<<' '<<int(s.hdrOutputMode)<<' '<<int(s.fgMotion)<<' '<<int(s.srMotion)<<' '<<int(s.nrMotion);+ o<<'\n';+ }return o.str();}bool PresetStore::parse(const std::string& data,std::vector<UserPreset>& out,std::wstring& def){- if(data.size()>65536)return false;std::istringstream in(data);in.imbue(std::locale::classic());std::string magic,d;int version=0;size_t count=0;- if(!(in>>magic>>version)||magic!="VEYRA_PRESETS"||(version<1||version>21)||!(in>>std::quoted(d)>>count)||count>64)return false;def=wide(d);if(!d.empty()&&def.empty())return false;+ if(data.size()>kMaxPresetBytes)return false;std::istringstream in(data);in.imbue(std::locale::classic());std::string magic,d;int version=0;size_t count=0;+ if(!(in>>magic>>version)||magic!="VEYRA_PRESETS"||(version<1||version>27)||!(in>>std::quoted(d)>>count)||count>64)return false;def=wide(d);if(!d.empty()&&def.empty())return false;for(size_t i=0;i<count;++i){UserPreset p;std::string n;int policy,flow,content,nr,sr;auto& s=p.settings;auto& m=s.model;auto& r=s.residual;if(!(in>>std::quoted(n)>>m.intensity>>m.tone>>m.structure>>m.skin>>m.style>>m.autoMask>>m.uiCorrection>>r.total>>r.darken>>r.brighten>>r.color>>r.luminance>>nr>>sr>>s.multiplier>>policy>>flow>>content))return false;if(version>=2){int enabled;if(!(in>>enabled>>s.protection.featherPixels)||enabled<0||enabled>1)return false;s.protection.enabled=enabled!=0;@@ -26,7 +69,7 @@ bool PresetStore::parse(const std::string& data,std::vector<UserPreset>& out,stdif(version>=3&&!(in>>s.videoSrQuality))return false;// Retired local FSR4 mode: keep the preset, use RTX Video SR high.if(version==20&&s.videoSrQuality==6)s.videoSrQuality=3;- if(version>=4){int backend;if(!(in>>backend)||backend<0||backend>(version>=13?2:(version>=6&&version<=7?2:1)))return false;+ if(version>=4){int backend;if(!(in>>backend)||backend<0||backend>(version>=25?3:version>=13?2:(version>=6&&version<=7?2:1)))return false;// Before v8, 1 meant removed FRUC and 2 meant XeSS. New writes use v10.s.frameGenerationBackend=version<8?(backend==2?FrameGenerationBackend::XeSS:FrameGenerationBackend::Dlss)@@ -34,7 +77,7 @@ bool PresetStore::parse(const std::string& data,std::vector<UserPreset>& out,stdif(version>=5){uint32_t target;if(!(in>>target))return false;s.srTarget=static_cast<pipeline::SrTarget>(target);}if(version>=6){int backend,half;if(!(in>>backend>>half)||half<0||half>1)return false;s.opticalFlowBackend=static_cast<OpticalFlowBackend>(backend);s.amdFlowHalfResolution=half!=0;}if(version>=7){int sync;if(!(in>>sync>>s.audioOffsetMs))return false;s.audioSync=static_cast<AudioSyncMode>(sync);}- if(version>=9){int runtime;if(!(in>>runtime))return false;s.nrRuntime=static_cast<NrRuntime>(runtime);}+ if(version>=9){int runtime;if(!(in>>runtime))return false;s.nrRuntime=currentNrRuntime(static_cast<NrRuntime>(runtime));}if(version>=10){int capture;if(!(in>>capture)||capture<0||capture>1)return false;s.captureCompatible=capture!=0;}if(version>=11){int low;if(!(in>>low)||low<0||low>1)return false;s.lowLatency=low!=0;}if(version>=12){int sdr;if(!(in>>sdr)||sdr<0||sdr>1)return false;s.forceSdrPreview=sdr!=0;}@@ -48,6 +91,37 @@ bool PresetStore::parse(const std::string& data,std::vector<UserPreset>& out,std// v18 appends the full colour grade block (see ColorSettings.h).if(version>=18){std::string lut;if(!readColorSettings(in,s.color,lut,version))return false;if(!lut.empty()&&!s.color.setLutName(wide(lut)))return false;}if(version>=20){int enabled;if(!(in>>enabled>>s.videoHdr.contrast>>s.videoHdr.saturation>>s.videoHdr.middleGray>>s.videoHdr.peakNits)||enabled<0||enabled>1)return false;s.videoHdr.enabled=enabled!=0;} if(version>=21){int temporal=0;if(!(in>>temporal)||temporal<0||temporal>1)return false;s.nrTemporal=temporal!=0;}+ if(version>=22){+ if(!(in>>s.additionalColorCount)||s.additionalColorCount>=kMaxColorInstances)return false;+ for(unsigned c=0;c<s.additionalColorCount;++c){std::string lut;+ if(!readColorSettings(in,s.additionalColors[c],lut,version))return false;+ if(!lut.empty()&&!s.additionalColors[c].setLutName(wide(lut)))return false;+ }+ }+ if(version>=23){+ if(!(in>>s.nrLayerCount)||s.nrLayerCount>kMaxNrInstances)return false;+ for(unsigned j=0;j<s.nrLayerCount;++j){auto& layer=s.nrLayers[j];int runtime,temporal,low,enabled,size;+ auto& lm=layer.model;auto& lr=layer.residual;+ if(!(in>>lm.intensity>>lm.tone>>lm.structure>>lm.skin>>lm.style>>lm.autoMask>>lm.uiCorrection+ >>lr.total>>lr.darken>>lr.brighten>>lr.color>>lr.luminance>>runtime>>temporal>>low>>enabled>>size)+ ||temporal<0||temporal>1||low<0||low>1||enabled<0||enabled>1)return false;+ layer.runtime=currentNrRuntime(static_cast<NrRuntime>(runtime));layer.temporal=temporal!=0;+ layer.lowLatencyPairing=low!=0;layer.enabled=enabled!=0;+ layer.sizePolicy=static_cast<pipeline::NrSizePolicy>(size);+ // v24 appends the tier after the size policy. A v23 store has no+ // tier, and Flow is what its `temporal=true` meant, which is+ // exactly the field default.+ if(version>=24){int tier;if(!(in>>tier)||!validNrAntiFlicker(NrAntiFlicker(tier)))return false;layer.antiFlicker=static_cast<NrAntiFlicker>(tier);}+ }+ }+ // v24: the output-stabiliser pair. Bounds are the ones the pass accepts:+ // 0 disables, 1 is full hold, and the tolerance is a relative delta.+ if(version>=24){+ if(!(in>>s.nrHoldStrength>>s.nrHoldTolerance))return false;+ if(!std::isfinite(s.nrHoldStrength)||s.nrHoldStrength<0.0f||s.nrHoldStrength>1.0f)return false;+ if(!std::isfinite(s.nrHoldTolerance)||s.nrHoldTolerance<0.0f||s.nrHoldTolerance>1.0f)return false;+ }+ if(version>=27){int hdr,fg,sr,nr;if(!(in>>hdr>>fg>>sr>>nr))return false;s.hdrOutputMode=HdrOutputMode(hdr);s.fgMotion=MotionSource(fg);s.srMotion=MotionSource(sr);s.nrMotion=MotionSource(nr);}p.name=wide(n);if(!nameOk(p.name)||std::any_of(out.begin(),out.end(),[&](auto& a){return a.name==p.name;})||nr<0||nr>1||sr<0||sr>1)return false;s.nr=nr;s.sr=sr;s.nrPolicy=static_cast<pipeline::NrSizePolicy>(policy);s.flow=static_cast<FlowQuality>(flow);s.content=static_cast<ContentRate>(content);if(!s.validate().empty())return false;out.push_back(std::move(p));@@ -56,7 +130,7 @@ bool PresetStore::parse(const std::string& data,std::vector<UserPreset>& out,stdreturn def.empty()||std::any_of(out.begin(),out.end(),[&](auto& a){return a.name==def;});}bool PresetStore::load(){- error_.clear();if(!std::filesystem::exists(path_))return true;if(std::filesystem::file_size(path_)>65536){corrupt_=true;error_=L"预设文件超过64KiB,原文件保留";return false;}std::ifstream f(path_,std::ios::binary);std::string data((std::istreambuf_iterator<char>(f)),{});std::vector<UserPreset> loaded;std::wstring def;+ error_.clear();if(!std::filesystem::exists(path_))return true;if(std::filesystem::file_size(path_)>kMaxPresetBytes){corrupt_=true;error_=L"预设文件超过2MiB,原文件保留";return false;}std::ifstream f(path_,std::ios::binary);std::string data((std::istreambuf_iterator<char>(f)),{});std::vector<UserPreset> loaded;std::wstring def;if(!f||!parse(data,loaded,def)){corrupt_=true;error_=L"预设文件损坏或版本不支持;原文件已保留,禁止覆盖。当前使用内建设置。";return false;}entries_=std::move(loaded);default_=std::move(def);corrupt_=false;return true;}diff --git a/src/engine/TiledImageProcessor.cpp b/src/engine/TiledImageProcessor.cppindex ca3e49fd..26a2ef28 100644--- a/src/engine/TiledImageProcessor.cpp+++ b/src/engine/TiledImageProcessor.cpp@@ -56,11 +56,19 @@ bool TiledImageProcessor::process(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotR// Source-normalized regions are mapped to this padded tile. Halo exceeds// the maximum feather, so clipping at tile edges cannot alter core pixels.engine::EnhancementSettings tileSettings;tileSettings.nr=desc.enableNr;tileSettings.model=desc.model;tileSettings.residual=desc.residual;tileSettings.protection=desc.protection;+ // Protection is tile-local; grading remains the same ordered chain as+ // the full image. Default colour settings would reject an enabled grade+ // (or a nonempty additional chain) before the first tile is processed.+ tileSettings.color=desc.color;tileSettings.additionalColors=desc.additionalColors;+ tileSettings.additionalColorCount=desc.additionalColorCount;for(auto& q:tileSettings.protection.regions){- q.left=std::clamp(float(q.left*input.width-originX+halo)/tileW,0.0f,1.0f);- q.right=std::clamp(float(q.right*input.width-originX+halo)/tileW,0.0f,1.0f);- q.top=std::clamp(float(q.top*input.height-originY+halo)/tileH,0.0f,1.0f);- q.bottom=std::clamp(float(q.bottom*input.height-originY+halo)/tileH,0.0f,1.0f);+ // A rectangle clipped to the tile is the same rectangle; an ellipse+ // clipped would be a different ellipse, so it keeps its full box.+ const float low=q.ellipse?-64.0f:0.0f,high=q.ellipse?65.0f:1.0f;+ q.left=std::clamp(float(q.left*input.width-originX+halo)/tileW,low,high);+ q.right=std::clamp(float(q.right*input.width-originX+halo)/tileW,low,high);+ q.top=std::clamp(float(q.top*input.height-originY+halo)/tileH,low,high);+ q.bottom=std::clamp(float(q.bottom*input.height-originY+halo)/tileH,low,high);}tileSettings.revision=desc.settingsRevision;if(!graph.applySettings(tileSettings))return false;pipeline::EnhanceGraph::FrameOutputs out;sink::RgbaImage tile;diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cppindex c0185996..da987def 100644--- a/src/engine/VideoExportJob.cpp+++ b/src/engine/VideoExportJob.cpp@@ -24,19 +24,15 @@ namespace { std::string utf8(const std::wstring& s){const int n=WideCharToMultiBbool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptions options,bool hevc,std::atomic<bool>& cancel,const std::function<void(double,const std::wstring&)>& progress,unsigned maxFrames,const std::function<bool()>& frameBoundary,const std::function<void(const ExportCounts&)>& counts){if(!std::isfinite(options.exportStartSeconds)||!std::isfinite(options.exportEndSeconds)||options.exportStartSeconds<0||options.exportEndSeconds<0||(options.exportEndSeconds>0&&options.exportEndSeconds<=options.exportStartSeconds)){progress(0,L"导出剪辑范围无效");return false;}if(std::filesystem::exists(output)||std::filesystem::exists(output+L".partial")){progress(0,L"目标或partial文件已存在,请使用其他名称");return false;}- // XeSS-FG and AMD FSR-FG interpolate inside the present swapchain: the- // provider presents the extra frames itself, so no output texture ever- // reaches the application (XeSS-FG 3.0.2 exports only xefgSwapChain*, and- // the FSR-FG context owns the proxy swapchain). Refusing the job left those- // users with no file at all, so export now runs the in-graph DLSS path and- // states the substitution. A rejected requested multiplier fails the job- // explicitly; a successful export must retain the requested cadence.+ // XeSS still has no exposed output texture. FSR preview now does, but+ // FSR encoder/HDR/cadence acceptance remains a separate task. Preserve the+ // established, explicit DLSS substitution for this release candidate.std::wstring fgNote;- if(options.fg&&presentSinkFrameGeneration(options.settings.frameGenerationBackend)){+ if(options.fg&&crossVendorFrameGeneration(options.settings.frameGenerationBackend)){const auto requested=options.settings.frameGenerationBackend;- fgNote=std::format(L"{}补帧由显示交换链直接生成,导出取不到它的画面;本次导出改用 DLSS 补帧 {}X",- requested==FrameGenerationBackend::XeSS?L"XeSS":L"AMD FSR",options.fgMultiplier);- veyra::log::warn("export",std::format("present-sink frame generation cannot feed the encoder requested={} multiplier={}; substituting the in-graph DLSS path",frameGenerationBackendName(requested),options.fgMultiplier));+ fgNote=std::format(L"{} 补帧导出尚未验收;本次导出改用 DLSS 补帧 {}X",+ requested==FrameGenerationBackend::XeSS?L"XeSS":requested==FrameGenerationBackend::Fsr4?L"FSR 4":L"FSR 3.1",options.fgMultiplier);+ veyra::log::warn("export",std::format("requested preview backend is not admitted for export requested={} multiplier={}; substituting the in-graph DLSS path",frameGenerationBackendName(requested),options.fgMultiplier));options.settings.frameGenerationBackend=FrameGenerationBackend::Dlss;}gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;pipeline::EnhanceGraph graph(ctx,ring);diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cppindex e5ea154a..10e1dade 100644--- a/src/engine/VideoPresenter.cpp+++ b/src/engine/VideoPresenter.cpp@@ -25,20 +25,20 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::EnhviewWidth_=viewHeight_=0;bufferMonitor_=nullptr;monitorWidth_=monitorHeight_=0;++generation_;Status st=Status::Ok;- if(graph.fgEnabled()&&!graph.xessEnabled()&&!graph.fsrEnabled()){+ if(graph.fgEnabled()&&!graph.xessEnabled()){D3D12_COMMAND_QUEUE_DESC desc{};desc.Type=D3D12_COMMAND_LIST_TYPE_DIRECT;HRESULT hr=ctx.device()->CreateCommandQueue(&desc,IID_PPV_ARGS(&presentationQueue_));if(SUCCEEDED(hr))hr=ctx.device()->CreateFence(0,D3D12_FENCE_FLAG_NONE,IID_PPV_ARGS(&presentationFence_));- if(FAILED(hr)){veyra::log::error("present",std::format("DLSS presentation queue/fence hr=0x{:X}",unsigned(hr)));close();return false;}+ if(FAILED(hr)){veyra::log::error("present",std::format("application frame-generation presentation queue/fence hr=0x{:X}",unsigned(hr)));close();return false;}presentationEvent_=CreateEventW(nullptr,FALSE,FALSE,nullptr);if(!presentationEvent_||!presentationRing_.initialize(ctx.device(),presentationQueue_.Get(),presentationFence_.Get(),presentationEvent_,3,st)){close();return false;}- veyra::log::info("present","DLSS presentation uses independent queue/fence, 3 command slots; shared textures use producer/consumer GPU fences");+ veyra::log::info("present","application frame-generation presentation uses independent queue/fence, 3 command slots; shared textures use producer/consumer GPU fences");}auto* queue=presentationQueue_?presentationQueue_.Get():ctx.directQueue();gpuTimer_.initialize(ctx.device(),queue);window_=window;RECT rc{};GetClientRect(window,&rc);- gfx::PresentSink::Desc d;d.targetWindow=window;d.width=std::max(1L,rc.right);d.height=std::max(1L,rc.bottom);d.vsync=false;+ gfx::PresentSink::Desc d;d.targetWindow=window;d.width=std::max(1L,rc.right);d.height=std::max(1L,rc.bottom);d.vsync=false;d.tearing=false;d.waitable=!GetEnvironmentVariableW(L"VEYRA_TEST_LEGACY_SWAPCHAIN",nullptr,0);- d.hdr=graph.hdrOutput();d.hdr10=graph.hdr10Output();d.xess=graph.xessEnabled();d.fsr=graph.fsrEnabled();d.renderWidth=graph.workWidth();d.renderHeight=graph.workHeight();d.captureCompatible=captureCompatible;d.fgMultiplier=graph.fgMultiplier();+ d.hdr=graph.hdrOutput();d.hdr10=graph.hdr10Output();d.xess=graph.xessEnabled();d.captureCompatible=captureCompatible;d.fgMultiplier=graph.fgMultiplier();// Candidate X2 (2026-09-22) tried XeLL pass-through for media-clock-paced// sources; the audited provider then rejects generation with -15// (LATENCY_REDUCTION_UNSUPPORTED) and Intel's guide states frame@@ -46,7 +46,7 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::Enh// VEYRA_TEST_XESS_LOW_LATENCY=0 remains a diagnostic-only toggle.(void)mediaClockPaced;wchar_t lowLatency[4]{};- d.xessLowLatencySleep=!(GetEnvironmentVariableW(L"VEYRA_TEST_XESS_LOW_LATENCY",lowLatency,4)&&lowLatency[0]==L'0');lastXessFrame_={};lastXessIdentity_={};xessWasEnabled_=false;lastFsrFrame_={};lastFsrIdentity_={};fsrWasEnabled_=false;+ d.xessLowLatencySleep=!(GetEnvironmentVariableW(L"VEYRA_TEST_XESS_LOW_LATENCY",lowLatency,4)&&lowLatency[0]==L'0');lastXessFrame_={};lastXessIdentity_={};xessWasEnabled_=false;if(d.xess){bufferMonitor_=MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST);MONITORINFO monitor{sizeof(monitor)};@@ -86,13 +86,13 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&auto* fence=presentationFence_?presentationFence_.Get():ctx.fence();const auto presentStart=std::chrono::steady_clock::now();const auto slotWaitStart=ring.cpuWaitMilliseconds();- xessFailed_=false;fsrFailed_=false;+ xessFailed_=false;RECT rc{};GetClientRect(window_,&rc);if(rc.right<1||rc.bottom<1)return true;const auto now=std::chrono::steady_clock::now();bool resized=false;const auto deferUntil=uint64_t(uintptr_t(GetPropW(window_,L"Veyra.ResizeDeferUntil")));if(viewWidth_!=unsigned(rc.right)||viewHeight_!=unsigned(rc.bottom)){- viewWidth_=rc.right;viewHeight_=rc.bottom;xessWasEnabled_=fsrWasEnabled_=false;+ viewWidth_=rc.right;viewHeight_=rc.bottom;xessWasEnabled_=false;}unsigned targetWidth=rc.right,targetHeight=rc.bottom;if(sink_.xess()){@@ -144,24 +144,27 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&// DXGI stretches the retained buffer while the native workspace unfolds.// Compute contain in CURRENT client coordinates, then map back to buffer// coordinates so that the onscreen image keeps its aspect throughout.- const float scale=std::min(float(rc.right)/graph.workWidth(),float(rc.bottom)/graph.workHeight());+ const auto [renderW,renderH]=view.renderedSize(float(rc.right),float(rc.bottom),float(graph.workWidth()),float(graph.workHeight()));D3D12_VIEWPORT viewport{0,0,float(sink_.bufferWidth()),float(sink_.bufferHeight()),0,1};D3D12_RECT rect{0,0,LONG(sink_.bufferWidth()),LONG(sink_.bufferHeight())};list->RSSetViewports(1,&viewport);list->RSSetScissorRects(1,&rect);ID3D12DescriptorHeap* heaps[]={pass_.heap.Get()};list->SetDescriptorHeaps(1,heaps);list->SetGraphicsRootSignature(pass_.rootSig.Get());list->SetPipelineState(pass_.pso.Get());const float samplingFlags=graph.highQualityPresentation()?2.0f:0.0f;- float dims[8]={float(graph.workWidth()),float(graph.workHeight()),samplingFlags,view.zoom,float(rc.right),float(rc.bottom),view.centerX,view.centerY};list->SetGraphicsRoot32BitConstants(0,8,dims,0);+ // PresentBlit uses a contain mapping. Cancel its fit so these dimensions+ // express the exact shared display transform, including stretch/SAR/fill.+ const float inverseFit=1.0f/std::min(float(rc.right)/renderW,float(rc.bottom)/renderH);+ float dims[8]={renderW,renderH,samplingFlags,inverseFit,float(rc.right),float(rc.bottom),view.centerX,view.centerY};list->SetGraphicsRoot32BitConstants(0,8,dims,0);list->SetGraphicsRootDescriptorTable(1,{pass_.heap->GetGPUDescriptorHandleForHeapStart().ptr+size_t(slot+(generated?2:0))*pass_.increment});list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);list->DrawInstanced(3,1,0,0);if(comparison&&!generated&&referencesValid){auto* reference=baseReference?graph.baseReference(slot):graph.sourceReference(slot);D3D12_RESOURCE_BARRIER b{};b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;b.Transition.pResource=reference;b.Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;b.Transition.StateBefore=D3D12_RESOURCE_STATE_COMMON;b.Transition.StateAfter=D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;list->ResourceBarrier(1,&b);dims[2]=samplingFlags+(graph.hdr10Output()?4:graph.hdrOutput()?0:1)+(graph.videoHdrActive()?8:0);list->SetGraphicsRoot32BitConstants(0,8,dims,0);list->SetGraphicsRootDescriptorTable(1,{pass_.heap->GetGPUDescriptorHandleForHeapStart().ptr+size_t(12+slot+(baseReference?2:0))*pass_.increment});- if(comparison==2)rect.right=LONG(std::clamp((rc.right*.5f+(std::clamp(split,0.0f,1.0f)-view.centerX)*graph.workWidth()*scale*view.zoom)*sink_.bufferWidth()/rc.right,0.0f,float(sink_.bufferWidth())));list->RSSetScissorRects(1,&rect);list->DrawInstanced(3,1,0,0);+ if(comparison==2)rect.right=LONG(std::clamp((rc.right*.5f+(std::clamp(split,0.0f,1.0f)-view.centerX)*renderW)*sink_.bufferWidth()/rc.right,0.0f,float(sink_.bufferWidth())));list->RSSetScissorRects(1,&rect);list->DrawInstanced(3,1,0,0);std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(1,&b);if(veyra::log::verboseFrameLogs())veyra::log::info("comparison",std::format("real-frame source={} epoch={} revision={} reference={} mode={} split={} (same leased frame)",identity.sourceFrameId,identity.epoch,identity.settingsRevision,baseReference?"base":"input",comparison,split));}for(auto& b:barriers)std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(2,barriers);- // Interpolation region for the present-sink FG backends (XeSS-FG, FSR-FG).+ // Interpolation region for the XeSS present-sink FG backend.// It must follow the PresentBlit view mapping (contain * zoom, view// center) rather than assuming the default centered view: the previous// exact `view == PreviewView{}` guard disabled generation forever after@@ -208,10 +211,11 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&states.transition(list,motion,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);states.transition(list,mapped,D3D12_RESOURCE_STATE_UNORDERED_ACCESS);const auto previous=reset?view:previousXessView_;+ const auto [prevRenderW,prevRenderH]=previous.renderedSize(float(reset?rc.right:previousXessWidth_),float(reset?rc.bottom:previousXessHeight_),float(graph.workWidth()),float(graph.workHeight()));const float mapping[16]={float(graph.workWidth()),float(graph.workHeight()),float(rc.right),float(rc.bottom),- view.zoom,view.centerX,view.centerY,reset?1.0f:0.0f,- previous.zoom,previous.centerX,previous.centerY,0,- float(reset?rc.right:previousXessWidth_),float(reset?rc.bottom:previousXessHeight_),0,0};+ renderW,view.centerX,view.centerY,reset?1.0f:0.0f,+ renderH,previous.centerX,previous.centerY,0,+ float(reset?rc.right:previousXessWidth_),float(reset?rc.bottom:previousXessHeight_),prevRenderW,prevRenderH};const auto heap=presentMotionPass_.heap->GetGPUDescriptorHandleForHeapStart().ptr;presentMotionPass_.bind(list,mapping,heap+size_t(slot*2)*presentMotionPass_.increment,heap+size_t(slot*2+1)*presentMotionPass_.increment);list->Dispatch((graph.workWidth()+7)/8,(graph.workHeight()+7)/8,1);@@ -237,22 +241,7 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&if(enabled)lastXessPts100ns_=sourcePts100ns;previousXessView_=view;previousXessWidth_=rc.right;previousXessHeight_=rc.bottom;}- if(auto* fsr=sink_.fsr()){- const bool enabled=regionVisible&&!generated&&!comparison&&graph.presentMotionValid(slot)&&identity.sourceFrameId!=lastFsrIdentity_.sourceFrameId;- const bool reset=!fsrWasEnabled_||identity.epoch!=lastFsrIdentity_.epoch||identity.settingsRevision!=lastFsrIdentity_.settingsRevision||graph.motionPreviousSource(slot)!=lastFsrIdentity_.sourceFrameId;- const float elapsed=lastFsrFrame_==std::chrono::steady_clock::time_point{}?0.0f:float(std::chrono::duration<double,std::milli>(now-lastFsrFrame_).count());- // The AMD presenter degrades inside the provider (generation off, plain- // presentation continues) instead of failing the frame: tearing the- // swapchain down would only cost the session a restart.- if(enabled)gpuTimer_.mark(list,diagnostics::GpuStage::FgBatch);- if(!fsr->tag(list,bb,graph.presentMotion(slot),graph.presentDepth(),fgRect,enabled,reset,elapsed))fsrFailed_=true;- if(enabled)gpuTimer_.mark(list,diagnostics::GpuStage::FgBatch,true);- if(sink_.fsr()->failed())fsrFailed_=true;- // Same repeat rule as XeSS above.- const bool fsrRepeatOnly=identity.sourceFrameId==lastFsrIdentity_.sourceFrameId;- lastFsrFrame_=now;fsrWasEnabled_=enabled||(fsrWasEnabled_&&fsrRepeatOnly);- if(!fsrRepeatOnly)lastFsrIdentity_=identity;else lastFsrIdentity_.epoch=identity.epoch,lastFsrIdentity_.settingsRevision=identity.settingsRevision;- }+gpuTimer_.mark(list,diagnostics::GpuStage::Blit,true);gpuTimer_.resolve(list);if(!ring.submitAndSignal(commandSlot))return false;gpuTimer_.submitted(ring.lastSignaledValue());lastBuffer_=backBufferIndex;hasPresented_=true;if(presentationQueue_)graph.presentationSubmitted(slot,fence,ring.lastSignaledValue());@@ -269,16 +258,16 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&// display actually scanned out. This is still not a photon measurement.static const bool displayStats=GetEnvironmentVariableW(L"VEYRA_TEST_NO_DISPLAY_STATS",nullptr,0)==0;const auto stats=displayStats?sink_.sampleFrameStatistics():gfx::PresentSink::FrameStatisticsDelta{};- if(stats.supported)veyra::log::info("display-stats",std::format("refreshHz={:.3f} presentCalls={} dxgiPresentCount={} refreshes={} presentRefreshDelta={} backend={} (DXGI GetFrameStatistics delta over ~1s. These counters CANNOT tell how many frames the panel actually showed: with vsync off and tearing allowed, dxgiPresentCount tracks completed Present calls, and both refresh counters just advance with the monitor. Measuring scanout needs PresentMon. XeSS/FSR generated presents are provider-internal.)",sink_.displayRefreshHz(),stats.presents,stats.displayed,stats.refreshes,stats.displayedRefresh,sink_.xess()?"XeSS":sink_.fsr()?"FSR":"DXGI"));- else if(FAILED(stats.result))veyra::log::info("display-stats",std::format("unavailable hr=0x{:X} backend={}",unsigned(stats.result),sink_.xess()?"XeSS":sink_.fsr()?"FSR":"DXGI"));+ if(stats.supported)veyra::log::info("display-stats",std::format("refreshHz={:.3f} presentCalls={} dxgiPresentCount={} refreshes={} presentRefreshDelta={} backend={} (DXGI GetFrameStatistics delta over ~1s. These counters CANNOT tell how many frames the panel actually showed: with vsync off and tearing allowed, dxgiPresentCount tracks completed Present calls, and both refresh counters just advance with the monitor. Measuring scanout needs PresentMon. XeSS generated presents are provider-internal.)",sink_.displayRefreshHz(),stats.presents,stats.displayed,stats.refreshes,stats.displayedRefresh,sink_.xess()?"XeSS":"DXGI"));+ else if(FAILED(stats.result))veyra::log::info("display-stats",std::format("unavailable hr=0x{:X} backend={}",unsigned(stats.result),sink_.xess()?"XeSS":"DXGI"));const auto& timing=sink_.lastPresentTiming();veyra::log::info("present-cost",std::format("generated={} totalMs={:.3f} recordSubmitMs={:.3f} slotWaitMs={:.3f} dxgiMs={:.3f} slow={} source={} epoch={} backend={} resized={} resizeMs={:.3f} beginMs={:.3f} commandsMs={:.3f} beforeMs={:.3f} presentCallMs={:.3f} bufferMs={:.3f} afterMs={:.3f} hr=0x{:X}",generated,std::chrono::duration<double,std::milli>(presentEnd-presentStart).count(),std::chrono::duration<double,std::milli>(dxgiStart-presentStart).count(),ring.cpuWaitMilliseconds()-slotWaitStart,- ms(presentEnd-dxgiStart),slow,identity.sourceFrameId,identity.epoch,sink_.xess()?"XeSS":sink_.fsr()?"FSR":"DXGI",resized,+ ms(presentEnd-dxgiStart),slow,identity.sourceFrameId,identity.epoch,sink_.xess()?"XeSS":"DXGI",resized,ms(resizeEnd-presentStart),ms(beginEnd-resizeEnd),ms(dxgiStart-beginEnd),timing.beforeMs,timing.callMs,timing.bufferMs,timing.afterMs,unsigned(timing.result)));}- xessFailed_=sink_.xessFailed();fsrFailed_=fsrFailed_||sink_.fsrFailed();return presented;+ xessFailed_=sink_.xessFailed();return presented;}bool VideoPresenter::readPresentedFrameForTest(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,sink::RgbaImage& image){if(presentationQueue_&&!presentationRing_.drainQueue())return false;@@ -305,29 +294,29 @@ PresentationSettings VideoPresenter::configurePresentation(gfx::D3D12DeviceConte}auto effective=requested;std::wstring capNotice;- if((xessActive()||fsrActive())&&requested.outputRate!=OutputRateMode::Off){+ if((xessActive())&&requested.outputRate!=OutputRateMode::Off){// Provider owns generated Present calls. Capping our real-frame input// would change the source cadence, not cap its final output.effective.outputRate=OutputRateMode::Off;capNotice=L" · 此补帧提供方暂不支持独立输出限帧;已保留设置";}- if(!reflexDisabled){effective.enabled=false;sink_.configurePacing(false,false);status=L"Reflex 驱动状态撤销失败;应用等待已停用,请关闭视频后重试";return effective;}- if(!requested.enabled){const bool restored=sink_.configurePacing(false,false);status=restored?L"帧同步已关闭":L"应用等待已关闭,但显示队列恢复失败;请关闭视频后重试";if(effective.outputRate==OutputRateMode::Custom)status+=std::format(L" · 输出上限 {:.3f} FPS",effective.customFps);status+=capNotice;return effective;}- if(xessActive()||fsrActive()){+ const bool vsync=presentationVsync(requested),tearing=presentationTearing(requested);+ providerOwnedPresentation_=xessActive();+ const std::wstring sync=vsync?L"显示同步:垂直同步":tearing?L"显示同步:允许撕裂":L"显示同步:自动 · 防撕裂(不等待垂直同步)";+ if(!reflexDisabled){effective.enabled=false;sink_.configurePacing(false,vsync,tearing);status=L"Reflex 驱动状态撤销失败;低延迟队列已停用 · "+sync;return effective;}+ if(xessActive()){// The provider owns Present for its generated frames, so neither the// latency waiter nor an output cap can reach them. Only the DXGI VSync// bit still applies (XeSS accepts it on the proxy chain).effective.enabled=false;providerOwnedPresentation_=true;- const bool vsync=xessActive()&&requested.display!=DisplaySync::Tearing;- sink_.configurePacing(false,vsync);- if(fsrActive()){effective.display=DisplaySync::Tearing;status=L"FSR 提供方自行调度:低延迟队列与输出上限均不生效,显示同步暂不支持";}- else status=vsync?L"XeSS 提供方自行调度:低延迟队列与输出上限不生效 · 垂直同步":L"XeSS 提供方自行调度:低延迟队列与输出上限不生效 · 允许撕裂";- if(xessActive()&&requested.display==DisplaySync::Automatic)status+=L"(自动;VRR 状态未知)";+ sink_.configurePacing(false,vsync,tearing);+ status=L"XeSS 提供方自行调度:低延迟队列与输出上限不生效 · "+sync;return effective;}providerOwnedPresentation_=false;- if(!sink_.configurePacing(true,requested.display!=DisplaySync::Tearing)){effective.enabled=false;status=L"显示队列控制不可用,已回退原呈现方式";return effective;}+ if(!requested.enabled){const bool restored=sink_.configurePacing(false,vsync,tearing);status=(restored?L"低延迟队列已关闭 · ":L"低延迟队列恢复失败 · ")+sync;if(effective.outputRate==OutputRateMode::Custom)status+=std::format(L" · 输出上限 {:.3f} FPS",effective.customFps);status+=capNotice;return effective;}+ if(!sink_.configurePacing(true,vsync,tearing)){effective.enabled=false;status=L"显示队列控制不可用 · "+sync;return effective;}// Low latency = queue depth 1, plus Reflex when frame generation is off// (generated outputs would need separately validated out-of-band markers).std::wstring latency=L"低延迟队列:队列深度 1";@@ -338,8 +327,6 @@ PresentationSettings VideoPresenter::configurePresentation(gfx::D3D12DeviceConteif(followDisplay)cap=std::format(L"输出上限:跟随显示器 {:.0f} Hz",requested.customFps);else if(requested.outputRate==OutputRateMode::Custom)cap=std::format(L"输出上限:{:.3f} FPS",requested.customFps);else cap=L"输出上限:关闭";- const std::wstring sync=requested.display==DisplaySync::Automatic?L"显示同步:自动(按垂直同步处理,VRR 状态未知)"- :requested.display==DisplaySync::Vsync?L"显示同步:垂直同步":L"显示同步:允许撕裂";status=latency+L" · "+cap+L" · "+sync;return effective;}diff --git a/src/gfx/CommandSlotRing.cpp b/src/gfx/CommandSlotRing.cppindex 4467adb8..9427f6ce 100644--- a/src/gfx/CommandSlotRing.cpp+++ b/src/gfx/CommandSlotRing.cpp@@ -109,9 +109,9 @@ ID3D12GraphicsCommandList* CommandSlotRing::acquire(uint32_t slot, Status& statureturn nullptr;}Slot& target = slots_[slot];-+ const uint64_t completed = fence_->GetCompletedValue();+ if(completed==UINT64_MAX){status=Status::DeviceFailure;veyra::log::error("gfx",std::format("slot-ring: removed-device fence sentinel slot={} removedReason=0x{:X}",slot,unsigned(device_->GetDeviceRemovedReason())));return nullptr;}if (target.fenceValue != 0) {- const uint64_t completed = fence_->GetCompletedValue();if (completed < target.fenceValue) {const HRESULT waitResult = fence_->SetEventOnCompletion(target.fenceValue, fenceEvent_);if (FAILED(waitResult)) {@@ -252,7 +252,9 @@ bool CommandSlotRing::waitIdle()if (highest == 0) {return true;}- if (fence_->GetCompletedValue() >= highest) {+ const auto completed=fence_->GetCompletedValue();+ if(completed==UINT64_MAX){veyra::log::error("gfx",std::format("slot-ring: drain refused removed-device fence sentinel removedReason=0x{:X}",unsigned(device_->GetDeviceRemovedReason())));return false;}+ if (completed >= highest) {return true;}const HRESULT setResult = fence_->SetEventOnCompletion(highest, fenceEvent_);@@ -265,7 +267,7 @@ bool CommandSlotRing::waitIdle()veyra::log::error("gfx", std::format("slot-ring: waitIdle wait={} fenceValue={}", wait, highest));return false;}- return true;+ return fence_->GetCompletedValue()!=UINT64_MAX&&SUCCEEDED(device_->GetDeviceRemovedReason());}uint32_t CommandSlotRing::timestampQueryIndex(uint32_t slot, bool end) constdiff --git a/src/gfx/D3D12DeviceContext.cpp b/src/gfx/D3D12DeviceContext.cppindex ec6dc94f..9d407b70 100644--- a/src/gfx/D3D12DeviceContext.cpp+++ b/src/gfx/D3D12DeviceContext.cpp@@ -1,6 +1,8 @@#include "veyra/gfx/D3D12DeviceContext.h"#include <windows.h>+#include <winevt.h>+#pragma comment(lib, "wevtapi.lib")#include <format>#include <string>@@ -122,6 +124,15 @@ bool D3D12DeviceContext::initialize(const DeviceContextDesc& desc, Status& statushutdown();}+ // Microsoft DRED settings apply only to subsequently created devices.+ // Enable before even the adapter's D3D12 capability probe below.+ ComPtr<ID3D12DeviceRemovedExtendedDataSettings1> dredSettings;+ const auto dredHr=D3D12GetDebugInterface(IID_PPV_ARGS(&dredSettings));+ if(SUCCEEDED(dredHr)) {+ dredSettings->SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);+ dredSettings->SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);+ }+ veyra::log::info("dred",std::format("configured before device creation hr=0x{:X} breadcrumbs={} pageFault={}",unsigned(dredHr),SUCCEEDED(dredHr),SUCCEEDED(dredHr)));// 1. Optional debug layer.if (desc.enableDebugLayer) {ComPtr<ID3D12Debug> debug;@@ -273,7 +284,10 @@ void D3D12DeviceContext::shutdown()bool D3D12DeviceContext::waitForFenceValue(uint64_t value, uint32_t timeoutMs){- if (fence_->GetCompletedValue() >= value) {+ if(!fence_)return false;+ const auto completed=fence_->GetCompletedValue();+ if(completed==UINT64_MAX){reportDeviceFailure("fence-sentinel",value);return false;}+ if (completed >= value) {return true;}const HRESULT result = fence_->SetEventOnCompletion(value, fenceEvent_);@@ -281,15 +295,63 @@ bool D3D12DeviceContext::waitForFenceValue(uint64_t value, uint32_t timeoutMs)veyra::log::error("gfx", std::format("SetEventOnCompletion failed hr={} value={}", veyra::hresultString(result), value));return false;}- return WaitForSingleObject(fenceEvent_, timeoutMs) == WAIT_OBJECT_0;+ const auto wait=WaitForSingleObject(fenceEvent_, timeoutMs);+ if(wait!=WAIT_OBJECT_0){reportDeviceFailure("fence-wait",value);return false;}+ uint32_t reason=0;+ return fence_->GetCompletedValue()!=UINT64_MAX&&checkDeviceAlive(reason);}bool D3D12DeviceContext::checkDeviceAlive(uint32_t& removedReason) const{- const HRESULT reason = device_->GetDeviceRemovedReason();+ const HRESULT reason = device_?device_->GetDeviceRemovedReason():E_POINTER;removedReason = static_cast<uint32_t>(reason);return SUCCEEDED(reason);}+bool D3D12DeviceContext::reportDeviceFailure(std::string_view operation,uint64_t requestedFence) const {+ uint32_t reason=0;const bool alive=checkDeviceAlive(reason);+ const auto completed=fence_?fence_->GetCompletedValue():0;+ veyra::log::error("gpu-failure",std::format("operation={} alive={} removedReason=0x{:X} requestedFence={} completedFence={} sentinel={} adapter={} device=0x{:X} luid={} driver={}",operation,alive,reason,requestedFence,completed,completed==UINT64_MAX,narrow(adapterInfo_.description),adapterInfo_.deviceId,adapterInfo_.luidString,narrow(adapterInfo_.driverVersion)));+ // Read at most 16 recent display/driver events; no application logs,+ // registry changes or global diagnostic settings are touched.+ const auto events=EvtQuery(nullptr,L"System",L"*[System[(Provider[@Name='Display'] or Provider[@Name='nvlddmkm']) and (EventID=4101 or EventID=153 or EventID=13 or EventID=14) and TimeCreated[timediff(@SystemTime)<=60000]]]",EvtQueryChannelPath|EvtQueryReverseDirection);+ if(events) {+ EVT_HANDLE items[16]{};DWORD count=0;+ if(EvtNext(events,16,items,0,0,&count))for(DWORD i=0;i<count;++i) {+ DWORD bytes=0,properties=0;+ EvtRender(nullptr,items[i],EvtRenderEventXml,0,nullptr,&bytes,&properties);+ if(bytes>0&&bytes<=65536) {+ std::vector<wchar_t> xml(bytes/sizeof(wchar_t)+1);+ if(EvtRender(nullptr,items[i],EvtRenderEventXml,DWORD(xml.size()*sizeof(wchar_t)),xml.data(),&bytes,&properties))+ veyra::log::error("gpu-system-event",std::format("recent60s={} xml={}",i,narrow(xml.data())));+ }+ EvtClose(items[i]);+ }+ else veyra::log::info("gpu-system-event",std::format("no readable recent display events win32={}",GetLastError()));+ EvtClose(events);+ } else veyra::log::warn("gpu-system-event",std::format("query unavailable win32={}",GetLastError()));+ if(alive||!device_)return alive;+ ComPtr<ID3D12DeviceRemovedExtendedData1> dred;+ const auto query=device_.As(&dred);+ if(FAILED(query)){veyra::log::error("dred",std::format("QueryInterface hr=0x{:X}",unsigned(query)));return false;}+ D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT1 crumbs{};+ const auto crumbsHr=dred->GetAutoBreadcrumbsOutput1(&crumbs);+ veyra::log::error("dred",std::format("breadcrumb query hr=0x{:X}",unsigned(crumbsHr)));+ if(SUCCEEDED(crumbsHr)) {+ uint32_t count=0;+ for(auto* n=crumbs.pHeadAutoBreadcrumbNode;n&&count<16;n=n->pNext,++count) {+ const auto last=n->pLastBreadcrumbValue?*n->pLastBreadcrumbValue:0;+ const auto nextOp=n->pCommandHistory&&last<std::min(n->BreadcrumbCount,65536u)?unsigned(n->pCommandHistory[last]):UINT_MAX;+ veyra::log::error("dred",std::format("breadcrumb={} completed={} total={} nextOp={} list={} queue={}",count,last,n->BreadcrumbCount,nextOp,n->pCommandListDebugNameA?n->pCommandListDebugNameA:"unnamed",n->pCommandQueueDebugNameA?n->pCommandQueueDebugNameA:"unnamed"));+ }+ }+ D3D12_DRED_PAGE_FAULT_OUTPUT1 fault{};const auto faultHr=dred->GetPageFaultAllocationOutput1(&fault);+ veyra::log::error("dred",std::format("pageFault query hr=0x{:X} address=0x{:X}",unsigned(faultHr),fault.PageFaultVA));+ if(SUCCEEDED(faultHr))for(const auto& group:{fault.pHeadExistingAllocationNode,fault.pHeadRecentFreedAllocationNode}) {+ uint32_t count=0;for(auto* n=group;n&&count<16;n=n->pNext,++count)+ veyra::log::error("dred",std::format("allocation={} type={} name={}",count,unsigned(n->AllocationType),n->ObjectNameA?n->ObjectNameA:"unnamed"));+ }+ return false;+}bool D3D12DeviceContext::videoMemoryInfo(uint64_t& budget,uint64_t& usage) const {ComPtr<IDXGIAdapter3> adapter;DXGI_QUERY_VIDEO_MEMORY_INFO info{};diff --git a/src/gfx/FsrFgPresenter.cpp b/src/gfx/FsrFgPresenter.cppindex 63c3cb8c..f87c428c 100644--- a/src/gfx/FsrFgPresenter.cpp+++ b/src/gfx/FsrFgPresenter.cpp@@ -3,9 +3,13 @@#include "veyra/Log.h"#include "veyra/RuntimePaths.h"-#include <atomic>+#include <algorithm>+#include <cmath>#include <filesystem>+#include <map>+#include <mutex>#include <string>+#include <vector>#ifdef VEYRA_HAS_FSR#include <ffx_api_loader.h>@@ -18,15 +22,19 @@ namespace veyra::gfx {#ifdef VEYRA_HAS_FSRnamespace {-void fsrMessage(uint32_t type, const wchar_t* message) {- if (message == nullptr) return;- const int length = WideCharToMultiByte(CP_UTF8, 0, message, -1, nullptr, 0, nullptr, nullptr);- std::string text(size_t(length > 0 ? length - 1 : 0), '\0');- if (length > 1) {- WideCharToMultiByte(CP_UTF8, 0, message, -1, text.data(), length, nullptr, nullptr);- }- if (type == FFX_API_MESSAGE_TYPE_ERROR) log::error("fsr-sdk", text);- else log::warn("fsr-sdk", text);+HMODULE loadResidentModule(const std::filesystem::path& path) {+ // One retained reference per absolute module path, even when graph rebuilds+ // or independent export workers create many short-lived contexts.+ static std::mutex mutex;+ static std::map<std::wstring, HMODULE> modules;+ std::lock_guard lock(mutex);+ const auto key = path.wstring();+ if (const auto found = modules.find(key); found != modules.end()) return found->second;+ const auto module = LoadLibraryExW(path.c_str(), nullptr,+ LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32);+ if (module) modules.emplace(key, module);+ else log::error("fsr-fg", std::format("runtime load failed path={} win32={}", path.string(), GetLastError()));+ return module;}FfxApiSurfaceFormat surfaceFormatFromDxgi(DXGI_FORMAT format) {@@ -61,102 +69,6 @@ FfxApiResource makeResource(ID3D12Resource* resource, uint32_t state) {return api;}-D3D12_RESOURCE_STATES dx12State(uint32_t ffxState) {- switch (ffxState) {- case FFX_API_RESOURCE_STATE_UNORDERED_ACCESS: return D3D12_RESOURCE_STATE_UNORDERED_ACCESS;- case FFX_API_RESOURCE_STATE_PIXEL_COMPUTE_READ:- return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;- case FFX_API_RESOURCE_STATE_COMPUTE_READ: return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;- case FFX_API_RESOURCE_STATE_COPY_SRC: return D3D12_RESOURCE_STATE_COPY_SOURCE;- case FFX_API_RESOURCE_STATE_COPY_DEST: return D3D12_RESOURCE_STATE_COPY_DEST;- case FFX_API_RESOURCE_STATE_PRESENT: return D3D12_RESOURCE_STATE_PRESENT;- case FFX_API_RESOURCE_STATE_RENDER_TARGET: return D3D12_RESOURCE_STATE_RENDER_TARGET;- default: return D3D12_RESOURCE_STATE_COMMON;- }-}--} // namespace-#endif--struct FsrFgPresenter::Impl {- // Written from the provider's presentation thread.- std::atomic<uint64_t> realFrames{0};- std::atomic<uint64_t> generatedFrames{0};- std::atomic<uint64_t> callbackFailures{0};- // Render thread.- uint64_t frameId = 0;- uint32_t requestedGenerated = 0;- uint32_t deliveredGenerated = 0;- bool failed = false;- bool softDisabled = false;- bool available = false;- std::string providerVersion;-- // A provider failure must not take playback down with it: generation is- // switched off, the frame keeps presenting through the proxy swapchain and- // the engine is told once so it can surface a warning.- void disableGeneration(const char* reason) {- if (!softDisabled) {- softDisabled = true;- failed = true;- log::warn("fsr-fg", std::format("frame generation disabled after {}; plain presentation continues", reason));- }- }-#ifdef VEYRA_HAS_FSR- HMODULE loader = nullptr;- ffxFunctions functions{};- ffxContext swapchainContext = nullptr;- ffxContext fgContext = nullptr;- IDXGISwapChain4* swapchain = nullptr; // borrowed; owned by the sink and the context- uint32_t width = 0;- uint32_t height = 0;- uint32_t backBufferFormat = FFX_API_SURFACE_FORMAT_UNKNOWN;-#endif-};--#ifdef VEYRA_HAS_FSR-namespace {--// Called by the provider for every frame that reaches the swapchain, real or-// interpolated, on its presentation thread. Veyra has no UI surface to-// composite, so this performs the same copy the provider's default callback-// would and only keeps counters. No logging or allocation happens here.-ffxReturnCode_t presentCallback(ffxCallbackDescFrameGenerationPresent* params, void* userCtx) {- auto* impl = static_cast<FsrFgPresenter::Impl*>(userCtx);- if (params == nullptr || impl == nullptr) return FFX_API_RETURN_ERROR_PARAMETER;- if (params->isGeneratedFrame) {- impl->generatedFrames.fetch_add(1, std::memory_order_relaxed);- } else {- impl->realFrames.fetch_add(1, std::memory_order_relaxed);- }- if (params->currentUI.resource != nullptr || params->commandList == nullptr ||- params->outputSwapChainBuffer.resource == nullptr || params->currentBackBuffer.resource == nullptr) {- impl->callbackFailures.fetch_add(1, std::memory_order_relaxed);- return FFX_API_RETURN_OK;- }- auto* list = static_cast<ID3D12GraphicsCommandList*>(params->commandList);- auto* destination = static_cast<ID3D12Resource*>(params->outputSwapChainBuffer.resource);- auto* source = static_cast<ID3D12Resource*>(params->currentBackBuffer.resource);- D3D12_RESOURCE_BARRIER barriers[2]{};- barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;- barriers[0].Transition.pResource = source;- barriers[0].Transition.StateBefore = dx12State(params->currentBackBuffer.state);- barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;- barriers[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;- barriers[1].Transition.pResource = destination;- barriers[1].Transition.StateBefore = dx12State(params->outputSwapChainBuffer.state);- barriers[1].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST;- list->ResourceBarrier(2, barriers);- list->CopyResource(destination, source);- for (auto& barrier : barriers) {- const D3D12_RESOURCE_STATES before = barrier.Transition.StateBefore;- barrier.Transition.StateBefore = barrier.Transition.StateAfter;- barrier.Transition.StateAfter = before;- }- list->ResourceBarrier(2, barriers);- return FFX_API_RETURN_OK;-}-const char* returnName(ffxReturnCode_t code) {switch (code) {case FFX_API_RETURN_OK: return "OK";@@ -174,423 +86,189 @@ const char* returnName(ffxReturnCode_t code) {} // namespace#endif-FsrFgPresenter::FsrFgPresenter() : p_(std::make_unique<Impl>()) {}--void FsrFgPresenter::shutdown() {+struct FsrFgPresenter::Impl {+ uint64_t frameId = 0;+ uint32_t width = 0, height = 0, backBufferFormat = 0;+ bool failed = false, available = false;+ std::string providerVersion;#ifdef VEYRA_HAS_FSR- auto& p = *p_;- // The provider requires generation to be switched off before the context- // goes away: that call flushes interpolation and UI composition GPU work,- // after which the context can release the proxy swapchain (and with it the- // real DXGI swapchain, which is what lets another swapchain be created for- // the same HWND later).- if (p.swapchainContext != nullptr) {- // Drain the provider's own presentation queue first: its pacing state- // still holds the last submitted frame id, and destroying the- // contexts with a present in flight crashed inside the provider- // (WER 0xC0000005 in amd_fidelityfx_framegeneration_dx12.dll).- ffxDispatchDescFrameGenerationSwapChainWaitForPresentsDX12 wait{};- wait.header.type = FFX_API_DISPATCH_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_WAIT_FOR_PRESENTS_DX12;- (void)p.functions.Dispatch(&p.swapchainContext, &wait.header);- log::info("fsr-fg", "shutdown: presentation queue drained");- veyra::Logger::instance().flush();- }- if (p.fgContext != nullptr && p.swapchain != nullptr) {- ffxConfigureDescFrameGeneration disable{};- disable.header.type = FFX_API_CONFIGURE_DESC_TYPE_FRAMEGENERATION;- disable.swapChain = p.swapchain;- disable.frameGenerationEnabled = false;- disable.presentCallback = presentCallback;- disable.presentCallbackUserContext = &p;- disable.generationRect = {0, 0, int32_t(p.width), int32_t(p.height)};- disable.frameID = p.frameId;- const auto result = p.functions.Configure(&p.fgContext, &disable.header);- log::info("fsr-fg", std::format("shutdown disable result={} frameId={}", returnName(result), p.frameId));- veyra::Logger::instance().flush();- }- // The context owns one reference to the proxy swapchain and releases it- // here; the sink drops its own reference before this object is destroyed.- if (p.fgContext != nullptr) {- const auto result = p.functions.DestroyContext(&p.fgContext, nullptr);- log::info("fsr-fg", std::format("framegen context destroyed result={}", returnName(result)));- p.fgContext = nullptr;- veyra::Logger::instance().flush();- }- if (p.swapchainContext != nullptr) {- const auto result = p.functions.DestroyContext(&p.swapchainContext, nullptr);- log::info("fsr-fg", std::format("swapchain context destroyed result={}", returnName(result)));- p.swapchainContext = nullptr;- veyra::Logger::instance().flush();- }- p.swapchain = nullptr;- p.available = false;+ HMODULE loader = nullptr;+ ffxFunctions functions{};+ ffxContext fgContext = nullptr;#endif-}+};-FsrFgPresenter::~FsrFgPresenter() {-#ifdef VEYRA_HAS_FSR- shutdown();- // The loader is intentionally never unloaded. Unloading it right after- // DestroyContext crashed with an access violation inside- // amd_fidelityfx_framegeneration_dx12.dll (Application Error 0xC0000005 at- // 0x10b9a9): the provider keeps internal presentation threads and state- // that do not survive module unload. Keeping the module resident for the- // process lifetime is the safe contract, and a later session can create a- // fresh context from it.-#endif-}+FsrFgPresenter::FsrFgPresenter() : p_(std::make_unique<Impl>()) {}-bool FsrFgPresenter::initialize(ID3D12Device* device, ID3D12CommandQueue* queue, IDXGIFactory2* factory,- HWND window, const DXGI_SWAP_CHAIN_DESC1& desc, uint32_t renderWidth,- uint32_t renderHeight, IDXGISwapChain4** swapchain, uint32_t fgMultiplier) {+bool FsrFgPresenter::initializeIndependent(ID3D12Device* device, uint32_t width, uint32_t height,+ DXGI_FORMAT format, bool requireMl) {#ifdef VEYRA_HAS_FSRauto& p = *p_;- (void)fgMultiplier;- const auto root = runtime::localDataDirectory() / "amd" / "fidelityfx";- const auto loaderPath = std::filesystem::absolute(root / "amd_fidelityfx_loader_dx12.dll");- const auto providerPath = std::filesystem::absolute(root / "amd_fidelityfx_framegeneration_dx12.dll");-- p.requestedGenerated = 1; // FSR 3.1.x providers deliver one generated frame per present-- // The loader resolves provider DLLs by base name through the normal search- // order, so pre-loading the provider by absolute path and pointing the- // legacy DLL directory at the same folder keeps the discovery deterministic- // without leaking the directory into the rest of the process.- wchar_t previousDirectory[MAX_PATH]{};- const DWORD previousLength = GetDllDirectoryW(MAX_PATH, previousDirectory);- SetDllDirectoryW(root.c_str());- struct DirectoryGuard {- const wchar_t* previous = nullptr;- DWORD previousLength = 0;- wchar_t buffer[MAX_PATH]{};- ~DirectoryGuard() { SetDllDirectoryW(previousLength > 0 ? buffer : nullptr); }- } directoryGuard;- directoryGuard.previous = previousDirectory;- directoryGuard.previousLength = previousLength;- if (previousLength > 0 && previousLength < MAX_PATH) {- wcsncpy_s(directoryGuard.buffer, previousDirectory, previousLength);- }-- p.loader = LoadLibraryExW(loaderPath.c_str(), nullptr,- LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32);- if (p.loader == nullptr) {- log::error("fsr-fg", std::format("loader load failed path={} win32={}", loaderPath.string(), GetLastError()));- return false;- }- if (std::filesystem::exists(providerPath)) {- // Signed AMD provider; the loader is expected to pick this module up.- if (LoadLibraryExW(providerPath.c_str(), nullptr,- LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32) == nullptr) {- log::warn("fsr-fg", std::format("provider preload failed path={} win32={}", providerPath.string(), GetLastError()));- }+ if (!device || !width || !height || p.fgContext) return false;+ const auto root = std::filesystem::absolute(runtime::localDataDirectory() / "amd" / "fidelityfx");+ const auto loaderPath = root / "amd_fidelityfx_loader_dx12.dll";+ const auto providerPath = root / "amd_fidelityfx_framegeneration_dx12.dll";+ // Absolute preloading makes provider discovery deterministic. Modules stay+ // resident, as in the existing integration; contexts are independently freed.+ p.loader = loadResidentModule(loaderPath);+ const auto provider = loadResidentModule(providerPath);+ if (!p.loader || !provider) {+ log::error("fsr-fg", std::format("independent runtime load failed root={} win32={}", root.string(), GetLastError()));+ p.failed = true; return false;}ffxLoadFunctions(&p.functions, p.loader);- if (p.functions.CreateContext == nullptr || p.functions.DestroyContext == nullptr ||- p.functions.Configure == nullptr || p.functions.Query == nullptr || p.functions.Dispatch == nullptr) {- log::error("fsr-fg", "loader is missing the FidelityFX API entry points");- return false;- }-- // Report which provider version serves this adapter before creating it, so- // the log carries the same evidence as the standalone probe.- {- uint64_t count = 0;- ffxQueryDescGetVersions versions{};- versions.header.type = FFX_API_QUERY_DESC_TYPE_GET_VERSIONS;- versions.createDescType = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATION;- versions.device = device;- versions.outputCount = &count;- uint64_t ids[8]{};- const char* names[8]{};- uint64_t capacity = 8;- versions.versionIds = ids;- versions.versionNames = names;- versions.outputCount = &capacity;- const auto queryResult = p.functions.Query(nullptr, &versions.header);- if (queryResult == FFX_API_RETURN_OK && capacity > 0) {- p.providerVersion = names[0] != nullptr ? names[0] : "unknown";- }- log::info("fsr-fg", std::format("providers query={} count={} framegen={} swapchainVersion={}", returnName(queryResult),- capacity, p.providerVersion.empty() ? "none" : p.providerVersion,- FFX_FRAMEGENERATION_SWAPCHAIN_DX12_VERSION));- }-- ffxCreateContextDescFrameGenerationSwapChainVersionDX12 swapchainVersion{};- swapchainVersion.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_VERSION_DX12;- swapchainVersion.version = FFX_FRAMEGENERATION_SWAPCHAIN_DX12_VERSION;- IDXGISwapChain4* proxy = nullptr;- ffxCreateContextDescFrameGenerationSwapChainForHwndDX12 swapchainDesc{};- swapchainDesc.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_FOR_HWND_DX12;- swapchainDesc.header.pNext = &swapchainVersion.header;- swapchainDesc.swapchain = &proxy;- swapchainDesc.hwnd = window;- swapchainDesc.desc = &const_cast<DXGI_SWAP_CHAIN_DESC1&>(desc);- swapchainDesc.fullscreenDesc = nullptr;- swapchainDesc.dxgiFactory = factory;- swapchainDesc.gameQueue = queue;- const auto swapchainResult = p.functions.CreateContext(&p.swapchainContext, &swapchainDesc.header, nullptr);- if (swapchainResult != FFX_API_RETURN_OK || p.swapchainContext == nullptr || proxy == nullptr) {- log::error("fsr-fg", std::format("swapchain context failed result={} (0x{:X})", returnName(swapchainResult),- unsigned(swapchainResult)));- p.failed = true;- return false;- }- p.swapchain = proxy;- p.width = desc.Width;- p.height = desc.Height;- p.backBufferFormat = surfaceFormatFromDxgi(desc.Format);-- ffxCreateBackendDX12Desc backendDesc{};- backendDesc.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_DX12;- backendDesc.device = device;- ffxCreateContextDescFrameGenerationVersion fgVersion{};- fgVersion.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATION_VERSION;- fgVersion.version = FFX_FRAMEGENERATION_VERSION;- ffxCreateContextDescFrameGeneration fgDesc{};- fgDesc.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATION;- fgDesc.header.pNext = &backendDesc.header;- backendDesc.header.pNext = &fgVersion.header;- // Debug checking makes the provider report the exact reason a dispatch is- // rejected instead of a bare runtime error code.- fgDesc.flags = 0;- fgDesc.displaySize = {p.width, p.height};- // The provider validates the per-frame renderSize against maxRenderSize; the- // working extent can be larger than the window buffer (contain-scaled- // preview), so the ceiling covers both.- fgDesc.maxRenderSize = {std::max(p.width, renderWidth), std::max(p.height, renderHeight)};- fgDesc.backBufferFormat = p.backBufferFormat;- auto fgResult = p.functions.CreateContext(&p.fgContext, &fgDesc.header, nullptr);- if (fgResult != FFX_API_RETURN_OK || p.fgContext == nullptr) {- log::warn("fsr-fg", std::format("frame generation context with version desc failed result={}; retrying without it",- returnName(fgResult)));- backendDesc.header.pNext = nullptr;- fgResult = p.functions.CreateContext(&p.fgContext, &fgDesc.header, nullptr);- }- if (fgResult != FFX_API_RETURN_OK || p.fgContext == nullptr) {- log::error("fsr-fg", std::format("frame generation context failed result={} (0x{:X})", returnName(fgResult),- unsigned(fgResult)));- p.failed = true;- return false;- }+ if (!p.functions.CreateContext || !p.functions.DestroyContext || !p.functions.Query ||+ !p.functions.Configure || !p.functions.Dispatch) {+ log::error("fsr-fg", "required loader API missing"); p.failed = true; return false;+ }++ uint64_t count = 0;+ ffxQueryDescGetVersions versions{};+ versions.header.type = FFX_API_QUERY_DESC_TYPE_GET_VERSIONS;+ versions.createDescType = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATION;+ versions.device = device; versions.outputCount = &count;+ auto result = p.functions.Query(nullptr, &versions.header);+ if (result != FFX_API_RETURN_OK || count == 0 || count > 64) {+ log::error("fsr-fg", std::format("provider inventory result={} count={}", returnName(result), count));+ p.failed = true; return false;+ }+ std::vector<uint64_t> ids(size_t(count), 0);+ std::vector<const char*> names(size_t(count), nullptr);+ versions.versionIds = ids.data(); versions.versionNames = names.data();+ result = p.functions.Query(nullptr, &versions.header);+ if (result != FFX_API_RETURN_OK || count > ids.size()) {+ log::error("fsr-fg", std::format("provider inventory read result={} count={} capacity={}", returnName(result), count, ids.size()));+ p.failed = true; return false;+ }+ uint64_t selected = 0;+ const char* family = requireMl ? "4.0." : "3.1.";+ for (size_t i = 0; i < size_t(count); ++i) {+ const std::string_view name = names[i] ? names[i] : "unknown";+ log::info("fsr-fg", std::format("inventory id=0x{:X} name={} request={}", ids[i], name, family));+ if (!selected && name.find(family) != std::string_view::npos) selected = ids[i];+ }+ if (!selected) {+ log::error("fsr-fg", std::format("requested FSR {} provider unavailable on this adapter; no version fallback", family));+ p.failed = true; return false;+ }+ ffxOverrideVersion overrideVersion{};+ overrideVersion.header.type = FFX_API_DESC_TYPE_OVERRIDE_VERSION;+ overrideVersion.versionId = selected;+ ffxCreateContextDescFrameGenerationVersion apiVersion{};+ apiVersion.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATION_VERSION;+ apiVersion.version = FFX_FRAMEGENERATION_VERSION;+ apiVersion.header.pNext = &overrideVersion.header;+ ffxCreateBackendDX12Desc backend{};+ backend.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_DX12;+ backend.device = device; backend.header.pNext = &apiVersion.header;+ ffxCreateContextDescFrameGeneration desc{};+ desc.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATION;+ desc.header.pNext = &backend.header;+ desc.flags = FFX_FRAMEGENERATION_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS |+ ((format == DXGI_FORMAT_R16G16B16A16_FLOAT || format == DXGI_FORMAT_R10G10B10A2_UNORM)+ ? FFX_FRAMEGENERATION_ENABLE_HIGH_DYNAMIC_RANGE : 0);+ desc.displaySize = desc.maxRenderSize = {width, height};+ desc.backBufferFormat = surfaceFormatFromDxgi(format);+ result = p.functions.CreateContext(&p.fgContext, &desc.header, nullptr);+ if (result != FFX_API_RETURN_OK || !p.fgContext) {+ log::error("fsr-fg", std::format("independent CreateContext id=0x{:X} result={} code=0x{:X}", selected, returnName(result), unsigned(result)));+ p.failed = true; return false;+ }+ ffxQueryGetProviderVersion actual{};+ actual.header.type = FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION;+ result = p.functions.Query(&p.fgContext, &actual.header);+ p.providerVersion = actual.versionName ? actual.versionName : "unknown";+ if (result != FFX_API_RETURN_OK || actual.versionId != selected ||+ p.providerVersion.find(family) == std::string::npos) {+ log::error("fsr-fg", std::format("actual provider rejected query={} requested=0x{:X} actual=0x{:X} name={}", returnName(result), selected, actual.versionId, p.providerVersion));+ p.failed = true; return false;+ }+ p.width = width; p.height = height; p.backBufferFormat = desc.backBufferFormat;p.available = true;- p.deliveredGenerated = p.requestedGenerated;- {- ffxConfigureDescGlobalDebug1 global{};- global.header.type = FFX_API_CONFIGURE_DESC_TYPE_GLOBALDEBUG1;- global.fpMessage = fsrMessage;- global.debugLevel = FFX_API_CONFIGURE_GLOBALDEBUG_LEVEL_WARNINGS;- p.functions.Configure(nullptr, &global.header);- p.functions.Configure(&p.fgContext, &global.header);- if (p.swapchainContext != nullptr) p.functions.Configure(&p.swapchainContext, &global.header);- }- *swapchain = proxy;- log::info("fsr-fg", std::format("provider={} swapchain={}x{} maxRender={}x{} format={} multiplierRequested={}X (delivered multiplier is reported per frame)",- p.providerVersion.empty() ? "unknown" : p.providerVersion, p.width, p.height,- fgDesc.maxRenderSize.width, fgDesc.maxRenderSize.height,- int(desc.Format), p.requestedGenerated + 1));+ log::info("fsr-fg", std::format("independent context provider={} id=0x{:X} extent={}x{} format={} swapchainContexts=0 generatedPerPair=1 guidance=estimated-video virtualCamera=1",+ p.providerVersion, actual.versionId, width, height, int(format)));return true;#else- (void)device; (void)queue; (void)factory; (void)window; (void)desc; (void)swapchain; (void)fgMultiplier;- log::error("fsr-fg", "AMD FidelityFX SDK headers were unavailable at build time");- return false;+ (void)device; (void)width; (void)height; (void)format; (void)requireMl;+ log::error("fsr-fg", "FSR SDK headers unavailable"); return false;#endif}-bool FsrFgPresenter::tag(ID3D12GraphicsCommandList* list, ID3D12Resource* backBuffer, ID3D12Resource* motion,- ID3D12Resource* depth, RECT region, bool enabled, bool reset, float elapsedMs) {+bool FsrFgPresenter::generate(ID3D12GraphicsCommandList* list, ID3D12Resource* color,+ ID3D12Resource* motion, ID3D12Resource* depth, ID3D12Resource* output,+ bool reset, float elapsedMs) {#ifdef VEYRA_HAS_FSRauto& p = *p_;- if (!p.available) return false;- if (region.right <= region.left || region.bottom <= region.top) return false;-+ if (!p.available || p.failed || !list || !color || !motion || !depth || !output ||+ color == output) return false;+ const auto c = color->GetDesc(), m = motion->GetDesc(), d = depth->GetDesc(), o = output->GetDesc();+ if (c.Width != p.width || c.Height != p.height || o.Width != c.Width || o.Height != c.Height ||+ c.Format != o.Format || uint32_t(surfaceFormatFromDxgi(c.Format)) != p.backBufferFormat ||+ m.Width != c.Width || m.Height != c.Height || m.Format != DXGI_FORMAT_R16G16_FLOAT ||+ d.Width != c.Width || d.Height != c.Height || d.Format != DXGI_FORMAT_R32_FLOAT ||+ !(o.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return false;+ const auto check = [&](ffxReturnCode_t result, const char* stage) {+ if (result == FFX_API_RETURN_OK) return true;+ log::error("fsr-fg", std::format("independent {} result={} code=0x{:X} frameId={}", stage, returnName(result), unsigned(result), p.frameId));+ p.failed = true; return false;+ };ffxConfigureDescFrameGeneration configure{};configure.header.type = FFX_API_CONFIGURE_DESC_TYPE_FRAMEGENERATION;- configure.swapChain = p.swapchain;- configure.presentCallback = presentCallback;- configure.presentCallbackUserContext = &p;- configure.frameGenerationEnabled = enabled;- configure.allowAsyncWorkloads = false;- configure.flags = 0;- configure.generationRect = {region.left, region.top, region.right - region.left, region.bottom - region.top};- configure.frameID = p.frameId;-- if (!enabled) {- const auto result = p.functions.Configure(&p.fgContext, &configure.header);- if (result != FFX_API_RETURN_OK) {- log::warn("fsr-fg", std::format("configure(disabled) result={} frameId={}", returnName(result), p.frameId));- p.disableGeneration("configure(disabled) rejection");- }- return true;- }- if (list == nullptr || backBuffer == nullptr || motion == nullptr || depth == nullptr) return false;- if (p.softDisabled) return true;-- // The provider runs its own presentation/pacing threads; flushing their- // outstanding presentations before recording the next frame is what the- // swapchain contract expects from an application that is not otherwise- // synchronized to the display (the player submits as fast as it decodes).- {- ffxDispatchDescFrameGenerationSwapChainWaitForPresentsDX12 wait{};- wait.header.type = FFX_API_DISPATCH_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_WAIT_FOR_PRESENTS_DX12;- const auto waitResult = p.functions.Dispatch(&p.swapchainContext, &wait.header);- if (waitResult != FFX_API_RETURN_OK) {- log::warn("fsr-fg", std::format("wait-for-presents result={} frameId={}", returnName(waitResult), p.frameId));- }- }-+ configure.flags = FFX_FRAMEGENERATION_FLAG_NO_SWAPCHAIN_CONTEXT_NOTIFY;+ configure.frameGenerationEnabled = true; configure.frameID = p.frameId;+ configure.generationRect = {0, 0, int32_t(p.width), int32_t(p.height)};+ if (!check(p.functions.Configure(&p.fgContext, &configure.header), "Configure")) return false;ffxDispatchDescFrameGenerationPrepareV2 prepare{};prepare.header.type = FFX_API_DISPATCH_DESC_TYPE_FRAMEGENERATION_PREPARE_V2;- prepare.frameID = p.frameId;- prepare.flags = 0;- prepare.commandList = list;- prepare.renderSize = {uint32_t(motion->GetDesc().Width), motion->GetDesc().Height};- prepare.jitterOffset = {0.0f, 0.0f};- // Guidance motion is pixel space in working-extent units, so the scale that- // converts it to UV inside the provider is 1:1. FSR reprojects with- // "previous = current + motion", which already matches Veyra's- // current->previous guidance (DLSSG needs the opposite sign).- prepare.motionVectorScale = {1.0f, 1.0f};- prepare.frameTimeDelta = elapsedMs > 0.0f ? elapsedMs : 16.6f;- prepare.reset = reset;- prepare.cameraNear = 0.1f;- prepare.cameraFar = 1000.0f;- prepare.cameraFovAngleVertical = 1.0f;- prepare.viewSpaceToMetersFactor = 0.0f;- // The graph leaves both guidance textures in the common state after each- // frame, so the declared state must be the truthful one: a mismatched- // barrier would corrupt the queue instead of failing loudly.+ prepare.commandList = list; prepare.frameID = p.frameId;+ prepare.renderSize = {p.width, p.height}; prepare.motionVectorScale = {1, 1};+ prepare.frameTimeDelta = std::isfinite(elapsedMs) && elapsedMs > 0 ? elapsedMs : 16.6667f;+ prepare.reset = reset; prepare.cameraNear = 0.1f; prepare.cameraFar = 1000.0f;+ prepare.cameraFovAngleVertical = 1.0f; prepare.viewSpaceToMetersFactor = 1.0f;+ // Video has estimated depth/motion, no engine camera. Use a stable virtual+ // right-handed basis, not zero-length vectors, and label this limitation.+ prepare.cameraUp[1] = prepare.cameraRight[0] = prepare.cameraForward[2] = 1.0f;prepare.depth = makeResource(depth, FFX_API_RESOURCE_STATE_COMMON);prepare.motionVectors = makeResource(motion, FFX_API_RESOURCE_STATE_COMMON);- const auto prepareResult = p.functions.Dispatch(&p.fgContext, &prepare.header);- if (prepareResult != FFX_API_RETURN_OK) {- log::warn("fsr-fg", std::format("prepare dispatch result={} frameId={}", returnName(prepareResult), p.frameId));- p.disableGeneration("prepare dispatch rejection");- return true;- }-+ if (!check(p.functions.Dispatch(&p.fgContext, &prepare.header), "PrepareV2")) return false;ffxDispatchDescFrameGeneration dispatch{};dispatch.header.type = FFX_API_DISPATCH_DESC_TYPE_FRAMEGENERATION;- dispatch.commandList = nullptr;- dispatch.presentColor = makeResource(backBuffer, FFX_API_RESOURCE_STATE_COMMON);- dispatch.numGeneratedFrames = p.requestedGenerated;- dispatch.reset = reset;- dispatch.backbufferTransferFunction = FFX_API_BACKBUFFER_TRANSFER_FUNCTION_SRGB;- dispatch.minMaxLuminance[0] = 0.0f;- dispatch.minMaxLuminance[1] = 1000.0f;- dispatch.generationRect = configure.generationRect;- dispatch.frameID = p.frameId;-- const auto configureResult = p.functions.Configure(&p.fgContext, &configure.header);- if (configureResult != FFX_API_RETURN_OK) {- log::warn("fsr-fg", std::format("configure result={} frameId={}", returnName(configureResult), p.frameId));- p.disableGeneration("configure rejection");- return true;- }- // The swapchain only hands out an interpolation command list while its own- // generation flag is on, so the queries must follow the configure.- ffxQueryDescFrameGenerationSwapChainInterpolationCommandListDX12 queryList{};- queryList.header.type = FFX_API_QUERY_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_INTERPOLATIONCOMMANDLIST_DX12;- queryList.pOutCommandList = &dispatch.commandList;- auto queryResult = p.functions.Query(&p.swapchainContext, &queryList.header);- if (queryResult != FFX_API_RETURN_OK || dispatch.commandList == nullptr) {- log::warn("fsr-fg", std::format("interpolation command list query result={} list={}", returnName(queryResult),- dispatch.commandList));- p.disableGeneration("interpolation command list query rejection");- return true;- }- ffxQueryDescFrameGenerationSwapChainInterpolationTextureDX12 queryTexture{};- queryTexture.header.type = FFX_API_QUERY_DESC_TYPE_FRAMEGENERATIONSWAPCHAIN_INTERPOLATIONTEXTURE_DX12;- queryTexture.pOutTexture = &dispatch.outputs[0];- queryResult = p.functions.Query(&p.swapchainContext, &queryTexture.header);- if (queryResult != FFX_API_RETURN_OK) {- log::warn("fsr-fg", std::format("interpolation texture query result={}", returnName(queryResult)));- p.disableGeneration("interpolation texture query rejection");- return true;- }-- if (p.frameId <= 2 || log::verboseFrameLogs()) {- const auto backBufferDesc = backBuffer->GetDesc();- const auto motionDesc = motion->GetDesc();- const auto depthDesc = depth->GetDesc();- const auto outputDesc = dispatch.outputs[0].resource != nullptr- ? static_cast<ID3D12Resource*>(dispatch.outputs[0].resource)->GetDesc()- : D3D12_RESOURCE_DESC{};- log::info("fsr-fg", std::format(- "trace frameId={} reset={} render={}x{} rect={}+{} {}x{} numGenerated={} present={}x{} fmt={} motion={}x{} fmt={} depth={}x{} fmt={} output={}x{} fmt={}",- p.frameId, reset, prepare.renderSize.width, prepare.renderSize.height, configure.generationRect.left,- configure.generationRect.top, configure.generationRect.width, configure.generationRect.height,- dispatch.numGeneratedFrames, uint32_t(backBufferDesc.Width), backBufferDesc.Height,- int(backBufferDesc.Format), uint32_t(motionDesc.Width), motionDesc.Height, int(motionDesc.Format),- uint32_t(depthDesc.Width), depthDesc.Height, int(depthDesc.Format), uint32_t(outputDesc.Width),- outputDesc.Height, int(outputDesc.Format)));- }- const auto dispatchResult = p.functions.Dispatch(&p.fgContext, &dispatch.header);- if (dispatchResult != FFX_API_RETURN_OK) {- log::warn("fsr-fg", std::format("frame generation dispatch result={} frameId={}", returnName(dispatchResult), p.frameId));- p.disableGeneration("frame generation dispatch rejection");- return true;- }- if (log::verboseFrameLogs()) {- log::info("fsr-fg", std::format("frameId={} region={}x{}+{}+{} generatedPerFrame={}", p.frameId,- configure.generationRect.width, configure.generationRect.height,- configure.generationRect.left, configure.generationRect.top,- p.requestedGenerated));- }+ dispatch.commandList = list; dispatch.frameID = p.frameId; dispatch.reset = reset;+ dispatch.presentColor = makeResource(color, FFX_API_RESOURCE_STATE_COMMON);+ dispatch.outputs[0] = makeResource(output, FFX_API_RESOURCE_STATE_COMMON);+ dispatch.numGeneratedFrames = 1; dispatch.generationRect = configure.generationRect;+ dispatch.backbufferTransferFunction = c.Format == DXGI_FORMAT_R16G16B16A16_FLOAT+ ? FFX_API_BACKBUFFER_TRANSFER_FUNCTION_SCRGB : c.Format == DXGI_FORMAT_R10G10B10A2_UNORM+ ? FFX_API_BACKBUFFER_TRANSFER_FUNCTION_PQ : FFX_API_BACKBUFFER_TRANSFER_FUNCTION_SRGB;+ dispatch.minMaxLuminance[0] = 0; dispatch.minMaxLuminance[1] = 1000;+ if (!check(p.functions.Dispatch(&p.fgContext, &dispatch.header), "Generate")) return false;+ if (p.frameId < 3 || log::verboseFrameLogs())+ log::info("fsr-fg", std::format("independent dispatch frameId={} reset={} elapsedMs={} outputs=1 transfer={} extent={}x{}",+ p.frameId, reset, prepare.frameTimeDelta, dispatch.backbufferTransferFunction, p.width, p.height));+ ++p.frameId;return true;#else- (void)list; (void)backBuffer; (void)motion; (void)depth; (void)region; (void)enabled; (void)reset; (void)elapsedMs;+ (void)list; (void)color; (void)motion; (void)depth; (void)output; (void)reset; (void)elapsedMs;return false;#endif}-void FsrFgPresenter::afterPresent() {- // Frame ids must advance by exactly one per presented frame; a gap makes the- // provider reset its interpolation history.+void FsrFgPresenter::shutdown() {+#ifdef VEYRA_HAS_FSRauto& p = *p_;- ++p.frameId;- // The provider reports on its own thread; a periodic sample is the only- // honest way to show whether interpolation reached the display path.- if (log::verboseFrameLogs() || p.frameId % 120 == 0) {- log::info("fsr-fg", std::format("frameId={} real={} generated={} presented={} callbackFailures={}",- p.frameId, p.realFrames.load(), p.generatedFrames.load(),- p.realFrames.load() + p.generatedFrames.load(), p.callbackFailures.load()));+ // The graph owner drains its queue and all texture consumers first.+ // No swapchain context or provider present thread exists on this path.+ if (p.fgContext) {+ const auto result = p.functions.DestroyContext(&p.fgContext, nullptr);+ log::info("fsr-fg", std::format("independent context destroyed result={}", returnName(result)));+ p.fgContext = nullptr;}+ p.available = false;+#endif}--uint64_t FsrFgPresenter::generatedCount() const { return p_->generatedFrames.load(); }-uint64_t FsrFgPresenter::presentedCount() const { return p_->realFrames.load() + p_->generatedFrames.load(); }-uint32_t FsrFgPresenter::maxGeneratedFrames() const { return p_->available ? p_->deliveredGenerated : 0; }+FsrFgPresenter::~FsrFgPresenter() { shutdown(); }+uint32_t FsrFgPresenter::maxGeneratedFrames() const { return p_->available ? 1u : 0u; }bool FsrFgPresenter::available() const { return p_->available; }bool FsrFgPresenter::failed() const { return p_->failed; }const char* FsrFgPresenter::providerVersion() const { return p_->providerVersion.c_str(); }--IDXGISwapChain4* FsrFgPresenter::swapchainHandle() const {-#ifdef VEYRA_HAS_FSR- return p_->swapchain;-#else- return nullptr;-#endif-}--void FsrFgPresenter::disableGeneration() {-#ifdef VEYRA_HAS_FSR- auto& p = *p_;- if (!p.available || p.softDisabled || p.fgContext == nullptr || p.swapchain == nullptr) return;- ffxConfigureDescFrameGeneration configure{};- configure.header.type = FFX_API_CONFIGURE_DESC_TYPE_FRAMEGENERATION;- configure.swapChain = p.swapchain;- configure.frameGenerationEnabled = false;- configure.presentCallback = presentCallback;- configure.presentCallbackUserContext = &p;- configure.generationRect = {0, 0, int32_t(p.width), int32_t(p.height)};- configure.frameID = p.frameId;- const auto result = p.functions.Configure(&p.fgContext, &configure.header);- if (result != FFX_API_RETURN_OK) {- log::warn("fsr-fg", std::format("disableGeneration result={} frameId={}", returnName(result), p.frameId));- return;- }- log::info("fsr-fg", "generation disabled; the AMD proxy keeps presenting real frames");-#endif-}-} // namespace veyra::gfxdiff --git a/src/gfx/PresentSink.cpp b/src/gfx/PresentSink.cppindex a5715634..126fb228 100644--- a/src/gfx/PresentSink.cpp+++ b/src/gfx/PresentSink.cpp@@ -179,59 +179,11 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,// external capture API. Neither mode changes the pixel format.scd.SwapEffect = desc.captureCompatible ? DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL : DXGI_SWAP_EFFECT_FLIP_DISCARD;scd.Flags = tearingSupported_ ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0;- if(desc.waitable&&!desc.xess&&!desc.fsr)scd.Flags|=DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;+ if(desc.waitable&&!desc.xess)scd.Flags|=DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;ComPtr<IDXGISwapChain1> swapChain1;- // Backend switch bookkeeping. A retained AMD proxy and a live XeSS wrapper- // each hold the window's single flip-model swapchain; the DXGI swapchain- // only dies once every reference (including the provider's) is gone, and- // a second CreateSwapChainForHwnd for the same window fails while it- // lives. Tear down whichever backend this session leaves before the next- // one initializes, and never pass a non-empty ComPtr::GetAddressOf() to- // an initializer (that overwrites without releasing and leaks the old- // reference, keeping the slot occupied for the process lifetime).- if(fsr_&&!desc.fsr&&desc.xess){- // Deliberately keep the proxy alive. Verified on this machine: once- // the FidelityFX proxy has wrapped the window, destroying it (even in- // the documented order, with a drained queue and the final COM- // reference released) leaves the window unable to host ANY later- // swapchain - XeSS's create and native create both fail, and the- // provider cannot recreate its own proxy either (ERROR_RUNTIME_ERROR).- // Retaining the proxy keeps the session playable; generation is- // switched off while the proxy presents plain frames.- fsr_->disableGeneration();- }- if(xess_&&!desc.xess){- log::info("present","releasing the XeSS swapchain");- waitForQueueIdle();- xess_.reset();- for(auto& b:backBuffers_)b.Reset();- swapChain_.Reset();- }- if(desc.fsr&&!fsr_){- fsr_=std::make_unique<FsrFgPresenter>();- IDXGISwapChain4* proxy=nullptr;- const uint32_t renderW=desc.renderWidth?desc.renderWidth:scd.Width;- const uint32_t renderH=desc.renderHeight?desc.renderHeight:scd.Height;- if(!fsr_->initialize(device,queue,factory_.Get(),hwnd_,scd,renderW,renderH,&proxy,desc.fgMultiplier)){- // Like XeSS: a missing or incompatible local runtime must never- // prevent basic playback.- log::warn("present", "AMD FSR frame generation unavailable; falling back to native presentation");- fsr_.reset();- }- }- if(fsr_){- if(!desc.fsr)fsr_->disableGeneration();- IDXGISwapChain4* proxy=fsr_->swapchainHandle();- ComPtr<IDXGISwapChain3> proxied;- if(proxy==nullptr||FAILED(proxy->QueryInterface(IID_PPV_ARGS(&proxied)))){- log::error("present", "retained FSR proxy swapchain is no longer usable");- status = Status::WindowFailure;- return false;- }- swapChain_=proxied;- log::info("present", std::format("using the retained AMD proxy swapchain (frame generation {})", desc.fsr?"on":"off"));- }+ // XeSS is the only provider that owns a swapchain. FSR is now a graph+ // effect producing application-owned textures, so it never retains an HWND.if(desc.xess){// The XeSS initializer writes through the pointer: release any// existing reference first so the previous swapchain (native or a@@ -250,21 +202,28 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,// XeSS is an optional experimental presenter. A missing or// incompatible local runtime must not prevent basic playback.log::warn("present", "XeSS FG initialization failed; falling back to native presentation");- // Keep a retained AMD proxy when one exists: the provider keeps- // the HWND's DXGI swapchain alive for the process lifetime, so a- // fresh CreateSwapChainForHwnd for the same window is known to- // fail and the proxy still presents plain frames.- if(!fsr_)swapChain_.Reset();+ swapChain_.Reset();xess_.reset();}}if (!swapChain_) {- HRESULT created=factory_->CreateSwapChainForHwnd(queue, hwnd_, &scd, nullptr, nullptr, &swapChain1);- if(FAILED(created)&&(scd.Flags&DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT)){+ const auto createNative=[&](){+ HRESULT result=E_FAIL;+ for(unsigned attempt=0;attempt<3;++attempt){+ swapChain1.Reset();+ result=factory_->CreateSwapChainForHwnd(queue,hwnd_,&scd,nullptr,nullptr,&swapChain1);+ if(result!=E_ACCESSDENIED||!IsWindow(hwnd_)||attempt==2)break;+ log::warn("present",std::format("swapchain transient access denied attempt={}; bounded owner-thread retry",attempt+1));+ Sleep(50);+ }+ return result;+ };+ HRESULT created=createNative();+ if(FAILED(created)&&created!=E_ACCESSDENIED&&(scd.Flags&DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT)){log::warn("pacing",std::format("waitable swapchain unavailable hr=0x{:X}; retrying baseline",unsigned(created)));scd.Flags&=~DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;swapChain1.Reset();- created=factory_->CreateSwapChainForHwnd(queue,hwnd_,&scd,nullptr,nullptr,&swapChain1);+ created=createNative();}if (FAILED(created)) {log::error("present",std::format("CreateSwapChainForHwnd failed hr=0x{:X}",unsigned(created)));@@ -307,14 +266,14 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,swapChainFlags_=actual.Flags;if(actual.Flags&DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT){latencyHandle_=swapChain_->GetFrameLatencyWaitableObject();- if(!configurePacing(false,desc.vsync))log::warn("pacing","baseline latency configuration failed; playback remains available");+ if(!configurePacing(false,desc.vsync,desc.tearing))log::warn("pacing","baseline latency configuration failed; playback remains available");}tearingSupported_=tearingSupported_&&(actual.Flags&DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING)!=0;displayRefreshHz_=displayRefreshFps(hwnd_);frameStatisticsBaseValid_=false;log::info("display-refresh",std::format("monitor refresh={:.3f} Hz at swapchain creation (0 = unknown); submissions above this rate cannot all be scanned out",displayRefreshHz_));log::info("present", std::format("present-sink: window {}x{} swapEffect={} buffers=3 vsync={} tearing={} captureCompatible={} (capture not verified)",- width_, height_, actual.SwapEffect==DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL?"flip-sequential":"flip-discard", desc_.vsync ? 1 : 0, tearingSupported_ ? 1 : 0, desc.captureCompatible));+ width_, height_, actual.SwapEffect==DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL?"flip-sequential":"flip-discard", desc_.vsync ? 1 : 0, (desc_.tearing && tearingSupported_) ? 1 : 0, desc.captureCompatible));return true;}@@ -373,9 +332,8 @@ bool PresentSink::present(Status& status)presentTiming_={};capacityAcquired_=false;xessFailed_=false;- fsrFailed_=false;const UINT syncInterval = desc_.vsync ? 1 : 0;- const UINT flags = (!desc_.vsync && tearingSupported_) ? DXGI_PRESENT_ALLOW_TEARING : 0;+ const UINT flags = (desc_.tearing && !desc_.vsync && tearingSupported_) ? DXGI_PRESENT_ALLOW_TEARING : 0;++attemptedPresentCount_;const bool beforeOk=!xess_||xess_->beforePresent();presentTiming_.beforeMs=split();@@ -383,13 +341,12 @@ bool PresentSink::present(Status& status)const HRESULT hr = swapChain_->Present(syncInterval, flags);presentTiming_.callMs=split();presentTiming_.result=hr;if(attemptedPresentCount_<=3||attemptedPresentCount_%120==0)- log::info("present-contract",std::format("backend={} sync={} flags=0x{:X} hr=0x{:X}",xess_?"XeSS":fsr_?"FSR":"DXGI",syncInterval,flags,unsigned(hr)));+ log::info("present-contract",std::format("backend={} sync={} flags=0x{:X} hr=0x{:X}",xess_?"XeSS":"DXGI",syncInterval,flags,unsigned(hr)));if (SUCCEEDED(hr)) {++presentCount_;backBufferIndex_ = swapChain_->GetCurrentBackBufferIndex();presentTiming_.bufferMs=split();const bool afterOk=!xess_||xess_->afterPresent();- if(fsr_)fsr_->afterPresent();presentTiming_.afterMs=split();if(!afterOk){xessFailed_=true;status=Status::WindowFailure;return false;}return true;@@ -464,20 +421,20 @@ PresentSink::FrameStatisticsDelta PresentSink::sampleFrameStatistics(){return delta;}-bool PresentSink::configurePacing(bool enabled,bool vsync){+bool PresentSink::configurePacing(bool enabled,bool vsync,bool tearing){// XeSS owns pacing, but its proxy accepts DXGI VSync independently.// Do not install another latency waiter on the provider swap chain.- if(xess_||fsr_){pacing_=false;capacityAcquired_=false;desc_.vsync=xess_&&vsync;log::info("pacing",std::format("provider={} applicationWait=0 vsync={}",xess_?"XeSS":"FSR",desc_.vsync));return !enabled;}+ if(xess_){pacing_=false;capacityAcquired_=false;desc_.vsync=xess_&&vsync;desc_.tearing=tearing;log::info("pacing",std::format("provider={} applicationWait=0 vsync={} tearing={}","XeSS",desc_.vsync,desc_.tearing));return !enabled;}const HRESULT hr=latencyHandle_?swapChain_->SetMaximumFrameLatency(enabled?1:3):enabled?E_NOTIMPL:S_OK;- log::info("pacing",std::format("DXGI enabled={} maximumLatency={} vsync={} hr=0x{:X}",enabled,enabled?1:3,vsync,unsigned(hr)));- pacing_=enabled&&SUCCEEDED(hr);desc_.vsync=vsync;capacityAcquired_=false;+ log::info("pacing",std::format("DXGI enabled={} maximumLatency={} vsync={} tearing={} hr=0x{:X}",enabled,enabled?1:3,vsync,tearing,unsigned(hr)));+ pacing_=enabled&&SUCCEEDED(hr);desc_.vsync=vsync;desc_.tearing=tearing;capacityAcquired_=false;return SUCCEEDED(hr);}bool PresentSink::presentationReady(){if(!pacing_||!latencyHandle_||capacityAcquired_)return true;const auto result=WaitForSingleObject(latencyHandle_,0);if(result==WAIT_OBJECT_0)capacityAcquired_=true;- if(result==WAIT_FAILED){log::warn("pacing",std::format("DXGI capacity wait failed error={}",GetLastError()));configurePacing(false,false);return true;}+ if(result==WAIT_FAILED){log::warn("pacing",std::format("DXGI capacity wait failed error={}",GetLastError()));configurePacing(false,desc_.vsync,desc_.tearing);return true;}return capacityAcquired_;}@@ -561,15 +518,6 @@ void PresentSink::shutdown()}swapChain_.Reset();xess_.reset();- // The AMD proxy context is deliberately NOT destroyed here. Verified on- // this machine: once the FidelityFX proxy wrapped the window, destroying- // it (documented order, drained queue, final COM reference released)- // leaves the window unable to host any later swapchain - XeSS and native- // creation both fail and the provider cannot recreate its own proxy- // (ERROR_RUNTIME_ERROR). Retaining the proxy keeps FSR sessions playable- // across settings changes; it is torn down at process/engine teardown,- // where the provider's own destructor crash was fixed by flushing its- // presentation queue and clearing the destroyed context pointers.log::info("present", "sink-shutdown: sub-step window-destroy-last");if (hwnd_ != nullptr && !desc_.targetWindow) {DestroyWindow(hwnd_);diff --git a/src/gfx/XessMfgUnlock.cpp b/src/gfx/XessMfgUnlock.cppindex 7b3653c6..d7740abf 100644--- a/src/gfx/XessMfgUnlock.cpp+++ b/src/gfx/XessMfgUnlock.cpp@@ -194,8 +194,9 @@ XessMfgUnlock::State XessMfgUnlock::apply(HMODULE provider, uint32_t generatedFr}uint8_t* destination = base + patch.rva;if (memcmp(destination, patch.expected, patch.size) != 0) {+ const auto actualBytes = toHex(destination, patch.size);state.detail = std::format(L"{} has unexpected bytes ({})", std::wstring(patch.name, patch.name + strlen(patch.name)),- std::wstring(toHex(destination, patch.size).begin(), toHex(destination, patch.size).end()));+ std::wstring(actualBytes.begin(), actualBytes.end()));veyra::log::error("xess-mfg", std::format("unlock aborted: {} at 0x{:X} expected [{}] found [{}]", patch.name, patch.rva,toHex(patch.expected, patch.size), toHex(destination, patch.size)));g_state = state;diff --git a/src/gfx/XessPresenter.cpp b/src/gfx/XessPresenter.cppindex 6b9813c3..0fd80294 100644--- a/src/gfx/XessPresenter.cpp+++ b/src/gfx/XessPresenter.cpp@@ -139,6 +139,7 @@ bool XessPresenter::initialize(ID3D12Device* device,ID3D12CommandQueue* queue,IDp.maxInterpolations=unlock.maxInterpolations;veyra::log::info("xess-mfg",std::format("unlock requestedGenerated={} applied={} identityVerified={} recognisedBuild={}",p.requestedGenerated,unlock.applied,unlock.identityVerified,unlock.recognisedBuild));+ log::info("xess-mfg",std::format("unlock detail={}",narrowDetail(unlock.detail)));if(!unlock.applied){log::error("xess-mfg",std::format("unlock unavailable for {}X request; keeping stock presentation",p.requestedGenerated+1));return false;@@ -174,11 +175,9 @@ bool XessPresenter::initialize(ID3D12Device* device,ID3D12CommandQueue* queue,ID}xefg_swapchain_d3d12_init_params_t init{};init.maxInterpolatedFrames=p.requestedGenerated>0?p.requestedGenerated:1;init.uiMode=XEFG_SWAPCHAIN_UI_MODE_AUTO;xefg_swapchain_properties_t properties{};- // If the present sink already owns a window swapchain (the retained AMD- // proxy after an FSR session), wrap it instead of creating a second one.- // DXGI refuses a second flip-model swapchain on an occupied HWND, which is- // exactly why switching FSR -> XeSS used to fail with Init=-17. The- // wrapper becomes the swapchain the sink presents through.+ // The API can wrap a caller-owned native swapchain if one is supplied.+ // Veyra's sink supplies an empty pointer after releasing the old backend;+ // independent FSR dispatch never creates or retains an HWND swapchain.DXGI_SWAP_CHAIN_DESC1 existingDesc{};IDXGISwapChain3* existing=swapchain!=nullptr?*swapchain:nullptr;const bool wrapExisting=existing!=nullptr&&SUCCEEDED(existing->GetDesc1(&existingDesc));diff --git a/src/ngx/DlssNrRuntimeAdapter.cpp b/src/ngx/DlssNrRuntimeAdapter.cppindex 13a04fec..ee7efea7 100644--- a/src/ngx/DlssNrRuntimeAdapter.cpp+++ b/src/ngx/DlssNrRuntimeAdapter.cpp@@ -550,6 +550,22 @@ void DlssNrRuntimeAdapter::restoreCallerCompatibility()bool DlssNrRuntimeAdapter::installAmpereCompatibility(ID3D12Device* device, Status& status){if(!module_||!shimInstalled_||!device||archLookupSlot_||g_ampere.nvapi){status=Status::InvalidArgument;return false;}+ // Read the loaded runtime's fixed version from its own resource (no version.lib).+ uint32_t versionMs=0,versionLs=0;+ if(HRSRC info=FindResourceW(module_,MAKEINTRESOURCEW(1),MAKEINTRESOURCEW(16))){+ const auto size=SizeofResource(module_,info);+ const auto* bytes=static_cast<const uint8_t*>(LockResource(LoadResource(module_,info)));+ for(DWORD at=0;bytes&&at+52<=size;at+=4){+ uint32_t signature=0;std::memcpy(&signature,bytes+at,4);+ if(signature!=0xFEEF04BDu)continue;+ std::memcpy(&versionMs,bytes+at+8,4);std::memcpy(&versionLs,bytes+at+12,4);break;+ }+ }+ veyra::log::info("nr-ampere",std::format("runtime version {}.{}.{}.{}",versionMs>>16,versionMs&0xFFFFu,versionLs>>16,versionLs&0xFFFFu));+ if(versionMs&&!nrRuntimeNeedsAmpereRewrite(versionMs,versionLs)){+ veyra::log::info("nr-ampere","runtime selects its own RTX30 route; architecture rewrite not installed");+ return true;+ }auto fail=[&](const char* reason){veyra::log::error("nr-ampere",reason);ClearAmpereContext();status=Status::DeviceFailure;return false;};wchar_t system[MAX_PATH]{};if(!GetSystemDirectoryW(system,MAX_PATH))return fail("system directory lookup failed");diff --git a/src/ngx/DlssgTransfusion.cpp b/src/ngx/DlssgTransfusion.cppnew file mode 100644index 00000000..8750d95d--- /dev/null+++ b/src/ngx/DlssgTransfusion.cpp@@ -0,0 +1,1598 @@+// DLSS-G 310.9.1 provider patches for RTX 40 / RTX 30. Ported from+// SilyNoMeta/DLSSG-Transfusion (MIT), tag v1.4.5.3-rtx20-30-40, commit+// b56bd2deed114507ad2c88f986d90ed50ffb4639, itself a fork of+// TonyJoaca/DLSSG-Transfusion (MIT, Copyright (c) 2026 Michael Robles).+// Function names follow upstream so each part can be traced back:+// patcher.cpp SafeScanDlssgArchSites/PatchDlssgArchGates,+// SafeFindUniqueImmediate/PatchDlssgMinimumArchitecture,+// kNgxPatch + PatchUniqueExecutablePattern+// midpoint_fix.cpp Lz4BlockDecompress, Find*PtxEntry, BuildTemporalFatbin,+// BuildBlackwellTransfusionFatbin, RetargetContainers,+// PatchProvider, PrepareModuleImage+// image_kernels.h SourceHash, VectorizeBlendStores+// cu_module_hook.h Replacement, Hook+// network_optimizer.h rules, CreateVariants, HookFunction, HookLaunch+// Veyra changes (see DlssgTransfusion.h): recorded writes with verified+// rollback, NvAPI through the provider's GetProcAddress import slot, kernels+// from runtime files, logging through veyra::log, Turing/Vulkan/Streamline/HUD+// and the scatter/input-motion experiments removed.+#include "veyra/ngx/DlssgTransfusion.h"++#include "veyra/FileIdentity.h"+#include "veyra/Log.h"+#include "compat/RestoreMemory.h"+#include "transfusion/quality_fix.h"++#include <algorithm>+#include <array>+#include <atomic>+#include <cstdio>+#include <cstring>+#include <filesystem>+#include <format>+#include <fstream>+#include <map>+#include <memory>+#include <mutex>+#include <string>+#include <string_view>+#include <unordered_map>+#include <vector>++namespace veyra::ngx {+namespace {++constexpr const char* kTag = "dlssg-tf";++// ---------------------------------------------------------------------------+// Shared state+// ---------------------------------------------------------------------------+struct Write {+ uint8_t* address = nullptr;+ std::vector<uint8_t> original;+};++using GetProcAddressFn = FARPROC(WINAPI*)(HMODULE, LPCSTR);+using QueryInterfaceFn = void*(__cdecl*)(uint32_t);+using CreateModuleFn = int(__cdecl*)(void* device, const void* blob, uint32_t size, void** module);+using CreateFunctionFn = int(__cdecl*)(void* device, void* module, const char* name, void** function);+using LaunchFn = int(__cdecl*)(void* commandList, const void* entries, uint32_t count);++struct Global {+ std::recursive_mutex mutex;+ HMODULE module = nullptr;+ std::vector<Write> writes;+ std::vector<void*> allocations; // rebuilt fatbins referenced by redirected descriptors+ DlssgTransfusion::State state;+ DlssgTransfusion::Options options;+ std::atomic<bool> active{false}; // hooks pass through when false+ std::atomic<uint32_t> targetSm{89};+ // Kernel payloads (runtime files), set before `active` and not modified while it is.+ std::unordered_map<uint16_t, std::string> networkPtx;+ std::string outputPull, outputPushFine;+ bool imageReplacements = false;+ // NvAPI originals: driver functions, valid for the process lifetime. Never+ // cleared because the provider may cache our wrappers.+ std::atomic<GetProcAddressFn> realGetProc{nullptr};+ std::atomic<QueryInterfaceFn> realQuery{nullptr};+ std::atomic<CreateModuleFn> createModule{nullptr};+ std::atomic<CreateFunctionFn> createFunction{nullptr};+ std::atomic<LaunchFn> launch{nullptr};+ std::atomic<uint32_t> resolutions{0}, accepted{0}, rejected{0}, rewritten{0};+ std::atomic<bool> exactProviderKernels{false};+ bool importHooked = false;+};++Global& global() {+ static Global value;+ return value;+}++bool env(const wchar_t* name) { return GetEnvironmentVariableW(name, nullptr, 0) > 0; }+// UTF-8 conversion for log messages (paths and detail strings may hold+// non-ASCII characters; narrowing them directly would lose them).+std::string utf8(const std::wstring& text) {+ if (text.empty()) return {};+ const int size = WideCharToMultiByte(CP_UTF8, 0, text.c_str(), static_cast<int>(text.size()), nullptr, 0, nullptr, nullptr);+ if (size <= 0) return {};+ std::string out(static_cast<size_t>(size), char{0});+ WideCharToMultiByte(CP_UTF8, 0, text.c_str(), static_cast<int>(text.size()), out.data(), size, nullptr, nullptr);+ return out;+}++std::string utf8(const std::filesystem::path& path) {+ const auto text = path.u8string();+ return std::string(reinterpret_cast<const char*>(text.data()), text.size());+}++// Records the original bytes, then writes through a temporary protection+// change. Every write is restored in reverse order by release().+bool patchBytes(void* destination, const void* source, size_t bytes) {+ auto& g = global();+ auto* p = static_cast<uint8_t*>(destination);+ MEMORY_BASIC_INFORMATION info{};+ if (!VirtualQuery(p, &info, sizeof(info)) || info.State != MEM_COMMIT) return false;+ constexpr DWORD kExecute = PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;+ const bool executable = (info.Protect & kExecute) != 0;+ DWORD old = 0;+ if (!VirtualProtect(p, bytes, executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE, &old)) return false;+ g.writes.push_back({p, std::vector<uint8_t>(p, p + bytes)});+ std::memcpy(p, source, bytes);+ if (executable) FlushInstructionCache(GetCurrentProcess(), p, bytes);+ DWORD ignored = 0;+ if (!VirtualProtect(p, bytes, old, &ignored)) {+ compat::memoryProtectionUncertain = true;+ log::error(kTag, std::format("protection restore failed address=0x{:X} win32={}", uintptr_t(p), GetLastError()));+ return false;+ }+ return true;+}++// ---------------------------------------------------------------------------+// PE helpers+// ---------------------------------------------------------------------------+const IMAGE_NT_HEADERS64* imageHeaders(HMODULE module) {+ if (!module) return nullptr;+ __try {+ const auto* base = reinterpret_cast<const uint8_t*>(module);+ const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(base);+ if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew <= 0 || dos->e_lfanew > 1024 * 1024) return nullptr;+ const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(base + dos->e_lfanew);+ if (nt->Signature != IMAGE_NT_SIGNATURE || nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) return nullptr;+ return nt;+ } __except (EXCEPTION_EXECUTE_HANDLER) {+ return nullptr;+ }+}++size_t sectionSpan(const IMAGE_NT_HEADERS64* nt, const IMAGE_SECTION_HEADER& section) {+ if (section.VirtualAddress >= nt->OptionalHeader.SizeOfImage) return 0;+ return std::min<size_t>(nt->OptionalHeader.SizeOfImage - section.VirtualAddress, section.Misc.VirtualSize);+}++// Import slot of `function` in the provider's own IAT.+void** findImportSlot(HMODULE module, const char* function) {+ const auto* nt = imageHeaders(module);+ if (!nt) return nullptr;+ auto* base = reinterpret_cast<uint8_t*>(module);+ const auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];+ if (!dir.VirtualAddress) return nullptr;+ void** found = nullptr;+ for (auto* d = reinterpret_cast<IMAGE_IMPORT_DESCRIPTOR*>(base + dir.VirtualAddress); d->Name; ++d) {+ if (!d->OriginalFirstThunk || !d->FirstThunk) continue;+ auto* names = reinterpret_cast<IMAGE_THUNK_DATA64*>(base + d->OriginalFirstThunk);+ auto* slots = reinterpret_cast<IMAGE_THUNK_DATA64*>(base + d->FirstThunk);+ for (; names->u1.AddressOfData; ++names, ++slots) {+ if (IMAGE_SNAP_BY_ORDINAL64(names->u1.Ordinal)) continue;+ const auto* byName = reinterpret_cast<IMAGE_IMPORT_BY_NAME*>(base + names->u1.AddressOfData);+ if (std::strcmp(reinterpret_cast<const char*>(byName->Name), function) != 0) continue;+ if (found) return nullptr; // ambiguous: never guess+ found = reinterpret_cast<void**>(&slots->u1.Function);+ }+ }+ return found;+}++// ---------------------------------------------------------------------------+// Code patches (patcher.cpp)+// ---------------------------------------------------------------------------+bool SafeScanDlssgArchSites(const uint8_t* base, const IMAGE_NT_HEADERS64* nt, uint8_t archNew,+ uint8_t** outSites, size_t maxSites, size_t* outFound, size_t* outAlreadyPatched) {+ __try {+ constexpr uint8_t kArchOld = 0xB0;+ const IMAGE_SECTION_HEADER* section = IMAGE_FIRST_SECTION(nt);+ for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++section) {+ if ((section->Characteristics & IMAGE_SCN_MEM_EXECUTE) == 0) continue;+ const uint8_t* start = base + section->VirtualAddress;+ const size_t size = sectionSpan(nt, *section);+ if (size < 7) continue;+ for (size_t off = 0; off + 7 <= size; ++off) {+ if (start[off] == 0x3D && start[off + 2] == 0x01 && start[off + 3] == 0x00 && start[off + 4] == 0x00) {+ if (start[off + 1] == kArchOld && *outFound < maxSites) outSites[(*outFound)++] = const_cast<uint8_t*>(start + off + 1);+ else if (start[off + 1] == archNew) ++(*outAlreadyPatched);+ continue;+ }+ if (start[off] == 0x81 && start[off + 1] >= 0xF8 && start[off + 3] == 0x01 && start[off + 4] == 0x00 && start[off + 5] == 0x00) {+ if (start[off + 2] == kArchOld && *outFound < maxSites) outSites[(*outFound)++] = const_cast<uint8_t*>(start + off + 2);+ else if (start[off + 2] == archNew) ++(*outAlreadyPatched);+ continue;+ }+ if ((start[off] >= 0x40 && start[off] <= 0x4F) && start[off + 1] == 0x81 && start[off + 2] >= 0xF8 &&+ start[off + 4] == 0x01 && start[off + 5] == 0x00 && start[off + 6] == 0x00) {+ if (start[off + 3] == kArchOld && *outFound < maxSites) outSites[(*outFound)++] = const_cast<uint8_t*>(start + off + 3);+ else if (start[off + 3] == archNew) ++(*outAlreadyPatched);+ }+ }+ }+ return true;+ } __except (EXCEPTION_EXECUTE_HANDLER) {+ return false;+ }+}++// Blackwell-only gates (0x1b0) are lowered to the architecture actually+// present: 0x190 on Ada, 0x170 on Ampere.+size_t PatchDlssgArchGates(HMODULE module, uint32_t target) {+ const auto* nt = imageHeaders(module);+ if (!nt) return 0;+ uint8_t* sites[64]{};+ size_t found = 0, already = 0;+ const auto archNew = static_cast<uint8_t>(target & 0xFF);+ if (!SafeScanDlssgArchSites(reinterpret_cast<uint8_t*>(module), nt, archNew, sites, std::size(sites), &found, &already)) return 0;+ if (found != DlssgTransfusion::kExpectedArchGateSites || already != 0) {+ log::error(kTag, std::format("arch gates: found {} site(s) ({} already patched), expected {}", found, already,+ DlssgTransfusion::kExpectedArchGateSites));+ return 0;+ }+ size_t written = 0;+ for (size_t i = 0; i < found; ++i) written += patchBytes(sites[i], &archNew, 1) ? 1 : 0;+ log::info(kTag, std::format("arch gates: {} site(s) rewrote 0x1b0 -> 0x{:x}", written, target));+ return written;+}++// Below Ada the provider itself refuses to start: NVSDK_NGX_GetGPUArchitecture+// returns Ada (400) and the three *_GetFeatureRequirements report it as the+// minimum. The exports are found by name and the unique immediate 400 in their+// first bytes is lowered to the real architecture. A hook would not do:+// GetFeatureRequirements checks that its caller is nvngx.dll.+uint32_t* SafeFindUniqueImmediate(uint8_t* function, size_t span, uint32_t value) {+ __try {+ uint32_t* hit = nullptr;+ for (size_t i = 0; i + sizeof(uint32_t) <= span; ++i) {+ uint32_t candidate = 0;+ std::memcpy(&candidate, function + i, sizeof(candidate));+ if (candidate != value) continue;+ if (hit) return nullptr; // ambiguous: never guess+ hit = reinterpret_cast<uint32_t*>(function + i);+ }+ return hit;+ } __except (EXCEPTION_EXECUTE_HANDLER) {+ return nullptr;+ }+}++size_t PatchDlssgMinimumArchitecture(HMODULE module, uint32_t target) {+ const auto* nt = imageHeaders(module);+ if (!nt) return 0;+ auto* base = reinterpret_cast<uint8_t*>(module);+ static constexpr const char* kExports[] = {+ "NVSDK_NGX_GetGPUArchitecture",+ "NVSDK_NGX_D3D11_GetFeatureRequirements",+ "NVSDK_NGX_D3D12_GetFeatureRequirements",+ "NVSDK_NGX_VULKAN_GetFeatureRequirements",+ };+ size_t patched = 0;+ for (const char* name : kExports) {+ auto* function = reinterpret_cast<uint8_t*>(GetProcAddress(module, name));+ if (!function) continue;+ const auto offset = static_cast<size_t>(function - base);+ if (offset >= nt->OptionalHeader.SizeOfImage) continue;+ const size_t span = std::min<size_t>(400, nt->OptionalHeader.SizeOfImage - offset);+ uint32_t* immediate = SafeFindUniqueImmediate(function, span, DlssgTransfusion::kAdaArchId);+ if (!immediate) {+ log::error(kTag, std::format("minimum architecture: {} has no unique Ada immediate", name));+ continue;+ }+ patched += patchBytes(immediate, &target, sizeof(target)) ? 1 : 0;+ }+ log::info(kTag, std::format("minimum architecture: {} of {} export(s) lowered 0x190 -> 0x{:x}", patched,+ std::size(kExports), target));+ return patched;+}++// DLSS-G provider count/index validator ("NGX device support"): the jz that+// refuses multi-frame counts on non-Blackwell is removed.+constexpr std::array<uint8_t, 13> kNgxPattern{0x84, 0xD2, 0x0F, 0x84, 0x03, 0x01, 0x00, 0x00, 0xBE, 0x05, 0x00, 0x00, 0x00};+constexpr size_t kNgxPatchOffset = 2;+constexpr std::array<uint8_t, 6> kNgxReplacement{0x90, 0x90, 0x90, 0x90, 0x90, 0x90};++uint8_t* SafeFindUniquePattern(const uint8_t* base, const IMAGE_NT_HEADERS64* nt, const uint8_t* pattern, size_t size, size_t* count) {+ __try {+ uint8_t* match = nullptr;+ const IMAGE_SECTION_HEADER* section = IMAGE_FIRST_SECTION(nt);+ for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++section) {+ if ((section->Characteristics & IMAGE_SCN_MEM_EXECUTE) == 0) continue;+ const uint8_t* start = base + section->VirtualAddress;+ const size_t span = sectionSpan(nt, *section);+ for (size_t off = 0; off + size <= span; ++off) {+ if (std::memcmp(start + off, pattern, size) != 0) continue;+ match = const_cast<uint8_t*>(start + off);+ ++*count;+ }+ }+ return match;+ } __except (EXCEPTION_EXECUTE_HANDLER) {+ return nullptr;+ }+}++bool PatchValidator(HMODULE module) {+ const auto* nt = imageHeaders(module);+ if (!nt) return false;+ size_t count = 0;+ uint8_t* match = SafeFindUniquePattern(reinterpret_cast<uint8_t*>(module), nt, kNgxPattern.data(), kNgxPattern.size(), &count);+ if (count != 1 || !match) {+ log::error(kTag, std::format("NGX device support: expected one code pattern, found {}", count));+ return false;+ }+ const bool ok = patchBytes(match + kNgxPatchOffset, kNgxReplacement.data(), kNgxReplacement.size());+ log::info(kTag, std::format("NGX device support: patched={} rva=0x{:X}", ok, uintptr_t(match + kNgxPatchOffset - reinterpret_cast<uint8_t*>(module))));+ return ok;+}++// ---------------------------------------------------------------------------+// Fatbin handling (midpoint_fix.cpp)+// ---------------------------------------------------------------------------+constexpr uint32_t kFatbinMagic = 0xBA55ED50u;+constexpr size_t kOuterHeader = 16;+constexpr uint32_t kPtxKind = 1;+constexpr uint32_t kAdaArch = 89;+constexpr uint32_t kBlackwellArch = 120;+constexpr uint32_t kArchParked = 122;+constexpr uint64_t kUncompressedFlags = 0x41;++uint16_t ReadU16(const uint8_t* p) { uint16_t v = 0; std::memcpy(&v, p, sizeof(v)); return v; }+uint32_t ReadU32(const uint8_t* p) { uint32_t v = 0; std::memcpy(&v, p, sizeof(v)); return v; }+uint64_t ReadU64(const uint8_t* p) { uint64_t v = 0; std::memcpy(&v, p, sizeof(v)); return v; }++std::string GetPtxEntryName(std::string_view ptx) {+ size_t pos = ptx.find(".entry ");+ if (pos == std::string_view::npos) return {};+ pos += sizeof(".entry ") - 1;+ size_t end = pos;+ while (end < ptx.size() && ptx[end] != '(' && ptx[end] != ' ' && ptx[end] != '\r' && ptx[end] != '\n') ++end;+ return std::string(ptx.substr(pos, end - pos));+}++// Rewrites the PTX .target directive to the target SM (uncompressed entries+// may change length).+bool RetargetPtxText(std::string& text, uint32_t sm) {+ const size_t directive = text.find(".target sm_");+ if (directive == std::string::npos) return false;+ size_t end = directive + sizeof(".target ") - 1;+ while (end < text.size() && text[end] != '\r' && text[end] != '\n' && text[end] != ' ' && text[end] != ',') ++end;+ text.replace(directive, end - directive, ".target sm_" + std::to_string(sm));+ return true;+}++bool Lz4BlockDecompress(const uint8_t* src, size_t srcSize, uint8_t* dst, size_t dstSize) {+ size_t in = 0, out = 0;+ while (in < srcSize) {+ const uint8_t token = src[in++];+ size_t literals = token >> 4;+ if (literals == 15) {+ uint8_t ext = 0;+ do {+ if (in >= srcSize) return false;+ ext = src[in++];+ literals += ext;+ } while (ext == 0xFF);+ }+ if (literals > srcSize - in || literals > dstSize - out) return false;+ std::memcpy(dst + out, src + in, literals);+ in += literals;+ out += literals;+ if (in == srcSize) break;+ if (srcSize - in < 2) return false;+ const size_t back = static_cast<size_t>(src[in]) | (static_cast<size_t>(src[in + 1]) << 8);+ in += 2;+ if (back == 0 || back > out) return false;+ size_t match = 4 + (token & 0x0F);+ if ((token & 0x0F) == 15) {+ uint8_t ext = 0;+ do {+ if (in >= srcSize) return false;+ ext = src[in++];+ match += ext;+ } while (ext == 0xFF);+ }+ if (match > dstSize - out) return false;+ for (size_t i = 0; i < match; ++i) dst[out + i] = dst[out + i - back];+ out += match;+ }+ return in == srcSize && out == dstSize;+}++bool FindPtxEntry(const uint8_t* fat, size_t fatSize, uint32_t arch, size_t& entryOffset) {+ if (fatSize < kOuterHeader || ReadU32(fat) != kFatbinMagic) return false;+ if (ReadU16(fat + 6) != kOuterHeader) return false;+ if (ReadU64(fat + 8) + kOuterHeader != fatSize) return false;+ size_t p = kOuterHeader;+ while (p + 64 <= fatSize) {+ const uint32_t kind = ReadU16(fat + p);+ const uint32_t hdr = ReadU32(fat + p + 4);+ const uint64_t payload = ReadU64(fat + p + 8);+ const size_t remain = fatSize - p;+ if (hdr < 64 || payload == 0 || hdr > remain || payload > remain - hdr) return false;+ if (kind == kPtxKind && ReadU32(fat + p + 28) == arch) {+ entryOffset = p;+ return true;+ }+ p += hdr + static_cast<size_t>(payload);+ }+ return false;+}++bool DecompressEntry(const uint8_t* fat, size_t entry, std::string& text) {+ const uint32_t hdr = ReadU32(fat + entry + 4);+ const uint32_t compressed = ReadU32(fat + entry + 16);+ const uint64_t raw = ReadU64(fat + entry + 56);+ if (compressed == 0 || raw == 0 || raw > (8u << 20)) return false;+ text.resize(static_cast<size_t>(raw));+ return Lz4BlockDecompress(fat + entry + hdr, compressed, reinterpret_cast<uint8_t*>(text.data()), text.size());+}++// Replaces one PTX entry (at `entry`) by an uncompressed payload for `sm`,+// truncating the fatbin after it so the driver JITs that PTX.+void EmitUncompressedEntry(const uint8_t* fat, size_t entry, const std::string& ptx, uint32_t sm, std::vector<uint8_t>& out) {+ const uint32_t hdr = ReadU32(fat + entry + 4);+ const size_t padded = (ptx.size() + 7) & ~size_t{7};+ const size_t finalSize = entry + hdr + padded;+ out.assign(fat, fat + entry + hdr);+ out.resize(finalSize, 0);+ std::memcpy(out.data() + entry + hdr, ptx.data(), ptx.size());+ const uint64_t payload64 = padded;+ const uint32_t zero32 = 0;+ const uint64_t zero64 = 0;+ std::memcpy(out.data() + entry + 8, &payload64, sizeof(payload64));+ std::memcpy(out.data() + entry + 16, &zero32, sizeof(zero32));+ std::memcpy(out.data() + entry + 40, &kUncompressedFlags, sizeof(kUncompressedFlags));+ std::memcpy(out.data() + entry + 56, &zero64, sizeof(zero64));+ std::memcpy(out.data() + entry + 28, &sm, sizeof(sm));+ const uint64_t outer = finalSize - kOuterHeader;+ std::memcpy(out.data() + 8, &outer, sizeof(outer));+}++// DLSS-G 310.9+ temporal profile (upstream kTemporalProfiles[1]): used only+// when the Blackwell kernels are disabled, where the Ada scatter kernel still+// blends every generated frame at the compiled-in midpoint.+constexpr size_t kScatterPtxBytes = 99626;+constexpr char kScatterEntry[] = "Kernel_EstimateIntermMvecsScatter";+constexpr char kScatterParam[] = ".param .align 8 .b8 Kernel_EstimateIntermMvecsScatter_param_0[144]";+constexpr char kScatterRegs[] = ".reg .f32 %f<1362>;";+constexpr char kScatterTemporalInput[] =+ "ld.param.f32 %f134, [Kernel_EstimateIntermMvecsScatter_param_0+32];\r\n"+ "mov.f32 %f135, 0f3F800000;\r\n"+ "sub.ftz.f32 %f136, %f135, %f134;\r\n";+constexpr char kCurrToPrev[] = "%f136";+constexpr char kPrevToCurr[] = "%f134";+constexpr size_t kExpectedMidpoints = 104;+constexpr char kJoinLabel[] = "$L__BB0_3:";+constexpr char kMidpointBits[] = "0f3F000000";+constexpr char kMulPrefix[] = "mul.ftz.f32 ";++bool BuildTemporalFatbin(const uint8_t* fat, size_t fatSize, uint32_t targetSm, std::vector<uint8_t>& out, std::string& why) {+ size_t entry = 0;+ if (!FindPtxEntry(fat, fatSize, kAdaArch, entry)) { why = "no sm_89 PTX entry"; return false; }+ if (ReadU64(fat + entry + 56) != kScatterPtxBytes) { why = "PTX size differs from the 310.9 profile"; return false; }+ std::string ptx;+ if (!DecompressEntry(fat, entry, ptx)) { why = "LZ4 decompression failed"; return false; }+ if (ptx.find(std::string(".entry ") + kScatterEntry + "(") == std::string::npos || ptx.find(kScatterParam) == std::string::npos ||+ ptx.find(kScatterRegs) == std::string::npos) {+ why = "temporal kernel signature changed";+ return false;+ }+ const size_t label = ptx.find(kJoinLabel);+ if (label == std::string::npos || ptx.find(kJoinLabel, label + 1) != std::string::npos) { why = "join label not unique"; return false; }+ size_t insertion = ptx.find('\n', label);+ if (insertion == std::string::npos) { why = "join label has no line end"; return false; }+ ++insertion;+ std::vector<size_t> marks;+ const size_t midLen = sizeof(kMidpointBits) - 1, mulLen = sizeof(kMulPrefix) - 1;+ for (size_t i = ptx.find(kMidpointBits); i != std::string::npos; i = ptx.find(kMidpointBits, i + 1)) {+ if (i + midLen >= ptx.size() || ptx[i + midLen] != ';') continue;+ size_t line = i;+ while (line > 0 && ptx[line - 1] != '\n') --line;+ if (i - line < mulLen || ptx.compare(line, mulLen, kMulPrefix) != 0) continue;+ marks.push_back(i);+ }+ if (marks.size() != kExpectedMidpoints) { why = std::format("found {} midpoint multiplies, expected {}", marks.size(), kExpectedMidpoints); return false; }+ if (marks.front() <= insertion) { why = "first midpoint precedes the insertion point"; return false; }+ std::string patched = ptx.substr(0, insertion) + kScatterTemporalInput;+ size_t src = insertion;+ for (size_t i = 0; i < marks.size(); ++i) {+ patched.append(ptx, src, marks[i] - src);+ patched += i < kExpectedMidpoints / 2 ? kCurrToPrev : kPrevToCurr;+ src = marks[i] + midLen;+ }+ patched.append(ptx, src, std::string::npos);+ if (targetSm != kAdaArch && !RetargetPtxText(patched, targetSm)) { why = "temporal PTX has no .target directive"; return false; }+ EmitUncompressedEntry(fat, entry, patched, targetSm, out);+ return true;+}++bool BuildBlackwellTransfusionFatbin(const uint8_t* fat, size_t fatSize, const char* kernelName, uint32_t targetSm,+ bool quality, bool explainedWarp, std::vector<uint8_t>& out, std::string& why) {+ size_t adaEntry = 0, bwEntry = 0;+ if (!FindPtxEntry(fat, fatSize, kAdaArch, adaEntry)) { why = "no sm_89 Ada PTX entry in fatbin"; return false; }+ if (!FindPtxEntry(fat, fatSize, kBlackwellArch, bwEntry)) { why = "no sm_120 Blackwell PTX entry in fatbin"; return false; }+ std::string ptx;+ if (!DecompressEntry(fat, bwEntry, ptx)) { why = "Blackwell LZ4 decompression failed"; return false; }+ if (std::strcmp(kernelName, "Kernel_BlendCandidatesFused") == 0 && quality) {+ std::string status;+ const bool patched = quality_fix::Patch(ptx, status, explainedWarp ? quality_fix::Policy::ExplainedWarp : quality_fix::Policy::Transfusion);+ log::info(kTag, std::format("quality PTX preparation: {} (patched={})", status, patched));+ }+ const size_t targetPos = ptx.find(".target sm_120");+ if (targetPos == std::string::npos) { why = "could not find .target sm_120 in Blackwell PTX"; return false; }+ size_t after = targetPos + sizeof(".target sm_120") - 1;+ while (after < ptx.size() && (ptx[after] == '\r' || ptx[after] == '\n' || ptx[after] == ' ')) ++after;+ ptx.replace(targetPos, after - targetPos, ".target sm_" + std::to_string(targetSm) + "\n");+ // The rewritten entry replaces the Ada PTX; label it for the target SM.+ EmitUncompressedEntry(fat, adaEntry, ptx, targetSm, out);+ return true;+}++std::string GetFatbinKernelName(const uint8_t* fat, size_t fatSize) {+ size_t entry = 0;+ if (!FindPtxEntry(fat, fatSize, kBlackwellArch, entry)) return {};+ std::string ptx;+ if (!DecompressEntry(fat, entry, ptx)) return {};+ return GetPtxEntryName(ptx);+}++// Retargets kernel containers in place so the driver compiles their PTX for+// the target SM. The .target directive sits in an LZ4 literal run in every+// container of the supported provider, so a same-length rewrite is enough.+// Ada: every container holding a Blackwell sm_120 PTX is relabelled sm_89 and+// its Ada images are parked at arch 122. Below Ada every container gets one+// PTX relabelled to the target SM (the Blackwell build when preferred and+// present, else the Ada PTX) and every other image parked.+unsigned RetargetContainers(uint8_t* base, const IMAGE_NT_HEADERS64* nt, bool preferBlackwell, uint32_t targetSm, bool& writeFailed) {+ unsigned rewritten = 0;+ const bool preAda = targetSm < kAdaArch;+ char target[16]{};+ std::snprintf(target, sizeof(target), "sm_%u", targetSm);+ const IMAGE_SECTION_HEADER* section = IMAGE_FIRST_SECTION(nt);+ for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++section) {+ if ((section->Characteristics & IMAGE_SCN_MEM_READ) == 0 || (section->Characteristics & IMAGE_SCN_MEM_EXECUTE) != 0) continue;+ const size_t size = sectionSpan(nt, *section);+ if (size < kOuterHeader) continue;+ uint8_t* start = base + section->VirtualAddress;+ for (uint8_t* c = start; c + kOuterHeader <= start + size;) {+ if (ReadU32(c) != kFatbinMagic) { ++c; continue; }+ const uint16_t headerSize = ReadU16(c + 6);+ const uint64_t fatSize = ReadU64(c + 8);+ const auto remain = static_cast<size_t>((start + size) - c);+ if (headerSize != 0x10 || fatSize == 0 || remain < 16 || fatSize > remain - 16) { c += 4; continue; }+ const size_t total = static_cast<size_t>(fatSize) + 16;+ struct Image { uint8_t* header; size_t hdr; size_t payload; uint16_t kind; uint32_t arch; };+ std::vector<Image> images;+ for (uint8_t* img = c + 16; img + 32 <= c + total;) {+ const uint32_t imgHeader = ReadU32(img + 4);+ const uint64_t payload = ReadU64(img + 8);+ const auto imgRemain = static_cast<size_t>((c + total) - img);+ if (imgHeader < 32 || payload == 0 || imgHeader > imgRemain || payload > imgRemain - imgHeader) break;+ images.push_back({img, imgHeader, static_cast<size_t>(payload), ReadU16(img), ReadU32(img + 28)});+ img += imgHeader + static_cast<size_t>(payload);+ }+ const Image* blackwell = nullptr;+ const Image* ada = nullptr;+ bool hasAdaImage = false;+ for (const auto& image : images) {+ if (image.kind == kPtxKind && image.arch == kBlackwellArch) blackwell = ℑ+ if (image.kind == kPtxKind && image.arch == kAdaArch) ada = ℑ+ if (image.arch == kAdaArch) hasAdaImage = true;+ }+ const Image* chosen = !preAda ? (hasAdaImage ? blackwell : nullptr) : ((preferBlackwell && blackwell) ? blackwell : ada);+ if (chosen) {+ // Same-length directive rewrite: "sm_120" -> "sm_89 ", "sm_89" -> "sm_86".+ char from[24]{}, to[24]{};+ std::snprintf(from, sizeof(from), ".target sm_%u", chosen->arch);+ std::snprintf(to, sizeof(to), ".target %-*s", static_cast<int>(std::strlen(from) - 8), target);+ uint8_t* body = chosen->header + chosen->hdr;+ uint8_t* bodyEnd = body + chosen->payload;+ const size_t fromLength = std::strlen(from);+ auto* at = std::search(body, bodyEnd, reinterpret_cast<const uint8_t*>(from), reinterpret_cast<const uint8_t*>(from) + fromLength);+ if (at != bodyEnd && std::strlen(to) == fromLength) {+ bool ok = patchBytes(at, to, fromLength);+ ok = patchBytes(chosen->header + 28, &targetSm, sizeof(targetSm)) && ok;+ for (const auto& image : images) {+ if (&image == chosen) continue;+ if (preAda || image.arch == kAdaArch) ok = patchBytes(image.header + 28, &kArchParked, sizeof(kArchParked)) && ok;+ }+ writeFailed |= !ok;+ ++rewritten;+ c += total;+ continue;+ }+ }+ c += 4;+ }+ }+ return rewritten;+}++bool SafeValidateFatbinCandidate(const uint8_t* candidate, size_t maxBytes, size_t& outTotal) {+ __try {+ if (ReadU32(candidate) != kFatbinMagic || ReadU16(candidate + 6) != kOuterHeader) return false;+ const uint64_t declared = ReadU64(candidate + 8);+ if (declared > (16u << 20) || declared < (1024 - kOuterHeader)) return false;+ const size_t total = static_cast<size_t>(declared) + kOuterHeader;+ if (total > maxBytes) return false;+ outTotal = total;+ return true;+ } __except (EXCEPTION_EXECUTE_HANDLER) {+ return false;+ }+}++struct ProviderResult {+ bool ok = false, blackwell = false, writeFailed = false;+ size_t descriptors = 0;+ unsigned retargeted = 0;+};++// PatchProvider: Blackwell kernels (the temporal scatter and the candidate+// blend rebuilt from their sm_120 PTX, every other container retargeted in+// place) or, when disabled, the Ada temporal midpoint fix.+ProviderResult PatchProvider(HMODULE module, uint32_t targetSm, const DlssgTransfusion::Options& options) {+ auto& g = global();+ ProviderResult result;+ const auto* nt = imageHeaders(module);+ if (!nt) return result;+ auto* base = reinterpret_cast<uint8_t*>(module);+ const auto start = reinterpret_cast<uintptr_t>(base);+ const size_t imageSize = nt->OptionalHeader.SizeOfImage;+ std::map<const uint8_t*, std::vector<uint64_t*>> fatbinSlots;+ const IMAGE_SECTION_HEADER* section = IMAGE_FIRST_SECTION(nt);+ for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++section) {+ if ((section->Characteristics & IMAGE_SCN_MEM_READ) == 0 || (section->Characteristics & IMAGE_SCN_MEM_EXECUTE) != 0) continue;+ uint8_t* sec = base + section->VirtualAddress;+ const size_t size = sectionSpan(nt, *section);+ for (size_t off = 0; off + sizeof(uint64_t) <= size; off += sizeof(uint64_t)) {+ const uint64_t value = ReadU64(sec + off);+ if (value < start || value >= start + imageSize) continue;+ const auto remaining = static_cast<size_t>((start + imageSize) - value);+ if (remaining < 16) continue;+ const auto* candidate = reinterpret_cast<const uint8_t*>(value);+ size_t total = 0;+ if (!SafeValidateFatbinCandidate(candidate, remaining, total)) continue;+ fatbinSlots[candidate].push_back(reinterpret_cast<uint64_t*>(sec + off));+ }+ }+ struct TargetFatbin {+ const char* kernelName;+ const uint8_t* fat = nullptr;+ size_t fatSize = 0;+ std::vector<uint64_t*> slots;+ };+ TargetFatbin targets[] = {{"Kernel_EstimateIntermMvecsScatter"}, {"Kernel_BlendCandidatesFused"}};+ const uint8_t* temporalFat = nullptr;+ size_t temporalFatSize = 0;+ std::vector<uint64_t*> temporalSlots;+ for (const auto& [candidate, slots] : fatbinSlots) {+ const size_t total = static_cast<size_t>(ReadU64(candidate + 8)) + kOuterHeader;+ size_t entry = 0;+ if (!temporalFat && FindPtxEntry(candidate, total, kAdaArch, entry) && ReadU64(candidate + entry + 56) == kScatterPtxBytes) {+ temporalFat = candidate;+ temporalFatSize = total;+ temporalSlots = slots;+ }+ const std::string name = GetFatbinKernelName(candidate, total);+ for (auto& target : targets) {+ if (!target.fat && !name.empty() && name == target.kernelName) {+ target.fat = candidate;+ target.fatSize = total;+ target.slots = slots;+ break;+ }+ }+ }+ auto redirect = [&](const std::vector<uint8_t>& rebuilt, const std::vector<uint64_t*>& slots) {+ void* memory = VirtualAlloc(nullptr, rebuilt.size(), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);+ if (!memory) return size_t{0};+ std::memcpy(memory, rebuilt.data(), rebuilt.size());+ g.allocations.push_back(memory);+ size_t written = 0;+ const auto value = reinterpret_cast<uint64_t>(memory);+ for (uint64_t* slot : slots) written += patchBytes(slot, &value, sizeof(value)) ? 1 : 0;+ result.writeFailed |= written != slots.size();+ return written;+ };+ if (options.blackwellKernels && targets[0].fat) {+ for (const auto& target : targets) {+ if (std::strcmp(target.kernelName, "Kernel_BlendCandidatesFused") == 0 && !options.qualityValidWarp) continue;+ if (&target != &targets[0] && result.descriptors == 0) break; // never ready on an incomplete temporal patch+ if (!target.fat || target.slots.empty()) continue;+ std::vector<uint8_t> rebuilt;+ std::string why;+ if (!BuildBlackwellTransfusionFatbin(target.fat, target.fatSize, target.kernelName, targetSm, options.qualityValidWarp,+ options.explainedWarp, rebuilt, why)) {+ log::error(kTag, std::format("Blackwell kernels for {} failed ({})", target.kernelName, why));+ continue;+ }+ const size_t written = redirect(rebuilt, target.slots);+ result.descriptors += written;+ log::info(kTag, std::format("redirected {} of {} {} descriptor(s) ({} bytes)", written, target.slots.size(), target.kernelName, rebuilt.size()));+ }+ if (result.descriptors) {+ result.retargeted = RetargetContainers(base, nt, true, targetSm, result.writeFailed);+ result.blackwell = true;+ result.ok = !result.writeFailed;+ log::info(kTag, std::format("{} container(s) retargeted in place (Blackwell preferred -> sm_{}), {} descriptor(s) redirected",+ result.retargeted, targetSm, result.descriptors));+ return result;+ }+ }+ // Ada temporal midpoint fix on EstimateIntermMvecsScatter.+ std::vector<uint8_t> rebuilt;+ std::string why;+ const bool built = temporalFat && !temporalSlots.empty() && BuildTemporalFatbin(temporalFat, temporalFatSize, targetSm, rebuilt, why);+ if (targetSm < kAdaArch) {+ result.retargeted = RetargetContainers(base, nt, false, targetSm, result.writeFailed);+ log::info(kTag, std::format("{} container(s) retargeted in place (Ada PTX -> sm_{})", result.retargeted, targetSm));+ }+ if (!built) {+ log::error(kTag, std::format("temporal midpoint rebuild failed ({})", temporalFat ? why : std::string("no temporal descriptor")));+ return result;+ }+ result.descriptors = redirect(rebuilt, temporalSlots);+ result.ok = result.descriptors > 0 && !result.writeFailed;+ log::info(kTag, std::format("redirected {} scatter descriptor(s) to the temporal-corrected rebuild ({} bytes)", result.descriptors, rebuilt.size()));+ return result;+}++// ---------------------------------------------------------------------------+// Exact image kernels (image_kernels.h, PrepareModuleImage)+// ---------------------------------------------------------------------------+constexpr uint64_t kOutputPullSourceHash = 0xf4194a9d30dea518ull; // NVIDIA 310.9.1 sm_120+constexpr uint64_t kOutputPushFineSourceHash = 0x3a728f2af0a08fc8ull; // NVIDIA 310.9.1 sm_120++// FNV-1a over the PTX with CR, trailing NULs and the first .target line+// removed, so a copy retargeted in place hashes like the original.+uint64_t SourceHash(std::string_view ptx) {+ std::string text;+ text.reserve(ptx.size());+ for (char c : ptx) if (c != '\r') text.push_back(c);+ while (!text.empty() && text.back() == '\0') text.pop_back();+ const size_t target = text.find(".target ");+ if (target != std::string::npos) {+ const size_t end = text.find('\n', target);+ text.erase(target, end == std::string::npos ? std::string::npos : end - target + 1);+ }+ uint64_t hash = 14695981039346656037ull;+ for (unsigned char c : text) hash = (hash ^ c) * 1099511628211ull;+ return hash;+}++struct StorePair { const char* base; const char* first; const char* second; };+constexpr StorePair kBlendStorePairs[] = {+ {"%rd83", "%r553", "%r554"}, {"%rd84", "%r555", "%r556"}, {"%rd72", "%r543", "%r544"}, {"%rd73", "%r545", "%r546"},+ {"%rd61", "%r491", "%r492"}, {"%rd62", "%r493", "%r494"}, {"%rd50", "%r382", "%r383"}, {"%rd51", "%r384", "%r385"},+ {"%rd39", "%r234", "%r235"}, {"%rd40", "%r236", "%r237"}};++// Merges the ten store pairs; all ten must be found exactly once, in order,+// or the text is left unchanged.+bool VectorizeBlendStores(std::string& ptx) {+ std::string text = ptx;+ for (const auto& pair : kBlendStorePairs) {+ const std::string first = std::string("st.global.u32 [") + pair.base + "], " + pair.first + ";";+ const std::string second = std::string("st.global.u32 [") + pair.base + "+4], " + pair.second + ";";+ const size_t a = text.find(first), b = text.find(second);+ if (a == std::string::npos || b == std::string::npos || b < a || text.find(first, a + 1) != std::string::npos ||+ text.find(second, b + 1) != std::string::npos)+ return false;+ text.replace(b, second.size(), std::string("st.global.v2.u32 [") + pair.base + "], {" + pair.first + ", " + pair.second + "};");+ text.erase(a, first.size());+ }+ ptx.swap(text);+ return true;+}++bool SafeCopyBlob(const void* blob, size_t size, uint8_t* out) {+ __try {+ std::memcpy(out, blob, size);+ return true;+ } __except (EXCEPTION_EXECUTE_HANDLER) {+ return false;+ }+}++// The in-place retarget cannot grow the compressed PTX, so the exact+// image-kernel optimizations happen on the image the provider hands to the+// driver. Returns true with a one-entry uncompressed fatbin.+bool PrepareModuleImage(const void* blob, std::vector<uint8_t>& replacement) {+ auto& g = global();+ const uint32_t targetSm = g.targetSm.load(std::memory_order_relaxed);+ if (!blob || !g.options.optimizedKernels) return false;+ std::vector<uint8_t> fat(kOuterHeader);+ if (!SafeCopyBlob(blob, kOuterHeader, fat.data()) || ReadU32(fat.data()) != kFatbinMagic || ReadU16(fat.data() + 6) != kOuterHeader) return false;+ // The provider passes its descriptor's size, which may still describe the+ // original image of a redirected rebuild; the driver follows the header.+ const uint64_t total = ReadU64(fat.data() + 8) + kOuterHeader;+ if (total > (16u << 20)) return false;+ fat.resize(static_cast<size_t>(total));+ if (!SafeCopyBlob(blob, fat.size(), fat.data())) return false;+ for (size_t p = kOuterHeader; p + 64 <= fat.size();) {+ const uint16_t kind = ReadU16(fat.data() + p);+ const uint32_t hdr = ReadU32(fat.data() + p + 4);+ const uint64_t payload = ReadU64(fat.data() + p + 8);+ if (hdr < 64 || payload == 0 || hdr > fat.size() - p || payload > fat.size() - p - hdr) return false;+ if (kind != kPtxKind || ReadU32(fat.data() + p + 28) != targetSm) {+ p += hdr + static_cast<size_t>(payload);+ continue;+ }+ const uint32_t compressed = ReadU32(fat.data() + p + 16);+ std::string text;+ if (compressed) {+ if (compressed > payload || !DecompressEntry(fat.data(), p, text)) return false;+ } else {+ text.assign(reinterpret_cast<const char*>(fat.data() + p + hdr), static_cast<size_t>(payload));+ }+ while (!text.empty() && text.back() == '\0') text.pop_back();+ const char* optimized = nullptr;+ const std::string entry = GetPtxEntryName(text);+ if (entry == "Kernel_OutputPull" || entry == "Kernel_OutputPushFine") {+ const bool pull = entry == "Kernel_OutputPull";+ if (SourceHash(text) == (pull ? kOutputPullSourceHash : kOutputPushFineSourceHash)) {+ g.exactProviderKernels.store(true, std::memory_order_release);+ if (g.imageReplacements) {+ text = pull ? g.outputPull : g.outputPushFine;+ RetargetPtxText(text, targetSm);+ optimized = pull ? "OutputPull (packed row masks)" : "OutputPushFine (early block exit)";+ }+ }+ } else if (entry == "Kernel_BlendCandidatesFused" && VectorizeBlendStores(text)) {+ optimized = "BlendCandidatesFused (vector stores)";+ }+ if (!optimized) return false;+ log::info(kTag, std::format("optimized image kernel: {} for sm_{}", optimized, targetSm));+ const size_t padded = (text.size() + 1 + 7) & ~size_t{7};+ replacement.assign(fat.begin(), fat.begin() + kOuterHeader);+ replacement.insert(replacement.end(), fat.begin() + static_cast<ptrdiff_t>(p), fat.begin() + static_cast<ptrdiff_t>(p + hdr));+ replacement.resize(kOuterHeader + hdr + padded, 0);+ std::memcpy(replacement.data() + kOuterHeader + hdr, text.data(), text.size());+ uint8_t* e = replacement.data() + kOuterHeader;+ const uint64_t payload64 = padded;+ const uint32_t zero32 = 0;+ const uint64_t zero64 = 0;+ std::memcpy(e + 8, &payload64, sizeof(payload64));+ std::memcpy(e + 16, &zero32, sizeof(zero32));+ std::memcpy(e + 40, &kUncompressedFlags, sizeof(kUncompressedFlags));+ std::memcpy(e + 56, &zero64, sizeof(zero64));+ const uint64_t outer = replacement.size() - kOuterHeader;+ std::memcpy(replacement.data() + 8, &outer, sizeof(outer));+ return true;+ }+ return false;+}++// ---------------------------------------------------------------------------+// NvAPI_D3D12_CreateCuModule (cu_module_hook.h)+// ---------------------------------------------------------------------------+// Replacement images keyed by the content of the original image; never freed,+// the driver may keep referring to a module's source image.+std::mutex cacheMutex;+std::unordered_map<uint64_t, std::unique_ptr<std::vector<uint8_t>>> cache;++bool SafeHash(const uint8_t* data, size_t size, uint64_t& hash) {+ __try {+ hash = 1469598103934665603ull;+ for (size_t i = 0; i < size; ++i) hash = (hash ^ data[i]) * 1099511628211ull;+ return true;+ } __except (EXCEPTION_EXECUTE_HANDLER) {+ return false;+ }+}++const std::vector<uint8_t>* Replacement(const void* blob, uint32_t size) {+ if (!blob || !size) return nullptr;+ uint64_t key = 0;+ if (!SafeHash(static_cast<const uint8_t*>(blob), size, key)) return nullptr;+ key ^= size;+ std::lock_guard lock(cacheMutex);+ const auto found = cache.find(key);+ if (found != cache.end()) return found->second.get();+ auto image = std::make_unique<std::vector<uint8_t>>();+ if (!PrepareModuleImage(blob, *image)) image.reset();+ return cache.emplace(key, std::move(image)).first->second.get();+}++int __cdecl HookCreateModule(void* device, const void* blob, uint32_t size, void** module) {+ auto& g = global();+ const auto original = g.createModule.load(std::memory_order_acquire);+ if (!g.active.load(std::memory_order_acquire)) return original(device, blob, size, module);+ const std::vector<uint8_t>* image = nullptr;+ try { image = Replacement(blob, size); } catch (...) { image = nullptr; }+ const void* source = image ? image->data() : blob;+ const auto sourceSize = image ? static_cast<uint32_t>(image->size()) : size;+ const int status = original(device, source, sourceSize, module);+ (status == 0 ? g.accepted : g.rejected).fetch_add(1, std::memory_order_relaxed);+ if (image) g.rewritten.fetch_add(1, std::memory_order_relaxed);+ if (status != 0) log::warn(kTag, std::format("CreateCuModule status={} size={} rewritten={}", status, size, image != nullptr));+ return status;+}++// ---------------------------------------------------------------------------+// DL1/DL2 network optimization (network_optimizer.h)+// The kernels and launch shapes of the dlssg_for_sm86 0.3.5 backend, whose+// output is bit-identical to NVIDIA's; NVIDIA's weights and parameters.+// ---------------------------------------------------------------------------+namespace net {+enum class Kind : uint8_t { Other, NetworkStart, NetworkEnd, Upscale, ElementWise, Conv, Pool, Dl2 };+enum class Grid : uint8_t { None, W16H4, Flat16, Flat32, Flat64, Pool2048 };++struct Rule {+ uint16_t resource; // sm_86 PTX kernel file k<resource>.ptx+ Grid grid;+ uint32_t z;+ uint32_t block;+ uint32_t paramBytes;+};++// Per NVIDIA conv rank. Fused ranks (the conv after each decoder add) have no+// plain rule: the fusion consumes them.+constexpr Rule kConvRules[17] = {+ {4000, Grid::W16H4, 1, 128, 48}, {4008, Grid::Flat16, 1, 128, 40}, {4002, Grid::W16H4, 4, 128, 48},+ {4004, Grid::W16H4, 4, 128, 48}, {4006, Grid::W16H4, 8, 256, 48}, {4010, Grid::Flat32, 8, 512, 40},+ {4012, Grid::Flat32, 8, 128, 40}, {0, Grid::None, 0, 0, 40}, {4014, Grid::Flat32, 2, 512, 40},+ {0, Grid::None, 0, 0, 40}, {4016, Grid::Flat16, 1, 256, 40}, {0, Grid::None, 0, 0, 40},+ {4018, Grid::Flat16, 1, 128, 40}, {0, Grid::None, 0, 0, 40}, {4020, Grid::Flat32, 1, 128, 40},+ {0, Grid::None, 0, 0, 40}, {4022, Grid::Flat16, 1, 64, 40}};+constexpr Rule kFusedRules[5] = {+ {4024, Grid::Flat16, 1, 256, 48}, {4026, Grid::Flat16, 1, 256, 48}, {4028, Grid::Flat16, 1, 256, 48},+ {4030, Grid::Flat16, 1, 128, 48}, {4032, Grid::Flat64, 1, 128, 48}};+constexpr Rule kPoolRule{4039, Grid::Pool2048, 1, 256, 36};++enum class Dl2 : uint8_t { InitialMerge, ConvPre, B0Conv0, B0Conv1, B0Conv2, B0Bot1, Upsample, CentralBlock, B1Conv0,+ B1Conv1, B1Bot1, Count };+struct Dl2Rule {+ const char* name; // NVIDIA kernel+ uint16_t resource; // sm_86 PTX kernel file+ const char* entry;+ uint32_t paramBytes;+ uint8_t hWord, wWord; // output height and width, as 32-bit parameter words+ uint16_t dx, dy, z; // grid: ceil(w/dx), ceil(h/dy), z; dy == 0: ceil(w*h/dx), z, 1+ uint32_t block;+ std::array<std::pair<uint8_t, uint32_t>, 6> shape; // expected parameter words (channels, kernel size)+};+constexpr Dl2Rule kDl2Rules[size_t(Dl2::Count)] = {+ {"k_initial_merge", 0, nullptr, 44, 0, 0, 0, 0, 0, 0, {}},+ {"custom_block0_convPre_kernel", 4042, "conv_dl2_merge_pool", 80, 17, 18, 8, 4, 1, 256,+ {{{uint8_t{4}, uint32_t{0x20}}, {uint8_t{5}, uint32_t{3}}, {uint8_t{6}, uint32_t{3}}, {uint8_t{7}, uint32_t{0xa}}, {uint8_t{13}, uint32_t{0xa}}, {uint8_t{19}, uint32_t{0x20}}}}},+ {"custom_block0_conv0_c8_kernel", 4044, "conv_dl2_pool", 80, 17, 18, 8, 2, 1, 128,+ {{{uint8_t{4}, uint32_t{0x20}}, {uint8_t{5}, uint32_t{3}}, {uint8_t{6}, uint32_t{3}}, {uint8_t{7}, uint32_t{0x20}}, {uint8_t{13}, uint32_t{0x20}}, {uint8_t{19}, uint32_t{0x20}}}}},+ {"custom_block0_conv1_kernel", 4046, "conv_dl2_pool", 80, 17, 18, 8, 2, 1, 256,+ {{{uint8_t{4}, uint32_t{0x40}}, {uint8_t{5}, uint32_t{3}}, {uint8_t{6}, uint32_t{3}}, {uint8_t{7}, uint32_t{0x20}}, {uint8_t{13}, uint32_t{0x20}}, {uint8_t{19}, uint32_t{0x40}}}}},+ {"custom_block0_conv2_kernel", 4050, "conv_dl2_resid", 92, 19, 20, 16, 2, 2, 128,+ {{{uint8_t{4}, uint32_t{0x40}}, {uint8_t{5}, uint32_t{3}}, {uint8_t{6}, uint32_t{3}}, {uint8_t{7}, uint32_t{0x40}}, {uint8_t{15}, uint32_t{0x40}}, {uint8_t{21}, uint32_t{0x40}}}}},+ {"custom_block0_conv_bot1_hf_kernel", 4062, "conv_dl2_bot1_block0", 144, 21, 22, 16, 4, 1, 128,+ {{{uint8_t{4}, uint32_t{8}}, {uint8_t{7}, uint32_t{0x20}}, {uint8_t{17}, uint32_t{0x20}}, {uint8_t{23}, uint32_t{4}}, {uint8_t{29}, uint32_t{1}}, {uint8_t{35}, uint32_t{3}}}}},+ {"custom_upsample_hf_kernel", 4059, "upsample_hf", 144, 21, 22, 256, 0, 3, 256,+ {{{uint8_t{5}, uint32_t{4}}, {uint8_t{11}, uint32_t{1}}, {uint8_t{17}, uint32_t{3}}, {uint8_t{23}, uint32_t{4}}, {uint8_t{29}, uint32_t{1}}, {uint8_t{35}, uint32_t{3}}}}},+ {"k_central_block", 0, nullptr, 68, 0, 0, 0, 0, 0, 0, {}},+ {"custom_block1_conv0_kernel", 4060, "conv_dl2_central_pool", 80, 17, 18, 8, 4, 1, 256,+ {{{uint8_t{4}, uint32_t{0x10}}, {uint8_t{5}, uint32_t{3}}, {uint8_t{6}, uint32_t{3}}, {uint8_t{7}, uint32_t{0x12}}, {uint8_t{13}, uint32_t{0x12}}, {uint8_t{19}, uint32_t{0x10}}}}},+ {"custom_block1_conv1_kernel", 4048, "conv_dl2_pool", 80, 17, 18, 8, 2, 1, 128,+ {{{uint8_t{4}, uint32_t{0x20}}, {uint8_t{5}, uint32_t{3}}, {uint8_t{6}, uint32_t{3}}, {uint8_t{7}, uint32_t{0x10}}, {uint8_t{13}, uint32_t{0x10}}, {uint8_t{19}, uint32_t{0x20}}}}},+ {"custom_block1_conv_bot1_hf_kernel", 4058, "conv_dl2_bot1_block1", 152, 27, 28, 16, 8, 1, 256,+ {{{uint8_t{4}, uint32_t{8}}, {uint8_t{7}, uint32_t{0x10}}, {uint8_t{23}, uint32_t{0x10}}, {uint8_t{29}, uint32_t{4}}, {uint8_t{33}, uint32_t{1}}, {uint8_t{37}, uint32_t{3}}}}}};++std::vector<uint16_t> resources() {+ std::vector<uint16_t> ids{kPoolRule.resource};+ for (const auto& r : kConvRules) if (r.resource) ids.push_back(r.resource);+ for (const auto& r : kFusedRules) ids.push_back(r.resource);+ for (const auto& r : kDl2Rules) if (r.resource) ids.push_back(r.resource);+ return ids;+}++struct Entry {+ void* function;+ uint32_t grid[3];+ uint32_t block[3];+ uint32_t sharedBytes, reserved;+ const void* params;+ uint32_t paramBytes, reserved2;+};+static_assert(sizeof(Entry) == 56);++struct Role {+ Kind kind = Kind::Other;+ Dl2 layer = Dl2::Count;+};+std::mutex mutex;+std::unordered_map<void*, Role> kinds; // provider function handle -> role+std::unordered_map<uint16_t, void*> functions; // our function per rule resource+void* device = nullptr;+std::atomic<bool> ready{false};+std::atomic<bool> failed{false};+std::atomic<uint64_t> optimizedRuns{0};+std::atomic<uint64_t> optimizedDl2Runs{0};+std::map<std::pair<uint16_t, uint32_t>, std::unique_ptr<std::vector<uint8_t>>> images; // module sources, kept alive++void* Function(uint16_t resource) {+ const auto found = functions.find(resource);+ return found != functions.end() ? found->second : nullptr;+}++bool Enabled() {+ auto& g = global();+ return g.active.load(std::memory_order_acquire) && g.options.optimizedKernels &&+ g.exactProviderKernels.load(std::memory_order_acquire);+}++Kind Classify(const char* name) {+ if (!name) return Kind::Other;+ if (std::strcmp(name, "Kernel_DL1Net_Input") == 0) return Kind::NetworkStart;+ if (std::strcmp(name, "Kernel_DL1Net_Output") == 0) return Kind::NetworkEnd;+ if (std::strcmp(name, "k_upscale") == 0) return Kind::Upscale;+ if (std::strcmp(name, "k_element_wise") == 0) return Kind::ElementWise;+ if (std::strcmp(name, "k_conv_fp16_nhwc") == 0) return Kind::Conv;+ if (std::strcmp(name, "k_pooling") == 0) return Kind::Pool;+ return Kind::Other;+}++Role ClassifyRole(const char* name) {+ for (size_t i = 0; name && i < std::size(kDl2Rules); ++i)+ if (std::strcmp(name, kDl2Rules[i].name) == 0) return {Kind::Dl2, static_cast<Dl2>(i)};+ return {Classify(name)};+}++// One uncompressed PTX entry; header fields as in the 310.9.1 provider's own+// fatbins (entry header 0x50 bytes, ISA 8.5).+std::vector<uint8_t> BuildFatbin(std::string_view ptx, uint32_t sm) {+ const size_t padded = (ptx.size() + 1 + 7) & ~size_t{7};+ std::vector<uint8_t> out(16 + 0x50 + padded, 0);+ const uint32_t magic = 0xBA55ED50u;+ const uint16_t version = 1, outerHeader = 0x10;+ const uint64_t outerSize = 0x50 + padded;+ std::memcpy(out.data(), &magic, 4);+ std::memcpy(out.data() + 4, &version, 2);+ std::memcpy(out.data() + 6, &outerHeader, 2);+ std::memcpy(out.data() + 8, &outerSize, 8);+ uint8_t* entry = out.data() + 16;+ const uint16_t kind = 1, entryVersion = 0x0101, isaMinor = 5, isaMajor = 8;+ const uint32_t headerSize = 0x50, field20 = 0x40, extra = 0x48;+ const uint64_t payload = padded, flags = 0x41;+ std::memcpy(entry, &kind, 2);+ std::memcpy(entry + 2, &entryVersion, 2);+ std::memcpy(entry + 4, &headerSize, 4);+ std::memcpy(entry + 8, &payload, 8);+ std::memcpy(entry + 20, &field20, 4);+ std::memcpy(entry + 24, &isaMinor, 2);+ std::memcpy(entry + 26, &isaMajor, 2);+ std::memcpy(entry + 28, &sm, 4);+ std::memcpy(entry + 40, &flags, 8);+ std::memcpy(entry + 64, &extra, 4);+ std::memcpy(entry + 0x50, ptx.data(), ptx.size());+ return out;+}++bool CreateVariant(void* providerDevice, uint16_t resource, const char* entry) {+ auto& g = global();+ const auto createModule = g.createModule.load(std::memory_order_acquire);+ const auto createFunction = g.createFunction.load(std::memory_order_acquire);+ const uint32_t sm = g.targetSm.load(std::memory_order_relaxed);+ const auto source = g.networkPtx.find(resource);+ if (source == g.networkPtx.end()) {+ log::warn(kTag, std::format("network optimization unavailable: kernel {} is not installed", resource));+ return false;+ }+ if (!createModule || !createFunction) return false;+ auto& image = images[{resource, sm}];+ if (!image) {+ std::string ptx = source->second;+ if (sm != 86) {+ const size_t target = ptx.find(".target sm_86");+ if (target == std::string::npos) return false;+ ptx.replace(target, sizeof(".target sm_86") - 1, ".target sm_" + std::to_string(sm));+ }+ image = std::make_unique<std::vector<uint8_t>>(BuildFatbin(ptx, sm));+ }+ void* module = nullptr;+ const int moduleStatus = createModule(providerDevice, image->data(), static_cast<uint32_t>(image->size()), &module);+ void* function = nullptr;+ const int status = moduleStatus == 0 ? createFunction(providerDevice, module, entry, &function) : moduleStatus;+ if (status != 0 || !function) {+ log::error(kTag, std::format("network optimization disabled: kernel {} not created (status {})", resource, status));+ return false;+ }+ functions[resource] = function;+ return true;+}++// Called with the lock held, from the provider's own network creation.+void CreateVariants(void* providerDevice) {+ ready.store(false, std::memory_order_release);+ functions.clear();+ bool ok = CreateVariant(providerDevice, kPoolRule.resource, "k_pooling");+ for (const Rule& rule : kConvRules) if (ok && rule.resource) ok = CreateVariant(providerDevice, rule.resource, "k_conv_fp16_nhwc");+ for (const Rule& rule : kFusedRules) if (ok) ok = CreateVariant(providerDevice, rule.resource, "k_conv_fp16_nhwc_fused_up");+ for (const Dl2Rule& rule : kDl2Rules) if (ok && rule.resource) ok = CreateVariant(providerDevice, rule.resource, rule.entry);+ if (!ok) {+ failed = true;+ return;+ }+ device = providerDevice;+ ready.store(true, std::memory_order_release);+ log::info(kTag, std::format("network optimization ready: {} DL1/DL2 kernels for sm_{}", functions.size(),+ global().targetSm.load(std::memory_order_relaxed)));+}++int __cdecl HookFunction(void* providerDevice, void* module, const char* name, void** function) {+ auto& g = global();+ const int status = g.createFunction.load(std::memory_order_acquire)(providerDevice, module, name, function);+ if (status != 0 || !function || !*function || !g.active.load(std::memory_order_acquire)) return status;+ const Role role = ClassifyRole(name);+ std::lock_guard lock(mutex);+ kinds[*function] = role; // handles are recycled: always take the latest meaning+ // The provider builds its network: build ours next to it, on its device.+ if (role.kind == Kind::Upscale && g.options.optimizedKernels && !failed.load() && (!ready.load() || device != providerDevice)) {+ ready.store(false, std::memory_order_release);+ CreateVariants(providerDevice);+ }+ return status;+}++struct Held {+ Entry entry{};+ std::array<uint8_t, 96> params{};+};+struct State {+ void* list = nullptr;+ bool active = false; // inside DL1, optimization still consistent+ int conv = 0; // NVIDIA conv rank+ int level = 0; // decoder level+ bool haveUpscale = false, haveAdd = false;+ Held upscale, add;+ Dl2 held = Dl2::Count; // DL2 producer held for fusion (merge or central block)+ Held dl2;+};+thread_local State t_state;++template <typename T> T Field(const void* params, size_t offset) {+ T value{};+ std::memcpy(&value, static_cast<const uint8_t*>(params) + offset, sizeof(value));+ return value;+}++bool Capture(const Entry& entry, Held& held) {+ if (entry.paramBytes > held.params.size() || !entry.params) return false;+ held.entry = entry;+ std::memcpy(held.params.data(), entry.params, entry.paramBytes);+ held.entry.params = held.params.data();+ return true;+}++// Replays held launches unchanged, in their original order.+void Flush(LaunchFn original) {+ auto& s = t_state;+ if (s.haveUpscale) original(s.list, &s.upscale.entry, 1);+ if (s.haveAdd) original(s.list, &s.add.entry, 1);+ if (s.held != Dl2::Count) original(s.list, &s.dl2.entry, 1);+ s.haveUpscale = s.haveAdd = false;+ s.held = Dl2::Count;+}++void Stop(LaunchFn original) {+ Flush(original);+ t_state.active = false;+}++uint32_t Ceil(uint64_t value, uint64_t divisor) { return static_cast<uint32_t>((value + divisor - 1) / divisor); }++void Shape(const Rule& rule, uint32_t w, uint32_t h, uint32_t channels, Entry& entry) {+ entry.grid[1] = entry.grid[2] = 1;+ switch (rule.grid) {+ case Grid::W16H4: entry.grid[0] = Ceil(w, 16); entry.grid[1] = Ceil(h, 4); entry.grid[2] = rule.z; break;+ case Grid::Flat16: entry.grid[0] = Ceil(uint64_t(w) * h, 16); entry.grid[2] = rule.z; break;+ case Grid::Flat32: entry.grid[0] = Ceil(uint64_t(w) * h, 32); entry.grid[2] = rule.z; break;+ case Grid::Flat64: entry.grid[0] = Ceil(uint64_t(w) * h, 64); entry.grid[2] = rule.z; break;+ case Grid::Pool2048: entry.grid[0] = Ceil(uint64_t(w) * h * channels, 2048); break;+ default: break;+ }+ entry.block[0] = rule.block;+ entry.block[1] = entry.block[2] = 1;+ entry.sharedBytes = 0;+}++// A specialized kernel with NVIDIA's parameters; dimensions are the output's.+int LaunchVariant(LaunchFn original, void* list, const Entry& entry, const Rule& rule, uint32_t w, uint32_t h, uint32_t channels) {+ Entry variant = entry;+ variant.function = Function(rule.resource);+ Shape(rule, w, h, channels, variant);+ return original(list, &variant, 1);+}++bool Dl2Shaped(const Dl2Rule& rule, const Entry& entry) {+ if (!entry.params || entry.paramBytes != rule.paramBytes) return false;+ for (const auto& [word, value] : rule.shape)+ if (word && Field<uint32_t>(entry.params, word * 4u) != value) return false;+ return true;+}++void Dl2Shape(const Dl2Rule& rule, const void* params, Entry& entry) {+ const uint32_t h = Field<uint32_t>(params, rule.hWord * 4u), w = Field<uint32_t>(params, rule.wWord * 4u);+ if (rule.dy) {+ entry.grid[0] = Ceil(w, rule.dx);+ entry.grid[1] = Ceil(h, rule.dy);+ entry.grid[2] = rule.z;+ } else {+ entry.grid[0] = Ceil(uint64_t(w) * h, rule.dx);+ entry.grid[1] = rule.z;+ entry.grid[2] = 1;+ }+ entry.block[0] = rule.block;+ entry.block[1] = entry.block[2] = 1;+ entry.sharedBytes = 0;+}++// Held producer (merge or central block) + its conv: one fused launch. The+// producer's output is the conv's input; the fused kernel never writes it.+// Returns false, launching nothing, when the two do not chain.+bool Dl2Fuse(LaunchFn original, void* list, const Dl2Rule& rule, const Entry& conv, bool central, int& status) {+ const uint8_t* producer = t_state.dl2.params.data();+ const void* p = conv.params;+ const uint32_t ih = Field<uint32_t>(p, 44), iw = Field<uint32_t>(p, 48);+ // merge: out, 3 inputs, h, w, factor; central block: out, 6 inputs, w, h, factor.+ const size_t inputs = central ? 6 : 3;+ const uint32_t ph = Field<uint32_t>(producer, 8 + inputs * 8 + (central ? 4 : 0));+ const uint32_t pw = Field<uint32_t>(producer, 8 + inputs * 8 + (central ? 0 : 4));+ if (Field<uint64_t>(producer, 0) != Field<uint64_t>(p, 32) || ph != ih || pw != iw) return false;+ // weights, bias, the producer's inputs, the conv's output, then+ // in h, w, out h, w and the producer's blend factor.+ std::array<uint8_t, 92> params{};+ const uint32_t tail[5] = {ih, iw, Field<uint32_t>(p, 68), Field<uint32_t>(p, 72), Field<uint32_t>(producer, 16 + inputs * 8)};+ std::memcpy(params.data(), p, 16);+ std::memcpy(params.data() + 16, producer + 8, inputs * 8);+ std::memcpy(params.data() + 16 + inputs * 8, static_cast<const uint8_t*>(p) + 56, 8);+ std::memcpy(params.data() + 24 + inputs * 8, tail, sizeof(tail));+ Entry fused{};+ fused.function = Function(rule.resource);+ Dl2Shape(rule, p, fused);+ fused.params = params.data();+ fused.paramBytes = static_cast<uint32_t>(24 + inputs * 8 + sizeof(tail)); // 68 or 92+ t_state.held = Dl2::Count;+ status = original(list, &fused, 1);+ return true;+}++int Dl2Launch(LaunchFn original, void* list, const Entry& entry, Dl2 layer) {+ auto& s = t_state;+ const Dl2Rule& rule = kDl2Rules[size_t(layer)];+ if (layer == Dl2::InitialMerge || layer == Dl2::CentralBlock) {+ Flush(original);+ if (entry.params && entry.paramBytes == rule.paramBytes && Capture(entry, s.dl2)) {+ s.held = layer;+ return 0;+ }+ return original(list, &entry, 1);+ }+ const Dl2 producer = layer == Dl2::ConvPre ? Dl2::InitialMerge : layer == Dl2::B1Conv0 ? Dl2::CentralBlock : Dl2::Count;+ if (producer != Dl2::Count) {+ int status = 0;+ if (s.held == producer && Dl2Shaped(rule, entry) && Dl2Fuse(original, list, rule, entry, producer == Dl2::CentralBlock, status)) {+ if (layer == Dl2::ConvPre && optimizedDl2Runs.fetch_add(1, std::memory_order_relaxed) == 0)+ log::info(kTag, std::format("network optimization: first optimized DL2 run ({}x{})", Field<uint32_t>(entry.params, 72),+ Field<uint32_t>(entry.params, 68)));+ return status;+ }+ Flush(original);+ return original(list, &entry, 1);+ }+ Flush(original);+ if (!Dl2Shaped(rule, entry)) return original(list, &entry, 1);+ Entry variant = entry;+ variant.function = Function(rule.resource);+ Dl2Shape(rule, entry.params, variant);+ return original(list, &variant, 1);+}++int __cdecl HookLaunch(void* list, const void* entries, uint32_t count) {+ const auto original = global().launch.load(std::memory_order_acquire);+ auto& s = t_state;+ if (!ready.load(std::memory_order_acquire) || count != 1 || !entries || !Enabled()) {+ Stop(original);+ return original(list, entries, count);+ }+ if (s.list != list) {+ Stop(original);+ s.list = list;+ }+ const Entry& entry = *static_cast<const Entry*>(entries);+ Role role;+ {+ std::lock_guard lock(mutex);+ const auto found = kinds.find(entry.function);+ if (found != kinds.end()) role = found->second;+ }+ const Kind kind = role.kind;+ if (kind == Kind::Dl2) return Dl2Launch(original, list, entry, role.layer);+ if (s.held != Dl2::Count) Flush(original); // a held DL2 producer not followed by its conv+ if (kind == Kind::NetworkStart) {+ Stop(original);+ s.active = true;+ s.conv = s.level = 0;+ return original(list, entries, count);+ }+ if (!s.active) return original(list, entries, count);+ switch (kind) {+ case Kind::Pool:+ Flush(original);+ if (entry.paramBytes == kPoolRule.paramBytes && entry.params)+ return LaunchVariant(original, list, entry, kPoolRule, Field<uint32_t>(entry.params, 24), Field<uint32_t>(entry.params, 28),+ Field<uint32_t>(entry.params, 32));+ break;+ case Kind::Upscale:+ Flush(original);+ if (++s.level <= 5 && entry.paramBytes == 40 && Capture(entry, s.upscale)) {+ s.haveUpscale = true;+ return 0;+ }+ break;+ case Kind::ElementWise:+ if (s.haveUpscale && !s.haveAdd && entry.paramBytes == 52 && Capture(entry, s.add) &&+ Field<uint64_t>(s.add.params.data(), 0) == Field<uint64_t>(s.upscale.params.data(), 8)) {+ s.haveAdd = true;+ return 0;+ }+ break;+ case Kind::Conv: {+ if (s.conv >= 17 || entry.paramBytes != kConvRules[s.conv].paramBytes || !entry.params) break;+ const Rule& rule = kConvRules[s.conv++];+ const uint32_t w = Field<uint32_t>(entry.params, entry.paramBytes - 8);+ const uint32_t h = Field<uint32_t>(entry.params, entry.paramBytes - 4);+ if (rule.resource) {+ if (s.haveUpscale || s.haveAdd) break;+ return LaunchVariant(original, list, entry, rule, w, h, 0);+ }+ // The conv after a decoder add: fuse upscale + add + conv.+ if (!s.haveUpscale || !s.haveAdd || s.level < 1 || s.level > 5) break;+ const uint8_t* up = s.upscale.params.data();+ const uint8_t* add = s.add.params.data();+ const uint32_t lh = Field<uint32_t>(up, 16), lw = Field<uint32_t>(up, 20);+ const uint32_t hh = Field<uint32_t>(up, 24), hw = Field<uint32_t>(up, 28);+ const bool chained = Field<uint64_t>(entry.params, 8) == Field<uint64_t>(add, 16) && w == hw && h == hh &&+ Field<uint32_t>(add, 24) == hw && Field<uint32_t>(add, 28) == hh && hw == 2 * lw && hh == 2 * lh;+ if (!chained) break;+ struct Params { uint64_t weights, low, skip, out; uint32_t lw, lh, hw, hh; } params{+ Field<uint64_t>(entry.params, 0), Field<uint64_t>(up, 0), Field<uint64_t>(add, 8), Field<uint64_t>(entry.params, 24), lw, lh, hw, hh};+ static_assert(sizeof(Params) == 48);+ const Rule& fusedRule = kFusedRules[s.level - 1];+ Entry fused{};+ fused.function = Function(fusedRule.resource);+ Shape(fusedRule, hw, hh, 0, fused);+ fused.params = ¶ms;+ fused.paramBytes = sizeof(params);+ s.haveUpscale = s.haveAdd = false;+ if (optimizedRuns.fetch_add(1, std::memory_order_relaxed) == 0)+ log::info(kTag, std::format("network optimization: first optimized DL1 run (decoder level {} fused, {}x{})", s.level, hw, hh));+ return original(list, &fused, 1);+ }+ case Kind::NetworkEnd:+ Stop(original);+ return original(list, entries, count);+ default:+ break;+ }+ // Anything unexpected: replay what is held, run this launch as is, and+ // leave the rest of this network run untouched.+ Stop(original);+ return original(list, entries, count);+}++void reset() {+ std::lock_guard lock(mutex);+ kinds.clear();+ functions.clear();+ device = nullptr;+ ready = false;+ failed = false;+ optimizedRuns = 0;+ optimizedDl2Runs = 0;+}+} // namespace net++// ---------------------------------------------------------------------------+// NvAPI entry point: the provider resolves nvapi_QueryInterface through its+// own GetProcAddress import; only that slot is redirected.+// ---------------------------------------------------------------------------+template <typename T> void* wrap(std::atomic<T>& original, void* function, void* hook) {+ const auto fn = reinterpret_cast<T>(function);+ T expected = nullptr;+ return original.compare_exchange_strong(expected, fn) || expected == fn ? hook : function;+}++void* __cdecl HookQueryInterface(uint32_t id) {+ auto& g = global();+ void* function = g.realQuery.load(std::memory_order_acquire)(id);+ if (!function || !g.active.load(std::memory_order_acquire) || !g.options.optimizedKernels) return function;+ if (id == 0xAD1A677Du) return wrap(g.createModule, function, reinterpret_cast<void*>(&HookCreateModule)); // NvAPI_D3D12_CreateCuModule+ if (id == 0xE2436E22u) return wrap(g.createFunction, function, reinterpret_cast<void*>(&net::HookFunction)); // NvAPI_D3D12_CreateCuFunction+ if (id == 0x24973538u) return wrap(g.launch, function, reinterpret_cast<void*>(&net::HookLaunch)); // NvAPI_D3D12_LaunchCuKernelChain+ return function;+}++FARPROC WINAPI HookGetProcAddress(HMODULE module, LPCSTR name) {+ auto& g = global();+ const FARPROC function = g.realGetProc.load(std::memory_order_acquire)(module, name);+ if (!function || reinterpret_cast<uintptr_t>(name) <= 0xFFFF || std::strcmp(name, "nvapi_QueryInterface") != 0 ||+ !g.active.load(std::memory_order_acquire))+ return function;+ const auto real = reinterpret_cast<QueryInterfaceFn>(function);+ QueryInterfaceFn expected = nullptr;+ if (!g.realQuery.compare_exchange_strong(expected, real) && expected != real) return function;+ g.resolutions.fetch_add(1, std::memory_order_relaxed);+ return reinterpret_cast<FARPROC>(&HookQueryInterface);+}++bool readFile(const std::filesystem::path& path, std::string& out) {+ std::ifstream in(path, std::ios::binary);+ if (!in) return false;+ out.assign(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());+ return !out.empty();+}++// Kernel files are user-replaceable runtime data: their identity is logged,+// not enforced (2026-09-11 decision); the provider fingerprint guard and the+// per-launch shape checks still decide whether they run.+void loadKernels(Global& g) {+ g.networkPtx.clear();+ g.outputPull.clear();+ g.outputPushFine.clear();+ g.imageReplacements = false;+ if (!g.options.optimizedKernels || g.options.kernelDirectory.empty()) return;+ const std::filesystem::path dir(g.options.kernelDirectory);+ size_t bytes = 0;+ for (uint16_t id : net::resources()) {+ std::string text;+ if (readFile(dir / std::format(L"k{}.ptx", id), text)) {+ bytes += text.size();+ g.networkPtx.emplace(id, std::move(text));+ }+ }+ g.imageReplacements = readFile(dir / L"OutputPull.ptx", g.outputPull) && readFile(dir / L"OutputPushFine.ptx", g.outputPushFine);+ std::string pullHash = g.outputPull.empty() ? "-" : sha256Hex(reinterpret_cast<const uint8_t*>(g.outputPull.data()), g.outputPull.size());+ log::info(kTag, std::format("optimized kernels dir={} network={}/{} ({} bytes) imageReplacements={} OutputPull sha256={}",+ utf8(dir), g.networkPtx.size(), net::resources().size(), bytes, g.imageReplacements, pullHash));+ if (g.networkPtx.size() != net::resources().size()) g.networkPtx.clear(); // partial sets never run+}++bool rollback(Global& g) {+ bool restored = true;+ for (auto it = g.writes.rbegin(); it != g.writes.rend(); ++it)+ restored = compat::restoreMemory(it->address, it->original.data(), it->original.size()) && restored;+ if (!restored) return false; // retain records and backing storage+ g.writes.clear();+ for (void* allocation : g.allocations) VirtualFree(allocation, 0, MEM_RELEASE);+ g.allocations.clear();+ return true;+}++} // namespace++bool DlssgTransfusion::moduleIsKnown(uint64_t size, const std::string& sha256Upper) {+ return size == kKnownModuleSize && sha256Upper == kKnownModuleSha256;+}++bool DlssgTransfusion::moduleIsKnown(const std::wstring& path) {+ FileIdentity identity;+ IdentityError error;+ return computeFileIdentity(path, identity, error) && moduleIsKnown(identity.sizeBytes, identity.sha256Upper);+}++DlssgTransfusion::Options DlssgTransfusion::defaultOptions(const std::wstring& kernelDirectory) {+ Options options;+ options.kernelDirectory = kernelDirectory;+ options.blackwellKernels = !env(L"VEYRA_DLSSG_TF_DISABLE_BLACKWELL");+ options.qualityValidWarp = !env(L"VEYRA_DLSSG_TF_DISABLE_QUALITY");+ options.optimizedKernels = !env(L"VEYRA_DLSSG_TF_DISABLE_OPTIMIZED");+ wchar_t policy[32]{};+ if (GetEnvironmentVariableW(L"VEYRA_DLSSG_TF_QUALITY_POLICY", policy, 32) > 0 && std::wstring(policy) == L"transfusion")+ options.explainedWarp = false;+ return options;+}++DlssgTransfusion::State DlssgTransfusion::apply(HMODULE module, Target target, const Options& options) {+ auto& g = global();+ std::lock_guard lock(g.mutex);+ State state;+ state.target = target;+ if (g.module || !g.writes.empty()) {+ state.detail = L"already applied in this process; release first";+ return state;+ }+ const auto* nt = imageHeaders(module);+ if (!nt || nt->FileHeader.TimeDateStamp != kKnownTimeDateStamp || nt->OptionalHeader.SizeOfImage != kKnownSizeOfImage) {+ state.detail = L"runtime identity (TimeDateStamp/SizeOfImage) does not match DLSS-G 310.9.1";+ g.state = state;+ return state;+ }+ state.identityVerified = true;+ const uint32_t arch = target == Target::Ampere ? kAmpereArchId : kAdaArchId;+ state.targetSm = target == Target::Ampere ? 86u : 89u;+ g.options = options;+ g.targetSm = state.targetSm;+ g.exactProviderKernels = false;+ g.resolutions = g.accepted = g.rejected = g.rewritten = 0;+ net::reset();+ auto refuse = [&](std::wstring why) {+ const bool restored = rollback(g);+ state.detail = why + (restored ? L"; rolled back" : L"; ROLLBACK UNPROVEN");+ state.applied = false;+ g.module = restored ? nullptr : module;+ g.state = state;+ log::error(kTag, utf8(state.detail));+ return state;+ };+ g.module = module;+ if (target == Target::Ampere) {+ state.minimumArchitectureExports = PatchDlssgMinimumArchitecture(module, arch);+ if (state.minimumArchitectureExports != kExpectedMinimumArchitectureExports) return refuse(L"minimum architecture exports mismatch");+ }+ state.archGateSites = PatchDlssgArchGates(module, arch);+ if (state.archGateSites != kExpectedArchGateSites) return refuse(L"arch gate sites mismatch");+ state.validatorPatched = PatchValidator(module);+ if (!state.validatorPatched) return refuse(L"count/index validator not patched");+ const auto provider = PatchProvider(module, state.targetSm, options);+ state.blackwellKernels = provider.blackwell;+ state.descriptorSlots = provider.descriptors;+ state.retargetedContainers = provider.retargeted;+ if (!provider.ok) return refuse(L"provider kernel patch failed");+ loadKernels(g);+ state.networkKernelsLoaded = g.networkPtx.size();+ state.imageKernelsLoaded = g.imageReplacements;+ if (options.optimizedKernels) {+ void** slot = findImportSlot(module, "GetProcAddress");+ if (!slot || !*slot) return refuse(L"GetProcAddress import slot not found");+ GetProcAddressFn expected = nullptr;+ const auto real = reinterpret_cast<GetProcAddressFn>(*slot);+ if (!g.realGetProc.compare_exchange_strong(expected, real) && expected != real) return refuse(L"GetProcAddress import changed");+ const void* hook = reinterpret_cast<const void*>(&HookGetProcAddress);+ if (!patchBytes(slot, &hook, sizeof(hook))) return refuse(L"GetProcAddress import slot not written");+ state.nvapiHooked = true;+ }+ state.writes = g.writes.size();+ state.applied = true;+ g.active = true;+ state.detail = std::format(L"target=sm_{} blackwell={} descriptors={} retargeted={} writes={} optimized={} network={} image={}",+ state.targetSm, state.blackwellKernels, state.descriptorSlots, state.retargetedContainers, state.writes,+ options.optimizedKernels, state.networkKernelsLoaded, state.imageKernelsLoaded);+ g.state = state;+ log::info(kTag, utf8(state.detail));+ return state;+}++bool DlssgTransfusion::release() {+ auto& g = global();+ std::lock_guard lock(g.mutex);+ if (!g.module && g.writes.empty()) return true;+ g.active = false;+ const bool restored = rollback(g);+ log::info(kTag, std::format("release restored={} nvapiResolutions={} modules accepted={} rejected={} rewritten={} dl1Runs={} dl2Runs={}",+ restored, g.resolutions.load(), g.accepted.load(), g.rejected.load(), g.rewritten.load(),+ net::optimizedRuns.load(), net::optimizedDl2Runs.load()));+ if (restored) {+ g.module = nullptr;+ g.state = State{};+ }+ return restored;+}++DlssgTransfusion::State DlssgTransfusion::snapshot() {+ auto& g = global();+ std::lock_guard lock(g.mutex);+ return g.state;+}++DlssgTransfusion::Counters DlssgTransfusion::counters() {+ auto& g = global();+ Counters c;+ c.nvapiResolutions = g.resolutions.load();+ c.modulesAccepted = g.accepted.load();+ c.modulesRejected = g.rejected.load();+ c.modulesRewritten = g.rewritten.load();+ c.exactProviderKernels = g.exactProviderKernels.load();+ c.networkReady = net::ready.load();+ c.networkFailed = net::failed.load();+ c.optimizedDl1Runs = net::optimizedRuns.load();+ c.optimizedDl2Runs = net::optimizedDl2Runs.load();+ return c;+}++bool DlssgTransfusion::applied() {+ return global().active.load(std::memory_order_acquire);+}++} // namespace veyra::ngxdiff --git a/src/ngx/FgCompatibilitySession.cpp b/src/ngx/FgCompatibilitySession.cppindex 81a77da9..2935716a 100644--- a/src/ngx/FgCompatibilitySession.cpp+++ b/src/ngx/FgCompatibilitySession.cpp@@ -5,6 +5,7 @@#include "veyra/ngx/FgCompatibilitySession.h"#include "veyra/ngx/AdaMfgUnlock.h"#include "veyra/ngx/AmpereMfgUnlock.h"+#include "veyra/ngx/DlssgTransfusion.h"#include "veyra/ngx/NvapiArchSpoof.h"#include "veyra/FileIdentity.h"#include "veyra/Log.h"@@ -60,10 +61,15 @@ struct FgCompatibilitySession::Impl {Microsoft::WRL::ComPtr<ID3D12Device> device;std::vector<Microsoft::WRL::ComPtr<ID3D12Resource>> resources;uint64_t serial=0;+ // transfusion: the 310.9.1 provider, patched by DlssgTransfusion instead of+ // the audited-310.7 Ada/Ampere unlocks. driverGates: scoped NGX core gates+ // located (required on 310.7, optional on 310.9.1).+ bool transfusion=false, driverGates=false;bool ampere=false, ready=false, allocated=false, initializing=false, initialized=false, startup=false, createAttempted=false, fatal=false, uncertainGate=false;Patch metadata,validation;uintptr_t deviceGate=0;bool programs() const {+ if(transfusion){const auto s=DlssgTransfusion::snapshot();return s.applied&&s.identityVerified;}if(ampere){const auto s=AmpereMfgUnlock::snapshot();return s.applied&&s.identityVerified&&s.fatbinsRedirected;}const auto s=AdaMfgUnlock::snapshot();return s.applied&&s.identityVerified&&s.kernelPatched&&s.mfgGatePatched;}@@ -80,6 +86,7 @@ FgCompatibilitySession::~FgCompatibilitySession(){const auto result=protected_pointer::ReplaceProtectedBytes(s.deviceGate,before,after,2,PAGE_EXECUTE_READ,&VirtualProtect,&FlushInstructionCache,PAGE_EXECUTE_READWRITE);restored=(result.disposition==protected_pointer::PublishDisposition::ePublishedRestored)&&restored;}+ restored=DlssgTransfusion::release()&&restored;restored=AdaMfgUnlock::release()&&restored;restored=AmpereMfgUnlock::release()&&restored;restored=NvapiArchSpoof::release()&&restored;@@ -111,7 +118,8 @@ bool FgCompatibilitySession::open(ID3D12Device* device,uint32_t vendor,uint32_tcomputeFileIdentity(path.wstring(),identity,error);log::info("fg-compat",std::format("provider path={} sha256={} bytes={} generation={} LUID={:08X}:{:08X} adapter=0x{:04X}",path.string(),identity.sha256Upper,identity.sizeBytes,s.serial,uint32_t(device->GetAdapterLuid().HighPart),device->GetAdapterLuid().LowPart,deviceId));- if(identity.sha256Upper!=AdaMfgUnlock::kKnownModuleSha256)return false;+ s.transfusion=DlssgTransfusion::moduleIsKnown(identity.sizeBytes,identity.sha256Upper);+ if(identity.sha256Upper!=AdaMfgUnlock::kKnownModuleSha256&&!s.transfusion)return false;s.provider=LoadLibraryExW(path.c_str(),nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_SYSTEM32);if(!s.provider)return false;wchar_t actual[32768]{};@@ -119,18 +127,29 @@ bool FgCompatibilitySession::open(ID3D12Device* device,uint32_t vendor,uint32_tconst auto entry=GetProcAddress(s.provider,"NVSDK_NGX_D3D12_CreateFeature");MEMORY_BASIC_INFORMATION memory{};if(!entry||!VirtualQuery(reinterpret_cast<const void*>(entry),&memory,sizeof(memory))||memory.AllocationBase!=s.provider)return false;- log::info("fg-compat",std::format("provider module=0x{:X} ownedCreate=0x{:X}",uintptr_t(s.provider),uintptr_t(entry)));+ log::info("fg-compat",std::format("provider module=0x{:X} ownedCreate=0x{:X} profile={}",uintptr_t(s.provider),uintptr_t(entry),s.transfusion?"310.9.1-transfusion":"310.7-audited"));+ if(s.transfusion){+ // Patched before NGX initializes the provider: its NvAPI entry point+ // and CUDA programs are resolved during Init.+ const auto options=DlssgTransfusion::defaultOptions((std::filesystem::path(directory)/L"dlssg-kernels").wstring());+ const auto state=DlssgTransfusion::apply(s.provider,s.ampere?DlssgTransfusion::Target::Ampere:DlssgTransfusion::Target::Ada,options);+ log::info("fg-compat",std::format("310.9.1 provider patches applied={} target={}",state.applied,s.ampere?"ampere":"ada"));+ if(!state.applied)return false;+ }return true;}+bool FgCompatibilitySession::transfusionProfile() const{return impl_->transfusion;}HMODULE FgCompatibilitySession::provider() const{return impl_->provider;}bool FgCompatibilitySession::prepareDriver(const std::wstring& directory,const char* project,const char* engine) {auto& s=*impl_;if(!s.provider||!s.programs()){log::error("fg-compat","prepareDriver: provider/programs missing");return false;}if(!s.ampere){s.ready=true;return true;}+ uintptr_t gate=0;+ compat::Image providerImage;if(!providerImage.Open(s.provider)){log::error("fg-compat","prepareDriver: invalid image");return false;}+ // On 310.9.1 DlssgTransfusion already removed the same count-policy branch.+ if(!s.transfusion){// The audited legacy provider has one preset. Preserve all count/index// checks, changing only its Blackwell-only choice of maximum=5.- compat::Image providerImage;if(!providerImage.Open(s.provider)){log::error("fg-compat","prepareDriver: invalid image");return false;}constexpr uint8_t pattern[]={0x84,0xd2,0x0f,0x84,0x03,0x01,0,0,0xbe,5,0,0,0};- uintptr_t gate=0;const auto* sections=IMAGE_FIRST_SECTION(providerImage.nt);for(unsigned i=0;i<providerImage.nt->FileHeader.NumberOfSections;++i){const auto& section=sections[i];@@ -158,6 +177,7 @@ bool FgCompatibilitySession::prepareDriver(const std::wstring& directory,const cif(patched.disposition==protected_pointer::PublishDisposition::ePublishedRestored)s.deviceGate=gate+2;if(patched.disposition==protected_pointer::PublishDisposition::eIndeterminate)s.uncertainGate=true;if(patched.disposition!=protected_pointer::PublishDisposition::ePublishedRestored){log::error("fg-compat",std::format("prepareDriver: count policy publication disposition={}",uint32_t(patched.disposition)));return false;}+ }Microsoft::WRL::ComPtr<IDXGIFactory4> factory;Microsoft::WRL::ComPtr<IDXGIAdapter> adapter;if(FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))||FAILED(factory->EnumAdapterByLuid(s.device->GetAdapterLuid(),IID_PPV_ARGS(&adapter))))return false;@@ -191,7 +211,15 @@ bool FgCompatibilitySession::prepareDriver(const std::wstring& directory,const cif(!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,reinterpret_cast<LPCWSTR>(module),&s.driver)||s.driver!=module)return false;metadata=m;validation=v;}- if(!s.driver)return false;+ if(!s.driver){+ if(!s.transfusion)return false;+ // 310.9.1: the provider's own minimum architecture was lowered, which+ // admits Ampere through the unmodified NGX core (upstream-validated).+ log::info("fg-compat","NGX core gates not located; 310.9.1 relies on the provider minimum-architecture patch");+ s.ready=s.programs();+ return s.ready;+ }+ s.driverGates=true;s.metadata={metadata+ampere_patterns::kAmpereNgxMetadataBranchOffset,ampere_patterns::kAmpereNgxMetadataOriginal};s.validation={validation+ampere_patterns::kAmpereNgxCreateValidationBranchOffset,ampere_patterns::kAmpereNgxCreateValidationOriginal};if(!s.metadata.set(true))return false;@@ -232,15 +260,15 @@ bool FgCompatibilitySession::beginInitialization(){if(!s.ready||!s.allocated||s.initializing||s.initialized||s.createAttempted||s.fatal)return false;// NGX caches provider initialization failures before the capability query.// Upstream BeginStartup covers this call as well as GetCapabilityParameters.- if(s.ampere&&!s.metadata.set(true)){s.fatal=true;return false;}+ if(s.driverGates&&!s.metadata.set(true)){s.fatal=true;return false;}s.initializing=true;- log::info("fg-compat",std::format("Init scope generation={} ampereMetadata={}",s.serial,s.ampere));+ log::info("fg-compat",std::format("Init scope generation={} ampereMetadata={}",s.serial,s.driverGates));return true;}bool FgCompatibilitySession::endInitialization(bool success){auto& s=*impl_;if(!s.initializing)return false;- const bool restored=!s.ampere||s.metadata.set(false);+ const bool restored=!s.driverGates||s.metadata.set(false);s.initializing=false;s.initialized=success&&restored;s.fatal|=!restored||!success;log::info("fg-compat",std::format("Init completed generation={} success={} metadataRestored={}",s.serial,success,restored));@@ -248,10 +276,10 @@ bool FgCompatibilitySession::endInitialization(bool success){}bool FgCompatibilitySession::beginCapabilities(){auto& s=*impl_;if(!s.ready||!s.allocated||!s.initialized||s.initializing||s.createAttempted||s.fatal)return false;- if(s.ampere&&!s.metadata.set(true)){s.fatal=true;return false;}return true;+ if(s.driverGates&&!s.metadata.set(true)){s.fatal=true;return false;}return true;}bool FgCompatibilitySession::endCapabilities(){- auto& s=*impl_;if(s.ampere&&!s.metadata.set(false)){s.fatal=true;return false;}return !s.fatal;+ auto& s=*impl_;if(s.driverGates&&!s.metadata.set(false)){s.fatal=true;return false;}return !s.fatal;}bool FgCompatibilitySession::publishStartup(NVSDK_NGX_Parameter* parameters){auto& s=*impl_;@@ -276,12 +304,12 @@ bool FgCompatibilitySession::beginCreate(ID3D12GraphicsCommandList* list){if(!list||!s.startup||s.createAttempted||s.fatal||!s.programs()||!s.allocated||FAILED(list->GetDevice(IID_PPV_ARGS(&device)))||device.Get()!=s.device.Get()||!sameLuid(device->GetAdapterLuid(),s.device->GetAdapterLuid()))return false;s.createAttempted=true;- if(s.ampere&&!s.validation.set(true)){s.fatal=true;return false;}+ if(s.driverGates&&!s.validation.set(true)){s.fatal=true;return false;}return true;}bool FgCompatibilitySession::endCreate(bool success){auto& s=*impl_;- if(s.ampere&&!s.validation.set(false))s.fatal=true;+ if(s.driverGates&&!s.validation.set(false))s.fatal=true;log::info("fg-compat",std::format("Create completed generation={} success={} driverGateRestored={}",s.serial,success,!s.fatal));return !s.fatal;}diff --git a/src/ngx/TrueHdrBackend.cpp b/src/ngx/TrueHdrBackend.cppindex 388b31ab..4f2ab3ba 100644--- a/src/ngx/TrueHdrBackend.cpp+++ b/src/ngx/TrueHdrBackend.cpp@@ -25,11 +25,18 @@ NVSDK_NGX_Result getCapabilities(NVSDK_NGX_Parameter** caps,unsigned& seh){return NVSDK_NGX_D3D12_GetCapabilityParameters(caps);} __except(EXCEPTION_EXECUTE_HANDLER){seh=GetExceptionCode();return NVSDK_NGX_Result_FAIL_PlatformError;}}+// GetCapabilityParameters hands out a block that NgxCoreHost never allocated,+// so it must not go through the core's allocate/destroy tracking table.+NVSDK_NGX_Result destroyCapabilities(NVSDK_NGX_Parameter* caps,unsigned& seh){+ seh=0;+ __try {return NVSDK_NGX_D3D12_DestroyParameters(caps);}+ __except(EXCEPTION_EXECUTE_HANDLER){seh=GetExceptionCode();return NVSDK_NGX_Result_FAIL_PlatformError;}+}NVSDK_NGX_Result getCapability(NVSDK_NGX_Parameter* caps,const char* key,int* value,unsigned& seh){__try {return caps->Get(key,value);}__except(EXCEPTION_EXECUTE_HANDLER){seh=GetExceptionCode();return NVSDK_NGX_Result_FAIL_PlatformError;}}-void capability(NgxCoreHost& core){+void capability(){NVSDK_NGX_Parameter* caps=nullptr;unsigned seh=0;const auto r=getCapabilities(&caps,seh);report(3,r,seh);@@ -40,7 +47,10 @@ void capability(NgxCoreHost& core){log::info("video-hdr",std::format("capability {}={} result=0x{:X} seh=0x{:X}",key,value,unsigned(result),seh));if(seh)break;}- core.destroyParameters(caps);+ unsigned destroySeh=0;+ const auto destroyed=destroyCapabilities(caps,destroySeh);+ const auto message=std::format("capability parameters destroyed result=0x{:X} seh=0x{:X}",unsigned(destroyed),destroySeh);+ if(NVSDK_NGX_SUCCEED(destroyed)&&!destroySeh)log::info("video-hdr",message);else log::error("video-hdr",message);}}bool TrueHdrBackend::create(NgxCoreHost& core,ID3D12GraphicsCommandList* list,const std::wstring& directory){@@ -50,7 +60,7 @@ bool TrueHdrBackend::create(NgxCoreHost& core,ID3D12GraphicsCommandList* list,comodule_=LoadLibraryExW(path.c_str(),nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_SYSTEM32);if(!module_){log::error("video-hdr",std::format("absolute runtime load failed win32={}",GetLastError()));return false;}log::info("video-hdr","loaded nvngx_truehdr.dll from explicit runtime directory; input=sRGB/RGBA8 output=linear-BT709/scRGB-FP16 (1=80nits)");- capability(core);+ capability();core_=&core;Status st=Status::Ok;params_=core.allocateParameters(st);if(!params_)return false;params_->Set("CreationNodeMask",1u);params_->Set("VisibilityNodeMask",1u);unsigned seh=0;const auto result=invoke(0,list,params_,&handle_,seh);diff --git a/src/ngx/transfusion/LICENSE.txt b/src/ngx/transfusion/LICENSE.txtnew file mode 100644index 00000000..c17ab9cd--- /dev/null+++ b/src/ngx/transfusion/LICENSE.txt@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Michael Robles++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/src/ngx/transfusion/quality_explained_warp.h b/src/ngx/transfusion/quality_explained_warp.hnew file mode 100644index 00000000..cd243f28--- /dev/null+++ b/src/ngx/transfusion/quality_explained_warp.h@@ -0,0 +1,117 @@+// Ported unchanged from SilyNoMeta/DLSSG-Transfusion (MIT) tag v1.4.5.3-rtx20-30-40,+// commit b56bd2deed114507ad2c88f986d90ed50ffb4639, source/native/quality_explained_warp.h.+// Copyright (c) 2026 Michael Robles (TonyJoaca/DLSSG-Transfusion), fork by SilyNoMeta; MIT, see LICENSE.txt.+#pragma once+// Explained-warp policy: dlssg_for_sm86's tuning of the valid-warp technique+// invented by Tony Joaca for Transfusion. A candidate takes the full warp when+// the warp explains the change between the two source frames, where+// Transfusion's own policy requires the two warped candidates to agree. It is+// that project's third iteration (v0.3.5-5, its "V3"; unrelated to+// Transfusion's V4): its 310.9.1-11 V1 without the UIR rule and without the+// asymmetric copy, on the Blackwell blend layout.+// Generated by dlssg_for_sm86 tools/companion/quality_program.py+// program_v3('blackwell'); kept byte-identical to that generator. Inserted at+// the same anchor as Transfusion's policy (before the UIR flag load), alternative+// to it, never combined.+//+// valid_i = finite warp inside the half-texel border+// explained = both valid, Em + 0.08 < Es and Em < 0.15 (warp explains the change)+// forced_i = valid_i, NVIDIA weight c_i >= 0.20, Es > 0.25, not explained+// explained or forced_i -> output_i = W_i (full warp); otherwise NVIDIA's blend+//+// Es / Em: RGB L1 difference of the two candidates, unwarped / warped.+#include <string_view>++namespace quality_fix+{+inline constexpr std::string_view kPolicyExplainedWarp = R"ptx(+{ // SM86_QUALITY_VALID_WARP_V3+.reg .f32 %qw_f<16>;+.reg .pred %qw_p<12>;+cvt.rn.f32.u32 %qw_f0, %r10;+div.approx.ftz.f32 %qw_f0, 0f3F000000, %qw_f0;+sub.f32 %qw_f2, 0f3F800000, %qw_f0;+cvt.rn.f32.u32 %qw_f1, %r11;+div.approx.ftz.f32 %qw_f1, 0f3F000000, %qw_f1;+sub.f32 %qw_f3, 0f3F800000, %qw_f1;+not.pred %qw_p0, %p17;+setp.ge.f32 %qw_p2, %f123, %qw_f0;+and.pred %qw_p0, %qw_p0, %qw_p2;+setp.le.f32 %qw_p2, %f123, %qw_f2;+and.pred %qw_p0, %qw_p0, %qw_p2;+setp.ge.f32 %qw_p2, %f124, %qw_f1;+and.pred %qw_p0, %qw_p0, %qw_p2;+setp.le.f32 %qw_p2, %f124, %qw_f3;+and.pred %qw_p0, %qw_p0, %qw_p2;+abs.f32 %qw_f12, %f125;+abs.f32 %qw_f13, %f126;+abs.f32 %qw_f14, %f127;+add.f32 %qw_f12, %qw_f12, %qw_f13;+add.f32 %qw_f12, %qw_f12, %qw_f14;+setp.lt.f32 %qw_p2, %qw_f12, 0f7F800000;+and.pred %qw_p0, %qw_p0, %qw_p2;+not.pred %qw_p1, %p16;+setp.ge.f32 %qw_p2, %f129, %qw_f0;+and.pred %qw_p1, %qw_p1, %qw_p2;+setp.le.f32 %qw_p2, %f129, %qw_f2;+and.pred %qw_p1, %qw_p1, %qw_p2;+setp.ge.f32 %qw_p2, %f130, %qw_f1;+and.pred %qw_p1, %qw_p1, %qw_p2;+setp.le.f32 %qw_p2, %f130, %qw_f3;+and.pred %qw_p1, %qw_p1, %qw_p2;+abs.f32 %qw_f12, %f131;+abs.f32 %qw_f13, %f132;+abs.f32 %qw_f14, %f133;+add.f32 %qw_f12, %qw_f12, %qw_f13;+add.f32 %qw_f12, %qw_f12, %qw_f14;+setp.lt.f32 %qw_p2, %qw_f12, 0f7F800000;+and.pred %qw_p1, %qw_p1, %qw_p2;+sub.f32 %qw_f12, %f115, %f119;+abs.f32 %qw_f12, %qw_f12;+sub.f32 %qw_f13, %f116, %f120;+abs.f32 %qw_f13, %qw_f13;+sub.f32 %qw_f14, %f117, %f121;+abs.f32 %qw_f14, %qw_f14;+add.f32 %qw_f4, %qw_f12, %qw_f13;+add.f32 %qw_f4, %qw_f4, %qw_f14;+sub.f32 %qw_f12, %f125, %f131;+abs.f32 %qw_f12, %qw_f12;+sub.f32 %qw_f13, %f126, %f132;+abs.f32 %qw_f13, %qw_f13;+sub.f32 %qw_f14, %f127, %f133;+abs.f32 %qw_f14, %qw_f14;+add.f32 %qw_f5, %qw_f12, %qw_f13;+add.f32 %qw_f5, %qw_f5, %qw_f14;+add.f32 %qw_f6, %qw_f5, 0f3DA3D70A;+setp.lt.f32 %qw_p3, %qw_f6, %qw_f4;+setp.lt.f32 %qw_p2, %qw_f5, 0f3E19999A;+and.pred %qw_p3, %qw_p3, %qw_p2;+and.pred %qw_p3, %qw_p3, %qw_p0;+and.pred %qw_p3, %qw_p3, %qw_p1;+setp.gt.f32 %qw_p4, %qw_f4, 0f3E800000;+not.pred %qw_p5, %qw_p3;+and.pred %qw_p8, %qw_p3, %qw_p0;+setp.ge.f32 %qw_p6, %f148, 0f3E4CCCCD;+and.pred %qw_p6, %qw_p6, %qw_p4;+and.pred %qw_p6, %qw_p6, %qw_p5;+and.pred %qw_p6, %qw_p6, %qw_p0;+@%qw_p6 mov.f32 %f39, %f125;+@%qw_p6 mov.f32 %f38, %f126;+@%qw_p6 mov.f32 %f37, %f127;+@%qw_p8 mov.f32 %f39, %f125;+@%qw_p8 mov.f32 %f38, %f126;+@%qw_p8 mov.f32 %f37, %f127;+and.pred %qw_p9, %qw_p3, %qw_p1;+setp.ge.f32 %qw_p7, %f149, 0f3E4CCCCD;+and.pred %qw_p7, %qw_p7, %qw_p4;+and.pred %qw_p7, %qw_p7, %qw_p5;+and.pred %qw_p7, %qw_p7, %qw_p1;+@%qw_p7 mov.f32 %f43, %f131;+@%qw_p7 mov.f32 %f42, %f132;+@%qw_p7 mov.f32 %f41, %f133;+@%qw_p9 mov.f32 %f43, %f131;+@%qw_p9 mov.f32 %f42, %f132;+@%qw_p9 mov.f32 %f41, %f133;+} // end SM86_QUALITY_VALID_WARP_V3+)ptx";+}diff --git a/src/ngx/transfusion/quality_fix.h b/src/ngx/transfusion/quality_fix.hnew file mode 100644index 00000000..429eed79--- /dev/null+++ b/src/ngx/transfusion/quality_fix.h@@ -0,0 +1,290 @@+// Ported unchanged from SilyNoMeta/DLSSG-Transfusion (MIT) tag v1.4.5.3-rtx20-30-40,+// commit b56bd2deed114507ad2c88f986d90ed50ffb4639, source/native/quality_fix.h.+// Copyright (c) 2026 Michael Robles (TonyJoaca/DLSSG-Transfusion), fork by SilyNoMeta; MIT, see LICENSE.txt.+#pragma once+#include <algorithm>+#include <cstdint>+#include <string>+#include <string_view>++#include "quality_explained_warp.h"++namespace quality_fix+{+// Valid-warp policy (technique invented by Tony Joaca for Transfusion) inserted+// before the UIR flag load; restart required to change.+enum class Policy : uint8_t+{+ Transfusion, // Tony's own tuning, QUALITY_VALID_WARP_V4: warped candidates agree (default)+ ExplainedWarp, // dlssg_for_sm86's tuning (its V3): the warp explains the frame change+};++// Registers for thin-geometry protection with tuned shadow rejection+// RenoDx Release 1.0 Validated Warp Blend: dual-track confidence boost and thin geometry recovery+inline constexpr std::string_view kRegisters = R"ptx(+.reg .pred %qv<7>;+.reg .f32 %qf<12>;+)ptx";++inline constexpr std::string_view kPolicy = R"ptx(+// QUALITY_VALID_WARP_V4+// MFGUNLOCK_VALIDATED_WARP_BLEND_V1_TUNED+cvt.rn.f32.u32 %qf0, %r10;+cvt.rn.f32.u32 %qf1, %r11;+rcp.approx.ftz.f32 %qf0, %qf0;+rcp.approx.ftz.f32 %qf1, %qf1;+mul.ftz.f32 %qf0, %qf0, 0f3F000000;+mul.ftz.f32 %qf1, %qf1, 0f3F000000;+sub.ftz.f32 %qf2, 0f3F800000, %qf0;+sub.ftz.f32 %qf3, 0f3F800000, %qf1;+setp.ge.f32 %qv0, %f123, %qf0;+setp.le.f32 %qv2, %f123, %qf2;+and.pred %qv0, %qv0, %qv2;+setp.ge.f32 %qv2, %f124, %qf1;+and.pred %qv0, %qv0, %qv2;+setp.le.f32 %qv2, %f124, %qf3;+and.pred %qv0, %qv0, %qv2;+not.pred %qv2, %p17;+and.pred %qv0, %qv0, %qv2;+setp.ge.f32 %qv1, %f129, %qf0;+setp.le.f32 %qv2, %f129, %qf2;+and.pred %qv1, %qv1, %qv2;+setp.ge.f32 %qv2, %f130, %qf1;+and.pred %qv1, %qv1, %qv2;+setp.le.f32 %qv2, %f130, %qf3;+and.pred %qv1, %qv1, %qv2;+not.pred %qv2, %p16;+and.pred %qv1, %qv1, %qv2;+abs.f32 %qf4, %f125;+abs.f32 %qf5, %f126;+abs.f32 %qf6, %f127;+add.f32 %qf4, %qf4, %qf5;+add.f32 %qf4, %qf4, %qf6;+setp.lt.f32 %qv2, %qf4, 0f7F800000;+and.pred %qv0, %qv0, %qv2;+abs.f32 %qf5, %f131;+abs.f32 %qf6, %f132;+abs.f32 %qf7, %f133;+add.f32 %qf5, %qf5, %qf6;+add.f32 %qf5, %qf5, %qf7;+setp.lt.f32 %qv2, %qf5, 0f7F800000;+and.pred %qv1, %qv1, %qv2;++and.pred %qv3, %qv0, %qv1;++// Unwarped L1 difference (%qf6 = |Unwarped0 - Unwarped1|)+sub.f32 %qf6, %f115, %f119;+sub.f32 %qf7, %f116, %f120;+sub.f32 %qf8, %f117, %f121;+abs.f32 %qf6, %qf6;+abs.f32 %qf7, %qf7;+abs.f32 %qf8, %qf8;+add.f32 %qf6, %qf6, %qf7;+add.f32 %qf6, %qf6, %qf8;++// Motion detector: Scene is in motion (UnwarpedDiff > 0.03f = 0f3CF5C28F).+// Fully preserves static HUD & UI elements (HUD does not move between frames, UnwarpedDiff == 0.0f).+setp.gt.f32 %qv2, %qf6, 0f3CF5C28F;+and.pred %qv3, %qv3, %qv2;++// Candidate Agreement Firewall (High-speed Dynamic Shadow Protection):+// On moving dynamic shadows (e.g. at 138 km/h), surface motion vectors diverge from shadow motion,+// creating large candidate color disagreement (|Cand0 - Cand1| > 18%).+// Excluding disagreeing candidates protects dynamic shadows from being erased or flickering,+// allowing stock DLSS-G neural blending to resolve shadows cleanly while locking true geometry.+sub.f32 %qf6, %f125, %f131;+sub.f32 %qf7, %f126, %f132;+sub.f32 %qf8, %f127, %f133;+abs.f32 %qf6, %qf6;+abs.f32 %qf7, %qf7;+abs.f32 %qf8, %qf8;+add.f32 %qf6, %qf6, %qf7;+add.f32 %qf6, %qf6, %qf8;+max.f32 %qf4, %qf4, %qf5;+max.f32 %qf4, %qf4, 0f3F19999A;+mul.f32 %qf4, %qf4, 0f3E0F5C29;+setp.le.f32 %qv4, %qf6, %qf4;+and.pred %qv3, %qv3, %qv4;++and.pred %qv0, %qv0, %qv3;+and.pred %qv1, %qv1, %qv3;++// Full geometric motion warp floor (0.98f = 0f3F7AE148)+// Eliminates fence tearing, eliminates background gap lag, locks airplane windows, zero HUD ghosting.+max.f32 %qf0, %f148, 0f3F7AE148;+min.f32 %qf0, %qf0, 0f3F800000;++max.f32 %qf1, %f149, 0f3F7AE148;+min.f32 %qf1, %qf1, 0f3F800000;++sub.f32 %qf2, %f125, %f115;+sub.f32 %qf3, %f126, %f116;+sub.f32 %qf4, %f127, %f117;+@%qv0 fma.rn.f32 %f39, %qf0, %qf2, %f115;+@%qv0 fma.rn.f32 %f38, %qf0, %qf3, %f116;+@%qv0 fma.rn.f32 %f37, %qf0, %qf4, %f117;+sub.f32 %qf2, %f131, %f119;+sub.f32 %qf3, %f132, %f120;+sub.f32 %qf4, %f133, %f121;+@%qv1 fma.rn.f32 %f43, %qf1, %qf2, %f119;+@%qv1 fma.rn.f32 %f42, %qf1, %qf3, %f120;+@%qv1 fma.rn.f32 %f41, %qf1, %qf4, %f121;+)ptx";++inline bool ReplaceOnce(std::string& text, const std::string_view from, const std::string_view to)+{+ const auto pos = text.find(from);+ if (pos == std::string::npos || text.find(from, pos + from.size()) != std::string::npos) return false;+ text.replace(pos, from.size(), to);+ return true;+}++inline bool Patch(std::string& ptx, std::string& why, Policy policy = Policy::Transfusion)+{+ std::string normalized = ptx;+ normalized.erase(std::remove(normalized.begin(), normalized.end(), '\r'), normalized.end());+ while (!normalized.empty() && normalized.back() == '\0') normalized.pop_back();+ uint64_t hash = 14695981039346656037ull;+ for (unsigned char c : normalized) hash = (hash ^ c) * 1099511628211ull;+ if (normalized.size() != 39638 || hash != 0x7a6f5f41105c6d85ull)+ {+ why = "quality patch skipped: unrecognized BlendCandidatesFused PTX";+ return false;+ }+ const std::string anchor = "ld.param.u8 %rs8, [%rd6+220];";+ const auto site = normalized.find(anchor);+ const auto registers = normalized.find(".reg .pred %p<260>;");+ if (site == std::string::npos || registers == std::string::npos)+ {+ why = "quality patch skipped: expected insertion sites missing";+ return false;+ }++ // Both policies read the same registers at the same point; explained-warp+ // declares its temporaries in its own scope, Transfusion at function scope.+ if (policy == Policy::ExplainedWarp)+ normalized.insert(site, kPolicyExplainedWarp);+ else+ {+ normalized.insert(site, kPolicy);+ normalized.insert(registers, kRegisters);+ }++ // Fast reciprocal for UI chroma average (div by 3.0f -> mul by 0.33333334f)+ ReplaceOnce(normalized,+ "mov.f32 %f193, 0f40400000;\n"+ "div.approx.ftz.f32 %f194, %f192, %f193;",+ "mul.ftz.f32 %f194, %f192, 0f3EAAAAAB;");++ // Full-resolution tensor output: bypass 8x redundant SFU divisions by 1.0f+ ReplaceOnce(normalized,+ "mov.f32 %f537, 0f3F800000;\n"+ "div.approx.ftz.f32 %f529, %f39, %f537;\n"+ "div.approx.ftz.f32 %f530, %f38, %f537;\n"+ "div.approx.ftz.f32 %f531, %f37, %f537;\n"+ "div.approx.ftz.f32 %f532, %f36, %f537;\n"+ "div.approx.ftz.f32 %f533, %f43, %f537;\n"+ "div.approx.ftz.f32 %f534, %f42, %f537;\n"+ "div.approx.ftz.f32 %f535, %f41, %f537;\n"+ "div.approx.ftz.f32 %f536, %f40, %f537;",+ "mov.f32 %f529, %f39;\n"+ "mov.f32 %f530, %f38;\n"+ "mov.f32 %f531, %f37;\n"+ "mov.f32 %f532, %f36;\n"+ "mov.f32 %f533, %f43;\n"+ "mov.f32 %f534, %f42;\n"+ "mov.f32 %f535, %f41;\n"+ "mov.f32 %f536, %f40;");++ // Downsampling Mode 2: replace 8x div by 4.0f with mul by 0.25f (0f3E800000)+ ReplaceOnce(normalized,+ "mov.f32 %f528, 0f40800000;\n"+ "div.approx.ftz.f32 %f520, %f44, %f528;\n"+ "div.approx.ftz.f32 %f521, %f45, %f528;\n"+ "div.approx.ftz.f32 %f522, %f46, %f528;\n"+ "div.approx.ftz.f32 %f523, %f47, %f528;\n"+ "div.approx.ftz.f32 %f524, %f48, %f528;\n"+ "div.approx.ftz.f32 %f525, %f49, %f528;\n"+ "div.approx.ftz.f32 %f526, %f50, %f528;\n"+ "div.approx.ftz.f32 %f527, %f51, %f528;",+ "mov.f32 %f528, 0f3E800000;\n"+ "mul.ftz.f32 %f520, %f44, %f528;\n"+ "mul.ftz.f32 %f521, %f45, %f528;\n"+ "mul.ftz.f32 %f522, %f46, %f528;\n"+ "mul.ftz.f32 %f523, %f47, %f528;\n"+ "mul.ftz.f32 %f524, %f48, %f528;\n"+ "mul.ftz.f32 %f525, %f49, %f528;\n"+ "mul.ftz.f32 %f526, %f50, %f528;\n"+ "mul.ftz.f32 %f527, %f51, %f528;");++ // Downsampling Mode 4: replace 8x div by 16.0f with mul by 0.0625f (0f3D800000)+ ReplaceOnce(normalized,+ "mov.f32 %f495, 0f41800000;\n"+ "div.approx.ftz.f32 %f487, %f52, %f495;\n"+ "div.approx.ftz.f32 %f488, %f53, %f495;\n"+ "div.approx.ftz.f32 %f489, %f54, %f495;\n"+ "div.approx.ftz.f32 %f490, %f55, %f495;\n"+ "div.approx.ftz.f32 %f491, %f56, %f495;\n"+ "div.approx.ftz.f32 %f492, %f57, %f495;\n"+ "div.approx.ftz.f32 %f493, %f58, %f495;\n"+ "div.approx.ftz.f32 %f494, %f59, %f495;",+ "mov.f32 %f495, 0f3D800000;\n"+ "mul.ftz.f32 %f487, %f52, %f495;\n"+ "mul.ftz.f32 %f488, %f53, %f495;\n"+ "mul.ftz.f32 %f489, %f54, %f495;\n"+ "mul.ftz.f32 %f490, %f55, %f495;\n"+ "mul.ftz.f32 %f491, %f56, %f495;\n"+ "mul.ftz.f32 %f492, %f57, %f495;\n"+ "mul.ftz.f32 %f493, %f58, %f495;\n"+ "mul.ftz.f32 %f494, %f59, %f495;");++ // Downsampling Mode 8: replace 8x div by 64.0f with mul by 0.015625f (0f3C800000)+ ReplaceOnce(normalized,+ "mov.f32 %f430, 0f42800000;\n"+ "div.approx.ftz.f32 %f422, %f68, %f430;\n"+ "div.approx.ftz.f32 %f423, %f69, %f430;\n"+ "div.approx.ftz.f32 %f424, %f70, %f430;\n"+ "div.approx.ftz.f32 %f425, %f71, %f430;\n"+ "div.approx.ftz.f32 %f426, %f72, %f430;\n"+ "div.approx.ftz.f32 %f427, %f73, %f430;\n"+ "div.approx.ftz.f32 %f428, %f74, %f430;\n"+ "div.approx.ftz.f32 %f429, %f75, %f430;",+ "mov.f32 %f430, 0f3C800000;\n"+ "mul.ftz.f32 %f422, %f68, %f430;\n"+ "mul.ftz.f32 %f423, %f69, %f430;\n"+ "mul.ftz.f32 %f424, %f70, %f430;\n"+ "mul.ftz.f32 %f425, %f71, %f430;\n"+ "mul.ftz.f32 %f426, %f72, %f430;\n"+ "mul.ftz.f32 %f427, %f73, %f430;\n"+ "mul.ftz.f32 %f428, %f74, %f430;\n"+ "mul.ftz.f32 %f429, %f75, %f430;");++ // Downsampling Mode 16: replace 8x div by 256.0f with mul by 0.00390625f (0f3B800000)+ ReplaceOnce(normalized,+ "mov.f32 %f333, 0f43800000;\n"+ "div.approx.ftz.f32 %f325, %f84, %f333;\n"+ "div.approx.ftz.f32 %f326, %f85, %f333;\n"+ "div.approx.ftz.f32 %f327, %f86, %f333;\n"+ "div.approx.ftz.f32 %f328, %f87, %f333;\n"+ "div.approx.ftz.f32 %f329, %f88, %f333;\n"+ "div.approx.ftz.f32 %f330, %f89, %f333;\n"+ "div.approx.ftz.f32 %f331, %f90, %f333;\n"+ "div.approx.ftz.f32 %f332, %f91, %f333;",+ "mov.f32 %f333, 0f3B800000;\n"+ "mul.ftz.f32 %f325, %f84, %f333;\n"+ "mul.ftz.f32 %f326, %f85, %f333;\n"+ "mul.ftz.f32 %f327, %f86, %f333;\n"+ "mul.ftz.f32 %f328, %f87, %f333;\n"+ "mul.ftz.f32 %f329, %f88, %f333;\n"+ "mul.ftz.f32 %f330, %f89, %f333;\n"+ "mul.ftz.f32 %f331, %f90, %f333;\n"+ "mul.ftz.f32 %f332, %f91, %f333;");++ ptx = std::move(normalized);+ why = policy == Policy::ExplainedWarp+ ? "explained-warp policy (dlssg_for_sm86 V3) and SFU reciprocal optimizations applied"+ : "precision-tuned thin-geometry protection and SFU reciprocal optimizations applied";+ return true;+}+}+diff --git a/src/pipeline/ColorGradeInstance.cpp b/src/pipeline/ColorGradeInstance.cppnew file mode 100644index 00000000..f71de234--- /dev/null+++ b/src/pipeline/ColorGradeInstance.cpp@@ -0,0 +1,117 @@+#include "veyra/pipeline/ColorGradeInstance.h"+#include <bit>+#include <cstring>++namespace veyra::pipeline {+namespace {+constexpr std::array<UINT,3> widths{ColorGradeTables::kCurveEntries,ColorGradeTables::kHueEntries,ColorGradeTables::kLumEntries};+ComPtr<ID3D12Resource> makeLut(ID3D12Device* device,unsigned size){+ D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_DEFAULT;+ D3D12_RESOURCE_DESC d{};d.Dimension=D3D12_RESOURCE_DIMENSION_TEXTURE3D;+ d.Width=size;d.Height=size;d.DepthOrArraySize=UINT16(size);d.MipLevels=1;+ d.Format=DXGI_FORMAT_R32G32B32A32_FLOAT;d.SampleDesc.Count=1;+ ComPtr<ID3D12Resource> result;+ const HRESULT hr=device->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&d,D3D12_RESOURCE_STATE_COMMON,nullptr,IID_PPV_ARGS(&result));+ if(FAILED(hr))veyra::log::error("color-instance",std::format("LUT allocation size={} hr=0x{:08X}",size,unsigned(hr)));+ return result;+}+}+bool ColorGradeInstance::initialize(ID3D12Device* device,uint32_t commandSlots){+ if(!commandSlots)return false;+ uploads_.resize(commandSlots);+ for(size_t t=0;t<textures_.size();++t){+ textures_[t]=makeTexture(device,widths[t],1,DXGI_FORMAT_R32G32B32A32_FLOAT,false);+ if(!textures_[t])return false;+ for(auto& slot:uploads_){slot[t]=makeUploadBuffer(device,uint64_t(widths[t])*16);if(!slot[t])return false;}+ }+ lut_=makeLut(device,1); // descriptor placeholder; never sampled+ return bool(lut_);+}+bool ColorGradeInstance::createPass(ID3D12Device* device){+ std::vector<uint8_t> cs;+ return pass_.loadShader("ColorGradePass.dxil",cs)&&pass_.create(device,cs,12,1,1,4+kColorGradeConstantCount,4);+}+void ColorGradeInstance::refresh(const engine::ColorSettings& settings){+ settings_=settings;+ auto effective=settings;+ // An unresolved/rejected LUT must stay disabled on subsequent live edits.+ if(!lutSize_&&effective.hasLut()){+ effective.lutName={};effective.lutStrength=100;effective.lutInputSpace=engine::ColorSettings::kLutInputCineon;+ }+ tables_=ColorGradeTables::bake(effective);+ // The input is already FP16. Sending a pure gain through neutral log/HSV+ // transforms can put an exactly representable value just below itself,+ // losing an entire FP16 step on store. Test the effective (including group+ // bypass/LUT rejection) settings, not a near-identity matrix tolerance.+ auto withoutExposure=effective;withoutExposure.exposure=0;+ exposureOnly_=!tables_.identity&&ColorGradeTables::bake(withoutExposure).identity;+ tables_.exposureOnly=exposureOnly_;+ dirty_=true;+}+bool ColorGradeInstance::setLut(ID3D12Device* device,const float* rgb,unsigned size){+ if(!rgb||size<2||size>64)return false;+ const size_t values=size_t(size)*size*size*3;+ for(size_t i=0;i<values;++i)if(!std::isfinite(rgb[i]))return false;+ auto texture=makeLut(device,size);+ const unsigned pitch=(size*16+255)&~255u;+ auto upload=makeUploadBuffer(device,uint64_t(pitch)*size*size);+ if(!texture||!upload)return false;+ void* p=nullptr;const HRESULT hr=upload->Map(0,nullptr,&p);+ if(FAILED(hr)){veyra::log::error("color-instance",std::format("LUT map hr=0x{:08X}",unsigned(hr)));return false;}+ for(unsigned z=0;z<size;++z)for(unsigned y=0;y<size;++y){+ auto* row=reinterpret_cast<float*>(static_cast<uint8_t*>(p)+(size_t(z)*size+y)*pitch);+ for(unsigned x=0;x<size;++x){+ const size_t i=((size_t(z)*size+y)*size+x)*3;+ row[x*4]=rgb[i];row[x*4+1]=rgb[i+1];row[x*4+2]=rgb[i+2];row[x*4+3]=1;+ }+ }+ upload->Unmap(0,nullptr);+ lut_=std::move(texture);lutUpload_=std::move(upload);lutSize_=size;lutPitch_=pitch;lutPending_=true;+ refresh(settings_);+ return true;+}+void ColorGradeInstance::stageLut(DescriptorStager& stager){+ if(!pass_.heap)return;+ D3D12_SHADER_RESOURCE_VIEW_DESC srv{};srv.Format=DXGI_FORMAT_R32G32B32A32_FLOAT;+ srv.ViewDimension=D3D12_SRV_DIMENSION_TEXTURE3D;srv.Shader4ComponentMapping=D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;srv.Texture3D.MipLevels=1;+ stager.stageSrv(lut_.Get(),&srv,pass_.heap.Get(),11);+}+void ColorGradeInstance::createViews(ID3D12Device* device,DescriptorStager& stager,ID3D12Resource* input,ID3D12Resource* output){+ input_=input;output_=output;+ stager.stageSrv(input,nullptr,pass_.heap.Get(),0);+ makeUav(device,output,DXGI_FORMAT_R16G16B16A16_FLOAT,cpuHandleOf(pass_,1));+ for(UINT t=0;t<3;++t)stager.stageSrv(textures_[t].Get(),nullptr,pass_.heap.Get(),8+t);+ stageLut(stager);+}+bool ColorGradeInstance::dispatch(ID3D12GraphicsCommandList* list,StateTracker& tracker,uint32_t slot,uint32_t width,uint32_t height,bool hdrWorking){+ if(slot>=uploads_.size()||!input_||!output_||input_==output_)return false;+ auto copy=[&](ID3D12Resource* dst,ID3D12Resource* src,UINT w,UINT h,UINT d,UINT pitch){+ tracker.transition(list,dst,D3D12_RESOURCE_STATE_COPY_DEST);+ D3D12_TEXTURE_COPY_LOCATION target{},source{};target.pResource=dst;target.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;+ source.pResource=src;source.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;+ source.PlacedFootprint.Footprint={DXGI_FORMAT_R32G32B32A32_FLOAT,w,h,d,pitch};+ list->CopyTextureRegion(&target,0,0,0,&source,nullptr);+ tracker.transition(list,dst,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ };+ if(dirty_){+ const float* data[]={tables_.curve.data(),tables_.hue.data(),tables_.lum.data()};+ for(size_t t=0;t<textures_.size();++t){+ void* p=nullptr;const HRESULT hr=uploads_[slot][t]->Map(0,nullptr,&p);+ if(FAILED(hr)){veyra::log::error("color-instance",std::format("table map slot={} table={} hr=0x{:08X}",slot,t,unsigned(hr)));return false;}+ std::memcpy(p,data[t],size_t(widths[t])*16);uploads_[slot][t]->Unmap(0,nullptr);+ copy(textures_[t].Get(),uploads_[slot][t].Get(),widths[t],1,1,widths[t]*16);+ }+ dirty_=false;+ }+ if(lutPending_){copy(lut_.Get(),lutUpload_.Get(),lutSize_,lutSize_,lutSize_,lutPitch_);lutPending_=false;}+ tracker.transition(list,input_,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ tracker.transition(list,output_,D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ float c[4+kColorGradeConstantCount]={std::bit_cast<float>(width),std::bit_cast<float>(height),hdrWorking?80.0f/203.0f:1.0f,exposureOnly_?1.0f:0.0f};+ packColorGradeConstants(tables_,c+4);+ pass_.bind(list,c,gpuHandleOf(pass_,0).ptr,gpuHandleOf(pass_,1).ptr,gpuHandleOf(pass_,8).ptr);+ list->Dispatch((width+15)/16,(height+15)/16,1);+ tracker.uavBarrier(list,output_);+ tracker.transition(list,output_,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ return true;+}+}diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cppindex 824df787..8a26285c 100644--- a/src/pipeline/EnhanceGraph.cpp+++ b/src/pipeline/EnhanceGraph.cpp@@ -7,6 +7,7 @@// views are created last. Per-frame execution uses the shared command slot// ring (NR evaluates on a fresh list - snippet constraint).#include "veyra/pipeline/EnhanceGraph.h"+#include "veyra/engine/GraphDescription.h"#include "veyra/engine/ColorLut.h"#include "veyra/engine/EffectChain.h"#include "veyra/diagnostics/CpuStallTrace.h"@@ -20,6 +21,7 @@#include <thread>#include "veyra/Log.h"+#include "veyra/pipeline/CaptureUploadFrame.h"#include "veyra/Result.h"#include "veyra/gfx/CommandSlotRing.h"#include "veyra/gfx/D3D12DeviceContext.h"@@ -29,6 +31,7 @@#include "veyra/ngx/AmpereMfgUnlock.h"#include "veyra/ngx/NvapiArchSpoof.h"#include "veyra/gfx/FsrSrBackend.h"+#include "veyra/gfx/FsrFgPresenter.h"#include "veyra/ngx/DlssNrParameters.h"#include "veyra/ngx/DlssNrRuntimeAdapter.h"#include "veyra/ngx/DlssSrBackend.h"@@ -49,6 +52,8 @@ extern "C" {namespace veyra::pipeline {using diagnostics::GpuStage;+static_assert(diagnostics::kTimedNrLayers==engine::kMaxNrInstances&&diagnostics::kTimedColorNodes==engine::kMaxColorInstances,+ "every NR layer / Color instance needs its own node timing slot");namespace {@@ -75,8 +80,8 @@ AVPixelFormat packedIngressFormat(uint32_t code){return AV_PIX_FMT_NONE;}// Coarse luma sample for scene analysis; mirrors the CPU luma weights.-uint8_t packedIngressLuma(const AVFrame& frame,uint32_t code,unsigned x,unsigned y){- const auto* p=frame.data[0]+ptrdiff_t(y)*frame.linesize[0];+uint8_t packedIngressLuma(const uint8_t* data,ptrdiff_t linesize,uint32_t code,unsigned x,unsigned y){+ const auto* p=data+ptrdiff_t(y)*linesize;switch(code){case 1:{const auto* q=p+x*3;return uint8_t((54*unsigned(q[2])+183*unsigned(q[1])+19*unsigned(q[0])+128)>>8);}case 2:{const unsigned w=unsigned(p[x*2])|(unsigned(p[x*2+1])<<8);@@ -145,16 +150,16 @@ bool EnhanceGraph::createColorResources(){// lutStrength stays 0 in that case, so it is never sampled.colorLutTex_=makeColorLut3D(context_.device(),1);colorLutSize_=0;- upColorCurve_=makeUploadBuffer(context_.device(),sizeof(float)*4*ColorGradeTables::kCurveEntries);- upColorHue_=makeUploadBuffer(context_.device(),sizeof(float)*4*ColorGradeTables::kHueEntries);- upColorLum_=makeUploadBuffer(context_.device(),sizeof(float)*4*ColorGradeTables::kLumEntries);- if(!colorCurveTex_||!colorHueTex_||!colorLumTex_||!colorLutTex_||!upColorCurve_||!upColorHue_||!upColorLum_){+ if(!colorCurveTex_||!colorHueTex_||!colorLumTex_||!colorLutTex_){veyra::log::error("color-grade",std::format("colour resources unavailable tables={} lut={}",colorCurveTex_?1:0,colorLutTex_?1:0));return false;}- if(FAILED(upColorCurve_->Map(0,nullptr,reinterpret_cast<void**>(&mappedColorCurve_)))||- FAILED(upColorHue_->Map(0,nullptr,reinterpret_cast<void**>(&mappedColorHue_)))||- FAILED(upColorLum_->Map(0,nullptr,reinterpret_cast<void**>(&mappedColorLum_))))return false;+ colorTableUploads_.resize(ring_.slotCount());+ constexpr UINT widths[]={ColorGradeTables::kCurveEntries,ColorGradeTables::kHueEntries,ColorGradeTables::kLumEntries};+ for(auto& slot:colorTableUploads_)for(unsigned t=0;t<3;++t){+ slot[t]=makeUploadBuffer(context_.device(),uint64_t(widths[t])*16);+ if(!slot[t])return false;+ }return true;}// Product default: dither exactly one LSB of whatever the graph is writing while@@ -164,21 +169,38 @@ float EnhanceGraph::outputDitherStep() const{if(desc_.outputDitherStep>=0.0f)return desc_.outputDitherStep;// A master switch that is on but neutral renders exactly like no grading at// all (contract), so it must not add noise either - only a real grade does.- if(!colorActive_||colorTables_.identity)return 0.0f;+ bool graded=colorActive_&&!colorTables_.identity;+ if(!graded&&additionalColorActiveCount_){+ for(const auto& instance:additionalColorInstances_)if(instance&&!instance->identity()){graded=true;break;}+ }+ if(!graded)for(const auto& instance:nodeColorInstances_)if(instance&&!instance->identity()){graded=true;break;}+ if(!graded)return 0.0f;if(hdr10Output())return 1.0f/1023.0f;if(desc_.hdrOutput)return 0.0f; // FP16 target: nothing to quantisereturn 1.0f/255.0f;}void EnhanceGraph::refreshColorTables(){- colorTables_=ColorGradeTables::bake(desc_.color);- if(!colorActive_||!mappedColorCurve_||!mappedColorHue_||!mappedColorLum_)return;- std::copy(colorTables_.curve.begin(),colorTables_.curve.end(),mappedColorCurve_);- std::copy(colorTables_.hue.begin(),colorTables_.hue.end(),mappedColorHue_);- std::copy(colorTables_.lum.begin(),colorTables_.lum.end(),mappedColorLum_);+ auto effective=desc_.color;+ if(!colorLutSize_&&effective.hasLut()){+ effective.lutName={};effective.lutStrength=100;effective.lutInputSpace=engine::ColorSettings::kLutInputCineon;+ }+ colorTables_=ColorGradeTables::bake(effective);+ // Preserve the original fused-ingress table lookup, including its FP16+ // rounding. The exact exposure shortcut belongs to independent instances;+ // enabling it here changes existing single-grade output/intermediate bits.colorDirty_=true;}-void EnhanceGraph::uploadColorTables(ID3D12GraphicsCommandList* list){- if(!colorDirty_)return;+bool EnhanceGraph::uploadColorTables(ID3D12GraphicsCommandList* list,uint32_t slot){+ if(!colorDirty_)return true;+ if(slot>=colorTableUploads_.size())return false;+ auto& uploads=colorTableUploads_[slot];+ constexpr UINT widths[]={ColorGradeTables::kCurveEntries,ColorGradeTables::kHueEntries,ColorGradeTables::kLumEntries};+ const float* data[]={colorTables_.curve.data(),colorTables_.hue.data(),colorTables_.lum.data()};+ for(unsigned t=0;t<3;++t){+ void* mapped=nullptr;const HRESULT hr=uploads[t]->Map(0,nullptr,&mapped);+ if(FAILED(hr)){veyra::log::error("color-grade",std::format("table map slot={} table={} hr=0x{:08X}",slot,t,unsigned(hr)));return false;}+ std::memcpy(mapped,data[t],size_t(widths[t])*16);uploads[t]->Unmap(0,nullptr);+ }auto copyTable=[&](ID3D12Resource* dst,ID3D12Resource* src,UINT width){tracker_.transition(list,dst,D3D12_RESOURCE_STATE_COPY_DEST);D3D12_TEXTURE_COPY_LOCATION d{},s{};@@ -188,9 +210,9 @@ void EnhanceGraph::uploadColorTables(ID3D12GraphicsCommandList* list){list->CopyTextureRegion(&d,0,0,0,&s,nullptr);tracker_.transition(list,dst,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);};- copyTable(colorCurveTex_.Get(),upColorCurve_.Get(),ColorGradeTables::kCurveEntries);- copyTable(colorHueTex_.Get(),upColorHue_.Get(),ColorGradeTables::kHueEntries);- copyTable(colorLumTex_.Get(),upColorLum_.Get(),ColorGradeTables::kLumEntries);+ copyTable(colorCurveTex_.Get(),uploads[0].Get(),ColorGradeTables::kCurveEntries);+ copyTable(colorHueTex_.Get(),uploads[1].Get(),ColorGradeTables::kHueEntries);+ copyTable(colorLumTex_.Get(),uploads[2].Get(),ColorGradeTables::kLumEntries);if(colorLutPending_&&!colorLutUpload_.empty()){const unsigned size=colorLutPending_;// D3D12 requires the copy source row pitch to be 256-byte aligned. A@@ -226,22 +248,39 @@ void EnhanceGraph::uploadColorTables(ID3D12GraphicsCommandList* list){list->CopyTextureRegion(&d,0,0,0,&s,nullptr);tracker_.transition(list,colorLutTex_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);}else{- veyra::log::warn("color-grade","lut staging buffer unavailable; keeping the previous table");+ veyra::log::error("color-grade","LUT upload unavailable; refusing to sample uninitialized texture");+ return false;}colorLutUpload_.clear();colorLutPending_=0;}colorDirty_=false;+ return true;}-bool EnhanceGraph::setColorLut(const float* rgb,unsigned size){- if(!colorActive_||size<2||size>64)return false;+bool EnhanceGraph::setColorLut(const float* rgb,unsigned size,unsigned instance){+ if(instance<nodeColorInstances_.size()&&nodeColorInstances_[instance]){+ auto& grade=*nodeColorInstances_[instance];+ if(!grade.setLut(context_.device(),rgb,size))return false;+ grade.stageLut(stager_);+ return true;+ }+ if(instance){+ if(instance>desc_.additionalColorCount||instance>=engine::kMaxColorInstances||!additionalColorInstances_[instance-1])return false;+ auto& grade=*additionalColorInstances_[instance-1];+ if(!grade.setLut(context_.device(),rgb,size))return false;+ grade.stageLut(stager_); // caller drained, same contract as ingress LUT+ return true;+ }+ if(!colorActive_||!rgb||size<2||size>64)return false;+ for(size_t i=0;i<size_t(size)*size*size*3;++i)if(!std::isfinite(rgb[i]))return false;if(!createColorResources())return false;- colorLutTex_=makeColorLut3D(context_.device(),size);- if(!colorLutTex_)return false;+ auto texture=makeColorLut3D(context_.device(),size);+ if(!texture)return false;+ colorLutTex_=std::move(texture);colorLutSize_=size;colorLutUpload_.assign(rgb,rgb+std::size_t(size)*size*size*3);colorLutPending_=size;- colorDirty_=true;+ refreshColorTables();// Callers must have drained the queue: the descriptor is re-staged in place.D3D12_SHADER_RESOURCE_VIEW_DESC lutSrv{};lutSrv.Format=DXGI_FORMAT_R32G32B32A32_FLOAT;@@ -252,9 +291,100 @@ bool EnhanceGraph::setColorLut(const float* rgb,unsigned size){return true;}+bool EnhanceGraph::createAdditionalColorResources(){+ additionalColorActiveCount_=0;+ for(unsigned i=0;i<desc_.additionalColorCount;++i){+ const auto& settings=desc_.additionalColors[i];+ if(!settings.enabled||desc_.nodeColor(i+1))continue;+ auto& instance=additionalColorInstances_[i];+ instance=std::make_unique<ColorGradeInstance>();+ if(!instance->initialize(context_.device(),ring_.slotCount()))return false;+ instance->refresh(settings);+ if(settings.hasLut()){+ // Ingress has already tone-mapped HDR -> SDR here. Validate against+ // the texture being graded, not the source's original transfer.+ // SDR -> RTX Video HDR also grades SDR before that later conversion.+ const bool mismatch=desc_.hdrWorking()?settings.lutInputSpace==engine::ColorSettings::kLutInputSrgb:settings.lutInputSpace==engine::ColorSettings::kLutInputPq;+ engine::ColorLutData lut;+ const engine::ColorLutStore store(runtime::localDataDirectory());+ if(mismatch||!store.resolve(settings.lutNameString(),lut)||!lut.valid()||!instance->setLut(context_.device(),lut.rgb.data(),unsigned(lut.size))){+ colorLutNotice_+=std::format(L" 调色实例 {} LUT 未加载:{};其他调色继续。",i+2,mismatch?L"输入空间不匹配":L"资源不可用");+ veyra::log::warn("color-grade",std::format("instance={} lut rejected mismatch={} name={}",i+1,mismatch,utf8Of(settings.lutNameString())));+ }else{+ veyra::log::info("color-grade",std::format("instance={} independent LUT size={} name={}",i+1,lut.size,utf8Of(settings.lutNameString())));+ }+ }+ ++additionalColorActiveCount_;+ }+ if(additionalColorActiveCount_){+ for(auto& texture:colorScratch_){texture=makeTexture(context_.device(),srcW_,srcH_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);if(!texture)return false;}+ if(!colorActive_){+ preGradeRgba_=makeTexture(context_.device(),srcW_,srcH_,DXGI_FORMAT_R32G32B32A32_FLOAT,true);+ if(!preGradeRgba_)return false;+ }+ }+ return true;+}++bool EnhanceGraph::createNodeColorResources(){+ tailColorActiveCount_=preNrColorActiveCount_=preSrColorActiveCount_=interNrColorActiveCount_=0;+ preSrColorOutput_=nullptr;+ interNrColorOutputs_={};+ if(!desc_.runtimeNodeOrder||!desc_.fixedExecutionPlan)return true;+ const auto& plan=*desc_.fixedExecutionPlan;+ for(uint32_t i=0;i<plan.stepCount;++i){+ const auto& step=plan.steps[i];+ if(step.type!=engine::EffectType::Color||!desc_.nodeColor(step.parameterIndex))continue;+ const auto parameter=step.parameterIndex;+ const auto& settings=parameter?desc_.additionalColors[parameter-1]:desc_.color;+ auto& instance=nodeColorInstances_[parameter];+ instance=std::make_unique<ColorGradeInstance>();+ if(!instance->initialize(context_.device(),ring_.slotCount()))return false;+ instance->refresh(settings);+ if(settings.hasLut()){+ const bool mismatch=desc_.hdrWorking()?settings.lutInputSpace==engine::ColorSettings::kLutInputSrgb:settings.lutInputSpace==engine::ColorSettings::kLutInputPq;+ engine::ColorLutData lut;+ const engine::ColorLutStore store(runtime::localDataDirectory());+ if(mismatch||!store.resolve(settings.lutNameString(),lut)||!lut.valid()||!instance->setLut(context_.device(),lut.rgb.data(),unsigned(lut.size))){+ colorLutNotice_+=std::format(L" 调色实例 {} LUT 未加载:{};其他调色继续。",parameter+1,mismatch?L"输入空间不匹配":L"资源不可用");+ veyra::log::warn("color-grade",std::format("node instance={} lut rejected mismatch={} name={}",parameter,mismatch,utf8Of(settings.lutNameString())));+ }+ }+ nodeColorOutputs_[parameter]=makeTexture(context_.device(),step.output.width,step.output.height,DXGI_FORMAT_R16G16B16A16_FLOAT,true);+ if(!nodeColorOutputs_[parameter])return false;+ if(desc_.preNrColor(parameter)){++preNrColorActiveCount_;preNrColorOutput_=nodeColorOutputs_[parameter].Get();}+ else if(desc_.preSrColor(parameter)){++preSrColorActiveCount_;preSrColorOutput_=nodeColorOutputs_[parameter].Get();}+ else if(const auto target=desc_.interNrColorTarget(parameter);target<engine::kMaxNrInstances){+ ++interNrColorActiveCount_;interNrColorOutputs_[target]=nodeColorOutputs_[parameter].Get();+ }+ else ++tailColorActiveCount_;+ }+ return true;+}+bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc){+ fgInitResult_=0;+ driverRequirementNotice_.clear();failedBackend_=engine::FailedBackend::Infrastructure;+ if(const auto error=desc.validateFixedExecutionPlan();!error.empty()){+ veyra::log::error("graph",std::format("execution plan rejected before GPU allocation: {}",error));return false;+ }+ if(desc.fixedExecutionPlan){+ const auto& plan=*desc.fixedExecutionPlan;+ veyra::log::info("graph",std::format("fixed execution plan accepted: steps={} nr={} output={}x{}; fixed base with node pre-NR/tail Color; mode={}",+ plan.stepCount,plan.resourceCounts[size_t(engine::EffectType::NrEnhance)],plan.output.width,plan.output.height,+ desc.runtimeNodeOrder?"node":"list"));+ for(uint32_t i=0;i<plan.stepCount;++i){+ const auto& step=plan.steps[i];+ if(step.type==engine::EffectType::NrEnhance)+ veyra::log::info("graph",std::format("fixed plan NR parameter={} resource={} input={}x{} processing={}x{} output={}x{}",+ step.parameterIndex,step.resourceIndex,step.input.width,step.input.height,+ step.processing.width,step.processing.height,step.output.width,step.output.height));+ }+ }+ if(desc.additionalColorCount>desc.additionalColors.size()||!desc.color.validate().empty())return false;+ for(unsigned i=0;i<desc.additionalColorCount;++i)if(!desc.additionalColors[i].validate().empty())return false;if(!desc.protection.validate().empty())return false;if(desc.compatibilityPreflight&&!desc.compatibilityPreflight(desc,context_)){failedBackend_=engine::FailedBackend::Fg;@@ -282,6 +412,16 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)// single-layer product path unchanged, more entries stack further NR passes.nrLayerCount_=desc.nrLayersModel.empty()?1u:uint32_t(desc.nrLayersModel.size());if(nrLayerCount_>engine::kMaxNrInstances)nrLayerCount_=engine::kMaxNrInstances;+ if(!desc_.nrLayersExtent.empty()&&desc_.nrLayersExtent.size()!=nrLayerCount_){+ veyra::log::error("resolution","NR layer extent count mismatch");return false;+ }+ if(desc_.nrLayersExtent.empty())desc_.nrLayersExtent.assign(nrLayerCount_,Extent{nrW_,nrH_});+ for(size_t i=0;i<desc_.nrLayersExtent.size();++i){+ const auto extent=desc_.nrLayersExtent[i],full=desc_.nrFullExtent(i);+ if(!extent.valid()||extent.width>full.width||extent.height>full.height){+ veyra::log::error("resolution","invalid NR layer extent");return false;+ }+ }if((desc.flowWidth==0)!=(desc.flowHeight==0)){veyra::log::error("resolution","partial flow extent is invalid");return false;}nvofW_ = desc.flowWidth?desc.flowWidth:srcW_;nvofH_ = desc.flowHeight?desc.flowHeight:srcH_;@@ -292,12 +432,13 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)if(!Extent{nvofW_,nvofH_}.valid()||nvofW_>srcW_||nvofH_>srcH_){veyra::log::error("resolution","invalid source-space flow extent");return false;}diagnostics::DiagnosticEvent initDiagnostic;initDiagnostic.stage="initialize";initDiagnostic.identity={epoch_+1,desc.settingsRevision,0};initDiagnostic.resolution.source={srcW_,srcH_};initDiagnostic.resolution.base=initDiagnostic.resolution.fg=initDiagnostic.resolution.output={workW_,workH_};initDiagnostic.resolution.nr={nrW_,nrH_};initDiagnostic.resolution.flow={nvofW_,nvofH_};initDiagnostic.flowApplied=std::to_string(unsigned(desc.flowQuality));initDiagnostic.runtimeHash="unverified-user-replaceable";Logger::diagnosticContext(initDiagnostic);veyra::log::info("resolution",std::format("source={}x{} base={}x{} nr={}x{} flow={}x{} fg={}x{} output={}x{}",srcW_,srcH_,workW_,workH_,nrW_,nrH_,nvofW_,nvofH_,workW_,workH_,workW_,workH_));- veyra::log::info("pipeline-order",desc.nrBeforeSr?"NR -> residual(source) -> SR -> FG (experimental preview)":"SR -> NR -> residual -> FG");+ veyra::log::info("pipeline-order",desc.splitNrAcrossSr()?"NR(source) -> SR -> NR(work) -> FG (node preview)":desc.nrBeforeSr?"NR -> residual(source) -> SR -> FG (experimental preview)":"SR -> NR -> residual -> FG");if(!desc.videoHdr.valid()||(desc.hdrOutput&&!desc.hdrInput&&!desc.convertVideoHdr())){veyra::log::error("hdr","HDR output requires native HDR input or explicit Video HDR conversion");return false;}srEnabled_ = desc.enableSr && (srcW_ != workW_ || srcH_ != workH_);nrEnabled_ = desc.enableNr && !desc.noFeatures && !desc.noNgx;- fgEnabled_ = desc.enableFg && !desc.noNgx && !desc.stillImage && desc.frameGenerationBackend!=engine::FrameGenerationBackend::XeSS- && desc.frameGenerationBackend!=engine::FrameGenerationBackend::Fsr;+ fgEnabled_ = desc.enableFg && !desc.noFeatures && !desc.stillImage &&+ desc.frameGenerationBackend != engine::FrameGenerationBackend::XeSS &&+ (!desc.noNgx || engine::fsrFrameGeneration(desc.frameGenerationBackend));nvofStandalone_ = desc.enableNvofStandalone && !desc.noFeatures;if(desc.opticalFlowBackend==engine::OpticalFlowBackend::AmdFidelityFx&&desc.amdFlowHalfResolution){nvofW_=std::max(1u,nvofW_/2);nvofH_=std::max(1u,nvofH_/2);}uint64_t budget=0,usage=0;@@ -305,13 +446,24 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)// layer adds two history/guide pairs on top. The stack is bounded (16 nodes),// so a deep chain can genuinely exhaust a small adapter; the estimate has to// count the layers or the check would pass and allocation would fail later.- const uint64_t nrStackLayers=uint64_t(std::max<size_t>(1,desc_.nrLayersModel.size()));- const uint64_t temporalLayers=uint64_t(desc_.nrTemporal?std::max<size_t>(1,desc_.nrLayersTemporal.size()):0);- const uint64_t layerExtent=uint64_t(desc_.nrBeforeSr?srcW_:workW_)*(desc_.nrBeforeSr?srcH_:workH_);- const uint64_t temporalBytes=temporalLayers*layerExtent*40;+ uint64_t nrTextureBytes=0;+ for(const auto extent:desc_.nrLayersExtent)+ nrTextureBytes+=uint64_t(extent.width)*extent.height*(extent.width==nrW_&&extent.height==nrH_?32u:36u);+ uint64_t fullLayerBytes=0,temporalBytes=0;+ for(size_t i=0;i<desc_.nrLayersExtent.size();++i){+ const auto full=desc_.nrFullExtent(i);const uint64_t pixels=uint64_t(full.width)*full.height;+ fullLayerBytes+=pixels*8;+ if(i<desc_.nrLayersTemporal.size()?desc_.nrLayersTemporal[i]:desc_.nrTemporal)temporalBytes+=pixels*40;+ }+ uint64_t tailColorBytes=0;+ for(uint32_t i=0;i<engine::kMaxColorInstances;++i)if(desc_.nodeColor(i))tailColorBytes+=uint64_t(workW_)*workH_*8;+ uint64_t interProtectionBytes=0;+ if(const auto target=desc_.interNrProtectionTarget();target<engine::kMaxNrInstances){+ const auto extent=desc_.nrFullExtent(target);interProtectionBytes=uint64_t(extent.width)*extent.height*8;+ }const uint64_t estimate=uint64_t(workW_)*workH_*(fgEnabled_?100:76)- +nrStackLayers*(uint64_t(nrW_)*nrH_*16+layerExtent*8)- +uint64_t(srcW_)*srcH_*32+temporalBytes;+ +nrTextureBytes+fullLayerBytes+ +uint64_t(srcW_)*srcH_*(32u+(desc_.protectionBeforeSr()?8u:0u))+temporalBytes+tailColorBytes+interProtectionBytes;if(context_.videoMemoryInfo(budget,usage)){veyra::log::info("memory",std::format("graph lower-bound={}MiB budget={}MiB usage={}MiB; SDK allocations additional",estimate>>20,budget>>20,usage>>20));if(usage>=budget||estimate>budget-usage){veyra::log::error("memory","insufficient adapter budget for requested graph textures");return false;}@@ -331,6 +483,7 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)if (!initZeroAndDepthTextures()) return false;if (!initNvof()) { failedBackend_=engine::FailedBackend::OpticalFlow; return false; }if (!initFsrSr()) return false;+ if (!initFsrFg()) return false;if(nrEnabled_&&GetEnvironmentVariableW(L"VEYRA_TEST_NR_INIT_FAILURE",nullptr,0)){failedBackend_=engine::FailedBackend::Nr;veyra::log::error("backend-recovery-test","test-only NR initialization rejection before SDK call; not a hardware failure");return false;@@ -344,6 +497,9 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)veyra::log::info("graph", std::format("initialized src={}x{} work={}x{} sr={} nr={} fg={} nvof={}",srcW_, srcH_, workW_, workH_, srEnabled_ ? 1 : 0, nrEnabled_ ? 1 : 0,fgEnabled_ ? 1 : 0, (nvof_ && nvof_->initialized()) ? 1 : 0));+ veyra::log::info("motion-policy",std::format("sr={} nr={} fg={} standalone={} hdrOutput={}",+ desc_.srUsesFlow()?"flow":"zero",desc_.nrUsesFlow()?"flow":"zero",desc_.fgUsesFlow()?"flow":"zero",+ desc_.enableNvofStandalone,hdr10Output()?"HDR10":desc_.hdrOutput?"scRGB":"SDR"));return true;}@@ -400,23 +556,35 @@ bool EnhanceGraph::createResources()// be described as engine-native depth.if(srEnabled_&&desc_.videoSrQuality==engine::kVideoSrFsr){fsrSrDepth_=makeTexture(context_.device(),srcW_,srcH_,DXGI_FORMAT_R32_FLOAT,false);- if(!fsrSrDepth_)return false;- fsrSrDepthPitch_=size_t(srcW_)*sizeof(float);+ fsrSrZeroMotion_=makeTexture(context_.device(),srcW_,srcH_,DXGI_FORMAT_R16G16_FLOAT,false);+ if(!fsrSrDepth_||!fsrSrZeroMotion_)return false;+ fsrSrDepthPitch_=(size_t(srcW_)*sizeof(float)+255)&~size_t(255);upFsrSrDepth_=makeUploadBuffer(context_.device(),fsrSrDepthPitch_*srcH_);- if(!upFsrSrDepth_)return false;+ upFsrSrZeroMotion_=makeUploadBuffer(context_.device(),fsrSrDepthPitch_*srcH_);+ if(!upFsrSrDepth_||!upFsrSrZeroMotion_)return false;}- const bool directBase=!srEnabled_&&srcW_==workW_&&srcH_==workH_;+ const bool directBase=!srEnabled_&&srcW_==workW_&&srcH_==workH_&&!desc_.splitNrAcrossSr();workRgba_=directBase?srcRgba_:makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);- for(unsigned i=0;i<2;++i){sourceReferences_[i]=makeTexture(context_.device(),srcW_,srcH_,DXGI_FORMAT_R16G16B16A16_FLOAT,false);baseReferences_[i]=(directBase&&!desc_.color.enabled)?sourceReferences_[i]:makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16B16A16_FLOAT,false);if(!sourceReferences_[i]||!baseReferences_[i])return false;}+ const bool anyColor=desc_.color.enabled||std::any_of(desc_.additionalColors.begin(),desc_.additionalColors.begin()+desc_.additionalColorCount,[](const auto& s){return s.enabled;});+ for(unsigned i=0;i<2;++i){sourceReferences_[i]=makeTexture(context_.device(),srcW_,srcH_,DXGI_FORMAT_R16G16B16A16_FLOAT,false);baseReferences_[i]=(directBase&&!anyColor)?sourceReferences_[i]:makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16B16A16_FLOAT,false);if(!sourceReferences_[i]||!baseReferences_[i])return false;}// The residual composite runs once, after the last NR layer, at the working// extent (or the source extent in the NR-first preview order).- residualRgba_=makeTexture(context_.device(),desc_.nrBeforeSr?srcW_:workW_,desc_.nrBeforeSr?srcH_:workH_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);+ residualRgba_=makeTexture(context_.device(),desc_.finalNrAfterSr()?workW_:srcW_,desc_.finalNrAfterSr()?workH_:srcH_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);+ if(desc_.protectionBeforeSr()){+ preSrProtectionRgba_=makeTexture(context_.device(),srcW_,srcH_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);+ if(!preSrProtectionRgba_)return false;+ }+ if(const auto target=desc_.interNrProtectionTarget();target<engine::kMaxNrInstances){+ const auto extent=desc_.nrFullExtent(target);+ interNrProtectionRgba_=makeTexture(context_.device(),extent.width,extent.height,DXGI_FORMAT_R16G16B16A16_FLOAT,true);+ if(!interNrProtectionRgba_)return false;+ }nrFlow_=makeTexture(context_.device(),nrW_,nrH_,DXGI_FORMAT_R16G16_FLOAT,true);baseFlow_=makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16_FLOAT,true);if(presentSinkFg())for(auto& motion:presentMotion_){motion=makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16_FLOAT,false);if(!motion)return false;}if(!residualRgba_||!nrFlow_||!baseFlow_)return false;// Colour grade tables (v4): only allocated when the stage is enabled.- colorActive_=desc_.color.enabled;+ colorActive_=desc_.color.enabled&&!desc_.nodeColor(0);if(colorActive_){if(!createColorResources())return false;refreshColorTables();@@ -458,6 +626,8 @@ bool EnhanceGraph::createResources()ColorGradeTables::kCurveEntries,ColorGradeTables::kHueEntries,ColorGradeTables::kLumEntries,desc_.color.lutInputSpace,desc_.color.hasLut()?1:0));}+ if(!createAdditionalColorResources())return false;+ if(!createNodeColorResources())return false;videoFrame_[0] = makeTexture(context_.device(), workW_, workH_, outputFormat(), true);videoFrame_[1] = makeTexture(context_.device(), workW_, workH_, outputFormat(), true);confTex_ = makeTexture(context_.device(), nvofW_, nvofH_, DXGI_FORMAT_R8_UNORM, true);@@ -465,7 +635,11 @@ bool EnhanceGraph::createResources()depthTex_ = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R32_FLOAT, false);// Valid placeholder descriptors keep disabled FG inexpensive. Enabling it// is a graph rebuild, so no in-flight descriptor is resized in place.- for(auto& frame:genFrame_){frame=makeTexture(context_.device(),fgEnabled_?workW_:1,fgEnabled_?workH_:1,outputFormat(),true);if(!frame)return false;}+ for(size_t i=0;i<kGeneratedPoolSlots;++i){+ const bool used=fgEnabled_&&(!fsrEnabled()||i<2);+ genFrame_[i]=makeTexture(context_.device(),used?workW_:1,used?workH_:1,outputFormat(),true);+ if(!genFrame_[i])return false;+ }nrZeroMotion_ = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R16G16_FLOAT, false);nrZeroDepth_ = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R32_FLOAT, false);rawW_ = (nvofW_ + nvofGrid_ - 1) / nvofGrid_;@@ -541,7 +715,7 @@ bool EnhanceGraph::initZeroAndDepthTextures()Status st = Status::Ok;ID3D12GraphicsCommandList* list = ring_.acquire(0, st);if (list == nullptr) return false;- auto uploadTex = [&](ID3D12Resource* tex, const ComPtr<ID3D12Resource>& up, DXGI_FORMAT fmt) {+ auto uploadTex = [&](ID3D12Resource* tex, const ComPtr<ID3D12Resource>& up, DXGI_FORMAT fmt,uint32_t width=0,uint32_t height=0,size_t pitch=0) {D3D12_RESOURCE_BARRIER b{};b.Transition.pResource = tex;b.Transition.StateBefore = D3D12_RESOURCE_STATE_COMMON;@@ -554,10 +728,10 @@ bool EnhanceGraph::initZeroAndDepthTextures()src.pResource = up.Get();src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;src.PlacedFootprint.Footprint.Format = fmt;- src.PlacedFootprint.Footprint.Width = workW_;- src.PlacedFootprint.Footprint.Height = workH_;+ src.PlacedFootprint.Footprint.Width = width?width:workW_;+ src.PlacedFootprint.Footprint.Height = height?height:workH_;src.PlacedFootprint.Footprint.Depth = 1;- src.PlacedFootprint.Footprint.RowPitch = static_cast<UINT>(dPitch_);+ src.PlacedFootprint.Footprint.RowPitch = static_cast<UINT>(pitch?pitch:dPitch_);list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);D3D12_RESOURCE_BARRIER back{};back.Transition.pResource = tex;@@ -569,6 +743,7 @@ bool EnhanceGraph::initZeroAndDepthTextures()uploadTex(depthTex_.Get(), upDepth_, DXGI_FORMAT_R32_FLOAT);uploadTex(nrZeroDepth_.Get(), upZeroDepth_, DXGI_FORMAT_R32_FLOAT);uploadTex(nrZeroMotion_.Get(), upZeroMotion_, DXGI_FORMAT_R16G16_FLOAT);+ if(fsrSrZeroMotion_){void* data=nullptr;D3D12_RANGE read{0,0};if(FAILED(upFsrSrZeroMotion_->Map(0,&read,&data))||!data)return false;std::memset(data,0,fsrSrDepthPitch_*srcH_);upFsrSrZeroMotion_->Unmap(0,nullptr);uploadTex(fsrSrZeroMotion_.Get(),upFsrSrZeroMotion_,DXGI_FORMAT_R16G16_FLOAT,srcW_,srcH_,fsrSrDepthPitch_);}if(fsrSrDepth_!=nullptr&&upFsrSrDepth_!=nullptr){D3D12_RESOURCE_BARRIER b{};b.Transition.pResource=fsrSrDepth_.Get();@@ -591,17 +766,10 @@ bool EnhanceGraph::initZeroAndDepthTextures()b.Transition.StateAfter=D3D12_RESOURCE_STATE_COMMON;list->ResourceBarrier(1,&b);}- list->Close();- ID3D12CommandList* lists[] = { list };- context_.directQueue()->ExecuteCommandLists(1, lists);- ComPtr<ID3D12Fence> initFence;- context_.device()->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&initFence));- context_.directQueue()->Signal(initFence.Get(), 1);- if (nvofOutEvent_ == nullptr) {- nvofOutEvent_ = CreateEventW(nullptr, FALSE, FALSE, nullptr);- }- initFence->SetEventOnCompletion(1, nvofOutEvent_);- WaitForSingleObject(nvofOutEvent_, 5000);+ // Keep recording/fence ownership in the ring. Closing this list directly+ // left slot 0 marked recording, so graph rebuild/shutdown closed it again.+ // This is the existing one-time initialization wait, never a per-pass wait.+ if(!ring_.submitAndSignal(0)||!ring_.waitIdle())return false;veyra::log::info("graph", "depth/zero guidance textures initialized");return true;}@@ -609,8 +777,9 @@ bool EnhanceGraph::initZeroAndDepthTextures()bool EnhanceGraph::initNvof(){if(desc_.stillImage){mvecSource_="single-image (no temporal motion)";return true;}- if (desc_.noFeatures || !(nvofStandalone_ || presentSinkFg() || (fgEnabled_&&desc_.frameGenerationBackend==engine::FrameGenerationBackend::Dlss) || (srEnabled_&&(desc_.videoSrQuality==0||desc_.videoSrQuality==engine::kVideoSrFsr)))) {- veyra::log::info("graph", "VEYRA_NO_FEATURES: NVOF session skipped");+ if (desc_.noFeatures || !(nvofStandalone_ || (presentSinkFg()&&desc_.fgUsesFlow()) || (fgEnabled_&&desc_.fgUsesFlow()&&desc_.frameGenerationBackend==engine::FrameGenerationBackend::Dlss) || (srEnabled_&&desc_.srUsesFlow()&&(desc_.videoSrQuality==0||desc_.videoSrQuality==engine::kVideoSrFsr)))) {+ mvecSource_="zero motion (no external flow consumer)";+ veyra::log::info("graph", "optical-flow session skipped: no external motion consumer");return true;}if(desc_.opticalFlowBackend==engine::OpticalFlowBackend::GpuDis){@@ -839,6 +1008,21 @@ bool EnhanceGraph::initFsrSr()return true;}+bool EnhanceGraph::fsrActive() const { return fsrFgBackend_&&fsrFgBackend_->available(); }+const char* EnhanceGraph::fsrProviderVersion() const { return fsrFgBackend_?fsrFgBackend_->providerVersion():""; }+bool EnhanceGraph::initFsrFg() {+ if(!fsrEnabled()||!fgEnabled_)return true;+ failedBackend_=engine::FailedBackend::Fg;+ if(desc_.fgMultiplier!=2){+ veyra::log::error("fsr-fg","FSR frame generation requires 2X");return false;+ }+ fsrFgBackend_=std::make_unique<gfx::FsrFgPresenter>();+ if(!fsrFgBackend_->initializeIndependent(context_.device(),workW_,workH_,outputFormat(),+ desc_.frameGenerationBackend==engine::FrameGenerationBackend::Fsr4))return false;+ failedBackend_=engine::FailedBackend::None;+ return true;+}+bool EnhanceGraph::initNgxFeatures(){failedBackend_=engine::FailedBackend::NgxCore;@@ -849,7 +1033,7 @@ bool EnhanceGraph::initNgxFeatures()}// FSR upscaling is a FidelityFX effect: a session whose only feature is// FSR SR must not require (or fail on) the NGX core.- const bool needNgxCore = nrEnabled_ || fgEnabled_ || desc_.convertVideoHdr() ||+ const bool needNgxCore = nrEnabled_ || (fgEnabled_ && !fsrEnabled()) || desc_.convertVideoHdr() ||(srEnabled_ && desc_.videoSrQuality!=engine::kVideoSrFsr);if (!needNgxCore) {veyra::log::info("graph", "NGX core skipped: AMD FSR upscaling is the only enabled stage");@@ -890,9 +1074,13 @@ bool EnhanceGraph::initNgxFeatures()failedBackend_=engine::FailedBackend::Fg;fgCompatibility_=std::make_unique<ngx::FgCompatibilitySession>();if(!fgCompatibility_->open(context_.device(),context_.adapter().vendorId,context_.adapter().deviceId,desc_.runtimeAbsPath))return false;+ // The 310.9.1 provider was patched by DlssgTransfusion inside open();+ // the audited-310.7 unlocks only apply to the 310.7 provider.+ if(!fgCompatibility_->transfusionProfile()){prepareAmpereFgSpoof();applyAdaMfgUnlock();applyAmpereMfgUnlock();+ }if(!fgCompatibility_->prepareDriver(desc_.runtimeAbsPath,projectId.c_str(),engineVersion.c_str()))return false;std::array<ID3D12Resource*,2> real={videoFrame_[0].Get(),videoFrame_[1].Get()};std::array<ID3D12Resource*,kGeneratedPoolSlots> generated{};@@ -919,6 +1107,10 @@ bool EnhanceGraph::initNgxFeatures()fgBackend_->setCompatibility(fgCompatibility_.get());ngx::DlssFgBackend::Capability fgCaps{};const bool fgAvailable = fgBackend_->queryCapability(*coreHost_, fgCaps, st);+ fgInitResult_=uint64_t(fgCaps.featureInitResult);+ driverRequirementNotice_.clear();+ if(fgCaps.needsUpdatedDriver&&fgCaps.minDriverVersionMajor>0)+ driverRequirementNotice_=std::format(L"当前 DLSS 补帧运行库要求至少 {}.{:02} 驱动(NGX 能力查询)",fgCaps.minDriverVersionMajor,fgCaps.minDriverVersionMinor);if (!fgAvailable) {veyra::log::error("graph", "FG capability startup failed; see native results and compatibility stage above");return false;@@ -961,13 +1153,14 @@ bool EnhanceGraph::initNgxFeatures()if(nrEnabled_){failedBackend_=engine::FailedBackend::Nr;if(desc_.nrRuntime!=engine::NrRuntime::Original&&desc_.nrRuntime!=engine::NrRuntime::Community&&desc_.nrRuntime!=engine::NrRuntime::Ampere)return false;- auto nrDirectory=std::filesystem::path(desc_.runtimeAbsPath);if(desc_.nrRuntime==engine::NrRuntime::Community)nrDirectory/=L"nr-community";- if(desc_.nrRuntime==engine::NrRuntime::Ampere)nrDirectory/=L"nr-ampere";- veyra::log::info("nr-runtime",std::format("selected={} path={}",engine::nrRuntimeName(desc_.nrRuntime),nrDirectory.string()));+ const auto selectedNr=engine::currentNrRuntime(desc_.nrRuntime);+ auto nrDirectory=std::filesystem::path(desc_.runtimeAbsPath);+ if(selectedNr==engine::NrRuntime::Ampere)nrDirectory/=L"nr-ampere";+ veyra::log::info("nr-runtime",std::format("selected={} requestedId={} path={}",engine::nrRuntimeName(selectedNr),int(desc_.nrRuntime),nrDirectory.string()));nrAdapter_ = std::make_unique<ngx::DlssNrRuntimeAdapter>();if (!nrAdapter_->load(nrDirectory.wstring(), st) ||!nrAdapter_->installCallerCompatibility(st) ||- (desc_.nrRuntime==engine::NrRuntime::Ampere && !nrAdapter_->installAmpereCompatibility(context_.device(), st)) ||+ (selectedNr==engine::NrRuntime::Ampere && !nrAdapter_->installAmpereCompatibility(context_.device(), st)) ||!nrAdapter_->snippetInitExt(context_.device(), nrDirectory.c_str(), nrResult_, nrSeh_) ||nrResult_ != static_cast<uint64_t>(NVSDK_NGX_Result_Success)) {veyra::log::error("graph", std::format("NR snippet init failed 0x{:X}", nrResult_));@@ -997,20 +1190,21 @@ bool EnhanceGraph::initNgxFeatures()nrInstances_.reserve(layers);for (size_t index = 0; index < layers; ++index) {auto instance = std::make_unique<NrInstance>();- const uint32_t fullW = desc_.nrBeforeSr ? srcW_ : workW_;- const uint32_t fullH = desc_.nrBeforeSr ? srcH_ : workH_;+ const auto extent=desc_.nrLayersExtent[index];+ const auto full=desc_.nrFullExtent(index);+ const uint32_t fullW=full.width,fullH=full.height;// Only a single layer may alias the graph's stage input, and only// when the extents already match: that is what the original graph// did, and the path has to stay byte-identical. Extra layers read// the previous layer's output, which the downsample produces.ID3D12Resource* borrowed = nullptr;if (layers == 1) {- const bool sameExtent = desc_.nrBeforeSr ? (nrW_ == srcW_ && nrH_ == srcH_)- : (nrW_ == workW_ && nrH_ == workH_);- if (sameExtent) borrowed = desc_.nrBeforeSr ? srcRgba_.Get() : workRgba_.Get();+ const bool sameExtent = extent.width==fullW&&extent.height==fullH;+ if (sameExtent) borrowed = nrBaseInput();}- if (!instance->create(context_.device(), nrW_, nrH_, fullW, fullH,- nrZeroMotion_.Get(), nrZeroDepth_.Get(), borrowed)) {+ auto* motion=extent.width==nrW_&&extent.height==nrH_?nrFlow_.Get():nullptr;+ if (!instance->create(context_.device(), extent.width, extent.height, fullW, fullH,+ nrZeroMotion_.Get(), nrZeroDepth_.Get(), borrowed, motion)) {veyra::log::error("graph", std::format("NR layer {} texture allocation failed", index + 1));return false;}@@ -1021,6 +1215,8 @@ bool EnhanceGraph::initNgxFeatures()instance->residualSettings = index < desc_.nrLayersResidual.size() ? desc_.nrLayersResidual[index] : desc_.residual;instance->protection = index < desc_.nrLayersProtection.size() ? desc_.nrLayersProtection[index] : desc_.protection;instance->temporalEnabled = index < desc_.nrLayersTemporal.size() ? desc_.nrLayersTemporal[index] : desc_.nrTemporal;+ veyra::log::info("resolution",std::format("NR layer={} internal={}x{} composite={}x{} sharedMotion={}",+ index+1,extent.width,extent.height,fullW,fullH,motion!=nullptr));nrInstances_.push_back(std::move(instance));}veyra::log::info("graph", std::format("NR layers={} extent={}x{}", layers, nrW_, nrH_));@@ -1029,18 +1225,19 @@ bool EnhanceGraph::initNgxFeatures()// NR feature create (8.5 create parameter contract), one handle per layer.for (size_t layerIndex = 0; nrEnabled_ && layerIndex < nrInstances_.size(); ++layerIndex) {auto* layer = nrInstances_[layerIndex].get();+ const uint32_t nrW=layer->width(),nrH=layer->height();namespace p = ngx::dlssnr;ngx::ParameterBlock pb(ngxParams_);- pb.setU32(p::kWidth, nrW_); pb.setU32(p::kHeight, nrH_);- pb.setU32(p::kInputWidth, nrW_); pb.setU32(p::kInputHeight, nrH_);- pb.setU32(p::kOutputWidth, nrW_); pb.setU32(p::kOutputHeight, nrH_);- pb.setU32(p::kOutputDotWidth, nrW_); pb.setU32(p::kOutputDotHeight, nrH_);+ pb.setU32(p::kWidth, nrW); pb.setU32(p::kHeight, nrH);+ pb.setU32(p::kInputWidth, nrW); pb.setU32(p::kInputHeight, nrH);+ pb.setU32(p::kOutputWidth, nrW); pb.setU32(p::kOutputHeight, nrH);+ pb.setU32(p::kOutputDotWidth, nrW); pb.setU32(p::kOutputDotHeight, nrH);pb.setU32(p::kUpscaling, 0);pb.setF32(p::kScale, 1.0f); pb.setF32(p::kScalingRatio, 1.0f);pb.setVoid(p::kComputeScalingRatioCallback,reinterpret_cast<void*>(&ngx::DlssNrRuntimeAdapter::scalingRatioCallback));pb.setI32(p::kHintRenderPreset, 0);- pb.setU32(p::kStdWidth, nrW_); pb.setU32(p::kStdHeight, nrH_);+ pb.setU32(p::kStdWidth, nrW); pb.setU32(p::kStdHeight, nrH);pb.setI32(p::kPerfQualityValue, 1);pb.setU32(p::kCreationNodeMask, 1); pb.setU32(p::kVisibilityNodeMask, 1);ID3D12GraphicsCommandList* list = ring_.acquire(0, st);@@ -1143,9 +1340,38 @@ bool EnhanceGraph::initNgxFeatures()return true;}+// Stage-5 output stabiliser. It reads the graph's NR result and the image that+// fed NR, writes into its own ping-pong, and the caller copies the result back+// into residualRgba_. Copying back is deliberate: every downstream reader+// (SR, FG, tail colour, diagnostic views) keeps binding the same texture, so+// enabling the stabiliser cannot silently mis-bind a consumer.+bool EnhanceGraph::createNrHoldPass()+{+ nrHoldPass_.reset();+ if(desc_.nrHoldStrength<=0.0f)return true;+ if(!residualRgba_)return false;+ auto pass=std::make_unique<NrHoldPass>();+ // Take the extent from the texture we actually stabilise rather than+ // recomputing it from the plan: the two must agree or the dispatch grid+ // would not cover the image.+ const auto resolved=residualRgba_->GetDesc();+ const auto width=uint32_t(resolved.Width),height=resolved.Height;+ // The base the shader compares against is the same image NR consumed.+ if(!pass->initialize(context_.device(),width,height,residualRgba_.Get(),nrBaseInput())){+ veyra::log::warn("nr-hold","output stabiliser unavailable; continuing without it");+ return true; // a missing stabiliser must not fail the graph+ }+ nrHoldPass_=std::move(pass);+ veyra::log::info("nr-hold",std::format("output stabiliser active extent={}x{} strength={:.3f} tolerance={:.3f}",+ width,height,desc_.nrHoldStrength,desc_.nrHoldTolerance));+ return true;+}+bool EnhanceGraph::createComputePasses(){std::vector<uint8_t> cs;+ for(auto& instance:additionalColorInstances_)if(instance&&!instance->createPass(context_.device()))return false;+ for(auto& instance:nodeColorInstances_)if(instance&&!instance->createPass(context_.device()))return false;{const UINT downsampleLayers=UINT(std::max<size_t>(1,nrInstances_.size()));const UINT downsampleRate=2*downsampleLayers; // one (source, target) pair per layer@@ -1158,11 +1384,22 @@ bool EnhanceGraph::createComputePasses()const UINT residualLayers=UINT(std::max<size_t>(1,nrInstances_.size()));if(!residualPass_.loadShader("NrResidualComposite.dxil",cs)||!residualPass_.create(context_.device(),cs,4*residualLayers,3*residualLayers,residualLayers,24))return false;- }- if(!flowAdaptPass_.loadShader("FlowAdapt.dxil",cs)||!flowAdaptPass_.create(context_.device(),cs,3,1,1))return false;- if (!yuvPass_.loadShader("YuvToLinearRgb.dxil", cs) || !yuvPass_.create(context_.device(), cs, 12, 2, 1, 12+kColorGradeConstantCount, 4)) return false;+ // The existing residual shader can mask the complete stack against its+ // original base. No extra texture: the final layer owns outputFull().+ if(nrInstances_.size()>1&&!stackProtectionPass_.create(context_.device(),cs,4,3,1,24))return false;+ }+ if(!flowAdaptPass_.loadShader("FlowAdapt.dxil",cs)||!flowAdaptPass_.create(context_.device(),cs,3+UINT(nrInstances_.size()),1,1))return false;+ // Stage-5 output stabiliser. Only allocated when the setting is non-zero:+ // a default session never pays for it and the dispatch is skipped below, so+ // the disabled path stays byte-identical to a build without this pass.+ if(desc_.nrHoldStrength>0.0f&&!createNrHoldPass())return false;+ // Keep the legacy ingress root signature when no independent colour grade+ // needs the FP32 side output. The extra UAV is part of the R5.3 contract+ // only for graphs that actually allocate preGradeRgba_.+ const UINT ingressUavCount = preGradeRgba_ ? 2u : 1u;+ if (!yuvPass_.loadShader("YuvToLinearRgb.dxil", cs) || !yuvPass_.create(context_.device(), cs, 12, 2, ingressUavCount, 12+kColorGradeConstantCount, 4)) return false;const char* rgbShader=desc_.packedInput?"PackedCaptureToLinear.dxil":desc_.yuy2Input?"Yuy2ToLinear.dxil":"RgbToLinear.dxil";- if((desc_.rgbInput||desc_.yuy2Input||desc_.packedInput)&&(!rgbPass_.loadShader(rgbShader,cs)||!rgbPass_.create(context_.device(),cs,12,1,1,8+kColorGradeConstantCount,4)))return false;+ if((desc_.rgbInput||desc_.yuy2Input||desc_.packedInput)&&(!rgbPass_.loadShader(rgbShader,cs)||!rgbPass_.create(context_.device(),cs,12,1,ingressUavCount,8+kColorGradeConstantCount,4)))return false;// Descriptor budget grows with the NR stack: encode needs one SRV+UAV pair// per layer, decode needs three SRVs and one UAV per layer. The base 8// slots the single-layer graph always used are kept as the floor.@@ -1218,6 +1455,45 @@ bool EnhanceGraph::createViews()stager_.stageSrv(resource, &srv, pass.heap.Get(), slot);};+ if(preNrColorActiveCount_){+ auto* input=workRgba_.Get();+ const auto& plan=*desc_.fixedExecutionPlan;+ for(uint32_t i=0;i<plan.stepCount;++i){+ const auto& step=plan.steps[i];+ if(step.type!=engine::EffectType::Color||!desc_.preNrColor(step.parameterIndex))continue;+ auto* output=nodeColorOutputs_[step.parameterIndex].Get();+ nodeColorInstances_[step.parameterIndex]->createViews(context_.device(),stager_,input,output);+ input=output;+ veyra::log::info("node-dispatch",std::format("pre-NR Color step={} parameter={} resource={} input={}x{} output={}x{}",+ i,step.parameterIndex,step.resourceIndex,step.input.width,step.input.height,step.output.width,step.output.height));+ }+ }+ if(interNrColorActiveCount_){+ const auto& plan=*desc_.fixedExecutionPlan;+ for(size_t layer=1;layer<nrInstances_.size();++layer){+ auto* input=interNrProtectionRgba_&&layer==desc_.interNrProtectionTarget()?interNrProtectionRgba_.Get():nrInstances_[layer-1]->fullTarget();+ for(uint32_t i=0;i<plan.stepCount;++i){+ const auto& step=plan.steps[i];+ if(step.type!=engine::EffectType::Color||desc_.interNrColorTarget(step.parameterIndex)!=layer)continue;+ auto* output=nodeColorOutputs_[step.parameterIndex].Get();+ nodeColorInstances_[step.parameterIndex]->createViews(context_.device(),stager_,input,output);+ input=output;+ veyra::log::info("node-dispatch",std::format("inter-NR Color step={} parameter={} resource={} beforeNR={} input={}x{} output={}x{}",+ i,step.parameterIndex,step.resourceIndex,layer,step.input.width,step.input.height,step.output.width,step.output.height));+ }+ }+ }+ if(preSrColorActiveCount_){+ auto* input=preSrBaseInput();+ const auto& plan=*desc_.fixedExecutionPlan;+ for(uint32_t i=0;i<plan.stepCount;++i){+ const auto& step=plan.steps[i];+ if(step.type!=engine::EffectType::Color||!desc_.preSrColor(step.parameterIndex))continue;+ auto* output=nodeColorOutputs_[step.parameterIndex].Get();+ nodeColorInstances_[step.parameterIndex]->createViews(context_.device(),stager_,input,output);+ input=output;+ }+ }stagedSrv(srcRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, blitPass_, 15);// Layer 0 downsamples the stage input; later layers downsample the previous// layer's result, so each gets its own slot-0 source.@@ -1230,9 +1506,7 @@ bool EnhanceGraph::createViews()for (size_t layerIndex = 0; layerIndex < nrInstances_.size(); ++layerIndex) {auto* layer = nrInstances_[layerIndex].get();const UINT k = UINT(layerIndex);- ID3D12Resource* source = layerIndex == 0- ? (desc_.nrBeforeSr ? srcRgba_.Get() : workRgba_.Get())- : nrInstances_[layerIndex - 1]->fullTarget();+ ID3D12Resource* source = nrLayerBase(layerIndex);stagedSrv(source, DXGI_FORMAT_R16G16B16A16_FLOAT, downsamplePass_, 2 * k);if (!layer->inputIsBorrowed()) {makeUav(context_.device(), layer->input(), DXGI_FORMAT_R16G16B16A16_FLOAT, cpu(downsamplePass_, 2 * layers + 2 * k));@@ -1251,9 +1525,7 @@ bool EnhanceGraph::createViews()const UINT k=UINT(layerIndex);// The shader reads base (t0), the NR-extent input (t1) and the neural// result (t2); the heap keeps those three per layer, in order.- ID3D12Resource* base=layerIndex==0- ?(desc_.nrBeforeSr?srcRgba_.Get():workRgba_.Get())- :nrInstances_[layerIndex-1]->fullTarget();+ ID3D12Resource* base=nrLayerBase(layerIndex);stagedSrv(base,DXGI_FORMAT_R16G16B16A16_FLOAT,residualPass_,3*k+0);stagedSrv(nrInstances_[layerIndex]->input(),DXGI_FORMAT_R16G16B16A16_FLOAT,residualPass_,3*k+1);stagedSrv(nrInstances_[layerIndex]->finalRgba(),DXGI_FORMAT_R16G16B16A16_FLOAT,residualPass_,3*k+2);@@ -1273,31 +1545,43 @@ bool EnhanceGraph::createViews()// the pass then writes the layer's full-extent target. Either way// `fullTarget()` is the finished image the next layer reads.layer->stabilised = layer->temporalEnabled;- ID3D12Resource* target = last ? residualRgba_.Get() : layer->outputFull();+ ID3D12Resource* target = last && nrInstances_.size()==1 ? residualRgba_.Get() : layer->outputFull();layer->setFullTarget(target);- ID3D12Resource* base = layerIndex == 0- ? (desc_.nrBeforeSr ? srcRgba_.Get() : workRgba_.Get())- : nrInstances_[layerIndex - 1]->fullTarget();+ ID3D12Resource* base = nrLayerBase(layerIndex);// Initialisation MUST come before the descriptor write: it is what// allocates the raw input the descriptor names. Writing the// descriptor first bound a null resource, so the composite went// nowhere and the final texture was never touched.if (layer->stabilised &&- !layer->temporal().initialize(context_.device(), base, flowTex_.Get(), target)) return false;+ !layer->temporal().initialize(context_.device(), base, flowTex_.Get(), target,+ layerIndex < desc_.nrLayersAntiFlicker.size()+ ? desc_.nrLayersAntiFlicker[layerIndex] : desc_.nrAntiFlicker)) return false;makeUav(context_.device(),layer->stabilised ? layer->temporal().raw() : target,DXGI_FORMAT_R16G16B16A16_FLOAT, cpu(residualPass_, 3 * residualLayers + UINT(layerIndex)));}}+ if(nrInstances_.size()>1){+ auto* original=nrBaseInput();+ stagedSrv(original,DXGI_FORMAT_R16G16B16A16_FLOAT,stackProtectionPass_,0);+ stagedSrv(original,DXGI_FORMAT_R16G16B16A16_FLOAT,stackProtectionPass_,1);+ auto* protectedInput=interNrProtectionRgba_?nrInstances_[desc_.interNrProtectionTarget()-1]->fullTarget():+ (preSrProtectionRgba_?nrInstances_[desc_.nrBeforeSrLayerCount()-1]->fullTarget():nrInstances_.back()->fullTarget());+ stagedSrv(protectedInput,DXGI_FORMAT_R16G16B16A16_FLOAT,stackProtectionPass_,2);+ auto* protectionOutput=interNrProtectionRgba_?interNrProtectionRgba_.Get():(preSrProtectionRgba_?preSrProtectionRgba_.Get():residualRgba_.Get());+ makeUav(context_.device(),protectionOutput,DXGI_FORMAT_R16G16B16A16_FLOAT,cpu(stackProtectionPass_,3));+ }stagedSrv(flowTex_.Get(),DXGI_FORMAT_R16G16_FLOAT,flowAdaptPass_,0);makeUav(context_.device(),nrFlow_.Get(),DXGI_FORMAT_R16G16_FLOAT,cpu(flowAdaptPass_,1));makeUav(context_.device(),baseFlow_.Get(),DXGI_FORMAT_R16G16_FLOAT,cpu(flowAdaptPass_,2));+ for(size_t i=0;i<nrInstances_.size();++i)+ makeUav(context_.device(),nrInstances_[i]->motion(),DXGI_FORMAT_R16G16_FLOAT,cpu(flowAdaptPass_,3+UINT(i)));if(desc_.hdrWorking()&&videoSrInput_){stagedSrv(srcRgba_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,hdrVideoSrPass_,0);stagedSrv(videoSrInput_.Get(),DXGI_FORMAT_R8G8B8A8_UNORM,hdrVideoSrPass_,1);stagedSrv(videoSrOutput_.Get(),DXGI_FORMAT_R8G8B8A8_UNORM,hdrVideoSrPass_,2);makeUav(context_.device(),workRgba_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,cpu(hdrVideoSrPass_,3));- stagedSrv(residualRgba_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,hdrVideoSrPass_,4);+ stagedSrv(srStageInput(),DXGI_FORMAT_R16G16B16A16_FLOAT,hdrVideoSrPass_,4);stagedSrv(videoSrInput_.Get(),DXGI_FORMAT_R8G8B8A8_UNORM,hdrVideoSrPass_,5);stagedSrv(videoSrOutput_.Get(),DXGI_FORMAT_R8G8B8A8_UNORM,hdrVideoSrPass_,6);}@@ -1305,10 +1589,14 @@ bool EnhanceGraph::createViews()if(desc_.rgbInput||desc_.yuy2Input||desc_.packedInput){stagedSrv(rgbTex_.Get(),DXGI_FORMAT_R8G8B8A8_UNORM,rgbPass_,0);makeUav(context_.device(),srcRgba_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,cpu(rgbPass_,1));+ if(preGradeRgba_)makeUav(context_.device(),preGradeRgba_.Get(),DXGI_FORMAT_R32G32B32A32_FLOAT,cpu(rgbPass_,2));}if (viewsTex) stagedSrv(lumaTex_.Get(), desc_.wideYuvInput()?DXGI_FORMAT_R16_UNORM:DXGI_FORMAT_R8_UNORM, yuvPass_, 0);if (viewsTex) stagedSrv(chromaTex_.Get(), desc_.wideYuvInput()?DXGI_FORMAT_R16G16_UNORM:DXGI_FORMAT_R8G8_UNORM, yuvPass_, 1);- if (viewsUav) makeUav(context_.device(), srcRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, cpu(yuvPass_, 2));+ if (viewsUav) {+ makeUav(context_.device(), srcRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, cpu(yuvPass_, 2));+ if(preGradeRgba_)makeUav(context_.device(),preGradeRgba_.Get(),DXGI_FORMAT_R32G32B32A32_FLOAT,cpu(yuvPass_,3));+ }// NR encode/decode descriptors are per layer. Each layer gets the same// slot layout inside its own ranges, so one shader pair serves every layer:// slot 0 = the layer's input, slot 1 = its proxy (encode) or neural output@@ -1342,7 +1630,7 @@ bool EnhanceGraph::createViews()// 13/14: genTex SRV (slot 2)if(videoSrInput_&&viewsUav)makeUav(context_.device(),videoSrInput_.Get(),DXGI_FORMAT_R8G8B8A8_UNORM,cpu(blitPass_,16));if(videoSrOutput_&&viewsTex)stagedSrv(videoSrOutput_.Get(),DXGI_FORMAT_R8G8B8A8_UNORM,blitPass_,17);- if (viewsTex) stagedSrv(residualRgba_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,blitPass_,18);+ if (viewsTex) stagedSrv(srStageInput(),DXGI_FORMAT_R16G16B16A16_FLOAT,blitPass_,18);if(videoHdrInput_&&viewsUav)makeUav(context_.device(),videoHdrInput_.Get(),DXGI_FORMAT_R8G8B8A8_UNORM,cpu(blitPass_,19));if(videoHdrOutput_&&viewsTex)stagedSrv(videoHdrOutput_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,blitPass_,20);if (viewsTex) stagedSrv(srcRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, blitPass_, 0);@@ -1361,8 +1649,35 @@ bool EnhanceGraph::createViews()stager_.stageSrv(colorLutTex_.Get(),&lutSrv,pass->heap.Get(),11);}}+ unsigned colorOrdinal=0;+ // When the ingress grade is disabled, independent instances must consume+ // the FP32 pre-grade conversion. Reading srcRgba_ here would quantize to+ // FP16 before the non-linear standalone grade and recreate the HDR drift.+ auto* colorInput=preGradeRgba_ ? preGradeRgba_.Get() : srcRgba_.Get();+ for(auto& instance:additionalColorInstances_)if(instance){+ // The last pass can write back to ingress once its input is scratch.+ // A single standalone pass uses one GPU CopyResource after dispatch.+ auto* target=(colorOrdinal+1==additionalColorActiveCount_&&colorOrdinal>0)?srcRgba_.Get():colorScratch_[colorOrdinal%2].Get();+ instance->createViews(context_.device(),stager_,colorInput,target);+ colorInput=target;++colorOrdinal;+ }if (viewsUav) makeUav(context_.device(), workRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, cpu(blitPass_, 1));- if (viewsTex) stagedSrv(nrEnabled_&&!desc_.nrBeforeSr ? residualRgba_.Get() : workRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, blitPass_, 2);+ auto* finalInput=nrEnabled_&&desc_.finalNrAfterSr()?residualRgba_.Get():(preNrColorOutput_?preNrColorOutput_:workRgba_.Get());+ if(tailColorActiveCount_){+ const auto& plan=*desc_.fixedExecutionPlan;+ for(uint32_t i=0;i<plan.stepCount;++i){+ const auto& step=plan.steps[i];+ if(step.type!=engine::EffectType::Color||!desc_.tailColor(step.parameterIndex))continue;+ auto& instance=*nodeColorInstances_[step.parameterIndex];+ auto* output=nodeColorOutputs_[step.parameterIndex].Get();+ instance.createViews(context_.device(),stager_,finalInput,output);+ finalInput=output;+ veyra::log::info("node-dispatch",std::format("tail Color step={} parameter={} resource={} input={}x{} output={}x{}",+ i,step.parameterIndex,step.resourceIndex,step.input.width,step.input.height,step.output.width,step.output.height));+ }+ tailColorOutput_=finalInput;+ }+ if (viewsTex) stagedSrv(finalInput, DXGI_FORMAT_R16G16B16A16_FLOAT, blitPass_, 2);if (viewsUav) makeUav(context_.device(), videoFrame_[0].Get(), outputFormat(), cpu(blitPass_, 3));if (viewsUav) makeUav(context_.device(), videoFrame_[1].Get(), outputFormat(), cpu(blitPass_, 4));if (viewsTex) stagedSrv(nvofInB_.Get(), DXGI_FORMAT_B8G8R8A8_UNORM, blitPass_, 5);@@ -1496,6 +1811,9 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameif(FAILED(hr)){veyra::log::error("graph",std::format("presentation handoff wait hr=0x{:X}",unsigned(hr)));return false;}}hardwareInputFrames_[parity].reset();+ // Set when this frame's own upload buffer feeds the GPU copy (see+ // CaptureUploadFrame.h); its read fence is recorded after submission.+ CaptureUploadFrame* gpuDirectFrame=nullptr;if(frame->format==AV_PIX_FMT_D3D12||frame->format==AV_PIX_FMT_D3D11){auto* retained=av_frame_clone(frame);if(!retained)return false;@@ -1544,7 +1862,13 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame}const unsigned ingressRowBytes=packed?packedIngressRowBytes(desc_.packedInput,srcW_):srcW_*(desc_.yuy2Input?2:4);if(frame->width!=int(srcW_)||frame->height!=int(srcH_)||!frame->data[0]||std::abs(int64_t(frame->linesize[0]))<int64_t(ingressRowBytes))return false;- for(uint32_t y=0;y<srcH_;++y){+ const unsigned ingressTexels=packed?packedIngressTexels(desc_.packedInput,srcW_):desc_.yuy2Input?srcW_/2:srcW_;+ // Live capture frame already in an upload buffer of this device+ // (CaptureUploadFrame.h): the GPU copies from the frame's own buffer.+ if(auto* upload=(packed||desc_.yuy2Input)?captureUploadFrame(frame):nullptr;upload&&upload->direct&&upload->proxyValid&&upload->planes==1&&+ upload->device.Get()==context_.device()&&frame->data[0]==upload->mapped&&upload->width==srcW_&&upload->height==srcH_&&+ upload->pitch>=ingressTexels*4&&upload->pixelBytes==(packed&&desc_.packedInput==1?3u:2u))gpuDirectFrame=upload;+ if(!gpuDirectFrame)for(uint32_t y=0;y<srcH_;++y){auto* dst=mappedRgb_[parity]+y*rgbPitch_;const auto* src=frame->data[0]+ptrdiff_t(y)*frame->linesize[0];if(packed||desc_.yuy2Input||frame->format==AV_PIX_FMT_RGBA)std::memcpy(dst,src,size_t(ingressRowBytes));else for(uint32_t x=0;x<srcW_;++x){@@ -1556,18 +1880,22 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameif(!desc_.stillImage){auto& sample=lumaSample_;sample.clear();sample.reserve(64*36);const bool bgr=frame->format==AV_PIX_FMT_BGRA||frame->format==AV_PIX_FMT_BGR0;+ // Upload-backed frames carry the same 64x36 pixels, sampled by the+ // capture callback; the write-combined buffer is never read here.+ const uint8_t* sampleData=gpuDirectFrame?gpuDirectFrame->proxy:frame->data[0];+ const ptrdiff_t samplePitch=gpuDirectFrame?ptrdiff_t(gpuDirectFrame->proxyPitch()):ptrdiff_t(frame->linesize[0]);for(unsigned y=0;y<36;++y)for(unsigned x=0;x<64;++x){- const unsigned sx=x*srcW_/64,sy=y*srcH_/36;- if(packed)sample.push_back(packedIngressLuma(*frame,desc_.packedInput,sx,sy));- else{const auto* p=frame->data[0]+ptrdiff_t(sy)*frame->linesize[0]+sx*(desc_.yuy2Input?2:4);+ const unsigned sx=gpuDirectFrame?x:x*srcW_/64,sy=gpuDirectFrame?y:y*srcH_/36;+ if(packed)sample.push_back(packedIngressLuma(sampleData,samplePitch,desc_.packedInput,sx,sy));+ else{const auto* p=sampleData+ptrdiff_t(sy)*samplePitch+sx*(desc_.yuy2Input?2:4);sample.push_back(desc_.yuy2Input?p[0]:uint8_t((54*unsigned(p[bgr?2:0])+183*unsigned(p[1])+19*unsigned(p[bgr?0:2])+128)>>8));}}analyzeLuma(sample);}tracker_.transition(list,rgbTex_.Get(),D3D12_RESOURCE_STATE_COPY_DEST);D3D12_TEXTURE_COPY_LOCATION dst{},src{};dst.pResource=rgbTex_.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;- src.pResource=upRgb_[parity].Get();src.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;- src.PlacedFootprint.Footprint={DXGI_FORMAT_R8G8B8A8_UNORM,packed?packedIngressTexels(desc_.packedInput,srcW_):desc_.yuy2Input?srcW_/2:srcW_,srcH_,1,UINT(rgbPitch_)};+ src.pResource=gpuDirectFrame?gpuDirectFrame->resource.Get():upRgb_[parity].Get();src.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;+ src.PlacedFootprint.Footprint={DXGI_FORMAT_R8G8B8A8_UNORM,ingressTexels,srcH_,1,gpuDirectFrame?gpuDirectFrame->pitch:UINT(rgbPitch_)};list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);tracker_.transition(list,rgbTex_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);} else if (frame->format == AV_PIX_FMT_D3D12 || frame->format == AV_PIX_FMT_D3D11) {@@ -1656,7 +1984,12 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameconst bool directUpload=sameLayout||(!desc_.wideYuvInput()&&(frame->format==AV_PIX_FMT_YUV420P||frame->format==AV_PIX_FMT_YUVJ420P));uint8_t* planes[4] = { directUpload?mappedLuma_[parity]:nv12Buf_.data(), directUpload?mappedChroma_[parity]:nv12Buf_.data() + lumaSize_ };const int strides[4] = { static_cast<int>(lumaPitch_), static_cast<int>(chromaPitch_) };- if(sameLayout){+ // Live capture frame already in an upload buffer of this device: no+ // CPU copy at all, the GPU copies from the frame's own buffer.+ if(auto* upload=sameLayout?captureUploadFrame(frame):nullptr;upload&&upload->direct&&upload->proxyValid&&upload->device.Get()==context_.device()&&+ frame->data[0]==upload->mapped&&upload->width==srcW_&&upload->height==srcH_&&upload->planes==2&&upload->pixelBytes==sampleBytes)gpuDirectFrame=upload;+ if(gpuDirectFrame){+ }else if(sameLayout){// Native semiplanar capture already matches the upload textures.// Copy rows once, preserving every code value and signed stride.const size_t rowBytes[2]={size_t(srcW_)*sampleBytes,size_t((srcW_+1)/2)*2*sampleBytes};@@ -1693,7 +2026,11 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameconst auto* sampleLuma=directUpload?frame->data[0]:planes[0];const auto samplePitch=directUpload?ptrdiff_t(frame->linesize[0]):ptrdiff_t(lumaPitch_);auto& sample=lumaSample_;sample.clear();sample.reserve(64*36);- for(unsigned y=0;y<36;++y)for(unsigned x=0;x<64;++x)+ static_assert(CaptureUploadFrame::kProxyWidth==64&&CaptureUploadFrame::kProxyHeight==36);+ // Same 64x36 points, sampled by the capture callback from the driver+ // sample: the upload buffer is write-combined and is never read here.+ if(gpuDirectFrame)for(unsigned i=0;i<64*36;++i)sample.push_back(gpuDirectFrame->proxy[i*sampleBytes+(sampleBytes-1)]);+ else for(unsigned y=0;y<36;++y)for(unsigned x=0;x<64;++x)sample.push_back(sampleLuma[ptrdiff_t(y*srcH_/36)*samplePitch+(x*srcW_/64)*sampleBytes+(sampleBytes-1)]);analyzeLuma(sample);if(!directUpload){for (uint32_t y = 0; y < srcH_; ++y)@@ -1701,20 +2038,21 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Framefor (uint32_t y = 0; y < (srcH_+1) / 2; ++y)std::memcpy(mappedChroma_[parity] + y * chromaPitch_, planes[1] + y * chromaPitch_, ((srcW_+1)/2)*(desc_.wideYuvInput()?4:2));}auto copyPlane = [&](ID3D12Resource* texture, ID3D12Resource* upload,- DXGI_FORMAT format, UINT width, UINT height, UINT pitch) {+ DXGI_FORMAT format, UINT width, UINT height, UINT pitch, UINT64 offset = 0) {tracker_.transition(list, texture, D3D12_RESOURCE_STATE_COPY_DEST);D3D12_TEXTURE_COPY_LOCATION dst{}, src{};dst.pResource = texture;dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;src.pResource = upload;src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;+ src.PlacedFootprint.Offset = offset;src.PlacedFootprint.Footprint = {format, width, height, 1, pitch};list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);};- copyPlane(lumaTex_.Get(), upLuma_[parity].Get(), desc_.wideYuvInput()?DXGI_FORMAT_R16_UNORM:DXGI_FORMAT_R8_UNORM,- srcW_, srcH_, static_cast<UINT>(lumaPitch_));- copyPlane(chromaTex_.Get(), upChroma_[parity].Get(), desc_.wideYuvInput()?DXGI_FORMAT_R16G16_UNORM:DXGI_FORMAT_R8G8_UNORM,- (srcW_+1)/2, (srcH_+1)/2, static_cast<UINT>(chromaPitch_));+ copyPlane(lumaTex_.Get(), gpuDirectFrame?gpuDirectFrame->resource.Get():upLuma_[parity].Get(), desc_.wideYuvInput()?DXGI_FORMAT_R16_UNORM:DXGI_FORMAT_R8_UNORM,+ srcW_, srcH_, gpuDirectFrame?gpuDirectFrame->pitch:static_cast<UINT>(lumaPitch_));+ copyPlane(chromaTex_.Get(), gpuDirectFrame?gpuDirectFrame->resource.Get():upChroma_[parity].Get(), desc_.wideYuvInput()?DXGI_FORMAT_R16G16_UNORM:DXGI_FORMAT_R8G8_UNORM,+ (srcW_+1)/2, (srcH_+1)/2, gpuDirectFrame?gpuDirectFrame->pitch:static_cast<UINT>(chromaPitch_), gpuDirectFrame?gpuDirectFrame->chromaOffset:0);tracker_.transition(list, lumaTex_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);tracker_.transition(list, chromaTex_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);}@@ -1722,15 +2060,15 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FramecpuTrace.mark("upload");// 2. YUV -> RGBA16F.- if(colorActive_&&colorDirty_)uploadColorTables(list);- auto convertInput=[&](bool grade){- tracker_.transition(list, srcRgba_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ if(colorActive_&&colorDirty_&&!uploadColorTables(list,slot))return false;+ auto convertInput=[&](bool grade, ID3D12Resource* target, UINT uavSlot){+ tracker_.transition(list, target, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);if(desc_.rgbInput||desc_.yuy2Input||desc_.packedInput){float c[8+kColorGradeConstantCount]={uintBits(srcW_),uintBits(srcH_),uintBits(workingTransferCode(resolved)),uintBits(resolved.range==ColorRange::Limited?1u:0u),resolved.range==ColorRange::Full?0.0f:1.0f,resolved.matrix==YuvMatrix::BT2020NCL?2.0f:resolved.matrix==YuvMatrix::BT601?0.0f:1.0f,resolved.primaries==ColorPrimaries::BT2020?1.0f:0.0f,uintBits(desc_.packedInput)};if(grade)packColorGradeConstants(colorTables_,c+8);if(resolved.scRgb){c[4]=desc_.hdrWorking()?1.f:2.f;c[5]=toneMapPeakNits_;}- rgbPass_.bind(list,c,gpuHandleOf(rgbPass_,gpuRgb?3+parity:0).ptr,gpuHandleOf(rgbPass_,1).ptr,gpuHandleOf(rgbPass_,8).ptr);+ rgbPass_.bind(list,c,gpuHandleOf(rgbPass_,gpuRgb?3+parity:0).ptr,gpuHandleOf(rgbPass_,1+uavSlot).ptr,gpuHandleOf(rgbPass_,8).ptr);list->Dispatch((srcW_+15)/16,(srcH_+15)/16,1);}else{float constants[12+kColorGradeConstantCount] = { resolved.range==ColorRange::Full?0.0f:1.0f,@@ -1739,21 +2077,35 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FrameuintBits(srcW_), uintBits(srcH_), uintBits((desc_.hdrWorking()?1u:0u)|(resolved.primaries==ColorPrimaries::BT2020?2u:0u)),uintBits(resolved.reconstructChroma?std::max(1u,unsigned(resolved.chromaLocation)):0u),toneMapPeakNits_,203.0f,0,0 };if(grade)packColorGradeConstants(colorTables_,constants+12);- yuvPass_.bind(list, constants, gpuHandleOf(yuvPass_, nv12Texture ? 3 + parity * 2 : 0).ptr, gpuHandleOf(yuvPass_, 2).ptr,gpuHandleOf(yuvPass_,8).ptr);+ yuvPass_.bind(list, constants, gpuHandleOf(yuvPass_, nv12Texture ? 3 + parity * 2 : 0).ptr, gpuHandleOf(yuvPass_, 2+uavSlot).ptr,gpuHandleOf(yuvPass_,8).ptr);list->Dispatch((srcW_ + 15) / 16, (srcH_ + 15) / 16, 1);}- tracker_.uavBarrier(list, srcRgba_.Get());+ tracker_.uavBarrier(list, target);};// Grading is fused into input conversion. Retain a genuinely ungraded// reference only when comparison requests it, then run the normal input.- if(colorActive_&&retainReferences){- convertInput(false);+ if(colorGradeActive()&&retainReferences){+ convertInput(false,srcRgba_.Get(),0);tracker_.transition(list,srcRgba_.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);tracker_.transition(list,sourceReferences_[parity].Get(),D3D12_RESOURCE_STATE_COPY_DEST);list->CopyResource(sourceReferences_[parity].Get(),srcRgba_.Get());tracker_.transition(list,sourceReferences_[parity].Get(),D3D12_RESOURCE_STATE_COMMON);}- convertInput(colorActive_);+ if(preGradeRgba_&&!colorActive_)convertInput(false,preGradeRgba_.Get(),1);+ else convertInput(colorActive_,srcRgba_.Get(),0);+ if(additionalColorActiveCount_){+ for(size_t i=0;i<additionalColorInstances_.size();++i)if(auto& instance=additionalColorInstances_[i]){+ // additionalColorInstances_[i] is Color parameter i+1.+ gpuTimer_.mark(list,diagnostics::colorNodeStage(unsigned(i+1)));+ if(!instance->dispatch(list,tracker_,slot,srcW_,srcH_,desc_.hdrWorking()))return false;+ gpuTimer_.mark(list,diagnostics::colorNodeStage(unsigned(i+1)),true);+ }+ }+ if(additionalColorActiveCount_==1){+ tracker_.transition(list,colorScratch_[0].Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);+ tracker_.transition(list,srcRgba_.Get(),D3D12_RESOURCE_STATE_COPY_DEST);+ list->CopyResource(srcRgba_.Get(),colorScratch_[0].Get());+ }tracker_.transition(list, srcRgba_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);if(gpuRgb)tracker_.transition(list,hardwareSurface->texture,D3D12_RESOURCE_STATE_COMMON);if (nv12Texture != nullptr) {@@ -1781,7 +2133,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame};// Guidance from original source-space color before SR/NR. Queue waits are GPU-side.bool haveFlow = false;- const bool runMotion = nvofStandalone_ || presentSinkFg() || fgEnabled_ || (srEnabled_ && (desc_.videoSrQuality==0||desc_.videoSrQuality==engine::kVideoSrFsr));+ const bool runMotion = nvofStandalone_ || (presentSinkFg()&&desc_.fgUsesFlow()) || (fgEnabled_&&desc_.fgUsesFlow()) || (srEnabled_&&desc_.srUsesFlow()&&(desc_.videoSrQuality==0||desc_.videoSrQuality==engine::kVideoSrFsr));if (runMotion && (gpuDis_ || amdOf_ || (nvof_ && nvof_->initialized()))) {const float dims[8] = {uintBits(nvofW_),uintBits(nvofH_),uintBits(nvofW_),uintBits(nvofH_),0,0,0,0};if (prevValid_) {@@ -1871,6 +2223,9 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Framelist->Dispatch((w+15)/16,(h+15)/16,1);tracker_.uavBarrier(list,output);tracker_.transition(list,output,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);};adapt(nrFlow_.Get(),nrW_,nrH_,1);adapt(baseFlow_.Get(),workW_,workH_,2);+ for(size_t i=0;i<nrInstances_.size();++i){const auto* layer=nrInstances_[i].get();+ if(layer->motion()!=nrFlow_.Get())adapt(layer->motion(),layer->width(),layer->height(),3+UINT(i));+ }}if(reset){++metrics_.resetCount;++epoch_;}out.historyReset=reset;@@ -1878,18 +2233,21 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameout.batch.a100ns=static_cast<int64_t>(std::llround(prevPtsMs_*10000));out.batch.b100ns=static_cast<int64_t>(std::llround(ptsMs*10000));gpuTimer_.identity(out.batch.identity);auto runSr=[&]()->bool{- if(srEnabled_&&fsrSrEnabled()&&haveFlow){+ if(desc_.splitNrAcrossSr())tracker_.transition(list,srStageInput(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ if(srEnabled_&&fsrSrEnabled()&&(haveFlow||!desc_.srUsesFlow())){// AMD FSR upscaling: FidelityFX effect, render-extent color + guidance// motion (previous = current + motion, same convention as the frame// generator) straight into the working texture. A frame without valid// motion falls through to the plain blit below instead of guessing.gpuTimer_.mark(list,GpuStage::Sr);const double deltaMs = (prevPtsMs_>=0.0&&ptsMs>prevPtsMs_)?(ptsMs-prevPtsMs_):16.6;- tracker_.transition(list,srcRgba_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);- tracker_.transition(list,flowTex_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ auto* srInput=desc_.splitNrAcrossSr()?srStageInput():(preSrColorOutput_?preSrColorOutput_:srcRgba_.Get());+ tracker_.transition(list,srInput,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ auto* srMotion=desc_.srUsesFlow()?flowTex_.Get():fsrSrZeroMotion_.Get();+ tracker_.transition(list,srMotion,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);tracker_.transition(list,fsrSrDepth_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);tracker_.transition(list,workRgba_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);- if(!fsrSrBackend_->evaluate(list,srcRgba_.Get(),flowTex_.Get(),fsrSrDepth_.Get(),workRgba_.Get(),+ if(!fsrSrBackend_->evaluate(list,srInput,srMotion,fsrSrDepth_.Get(),workRgba_.Get(),srcW_,srcH_,workW_,workH_,reset,float(deltaMs))){failedBackend_=engine::FailedBackend::Sr;return false;@@ -1903,10 +2261,11 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FramegpuTimer_.mark(list,GpuStage::Sr);tracker_.transition(list, workRgba_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);ngx::DlssSrBackend::EvalDesc ed{};- ed.color = desc_.nrBeforeSr?residualRgba_.Get():srcRgba_.Get();+ ed.color = srStageInput();+ tracker_.transition(list,ed.color,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);ed.output = workRgba_.Get();ed.depth = nrZeroDepth_.Get();- ed.motionVectors = haveFlow?baseFlow_.Get():nrZeroMotion_.Get();+ ed.motionVectors = haveFlow&&desc_.srUsesFlow()?baseFlow_.Get():nrZeroMotion_.Get();if(desc_.srMotionProbe)ed.motionVectors=desc_.srMotionProbe;ed.reset = reset;if (!srBackend_->evaluate(list, ngxParams_, ed, st)) {@@ -1922,7 +2281,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameconst float constants[8] = {uintBits(srcW_), uintBits(srcH_),uintBits(workW_), uintBits(workH_), 0, 0, 0, 0 };- blitPass_.bind(list, constants, gpuHandleOf(blitPass_, 0).ptr, gpuHandleOf(blitPass_, 1).ptr);+ blitPass_.bind(list, constants, gpuHandleOf(blitPass_, (preSrColorOutput_||desc_.splitNrAcrossSr())?18:0).ptr, gpuHandleOf(blitPass_, 1).ptr);list->Dispatch((workW_ + 15) / 16, (workH_ + 15) / 16, 1);tracker_.uavBarrier(list, workRgba_.Get());tracker_.transition(list, workRgba_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);@@ -1930,7 +2289,24 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameif (desc_.stageMark) desc_.stageMark("sr");cpuTrace.mark("sr");return true;};+ auto runBoundaryColor=[&](bool beforeSr)->bool{+ if(beforeSr?preSrColorActiveCount_:preNrColorActiveCount_){+ auto& logged=beforeSr?preSrColorExecutionLogged_:preNrColorExecutionLogged_;+ const auto& plan=*desc_.fixedExecutionPlan;+ for(uint32_t i=0;i<plan.stepCount;++i){+ const auto& step=plan.steps[i];+ if(step.type!=engine::EffectType::Color||!(beforeSr?desc_.preSrColor(step.parameterIndex):desc_.preNrColor(step.parameterIndex)))continue;+ gpuTimer_.mark(list,diagnostics::colorNodeStage(step.parameterIndex));+ if(!nodeColorInstances_[step.parameterIndex]->dispatch(list,tracker_,slot,step.output.width,step.output.height,desc_.hdrWorking()))return false;+ gpuTimer_.mark(list,diagnostics::colorNodeStage(step.parameterIndex),true);+ if(!logged)veyra::log::info("node-dispatch",std::format("recorded {} Color step={} parameter={} resource={}",beforeSr?"pre-SR":"pre-NR",i,step.parameterIndex,step.resourceIndex));+ if(desc_.stageMark)desc_.stageMark(beforeSr?"pre-sr-color":"pre-nr-color");+ }+ logged=true;+ }+ return true;};if(!desc_.nrBeforeSr&&!runSr())return false;+ if(!desc_.splitNrAcrossSr()&&!runBoundaryColor(false))return false;if(desc_.nrBeforeSr&&retainReferences){tracker_.transition(list,workRgba_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);const float c[8]={uintBits(srcW_),uintBits(srcH_),uintBits(workW_),uintBits(workH_),0,0,0,0};@@ -1940,11 +2316,35 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame// Comparison references belong to this real-frame lease. Avoid the two// full-frame copies when comparison is disabled.auto retain=[&](ID3D12Resource* src,ID3D12Resource* dst){tracker_.transition(list,src,D3D12_RESOURCE_STATE_COPY_SOURCE);tracker_.transition(list,dst,D3D12_RESOURCE_STATE_COPY_DEST);list->CopyResource(dst,src);tracker_.transition(list,dst,D3D12_RESOURCE_STATE_COMMON);tracker_.transition(list,src,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);};- if(!colorActive_)retain(srcRgba_.Get(),sourceReferences_[parity].Get());+ if(!colorGradeActive())retain(srcRgba_.Get(),sourceReferences_[parity].Get());if(baseReferences_[parity].Get()!=sourceReferences_[parity].Get())retain(workRgba_.Get(),baseReferences_[parity].Get());}+ // A downstream NR layer consumes the CURRENT upstream residual/temporal+ // result. Record that result before submitting the next layer's encode,+ // not in a second loop after all layers have already evaluated.+ auto compositeNrLayer = [&](size_t layerIndex) {+ auto* layer=nrInstances_[layerIndex].get();+ if(layer->handle()==nullptr||!layer->enabled)return;+ const bool temporallyStabilised=layer->stabilised;+ ID3D12Resource* destination=temporallyStabilised?layer->temporal().raw():layer->fullTarget();+ const auto& r=layer->residualSettings;+ // One exclusion stage protects against ALL NR layers, not only the+ // last layer's delta. Keep unmasked per-layer histories in a stack.+ const auto protection=nrInstances_.size()>1?engine::ProtectionSettings{}:layer->protection;+ tracker_.transition(list,destination,D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ float c[24]={r.total,r.darken,r.brighten,r.color,r.luminance,protection.enabled?1.0f:0.0f,protection.featherPixels,desc_.hdrWorking()?1.0f:0.0f};+ for(size_t i=0;i<4;++i){const auto q=engine::protectionConstants(protection.regions[i]);c[8+i*4]=q[0];c[9+i*4]=q[1];c[10+i*4]=q[2];c[11+i*4]=q[3];}+ const UINT residualLayers=UINT(std::max<size_t>(1,nrInstances_.size()));+ residualPass_.bind(list,c,gpuHandleOf(residualPass_,3u*UINT(layerIndex)).ptr,+ gpuHandleOf(residualPass_,3u*residualLayers+UINT(layerIndex)).ptr);+ list->Dispatch((layer->fullWidth()+15)/16,(layer->fullHeight()+15)/16,1);+ tracker_.uavBarrier(list,destination);+ tracker_.transition(list,destination,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ if(temporallyStabilised)layer->temporal().run(list,tracker_,reset,haveFlow,ptsMs-prevPtsMs_,r.total,protection);+ };+// 4. NR layers, in order. Each layer encodes its input to the 8-bit parity// proxy, evaluates its own Feature-18 handle, and decodes back to linear// FP16. Layer k reads layer k-1's decoded output, so the stack is a chain,@@ -1956,18 +2356,47 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame// (the original single-layer code did exactly the same, hence the identical// output). The ring is drained by submission, never by a CPU wait.if (nrEnabled_ && nrCreated()) {- const uint32_t sourceW = desc_.nrBeforeSr ? srcW_ : workW_;- const uint32_t sourceH = desc_.nrBeforeSr ? srcH_ : workH_;for (size_t layerIndex = 0; layerIndex < nrInstances_.size(); ++layerIndex) {+ const bool preSrProtection=preSrProtectionRgba_&&layerIndex==desc_.nrBeforeSrLayerCount();+ const bool interNrProtection=interNrProtectionRgba_&&layerIndex==desc_.interNrProtectionTarget();+ if(preSrProtection||interNrProtection){+ auto* original=nrBaseInput();+ auto* prefix=nrInstances_[layerIndex-1]->fullTarget();+ auto* output=interNrProtection?interNrProtectionRgba_.Get():preSrProtectionRgba_.Get();+ const auto extent=desc_.nrFullExtent(layerIndex-1);+ tracker_.transition(list,original,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ tracker_.transition(list,prefix,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ tracker_.transition(list,output,D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ // The original and upstream stack share this boundary's+ // extent. Later NR layers consume the masked result.+ float c[24]={1,1,1,1,1,1,desc_.protection.featherPixels,1.f};+ for(size_t i=0;i<4;++i){const auto q=engine::protectionConstants(desc_.protection.regions[i]);c[8+i*4]=q[0];c[9+i*4]=q[1];c[10+i*4]=q[2];c[11+i*4]=q[3];}+ stackProtectionPass_.bind(list,c,gpuHandleOf(stackProtectionPass_,0).ptr,gpuHandleOf(stackProtectionPass_,3).ptr);+ list->Dispatch((extent.width+15)/16,(extent.height+15)/16,1);+ tracker_.uavBarrier(list,output);+ tracker_.transition(list,output,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ if(desc_.stageMark)desc_.stageMark(interNrProtection?"inter-nr-protection":"pre-sr-protection");+ }+ if(desc_.splitNrAcrossSr()&&layerIndex==desc_.nrBeforeSrLayerCount()){+ if(!runBoundaryColor(true)||!runSr()||!runBoundaryColor(false))return false;+ }auto* layer = nrInstances_[layerIndex].get();+ const uint32_t sourceW=layer->fullWidth(),sourceH=layer->fullHeight();if (layer->handle() == nullptr || !layer->enabled) continue;- if (layer->width() != nrW_ || layer->height() != nrH_) {- veyra::log::error("graph", std::format("NR layer {} extent mismatch", layerIndex + 1));- return false;+ if(interNrColorActiveCount_){+ const auto& plan=*desc_.fixedExecutionPlan;+ for(uint32_t i=0;i<plan.stepCount;++i){+ const auto& step=plan.steps[i];+ if(step.type!=engine::EffectType::Color||desc_.interNrColorTarget(step.parameterIndex)!=layerIndex)continue;+ gpuTimer_.mark(list,diagnostics::colorNodeStage(step.parameterIndex));+ if(!nodeColorInstances_[step.parameterIndex]->dispatch(list,tracker_,slot,step.output.width,step.output.height,desc_.hdrWorking()))return false;+ gpuTimer_.mark(list,diagnostics::colorNodeStage(step.parameterIndex),true);+ if(!interNrColorExecutionLogged_)veyra::log::info("node-dispatch",std::format("recorded inter-NR Color step={} parameter={} resource={} afterNR={} beforeNR={}",i,step.parameterIndex,step.resourceIndex,layerIndex-1,layerIndex));+ if(desc_.stageMark)desc_.stageMark("inter-nr-color");+ }}- ID3D12Resource* stageInput = layerIndex == 0- ? (desc_.nrBeforeSr ? srcRgba_.Get() : workRgba_.Get())- : nrInstances_[layerIndex - 1]->outputFull();+ const uint32_t nrW=layer->width(),nrH=layer->height();+ ID3D12Resource* stageInput = nrLayerBase(layerIndex);// 4a. Downsample (unless the layer borrows the graph's input) and// the parity encode, on one list.@@ -1976,23 +2405,23 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frametracker_.transition(list, layer->input(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);} else {tracker_.transition(list, layer->input(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);- const float down[8] = {uintBits(sourceW), uintBits(sourceH), uintBits(nrW_), uintBits(nrH_), 0, 0, 0, 0};+ const float down[8] = {uintBits(sourceW), uintBits(sourceH), uintBits(nrW), uintBits(nrH), 0, 0, 0, 0};const UINT layers = UINT(std::max<size_t>(1, nrInstances_.size()));downsamplePass_.bind(list, down, gpuHandleOf(downsamplePass_, 2u * UINT(layerIndex)).ptr,gpuHandleOf(downsamplePass_, 2u * layers + 2u * UINT(layerIndex)).ptr);- list->Dispatch((nrW_ + 15) / 16, (nrH_ + 15) / 16, 1);+ list->Dispatch((nrW + 15) / 16, (nrH + 15) / 16, 1);tracker_.uavBarrier(list, layer->input());tracker_.transition(list, layer->input(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);}tracker_.transition(list, layer->proxy(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);const float constants[8] = {1.0f, 1.0f, 1.0f, desc_.hdrWorking() ? 1.0f : 0.0f,- uintBits(nrW_), uintBits(nrH_), 0.0f, 0.0f};+ uintBits(nrW), uintBits(nrH), 0.0f, 0.0f};{const UINT layers = UINT(std::max<size_t>(1, nrInstances_.size()));encPass_.bind(list, constants, gpuHandleOf(encPass_, UINT(layerIndex)).ptr,gpuHandleOf(encPass_, layers + UINT(layerIndex)).ptr);}- list->Dispatch((nrW_ + 15) / 16, (nrH_ + 15) / 16, 1);+ list->Dispatch((nrW + 15) / 16, (nrH + 15) / 16, 1);tracker_.uavBarrier(list, layer->proxy());tracker_.transition(list, layer->proxy(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);(void)stageInput;@@ -2013,12 +2442,12 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Framengx::ParameterBlock pb(layer->parameters());pb.setD3D12Resource(p::kColor, layer->proxy());pb.setD3D12Resource(p::kOutput, layer->neural());- pb.setD3D12Resource(p::kMVec, haveFlow ? nrFlow_.Get() : layer->zeroMotion());+ pb.setD3D12Resource(p::kMVec, haveFlow&&desc_.nrUsesFlow() ? layer->motion() : layer->zeroMotion());pb.setD3D12Resource(p::kDepth, layer->zeroDepth());- pb.setU32(p::kColorSubrectWidth, nrW_); pb.setU32(p::kColorSubrectHeight, nrH_);- pb.setU32(p::kOutputSubrectWidth, nrW_); pb.setU32(p::kOutputSubrectHeight, nrH_);- pb.setU32(p::kMVecSubrectWidth, nrW_); pb.setU32(p::kMVecSubrectHeight, nrH_);- pb.setU32(p::kDepthSubrectWidth, nrW_); pb.setU32(p::kDepthSubrectHeight, nrH_);+ pb.setU32(p::kColorSubrectWidth, nrW); pb.setU32(p::kColorSubrectHeight, nrH);+ pb.setU32(p::kOutputSubrectWidth, nrW); pb.setU32(p::kOutputSubrectHeight, nrH);+ pb.setU32(p::kMVecSubrectWidth, nrW); pb.setU32(p::kMVecSubrectHeight, nrH);+ pb.setU32(p::kDepthSubrectWidth, nrW); pb.setU32(p::kDepthSubrectHeight, nrH);pb.setF32(p::kMVecScaleX, 1.0f); pb.setF32(p::kMVecScaleY, 1.0f);pb.setI32(p::kDepthInverted, 1);pb.setI32(p::kIndicatorInvertX, 0);@@ -2035,7 +2464,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Framepb.setF32(p::kSkinStructureStrength, model.skin);pb.setI32(p::kUseAutoMask, model.autoMask);pb.setI32(p::kUICorrection, model.uiCorrection);- if (desc_.nrParameterProbe) desc_.nrParameterProbe(layer->parameters(), layer->proxy(), layer->neural(), nrW_, nrH_);+ if (desc_.nrParameterProbe) desc_.nrParameterProbe(layer->parameters(), layer->proxy(), layer->neural(), nrW, nrH);static bool injectedFailureConsumed = false;if (!injectedFailureConsumed && model.style == 2 && GetEnvironmentVariableW(L"VEYRA_TEST_REJECT_NR_STYLE2", nullptr, 0)) {injectedFailureConsumed = true;@@ -2048,6 +2477,9 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Framereturn false;}gpuTimer_.mark(nlist, GpuStage::Nr);+ // Node span: this layer's evaluate + parity decode on its own+ // list. The small encode/composite passes stay in stage spans.+ gpuTimer_.mark(nlist, diagnostics::nrLayerStage(unsigned(layerIndex)));uint64_t er = 0; uint32_t es = 0;cpuTrace.mark("nrParameters");if (!nrAdapter_->snippetEvaluateFeature(nlist, layer->handle(), layer->parameters(), er, es) ||@@ -2068,58 +2500,94 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame// 4c. Parity decode to the layer's own linear output.tracker_.transition(nlist, layer->finalRgba(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);const float constants[8] = {1.0f, 1.0f, 1.0f, desc_.hdrWorking() ? 1.0f : 0.0f,- uintBits(nrW_), uintBits(nrH_), 0.0f, 0.0f};+ uintBits(nrW), uintBits(nrH), 0.0f, 0.0f};{const UINT layers = UINT(std::max<size_t>(1, nrInstances_.size()));decPass_.bind(nlist, constants, gpuHandleOf(decPass_, 3u * UINT(layerIndex)).ptr,gpuHandleOf(decPass_, 3u * layers + UINT(layerIndex)).ptr);}- nlist->Dispatch((nrW_ + 15) / 16, (nrH_ + 15) / 16, 1);+ nlist->Dispatch((nrW + 15) / 16, (nrH + 15) / 16, 1);tracker_.uavBarrier(nlist, layer->finalRgba());tracker_.transition(nlist, layer->finalRgba(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ gpuTimer_.mark(nlist, diagnostics::nrLayerStage(unsigned(layerIndex)), true);layer->historyValid = true;layer->inputRevision = 1;}+ if (layerIndex + 1 < nrInstances_.size()) compositeNrLayer(layerIndex);+ if(desc_.splitNrAcrossSr()&&desc_.stageMark)desc_.stageMark("nr-layer");}+ if(interNrColorActiveCount_)interNrColorExecutionLogged_=true;}if (desc_.stageMark) desc_.stageMark("nr");cpuTrace.mark("nr");- // 5. Residual composite, once per layer. The shader takes the high-res base- // (t0), the NR-extent input (t1) and the NR-extent neural result (t2), and- // writes the high-res result (u0). Layer k composites onto layer k-1's- // result; the last layer writes the graph's residual texture, which is what- // the output blit already consumes. With a single layer both endpoints are- // the original pair, so the product path is unchanged.+ // 5. Final residual composite. Intermediate layers were composed before+ // their consumers above. Keep the single-layer command order unchanged.if(nrEnabled_&&nrCreated()){gpuTimer_.mark(list,GpuStage::Residual);- for(size_t layerIndex=0;layerIndex<nrInstances_.size();++layerIndex){- auto* layer=nrInstances_[layerIndex].get();- if(layer->handle()==nullptr||!layer->enabled)continue;- const bool last=(layerIndex+1==nrInstances_.size());- // A stabilised layer composites into the temporal pass's raw input- // (the pass then writes the real target); otherwise it writes the- // target directly. A stacked chain with the switch off keeps the- // byte-exact single-layer behaviour because no layer is stabilised.- const bool temporallyStabilised=layer->stabilised;- ID3D12Resource* destination=temporallyStabilised?layer->temporal().raw():(last?residualRgba_.Get():layer->outputFull());- const auto& r=layer->residualSettings;- const auto& protection=layer->protection;- tracker_.transition(list,destination,D3D12_RESOURCE_STATE_UNORDERED_ACCESS);- float c[24]={r.total,r.darken,r.brighten,r.color,r.luminance,protection.enabled?1.0f:0.0f,protection.featherPixels,desc_.hdrWorking()?1.0f:0.0f};- for(size_t i=0;i<4;++i){const auto q=protection.regions[i];c[8+i*4]=q.left;c[9+i*4]=q.top;c[10+i*4]=q.right;c[11+i*4]=q.bottom;}- const UINT residualLayers=UINT(std::max<size_t>(1,nrInstances_.size()));- residualPass_.bind(list,c,gpuHandleOf(residualPass_,3u*UINT(layerIndex)).ptr,- gpuHandleOf(residualPass_,3u*residualLayers+UINT(layerIndex)).ptr);- list->Dispatch(((desc_.nrBeforeSr?srcW_:workW_)+15)/16,((desc_.nrBeforeSr?srcH_:workH_)+15)/16,1);- tracker_.uavBarrier(list,destination);- tracker_.transition(list,destination,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);- if(temporallyStabilised)layer->temporal().run(list,tracker_,reset,haveFlow,ptsMs-prevPtsMs_,r.total,protection);+ if(!nrInstances_.empty())compositeNrLayer(nrInstances_.size()-1);+ if(nrInstances_.size()>1){+ auto* final=nrInstances_.back()->fullTarget();+ if(desc_.protection.enabled&&!preSrProtectionRgba_&&!interNrProtectionRgba_){+ auto* original=nrBaseInput();+ tracker_.transition(list,original,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ tracker_.transition(list,final,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ tracker_.transition(list,residualRgba_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ // Each layer already applies its own SDR/HDR residual policy.+ // This final exclusion mask must preserve the stack's signed+ // temporal output, including pixels outside protected regions.+ float c[24]={1,1,1,1,1,1,desc_.protection.featherPixels,1.f};+ for(size_t i=0;i<4;++i){const auto q=engine::protectionConstants(desc_.protection.regions[i]);c[8+i*4]=q[0];c[9+i*4]=q[1];c[10+i*4]=q[2];c[11+i*4]=q[3];}+ stackProtectionPass_.bind(list,c,gpuHandleOf(stackProtectionPass_,0).ptr,gpuHandleOf(stackProtectionPass_,3).ptr);+ list->Dispatch(((desc_.nrBeforeSr?srcW_:workW_)+15)/16,((desc_.nrBeforeSr?srcH_:workH_)+15)/16,1);+ tracker_.uavBarrier(list,residualRgba_.Get());+ }else{+ // Byte-exact unprotected output, avoiding residual subtraction+ // roundoff and keeping the additional cost explicit.+ tracker_.transition(list,final,D3D12_RESOURCE_STATE_COPY_SOURCE);+ tracker_.transition(list,residualRgba_.Get(),D3D12_RESOURCE_STATE_COPY_DEST);+ list->CopyResource(residualRgba_.Get(),final);+ tracker_.transition(list,final,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ }+ tracker_.transition(list,residualRgba_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);}gpuTimer_.mark(list,GpuStage::Residual,true);}- if(desc_.nrBeforeSr&&!runSr())return false;+ // 5b. Output stabiliser (anti-flicker, default off). Runs after the last NR+ // layer and the residual composite, before SR/FG, so it can only smooth what+ // NR emitted -- never a generated frame. The pass writes its own target and+ // the result is copied back into residualRgba_, which deliberately leaves+ // every downstream binding (SR, FG, tail colour, diagnostics) untouched.+ if(nrHoldPass_){+ gpuTimer_.mark(list,GpuStage::Residual);+ nrHoldPass_->run(list,tracker_,reset,desc_.nrHoldStrength,desc_.nrHoldTolerance);+ if(nrHoldPass_->active()&&nrHoldPass_->result()!=residualRgba_.Get()){+ auto* stabilised=nrHoldPass_->result();+ tracker_.transition(list,stabilised,D3D12_RESOURCE_STATE_COPY_SOURCE);+ tracker_.transition(list,residualRgba_.Get(),D3D12_RESOURCE_STATE_COPY_DEST);+ list->CopyResource(residualRgba_.Get(),stabilised);+ tracker_.transition(list,residualRgba_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ }+ gpuTimer_.mark(list,GpuStage::Residual,true);+ }++ if(!desc_.splitNrAcrossSr()&&!runBoundaryColor(true))return false;+ if(desc_.nrBeforeSr&&!desc_.splitNrAcrossSr()&&!runSr())return false;+ if(tailColorActiveCount_){+ const auto& plan=*desc_.fixedExecutionPlan;+ for(uint32_t i=0;i<plan.stepCount;++i){+ const auto& step=plan.steps[i];+ if(step.type!=engine::EffectType::Color||!desc_.tailColor(step.parameterIndex))continue;+ gpuTimer_.mark(list,diagnostics::colorNodeStage(step.parameterIndex));+ if(!nodeColorInstances_[step.parameterIndex]->dispatch(list,tracker_,slot,step.output.width,step.output.height,desc_.hdrWorking()))return false;+ gpuTimer_.mark(list,diagnostics::colorNodeStage(step.parameterIndex),true);+ if(!tailColorExecutionLogged_)veyra::log::info("node-dispatch",std::format("recorded tail Color step={} parameter={} resource={} after SR/NR/protection",i,step.parameterIndex,step.resourceIndex));+ if(desc_.stageMark)desc_.stageMark("tail-color");+ }+ tailColorExecutionLogged_=true;+ cpuTrace.mark("tailColor");+ }if(videoHdrBackend_){gpuTimer_.mark(list,GpuStage::VideoHdr);tracker_.transition(list,videoHdrInput_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);@@ -2139,7 +2607,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame{const UINT srcSlot = videoHdrBackend_?20:2;const UINT uavSlot = 3 + parity;- tracker_.transition(list, (nrEnabled_ && nrCreated() && !desc_.nrBeforeSr) ? residualRgba_.Get() : workRgba_.Get(),+ tracker_.transition(list, tailColorOutput_?tailColorOutput_:(nrEnabled_ && nrCreated() && desc_.finalNrAfterSr()) ? residualRgba_.Get() : (preNrColorOutput_?preNrColorOutput_:workRgba_.Get()),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);tracker_.transition(list, videoFrame_[parity].Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);const float constants[8] = {@@ -2152,17 +2620,19 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame}if(presentSinkFg()){- auto* input=haveFlow&&!reset?baseFlow_.Get():nrZeroMotion_.Get();+ auto* input=desc_.fgUsesFlow()&&haveFlow&&!reset?baseFlow_.Get():nrZeroMotion_.Get();tracker_.transition(list,input,D3D12_RESOURCE_STATE_COPY_SOURCE);tracker_.transition(list,presentMotion_[parity].Get(),D3D12_RESOURCE_STATE_COPY_DEST);list->CopyResource(presentMotion_[parity].Get(),input);tracker_.transition(list,input,D3D12_RESOURCE_STATE_COMMON);tracker_.transition(list,presentMotion_[parity].Get(),D3D12_RESOURCE_STATE_COMMON);- presentMotionValid_[parity]=haveFlow&&!reset;+ // Zero guidance still has valid source history. Marking it invalid+ // would reset XeSS on every frame and suppress interpolation.+ presentMotionValid_[parity]=(desc_.fgUsesFlow()?haveFlow:prevValid_)&&!reset;motionPreviousSource_[parity]=previousSource_;}previousSource_=sourceFrameId;- const bool fgBackendAvailable=fgEnabled_&&(fgBackend_&&fgBackend_->created());+ const bool fgBackendAvailable=fgEnabled_&&fgCreated();const unsigned fgMultiplier=previewMultiplier&&fgBackendAvailable?std::clamp(previewMultiplier,2u,desc_.fgMultiplier):desc_.fgMultiplier;out.fgCandidates=fgBackendAvailable?fgMultiplier-1:0;bool resetFg=reset||!prevValid_||fgHistorySkipped_;@@ -2195,15 +2665,16 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameout.videoFenceObject = context_.fence();// FG reads enhanced SDR color, not the pre-NR guidance input.- if (runFg && fgBackend_ && fgBackend_->created()) {+ if (runFg && fgCreated()) {for(uint32_t sub=1;sub<=fgCalls;++sub){const uint32_t generatedSlot=parity+(sub-1)*2;auto* flist=ring_.acquireNext(slot,st); if(!flist)return false;- auto* motion=desc_.fgMotionProbe?desc_.fgMotionProbe:(haveFlow?baseFlow_.Get():nrZeroMotion_.Get());+ auto* motion=desc_.fgMotionProbe?desc_.fgMotionProbe:(haveFlow&&desc_.fgUsesFlow()?baseFlow_.Get():nrZeroMotion_.Get());tracker_.transition(flist,videoFrame_[parity].Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);if(!desc_.fgMotionProbe)tracker_.transition(flist,motion,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);tracker_.transition(flist,depthTex_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);tracker_.transition(flist,genFrame_[generatedSlot].Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ if(!fsrFgBackend_){// One status resource for the whole input-frame pair, just like the// unchanged input parameters. Later MFG calls may retain its value.if(sub==1){@@ -2211,6 +2682,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameflist->CopyBufferRegion(fgDisable_[parity].Get(),0,fgDisableInit_.Get(),0,4);}tracker_.transition(flist,fgDisable_[parity].Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ }ngx::DlssFgBackend::EvalDesc fe{};fe.hdr=hdr10Output();fe.backbuffer=videoFrame_[parity].Get(); fe.depth=depthTex_.Get(); fe.mvecs=motion;fe.outputInterpolated=genFrame_[generatedSlot].Get(); fe.reset=resetFg;@@ -2223,14 +2695,27 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameif(sub==1)gpuTimer_.mark(flist,GpuStage::FgBatch);const auto timingStage=static_cast<GpuStage>(unsigned(GpuStage::Fg1)+sub-1);gpuTimer_.mark(flist,timingStage);cpuTrace.mark("fgPrepare");- if(!fgBackend_->evaluate(flist,ngxParams_,fe,st)){failedBackend_=engine::FailedBackend::Fg;return false;}+ if(fsrFgBackend_){+ // The SDK restores all externally registered textures to COMMON.+ tracker_.transition(flist,videoFrame_[parity].Get(),D3D12_RESOURCE_STATE_COMMON);+ tracker_.transition(flist,motion,D3D12_RESOURCE_STATE_COMMON);+ tracker_.transition(flist,depthTex_.Get(),D3D12_RESOURCE_STATE_COMMON);+ tracker_.transition(flist,genFrame_[generatedSlot].Get(),D3D12_RESOURCE_STATE_COMMON);+ const float interval=prevValid_&&ptsMs>prevPtsMs_?float(ptsMs-prevPtsMs_):16.6667f;+ if(!fsrFgBackend_->generate(flist,videoFrame_[parity].Get(),motion,depthTex_.Get(),+ genFrame_[generatedSlot].Get(),resetFg,interval)){+ failedBackend_=engine::FailedBackend::Fg;return false;+ }+ }else if(!fgBackend_->evaluate(flist,ngxParams_,fe,st)){failedBackend_=engine::FailedBackend::Fg;return false;}cpuTrace.mark("fgEvaluate");++out.fgEvaluated;gpuTimer_.mark(flist,timingStage,true);if(sub==fgCalls)gpuTimer_.mark(flist,GpuStage::FgBatch,true);tracker_.uavBarrier(flist,genFrame_[generatedSlot].Get());+ if(!fsrFgBackend_){tracker_.uavBarrier(flist,fgDisable_[parity].Get());tracker_.transition(flist,fgDisable_[parity].Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);flist->CopyBufferRegion(fgDisableReadback_[generatedSlot].Get(),0,fgDisable_[parity].Get(),0,4);+ }tracker_.transition(flist,videoFrame_[parity].Get(),D3D12_RESOURCE_STATE_COMMON);tracker_.transition(flist,genFrame_[generatedSlot].Get(),D3D12_RESOURCE_STATE_COMMON);tracker_.transition(flist,depthTex_.Get(),D3D12_RESOURCE_STATE_COMMON);@@ -2256,6 +2741,9 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame// transition videoFrame_[parity] back to COMMON. Recording it before FG// (sweep A2, tried 2026-09-22) raised cross-queue barrier errors.uploadFences_[parity]=ring_.lastSignaledValue();+ // The capture callback must not rewrite this frame's buffer before the+ // lists submitted above have read it.+ if(gpuDirectFrame)gpuDirectFrame->gpuRead(context_.fence(),uploadFences_[parity]);prevPtsMs_ = ptsMs;prevValid_ = true;@@ -2279,15 +2767,23 @@ bool EnhanceGraph::resolveFrame(FrameOutputs& out,uint32_t index)auto& frame=out.batch.frames[index];if(!frame.lease||!frame.lease->ready())return false;if(frame.kind!=FrameKind::Generated||frame.validity!=GenerationValidity::Pending)return true;+ if(fsrActive()){+ frame.validity=out.contentDuplicate?GenerationValidity::Disabled:GenerationValidity::Valid;+ if(out.contentDuplicate){++metrics_.fgDisabledFrames;++metrics_.fgDuplicateSuppressed;}else ++metrics_.fgGeneratedFrames;+ return true;+ }// Readback heaps may stay mapped; the 4-byte status is read directly.auto& mapped=fgDisableMapped_[frame.lease->slot];if(!mapped){D3D12_RANGE range{0,4};void* data=nullptr;const HRESULT hr=fgDisableReadback_[frame.lease->slot]->Map(0,&range,&data);if(FAILED(hr)){frame.validity=GenerationValidity::Failed;veyra::log::error("fg-status",std::format("Map hr=0x{:X}",unsigned(hr)));return true;}mapped=static_cast<const volatile uint8_t*>(data);}const bool disabled=*mapped!=0;const bool rejected=disabled||out.contentDuplicate;+ metrics_.fgProviderDisabled+=disabled;+ metrics_.fgDuplicateSuppressed+=out.contentDuplicate;+ metrics_.fgBothDisabled+=disabled&&out.contentDuplicate;frame.validity=rejected?GenerationValidity::Disabled:GenerationValidity::Valid;if(rejected)++metrics_.fgDisabledFrames;else ++metrics_.fgGeneratedFrames;- if(veyra::log::verboseFrameLogs())veyra::log::info("fg-status",std::format("batch={} frame={} epoch={} revision={} subframe={} fence={} disable={} valid={}",out.batch.batchId,out.realFrameIndex,out.batch.identity.epoch,out.batch.identity.settingsRevision,frame.subframe,frame.lease->readyFence,disabled,!rejected));+ if(veyra::log::verboseFrameLogs())veyra::log::info("fg-status",std::format("batch={} frame={} epoch={} revision={} subframe={} fence={} providerDisabled={} contentDuplicate={} valid={}",out.batch.batchId,out.realFrameIndex,out.batch.identity.epoch,out.batch.identity.settingsRevision,frame.subframe,frame.lease->readyFence,disabled,out.contentDuplicate,!rejected));return true;}@@ -2305,15 +2801,31 @@ bool EnhanceGraph::resolveGeneration(FrameOutputs& out)if(complete)out.hasGenerated=anyValid;return complete;}+uint64_t EnhanceGraph::failedNgxResult() const {+ switch(failedBackend_) {+ case engine::FailedBackend::Nr:return nrResult_;+ case engine::FailedBackend::Sr:return srBackend_?srBackend_->createResult():0;+ case engine::FailedBackend::Fg:return fgBackend_&&fgBackend_->createResult()?fgBackend_->createResult():fgInitResult_;+ default:return 0;+ }+}bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){+ if(!s.validate().empty())return false;+ if(s.hdrOutputMode!=desc_.hdrOutputMode||s.fgMotion!=desc_.fgMotion||s.srMotion!=desc_.srMotion||s.nrMotion!=desc_.nrMotion)return false;+ // These change the admitted split topology/reference contract. Refuse+ // before mutating any live parameter; the controller must rebuild.+ if((desc_.splitNrAcrossSr()||interNrProtectionRgba_)&&(!s.nr||s.protection.enabled!=desc_.protection.enabled||+ (s.protection.enabled&&!desc_.protectionBeforeSr()&&!interNrProtectionRgba_)))return false;+ auto nextNr=desc_;engine::describeNrLayers(s,nextNr);+ if(!desc_.nrLayersSizePolicy.empty()&&nextNr.nrLayersSizePolicy!=desc_.nrLayersSizePolicy)return false;if(s.nrTemporal!=desc_.nrTemporal)return false;- // Settings or protection changes must not revive old corrections: every- // layer's history is dropped, and later layers are marked as needing a- // reset because their input just changed.- for(size_t layerIndex=0;layerIndex<nrInstances_.size();++layerIndex){- nrInstances_[layerIndex]->temporal().reset();- if(layerIndex>0)++nrInstances_[layerIndex]->inputRevision;+ if(s.nr&&desc_.enableNr){+ if(s.activeNrLayerCount()!=nrInstances_.size())return false;+ for(size_t i=0;i<nrInstances_.size();++i){+ const bool temporal=i<nextNr.nrLayersTemporal.size()?nextNr.nrLayersTemporal[i]:s.nrTemporal;+ if(temporal!=nrInstances_[i]->temporalEnabled)return false;+ }}// A non-NVIDIA adapter keeps the user's requested NR setting in the UI// but has this NGX-only stage explicitly disabled in the graph. Do not@@ -2323,38 +2835,80 @@ bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){// DLSS allocates multiplier-specific feature/output resources.// XeSS has a fixed 2X proxy swapchain contract. Settings callers must// rebuild instead of accepting a change that cannot take effect in place.- if(s.nrRuntime!=desc_.nrRuntime||std::max(2u,s.multiplier)!=desc_.fgMultiplier||s.frameGenerationBackend!=desc_.frameGenerationBackend||s.videoSrQuality!=desc_.videoSrQuality||!s.validate().empty()||(s.multiplier>1&&!engine::presentSinkFrameGeneration(s.frameGenerationBackend)&&(!fgCapsAvailable_||s.multiplier-1>uint32_t(fgMultiFrameMax_))))return false;+ if(s.nrRuntime!=desc_.nrRuntime||std::max(2u,s.multiplier)!=desc_.fgMultiplier||s.frameGenerationBackend!=desc_.frameGenerationBackend||s.videoSrQuality!=desc_.videoSrQuality||!s.validate().empty()||(s.multiplier>1&&s.frameGenerationBackend==engine::FrameGenerationBackend::Dlss&&(!fgCapsAvailable_||s.multiplier-1>uint32_t(fgMultiFrameMax_))))return false;// The colour master switch changes the graph shape (tables + shader branch)// and must rebuild; every other colour field is a live uniform update.if(s.color.enabled!=desc_.color.enabled)return false;+ if(s.additionalColorCount!=desc_.additionalColorCount)return false;+ for(unsigned i=0;i<s.additionalColorCount;++i){+ const auto& a=s.additionalColors[i];const auto& b=desc_.additionalColors[i];+ if(a.enabled!=b.enabled||a.lutName!=b.lutName||a.lutInputSpace!=b.lutInputSpace)return false;+ }if(s.videoHdr.enabled!=desc_.videoHdr.enabled)return false;- desc_.videoHdr=s.videoHdr;// Switching the referenced .cube re-stages a descriptor, which needs the// queue drained: treat it as a rebuild (parameters stay live).- if(s.color.lutNameString()!=desc_.color.lutNameString())return false;- if(!(s.color==desc_.color)){desc_.color=s.color;refreshColorTables();}+ if(s.color.lutNameString()!=desc_.color.lutNameString()||s.color.lutInputSpace!=desc_.color.lutInputSpace)return false;+ desc_.videoHdr=s.videoHdr;+ if(!(s.color==desc_.color)){+ desc_.color=s.color;+ if(nodeColorInstances_[0])nodeColorInstances_[0]->refresh(s.color);+ else refreshColorTables();+ }+ for(unsigned i=0;i<s.additionalColorCount;++i)if(!(s.additionalColors[i]==desc_.additionalColors[i])){+ desc_.additionalColors[i]=s.additionalColors[i];+ if(additionalColorInstances_[i])additionalColorInstances_[i]->refresh(s.additionalColors[i]);+ if(nodeColorInstances_[i+1])nodeColorInstances_[i+1]->refresh(s.additionalColors[i]);+ }desc_.contentRate=s.content;desc_.model=s.model;desc_.residual=s.residual;desc_.protection=s.protection;desc_.settingsRevision=s.revision;- // Live parameter update: layer 0 keeps the product behaviour of taking the- // settings struct directly; further layers keep whatever the chain gave them.- if(!nrInstances_.empty()){- nrInstances_.front()->model=s.model;- nrInstances_.front()->residualSettings=s.residual;- nrInstances_.front()->protection=s.protection;- nrInstances_.front()->temporalEnabled=s.nrTemporal;- for(size_t layerIndex=1;layerIndex<nrInstances_.size();++layerIndex)++nrInstances_[layerIndex]->inputRevision;- }- desc_.fgMultiplier=std::max(2u,s.multiplier);desc_.enableNvofStandalone=s.nr&&!desc_.stillImage;nvofStandalone_=desc_.enableNvofStandalone;+ desc_.nrLayersModel=std::move(nextNr.nrLayersModel);+ desc_.nrLayersResidual=std::move(nextNr.nrLayersResidual);+ desc_.nrLayersTemporal=std::move(nextNr.nrLayersTemporal);+ desc_.nrLayersProtection=std::move(nextNr.nrLayersProtection);+ for(size_t i=0;i<nrInstances_.size();++i){+ auto& layer=*nrInstances_[i];+ if(s.nr){+ layer.model=i<desc_.nrLayersModel.size()?desc_.nrLayersModel[i]:s.model;+ layer.residualSettings=i<desc_.nrLayersResidual.size()?desc_.nrLayersResidual[i]:s.residual;+ layer.protection=i<desc_.nrLayersProtection.size()?desc_.nrLayersProtection[i]:s.protection;+ }+ layer.temporal().reset();+ // Reset this feature and its downstream consumers after input/parameter+ // changes, not just the final temporal filter. Rejected settings above+ // leave both the parameters and the history untouched.+ ++layer.inputRevision;+ }+ desc_.fgMultiplier=std::max(2u,s.multiplier);+ const bool temporalMotion=s.nrTemporal||std::any_of(s.nrLayers.begin(),s.nrLayers.begin()+s.nrLayerCount,[](const auto& n){return n.enabled&&n.temporal;});+ desc_.enableNvofStandalone=s.nr&&!desc_.stillImage&&(desc_.nrUsesFlow()||temporalMotion);nvofStandalone_=desc_.enableNvofStandalone;setNrEnabled(s.nr);setFgEnabled(s.multiplier>1&&!engine::presentSinkFrameGeneration(s.frameGenerationBackend));veyra::log::info("settings",std::format("requested revision={} intensity={} tone={} structure={} skin={} style={} autoMask={} UI={} residual={}/{}/{}/{}/{} multiplier={}",s.revision,s.model.intensity,s.model.tone,s.model.structure,s.model.skin,s.model.style,s.model.autoMask,s.model.uiCorrection,s.residual.total,s.residual.darken,s.residual.brighten,s.residual.color,s.residual.luminance,s.multiplier));return true;}void EnhanceGraph::setNrEnabled(bool on){+ const bool wasEnabled=nrEnabled_;nrEnabled_ = on && nrCreated();+ if(tailColorOutput_){+ // Live colour edits also call this setter. Keep the final blit bound+ // to the tail, rather than silently bypassing every downstream grade.+ // A genuine NR bypass changes only the first tail pass's input.+ if(wasEnabled!=nrEnabled_){+ const auto& plan=*desc_.fixedExecutionPlan;+ for(uint32_t i=0;i<plan.stepCount;++i){+ const auto& step=plan.steps[i];+ if(step.type!=engine::EffectType::Color||!desc_.tailColor(step.parameterIndex))continue;+ nodeColorInstances_[step.parameterIndex]->createViews(context_.device(),stager_,+ nrEnabled_&&desc_.finalNrAfterSr()?residualRgba_.Get():(preNrColorOutput_?preNrColorOutput_:workRgba_.Get()),+ nodeColorOutputs_[step.parameterIndex].Get());+ break;+ }+ }+ return;+ }// Refresh the section-5 blit SRV exactly as the probe did at runtime// (direct write into the visible heap - proven safe for this refresh).makeSrv(context_.device(),- nrEnabled_&&!desc_.nrBeforeSr ? residualRgba_.Get() : workRgba_.Get(),+ nrEnabled_&&desc_.finalNrAfterSr() ? residualRgba_.Get() : (preNrColorOutput_?preNrColorOutput_:workRgba_.Get()),DXGI_FORMAT_R16G16B16A16_FLOAT, cpuHandleOf(blitPass_, 2));}@@ -2362,7 +2916,7 @@ ID3D12Fence* EnhanceGraph::contextFence()const{return context_.fence();}uint32_t EnhanceGraph::actualFlowPerf()const{return nvof_?nvof_->caps().actualPerfLevel:0;}bool EnhanceGraph::fgCreated() const{- return fgBackend_ && fgBackend_->created();+ return fsrActive() || (fgBackend_ && fgBackend_->created());}uint64_t EnhanceGraph::lastNvofSignal() const@@ -2422,7 +2976,9 @@ void EnhanceGraph::shutdown()for(auto& motion:presentMotion_)motion.Reset();if(fsrSrBackend_){fsrSrBackend_->release();fsrSrBackend_.reset();}fsrSrDepth_.Reset();+ fsrSrZeroMotion_.Reset();upFsrSrZeroMotion_.Reset();upFsrSrDepth_.Reset();+ fsrFgBackend_.reset();if (fgBackend_) fgBackend_->release();if(videoSrBackend_){videoSrBackend_->release();videoSrBackend_.reset();}videoHdrBackend_.reset();videoHdrInput_.Reset();videoHdrOutput_.Reset();@@ -2445,6 +3001,21 @@ void EnhanceGraph::shutdown()if (nvof_) nvof_->shutdown();if (nvofOutEvent_ != nullptr) { CloseHandle(nvofOutEvent_); nvofOutEvent_ = nullptr; }+ // Each NR instance owns a core-allocated parameter block independently of+ // the shared graph parameters. Destroy it after feature release, while the+ // core is still alive, rather than relying on its shutdown leak fallback.+ if (coreHost_ && coreHost_->initialized()) {+ unsigned releasedNrParameters = 0;+ for (auto layer = nrInstances_.rbegin(); layer != nrInstances_.rend(); ++layer) {+ if ((*layer)->parameters() == nullptr) continue;+ coreHost_->destroyParameters((*layer)->parameters());+ (*layer)->setParameters(nullptr);+ ++releasedNrParameters;+ }+ if (releasedNrParameters != 0) {+ veyra::log::info("graph", std::format("NR parameter blocks explicitly destroyed={}", releasedNrParameters));+ }+ }if (coreHost_ && coreHost_->initialized() && ngxParams_ != nullptr) {coreHost_->destroyParameters(ngxParams_);ngxParams_ = nullptr;@@ -2463,14 +3034,26 @@ void EnhanceGraph::shutdown()decPass_ = ComputePass{};rgbPass_={};rgbTex_.Reset();for(unsigned i=0;i<2;++i){if(upRgb_[i]&&mappedRgb_[i])upRgb_[i]->Unmap(0,nullptr);mappedRgb_[i]=nullptr;upRgb_[i].Reset();}- downsamplePass_={};residualPass_={};flowAdaptPass_={};+ downsamplePass_={};residualPass_={};stackProtectionPass_={};flowAdaptPass_={};for(auto& layer:nrInstances_)layer->close();nrInstances_.clear();- residualRgba_.Reset();nrFlow_.Reset();baseFlow_.Reset();+ residualRgba_.Reset();preSrProtectionRgba_.Reset();interNrProtectionRgba_.Reset();nrFlow_.Reset();baseFlow_.Reset();for(unsigned i=0;i<kGeneratedPoolSlots;++i){if(fgDisableMapped_[i]&&fgDisableReadback_[i]){D3D12_RANGE written{0,0};fgDisableReadback_[i]->Unmap(0,&written);}fgDisableMapped_[i]=nullptr;fgDisable_[i].Reset();fgDisableReadback_[i].Reset();generatedLeases_[i].reset();genFrame_[i].Reset();}for(auto& lease:realLeases_)lease.reset();fgDisableInit_.Reset();encPass_ = ComputePass{};blitPass_ = ComputePass{};hdrVideoSrPass_={};yuvPass_ = ComputePass{};+ for(auto i=additionalColorInstances_.rbegin();i!=additionalColorInstances_.rend();++i)i->reset();+ for(auto i=nodeColorInstances_.rbegin();i!=nodeColorInstances_.rend();++i)i->reset();+ nodeColorOutputs_={};tailColorActiveCount_=preNrColorActiveCount_=preSrColorActiveCount_=interNrColorActiveCount_=0;+ preSrColorOutput_=nullptr;preSrColorExecutionLogged_=false;+ interNrColorOutputs_={};interNrColorExecutionLogged_=false;+ tailColorOutput_=preNrColorOutput_=nullptr;tailColorExecutionLogged_=preNrColorExecutionLogged_=false;+ colorScratch_={};additionalColorActiveCount_=0;+ colorTableUploads_.clear();+ colorLutStaging_={};colorLutUpload_.clear();colorLutPending_=colorLutSize_=colorLutStagingSlot_=0;+ colorCurveTex_.Reset();colorHueTex_.Reset();colorLumTex_.Reset();colorLutTex_.Reset();+ colorActive_=false;colorDirty_=true;colorTables_={};colorLutNotice_.clear();+ stager_={};toneMapPeakNits_=0;densifyPass_ = ComputePass{};confTex_.Reset();@@ -2486,7 +3069,7 @@ void EnhanceGraph::shutdown()neuralTex_.Reset();proxyTex_.Reset();for(auto& r:sourceReferences_)r.Reset();for(auto& r:baseReferences_)r.Reset();workRgba_.Reset();- srcRgba_.Reset();videoSrInput_.Reset();videoSrOutput_.Reset();+ preGradeRgba_.Reset();srcRgba_.Reset();videoSrInput_.Reset();videoSrOutput_.Reset();chromaTex_.Reset();lumaTex_.Reset();upZeroMotion_.Reset();diff --git a/src/pipeline/NrHoldPass.cpp b/src/pipeline/NrHoldPass.cppnew file mode 100644index 00000000..5f68469f--- /dev/null+++ b/src/pipeline/NrHoldPass.cpp@@ -0,0 +1,82 @@+#include "veyra/pipeline/NrHoldPass.h"+#include <bit>+#include <cmath>++namespace veyra::pipeline {++bool NrHoldPass::initialize(ID3D12Device* device, uint32_t width, uint32_t height,+ ID3D12Resource* current, ID3D12Resource* base)+{+ close();+ if (!device || !current || !base || width == 0 || height == 0) return false;+ current_ = current;+ base_ = base;+ width_ = width;+ height_ = height;+ // The source may be a different extent from the NR output under the+ // realtime NR policy; the shader rescales its neighbourhood accordingly.+ const auto baseDesc = base->GetDesc();+ baseWidth_ = uint32_t(baseDesc.Width);+ baseHeight_ = baseDesc.Height;+ for (unsigned i = 0; i < 2; ++i) {+ output_[i] = makeTexture(device, width, height, DXGI_FORMAT_R16G16B16A16_FLOAT, true);+ previousBase_[i] = makeTexture(device, width, height, DXGI_FORMAT_R16G16B16A16_FLOAT, true);+ if (!output_[i] || !previousBase_[i]) return false;+ }+ std::vector<uint8_t> shader;+ // One descriptor set per ping-pong phase (8 slots each): 4 SRVs + 2 UAVs.+ // The set is staged once and never rewritten per frame.+ if (!pass_.loadShader("NrHold.dxil", shader) || !pass_.create(device, shader, 16, 4, 2)) return false;+ DescriptorStager staging;+ if (!staging.initialize(device, 16)) return false;+ for (unsigned i = 0; i < 2; ++i) {+ // Reading the *other* phase's results as history keeps the slot mapping+ // stable across frames.+ ID3D12Resource* sources[] = {current, output_[1 - i].Get(), base, previousBase_[1 - i].Get()};+ for (unsigned j = 0; j < 4; ++j) staging.stageSrv(sources[j], nullptr, pass_.heap.Get(), i * 8 + j);+ makeUav(device, output_[i].Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, cpuHandleOf(pass_, i * 8 + 4));+ makeUav(device, previousBase_[i].Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, cpuHandleOf(pass_, i * 8 + 5));+ }+ return true;+}++void NrHoldPass::run(ID3D12GraphicsCommandList* list, StateTracker& tracker, bool reset,+ float strength, float tolerance)+{+ if (pass_.pso == nullptr || strength <= 0.f || !std::isfinite(strength)) return;+ const unsigned i = index_;+ // History is only meaningful when the previous frame was actually written+ // by this pass; on a reset the shader sees UseHistory 0 and publishes the+ // current value unchanged while still seeding the anchor.+ const float c[8] = {+ std::bit_cast<float>(width_), std::bit_cast<float>(height_),+ std::bit_cast<float>(baseWidth_), std::bit_cast<float>(baseHeight_),+ strength, tolerance, valid_ && !reset ? 1.f : 0.f, 0.f};+ tracker.transition(list, current_, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ tracker.transition(list, output_[1 - i].Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ tracker.transition(list, base_, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ tracker.transition(list, previousBase_[1 - i].Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ for (auto* r : {output_[i].Get(), previousBase_[i].Get()})+ tracker.transition(list, r, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ pass_.bind(list, c, gpuHandleOf(pass_, i * 8).ptr, gpuHandleOf(pass_, i * 8 + 4).ptr);+ list->Dispatch((width_ + 7) / 8, (height_ + 7) / 8, 1);+ for (auto* r : {output_[i].Get(), previousBase_[i].Get()})+ tracker.uavBarrier(list, r);+ // The written pair becomes the next frame's history source. A reset still+ // advances the ping-pong: the current frame is what the next one compares+ // against, reset or not.+ valid_ = true;+ index_ = 1 - i;+}++void NrHoldPass::close()+{+ pass_ = {};+ for (auto& r : output_) r.Reset();+ for (auto& r : previousBase_) r.Reset();+ current_ = base_ = nullptr;+ width_ = height_ = baseWidth_ = baseHeight_ = index_ = 0;+ valid_ = false;+}++} // namespace veyra::pipelinediff --git a/src/pipeline/NrInstance.cpp b/src/pipeline/NrInstance.cppindex 9fcec8f9..e9fcc786 100644--- a/src/pipeline/NrInstance.cpp+++ b/src/pipeline/NrInstance.cpp@@ -4,7 +4,7 @@ namespace veyra::pipeline {bool NrInstance::create(ID3D12Device* device, uint32_t width, uint32_t height,uint32_t fullWidth, uint32_t fullHeight,ID3D12Resource* zeroMotion, ID3D12Resource* zeroDepth,- ID3D12Resource* borrowedInput) {+ ID3D12Resource* borrowedInput, ID3D12Resource* borrowedMotion) {if (device == nullptr || width == 0 || height == 0 || zeroMotion == nullptr || zeroDepth == nullptr) return false;if (fullWidth == 0 || fullHeight == 0) return false;close();@@ -20,7 +20,7 @@ bool NrInstance::create(ID3D12Device* device, uint32_t width, uint32_t height,// A borrowed input keeps the graph's original aliasing behaviour (no copy,// no downsample); otherwise the layer owns an NR-extent input.inputIsBorrowed_ = borrowedInput != nullptr;- if (borrowedInput != nullptr) input_ = borrowedInput; // borrowed: never released here+ if (borrowedInput != nullptr) input_ = borrowedInput; // ComPtr holds its own reference to the graph's input.else input_ = makeTexture(device, width, height, DXGI_FORMAT_R16G16B16A16_FLOAT, true);proxy_ = makeTexture(device, width, height, DXGI_FORMAT_R8G8B8A8_UNORM, true);neural_ = makeTexture(device, width, height, DXGI_FORMAT_R8G8B8A8_UNORM, true);@@ -30,20 +30,25 @@ bool NrInstance::create(ID3D12Device* device, uint32_t width, uint32_t height,// so an unused allocation there is harmless but wasteful, hence the caller// telling us the extent rather than us guessing the role.outputFull_ = makeTexture(device, fullWidth, fullHeight, DXGI_FORMAT_R16G16B16A16_FLOAT, true);- if (!input_ || !proxy_ || !neural_ || !finalRgba_ || !residual_ || !outputFull_) { close(); return false; }+ if(borrowedMotion)motion_=borrowedMotion;+ else motion_=makeTexture(device,width,height,DXGI_FORMAT_R16G16_FLOAT,true);+ if (!input_ || !proxy_ || !neural_ || !finalRgba_ || !residual_ || !outputFull_ || !motion_) { close(); return false; }historyValid = false;return true;}void NrInstance::close() {temporal_.close();- if (!inputIsBorrowed_) input_.Reset();+ // Both owned and borrowed inputs are ComPtrs. Release this reference in+ // either case; the graph retains its own reference to a borrowed input.+ input_.Reset();inputIsBorrowed_ = false;proxy_.Reset();neural_.Reset();finalRgba_.Reset();residual_.Reset();outputFull_.Reset();+ motion_.Reset();baseFull_ = nullptr;fullTarget_ = nullptr;zeroMotion_ = zeroDepth_ = nullptr;diff --git a/src/pipeline/NrTemporalPass.cpp b/src/pipeline/NrTemporalPass.cppindex 68a2e04c..8258db44 100644--- a/src/pipeline/NrTemporalPass.cpp+++ b/src/pipeline/NrTemporalPass.cpp@@ -3,40 +3,120 @@#include <cmath>#include <algorithm>namespace veyra::pipeline {-bool NrTemporalPass::initialize(ID3D12Device* device,ID3D12Resource* base,ID3D12Resource* motion,ID3D12Resource* output){- close();base_=base;motion_=motion;output_=output;+namespace {+// Route numbers must match shaders/NrTemporal.hlsl.+unsigned routeOf(engine::NrAntiFlicker tier){+ switch(tier){+ case engine::NrAntiFlicker::Static: return 1;+ case engine::NrAntiFlicker::Flow: return 2;+ case engine::NrAntiFlicker::FlowPlus: return 3;+ case engine::NrAntiFlicker::LowFrequency: return 4;+ default: return 0;+ }+}+}+bool NrTemporalPass::initialize(ID3D12Device* device,ID3D12Resource* base,ID3D12Resource* motion,ID3D12Resource* output,+ engine::NrAntiFlicker tier){+ close();base_=base;motion_=motion;output_=output;tier_=tier;if(!base||!motion||!output)return false;auto desc=base->GetDesc();width_=unsigned(desc.Width);height_=desc.Height;+ // The low-frequency route filters a half-resolution observation, so it needs+ // its own pair of half-extent textures. Other routes never allocate them and+ // bind the guide history into those slots instead: the shader cannot read+ // them outside route 4, so an unused binding is safe and costs nothing.+ const bool lowFrequency=routeOf(tier)==4;+ if(lowFrequency){+ lowWidth_=(width_+1)/2;lowHeight_=(height_+1)/2;+ lowResidual_=makeTexture(device,lowWidth_,lowHeight_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);+ lowGuide_=makeTexture(device,lowWidth_,lowHeight_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);+ if(!lowResidual_||!lowGuide_)return false;+ }else{lowWidth_=width_;lowHeight_=height_;}raw_=makeTexture(device,width_,height_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);for(unsigned i=0;i<2;++i){history_[i]=makeTexture(device,width_,height_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);guide_[i]=makeTexture(device,width_,height_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);if(!history_[i]||!guide_[i])return false;}- std::vector<uint8_t> shader;if(!raw_||!pass_.loadShader("NrTemporal.dxil",shader)||!pass_.create(device,shader,16,5,3,24))return false;- DescriptorStager staging;if(!staging.initialize(device,10))return false;+ std::vector<uint8_t> shader;+ // 7 SRVs (base, raw, history, guide, motion, low residual, low guide), 3 UAVs,+ // 28 constants: the original 24 plus Route, LowSize and a pad.+ if(!raw_||!pass_.loadShader("NrTemporal.dxil",shader)||!pass_.create(device,shader,20,7,3,28))return false;+ if(lowFrequency){+ std::vector<uint8_t> reduce;+ // 3 SRVs + 2 UAVs = 5 slots per phase, two phases.+ if(!reducePass_.loadShader("NrTemporalReduce.dxil",reduce)||!reducePass_.create(device,reduce,10,3,2,8))return false;+ DescriptorStager reduceStaging;if(!reduceStaging.initialize(device,10))return false;+ for(unsigned i=0;i<2;++i){+ // Input and Base are the same image in this graph; the reduce shader+ // only needs the difference Raw - Base plus the guide.+ ID3D12Resource* sources[]={base,base,raw_.Get()};+ for(unsigned j=0;j<3;++j)reduceStaging.stageSrv(sources[j],nullptr,reducePass_.heap.Get(),i*5+j);+ makeUav(device,lowResidual_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,cpuHandleOf(reducePass_,i*5+3));+ makeUav(device,lowGuide_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,cpuHandleOf(reducePass_,i*5+4));+ }+ }+ DescriptorStager staging;if(!staging.initialize(device,20))return false;for(unsigned i=0;i<2;++i){- ID3D12Resource* sources[]={base,raw_.Get(),history_[1-i].Get(),guide_[1-i].Get(),motion};- for(unsigned j=0;j<5;++j)staging.stageSrv(sources[j],nullptr,pass_.heap.Get(),i*8+j);- makeUav(device,output,DXGI_FORMAT_R16G16B16A16_FLOAT,cpuHandleOf(pass_,i*8+5));- makeUav(device,history_[i].Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,cpuHandleOf(pass_,i*8+6));- makeUav(device,guide_[i].Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,cpuHandleOf(pass_,i*8+7));- }return true;+ ID3D12Resource* sources[]={base,raw_.Get(),history_[1-i].Get(),guide_[1-i].Get(),motion,+ lowFrequency?lowResidual_.Get():guide_[1-i].Get(),+ lowFrequency?lowGuide_.Get():guide_[1-i].Get()};+ for(unsigned j=0;j<7;++j)staging.stageSrv(sources[j],nullptr,pass_.heap.Get(),i*10+j);+ makeUav(device,output,DXGI_FORMAT_R16G16B16A16_FLOAT,cpuHandleOf(pass_,i*10+7));+ makeUav(device,history_[i].Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,cpuHandleOf(pass_,i*10+8));+ makeUav(device,guide_[i].Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,cpuHandleOf(pass_,i*10+9));+ }+ return true;}void NrTemporalPass::run(ID3D12GraphicsCommandList* list,StateTracker& tracker,bool reset,bool haveMotion,double frameMs,float total,const engine::ProtectionSettings& protection){const auto i=index_;- const bool useHistory=valid_&&!reset&&haveMotion&&std::isfinite(frameMs)&&frameMs>0&&frameMs<=250;+ // An interval outside the window is not a normal step: the history chain was+ // built on a different cadence, so it must not be blended across. Judging it+ // here (rather than only at the call site) keeps the invariant with the pass+ // that owns `valid_`, so a caller that forgets to reset cannot silently+ // reuse a stale chain. The threshold matches the graph's own timeline rule.+ const bool intervalSane=std::isfinite(frameMs)&&frameMs>0&&frameMs<=250;+ if(!intervalSane&&valid_)valid_=false;+ const bool useHistory=valid_&&!reset&&haveMotion&&intervalSane;+ // 80 ms past-history EMA; no future frames or presentation holdback.+ const float weight=useHistory?float(std::exp(-frameMs/80.0)):0.f;+ const unsigned route=routeOf(tier_);+ if(route==4){+ // The reduce pass writes the *other* phase's half-resolution pair, which+ // the main pass then reads as its current observation.+ tracker.transition(list,base_,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ tracker.transition(list,raw_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ for(auto* r:{lowResidual_.Get(),lowGuide_.Get()})tracker.transition(list,r,D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ const float rc[8]={std::bit_cast<float>(width_),std::bit_cast<float>(height_),+ std::bit_cast<float>(lowWidth_),std::bit_cast<float>(lowHeight_),+ 0.f,protection.enabled?1.f:0.f,0.f,0.f};+ reducePass_.bind(list,rc,gpuHandleOf(reducePass_,0).ptr,gpuHandleOf(reducePass_,3).ptr);+ list->Dispatch((lowWidth_+7)/8,(lowHeight_+7)/8,1);+ for(auto* r:{lowResidual_.Get(),lowGuide_.Get()}){tracker.uavBarrier(list,r);tracker.transition(list,r,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);}+ }tracker.transition(list,raw_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);tracker.transition(list,base_,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);tracker.transition(list,motion_,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);tracker.transition(list,history_[1-i].Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);tracker.transition(list,guide_[1-i].Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);for(auto* r:{output_,history_[i].Get(),guide_[i].Get()})tracker.transition(list,r,D3D12_RESOURCE_STATE_UNORDERED_ACCESS);- // 80 ms past-history EMA; no future frames or presentation holdback.- const float weight=useHistory?float(std::exp(-frameMs/80.0)):0.f;- float c[24]={std::bit_cast<float>(width_),std::bit_cast<float>(height_),weight,total,protection.enabled?1.f:0.f,protection.featherPixels,0,0};- for(unsigned n=0;n<4;++n){const auto r=protection.regions[n];c[8+n*4]=r.left;c[9+n*4]=r.top;c[10+n*4]=r.right;c[11+n*4]=r.bottom;}- pass_.bind(list,c,gpuHandleOf(pass_,i*8).ptr,gpuHandleOf(pass_,i*8+5).ptr);+ float c[28]={std::bit_cast<float>(width_),std::bit_cast<float>(height_),weight,total,protection.enabled?1.f:0.f,protection.featherPixels,0,0};+ for(unsigned n=0;n<4;++n){const auto r=engine::protectionConstants(protection.regions[n]);c[8+n*4]=r[0];c[9+n*4]=r[1];c[10+n*4]=r[2];c[11+n*4]=r[3];}+ // Route and the low-frequency extent follow the region block. The shader+ // reads LowSize only on route 4 and the pad is never read: they exist to+ // keep the region offsets identical to the pre-tier layout.+ c[24]=std::bit_cast<float>(route);+ c[25]=std::bit_cast<float>(lowWidth_);+ c[26]=std::bit_cast<float>(lowHeight_);+ c[27]=0.f;+ pass_.bind(list,c,gpuHandleOf(pass_,i*10).ptr,gpuHandleOf(pass_,i*10+7).ptr);list->Dispatch((width_+7)/8,(height_+7)/8,1);for(auto* r:{output_,history_[i].Get(),guide_[i].Get()}){tracker.uavBarrier(list,r);tracker.transition(list,r,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);}valid_=true;index_=1-i;}-void NrTemporalPass::close(){pass_={};raw_.Reset();for(auto& r:history_)r.Reset();for(auto& r:guide_)r.Reset();base_=motion_=output_=nullptr;width_=height_=index_=0;valid_=false;}+void NrTemporalPass::close(){+ pass_={};reducePass_={};raw_.Reset();+ for(auto& r:history_)r.Reset();+ for(auto& r:guide_)r.Reset();+ lowResidual_.Reset();+ lowGuide_.Reset();+ base_=motion_=output_=nullptr;width_=height_=lowWidth_=lowHeight_=index_=0;+ tier_=engine::NrAntiFlicker::Flow;valid_=false;+}}diff --git a/src/sink/WasapiAudioSink.cpp b/src/sink/WasapiAudioSink.cppindex 0b51edc6..46aa4e3f 100644--- a/src/sink/WasapiAudioSink.cpp+++ b/src/sink/WasapiAudioSink.cpp@@ -1,5 +1,8 @@#include "veyra/sink/AudioGain.h"#include "veyra/sink/WasapiAudioSink.h"+#include <functiondiscoverykeys_devpkey.h>+#include <propvarutil.h>+#pragma comment(lib, "propsys.lib")#include <algorithm>#include <array>@@ -345,18 +348,105 @@ bool AudioRenderer::copyPcm(BYTE* destination,const float* input,size_t frames){std::memcpy(destination,mixed_.data(),frames*outputFormat_.channels*sizeof(float));return true;}+namespace {+std::mutex gEndpointMutex;+std::wstring gPreferredEndpoint;+bool gForceStereo = false;+ActiveRenderEndpoint gActiveEndpoint;+std::atomic<uint64_t> gEndpointGeneration{1};+std::wstring endpointName(IMMDevice* device){+ std::wstring name;IPropertyStore* store=nullptr;+ if(device&&SUCCEEDED(device->OpenPropertyStore(STGM_READ,&store))){+ PROPVARIANT value;PropVariantInit(&value);+ if(SUCCEEDED(store->GetValue(PKEY_Device_FriendlyName,&value))&&value.vt==VT_LPWSTR&&value.pwszVal)name=value.pwszVal;+ PropVariantClear(&value);store->Release();+ }+ return name;+}+std::wstring endpointId(IMMDevice* device){+ std::wstring id;LPWSTR raw=nullptr;+ if(device&&SUCCEEDED(device->GetId(&raw))&&raw){id=raw;CoTaskMemFree(raw);}+ return id;+}+std::string narrowName(const std::wstring& w){+ if(w.empty())return {};+ const int n=WideCharToMultiByte(CP_UTF8,0,w.data(),int(w.size()),nullptr,0,nullptr,nullptr);+ std::string out(size_t(std::max(n,0)),'\0');+ if(n>0)WideCharToMultiByte(CP_UTF8,0,w.data(),int(w.size()),out.data(),n,nullptr,nullptr);+ return out;+}+}+std::vector<RenderEndpoint> enumerateRenderEndpoints(){+ std::vector<RenderEndpoint> out;+ const HRESULT com=CoInitializeEx(nullptr,COINIT_MULTITHREADED);+ IMMDeviceEnumerator* enumerator=nullptr;+ if(SUCCEEDED(CoCreateInstance(__uuidof(MMDeviceEnumerator),nullptr,CLSCTX_ALL,__uuidof(IMMDeviceEnumerator),reinterpret_cast<void**>(&enumerator)))){+ std::wstring defaultId;IMMDevice* fallback=nullptr;+ if(SUCCEEDED(enumerator->GetDefaultAudioEndpoint(eRender,eConsole,&fallback))){defaultId=endpointId(fallback);fallback->Release();}+ IMMDeviceCollection* devices=nullptr;+ if(SUCCEEDED(enumerator->EnumAudioEndpoints(eRender,DEVICE_STATE_ACTIVE,&devices))){+ UINT count=0;devices->GetCount(&count);+ for(UINT i=0;i<count;++i){+ IMMDevice* device=nullptr;+ if(FAILED(devices->Item(i,&device)))continue;+ RenderEndpoint e;e.id=endpointId(device);e.name=endpointName(device);e.isDefault=e.id==defaultId;+ device->Release();+ if(!e.id.empty())out.push_back(std::move(e));+ }+ devices->Release();+ }+ enumerator->Release();+ }+ if(SUCCEEDED(com))CoUninitialize();+ return out;+}+void setPreferredRenderEndpoint(std::wstring id){+ std::lock_guard lock(gEndpointMutex);+ if(gPreferredEndpoint==id)return;+ gPreferredEndpoint=std::move(id);+ gEndpointGeneration.fetch_add(1);+ log::info("audio-endpoint",std::format("preferred endpoint set id={}",gPreferredEndpoint.empty()?std::string("<system default>"):narrowName(gPreferredEndpoint)));+}+std::wstring preferredRenderEndpoint(){std::lock_guard lock(gEndpointMutex);return gPreferredEndpoint;}+void setForceStereoDownmix(bool enabled){+ std::lock_guard lock(gEndpointMutex);+ if(gForceStereo==enabled)return;+ gForceStereo=enabled;gEndpointGeneration.fetch_add(1);+ log::info("audio-endpoint",std::format("force stereo downmix={}",enabled));+}+bool forceStereoDownmix(){std::lock_guard lock(gEndpointMutex);return gForceStereo;}+ActiveRenderEndpoint activeRenderEndpoint(){std::lock_guard lock(gEndpointMutex);return gActiveEndpoint;}+uint64_t renderEndpointGeneration(){return gEndpointGeneration.load();}+struct AudioRenderer::EndpointNotifier : IMMNotificationClient {std::atomic<HRESULT>* error;std::atomic<unsigned long> refs{1};- explicit EndpointNotifier(std::atomic<HRESULT>* target):error(target){}+ AudioRenderer* owner=nullptr;+ explicit EndpointNotifier(std::atomic<HRESULT>* target,AudioRenderer* renderer):error(target),owner(renderer){}+ void invalidate(const char* why){+ error->store(AUDCLNT_E_DEVICE_INVALIDATED);+ log::info("audio",std::format("{}; scheduling endpoint rebuild",why));+ }ULONG STDMETHODCALLTYPE AddRef()override{return ULONG(++refs);}ULONG STDMETHODCALLTYPE Release()override{const ULONG n=ULONG(--refs);if(!n)delete this;return n;}HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** pp)override{if(!pp)return E_POINTER;if(id==__uuidof(IUnknown)||id==__uuidof(IMMNotificationClient)){*pp=this;AddRef();return S_OK;}*pp=nullptr;return E_NOINTERFACE;}- HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(LPCWSTR,DWORD)override{return S_OK;}- HRESULT STDMETHODCALLTYPE OnDeviceAdded(LPCWSTR)override{return S_OK;}- HRESULT STDMETHODCALLTYPE OnDeviceRemoved(LPCWSTR)override{return S_OK;}+ // The chosen device going away drops to the default; its return switches back.+ HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(LPCWSTR id,DWORD state)override{+ if(!id||!owner)return S_OK;+ if(!owner->followsDefault_.load()&&owner->deviceId_==id&&state!=DEVICE_STATE_ACTIVE)invalidate("chosen render endpoint left the active state");+ else if(owner->onFallback_.load()&&owner->preferredId_==id&&state==DEVICE_STATE_ACTIVE)invalidate("chosen render endpoint is back");+ return S_OK;+ }+ HRESULT STDMETHODCALLTYPE OnDeviceAdded(LPCWSTR id)override{+ if(id&&owner&&owner->onFallback_.load()&&owner->preferredId_==id)invalidate("chosen render endpoint was added");+ return S_OK;+ }+ HRESULT STDMETHODCALLTYPE OnDeviceRemoved(LPCWSTR id)override{+ if(id&&owner&&!owner->followsDefault_.load()&&owner->deviceId_==id)invalidate("chosen render endpoint was removed");+ return S_OK;+ }HRESULT STDMETHODCALLTYPE OnPropertyValueChanged(LPCWSTR,const PROPERTYKEY)override{return S_OK;}HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(EDataFlow flow,ERole role,LPCWSTR)override{- if(flow==eRender&&role==eConsole){+ if(flow==eRender&&role==eConsole&&(!owner||owner->followsDefault_.load())){// Same code the write path reports when the device disappears; the// pipeline thread treats it as a recoverable endpoint loss.error->store(AUDCLNT_E_DEVICE_INVALIDATED);@@ -367,7 +457,7 @@ struct AudioRenderer::EndpointNotifier : IMMNotificationClient {};void AudioRenderer::registerEndpointNotification(){if(!enum_||notifier_)return;- notifier_=new EndpointNotifier(&lastError_);+ notifier_=new EndpointNotifier(&lastError_,this);const HRESULT hr=enum_->RegisterEndpointNotificationCallback(notifier_);if(FAILED(hr)){log::warn("audio",std::format("RegisterEndpointNotificationCallback hr=0x{:08X}; device changes recover on the next write error",unsigned(hr)));notifier_->Release();notifier_=nullptr;}}@@ -392,8 +482,27 @@ bool AudioRenderer::start(AudioFormat input,double requestedBufferMs)hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL,__uuidof(IMMDeviceEnumerator), reinterpret_cast<void**>(&enum_));if (!checked(hr,"Create MMDeviceEnumerator")) return false;- hr = enum_->GetDefaultAudioEndpoint(eRender, eConsole, &device_);- if (!checked(hr,"GetDefaultAudioEndpoint")) return false;+ // Read the choice and its generation together, so a change made while this+ // endpoint opens is seen as stale on the next check and rebuilds again.+ bool stereo=false;+ {std::lock_guard lock(gEndpointMutex);preferredId_=gPreferredEndpoint;stereo=gForceStereo;endpointGeneration_.store(gEndpointGeneration.load());}+ followsDefault_=true;onFallback_=false;+ if(!preferredId_.empty()){+ IMMDevice* chosen=nullptr;DWORD state=0;+ if(SUCCEEDED(enum_->GetDevice(preferredId_.c_str(),&chosen))&&SUCCEEDED(chosen->GetState(&state))&&state==DEVICE_STATE_ACTIVE){+ device_=chosen;followsDefault_=false;+ }else{+ if(chosen)chosen->Release();+ onFallback_=true;+ log::warn("audio-endpoint","chosen render endpoint unavailable; using the system default until it returns");+ }+ }+ if(!device_){+ hr = enum_->GetDefaultAudioEndpoint(eRender, eConsole, &device_);+ if (!checked(hr,"GetDefaultAudioEndpoint")) return false;+ }+ deviceId_=endpointId(device_);+ const std::wstring deviceName=endpointName(device_);registerEndpointNotification();hr = device_->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr,reinterpret_cast<void**>(&client_));@@ -404,7 +513,16 @@ bool AudioRenderer::start(AudioFormat input,double requestedBufferMs)outputFormat_=input;if(!known||(deviceFormat.layout.mask&input.mask)!=input.mask)outputFormat_=known?deviceFormat.layout:AudioFormat{};+ // Forced stereo: the engine's own swr downmix, then Windows maps stereo onto+ // the device (AUTOCONVERTPCM), exactly as for any stereo source.+ if(stereo&&input.channels>2)outputFormat_=AudioFormat{};CoTaskMemFree(deviceMix);+ {+ std::lock_guard lock(gEndpointMutex);+ gActiveEndpoint={deviceId_,deviceName,onFallback_.load(),outputFormat_.channels,outputFormat_.channels<input.channels,true};+ }+ log::info("audio-endpoint",std::format("opened name={} chosen={} fallback={} forceStereo={}",+ narrowName(deviceName),!followsDefault_.load(),onFallback_.load(),stereo));auto mix=floatWave(outputFormat_);if(outputFormat_!=inputFormat_){AVChannelLayout from{},to{};av_channel_layout_from_mask(&from,inputFormat_.mask);av_channel_layout_from_mask(&to,outputFormat_.mask);diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cppindex 58e78b70..7df5f61b 100644--- a/src/source/CaptureCardSource.cpp+++ b/src/source/CaptureCardSource.cpp@@ -3,6 +3,7 @@#include "veyra/source/WasapiAudioInput.h"#include "veyra/source/CaptureTiming.h"#include "veyra/source/CaptureMediaType.h"+#include "veyra/pipeline/CaptureUploadFrame.h"#include "veyra/source/NativeCaptureSink.h"#include <avrt.h>#include "veyra/source/CaptureBuffer.h"@@ -39,6 +40,7 @@ extern "C" {#include <chrono>#include "veyra/source/CaptureAudioClock.h"#include <cmath>+#include <cwctype>#include <string_view>extern "C" {#include <libavutil/frame.h>@@ -54,6 +56,32 @@ struct __declspec(uuid("6B652FFF-11FE-4FCE-92AD-0266B5D7C78F")) ISampleGrabber:Iconst CLSID SampleGrabberClass={0xc1f400a0,0x3f08,0x11d3,{0x9f,0x0b,0x00,0x60,0x08,0x03,0x9e,0x37}};const CLSID NullRendererClass={0xc1f400a4,0x3f08,0x11d3,{0x9f,0x0b,0x00,0x60,0x08,0x03,0x9e,0x37}};void freeType(AM_MEDIA_TYPE* t,bool pointer=true){if(!t)return;CoTaskMemFree(t->pbFormat);if(t->pUnk)t->pUnk->Release();if(pointer)CoTaskMemFree(t);}+// Adapted from obsproject/libdshowcapture c13d4b7b0c66979396ba0a9060c9aafc15bb7b22,+// source/device-vendor.cpp SetTonemapperAvermedia (Lain Bailey, LGPL-2.1-or-later).+// Veyra scopes the request to the selected AVerMedia PCI/USB filter, logs Set+// and readback, and reissues it on EVERY connection (including after OBS).+// Only the P010/P016 passthrough request is issued. Forcing the hardware+// tonemapper ON for 8-bit formats is NOT done: on the reported GC573 the 4K+// RGB24 path ran at 15 fps until another app switched the tonemapper off, so+// re-enabling it on every connect could pin users to that state. For 8-bit+// formats the current device state is only read back and logged.+void configureAverToneMap(IBaseFilter* filter,std::wstring_view devicePath,bool passthrough) {+ const bool enable=false;+ std::wstring path(devicePath);+ std::transform(path.begin(),path.end(),path.begin(),[](wchar_t c){return wchar_t(towlower(c));});+ if(path.find(L"ven_1461")==path.npos&&path.find(L"vid_07ca")==path.npos)return;+ constexpr GUID property{0x8A80D56F,0xFAC5,0x4692,{0xA4,0x16,0xCF,0x20,0xD4,0xA1,0x8F,0x47}};+ struct Payload {KSPROPERTY property;DWORD enable;} data{};data.enable=enable;+ ComPtr<IKsPropertySet> ps;+ const auto query=filter->QueryInterface(IID_PPV_ARGS(&ps));+ if(FAILED(query)){log::warn("capture-tonemap",std::format("AVerMedia IKsPropertySet unavailable hr=0x{:X}",unsigned(query)));return;}+ const auto set=passthrough?ps->Set(property,2,&data.enable,sizeof(data)-sizeof(data.property),&data,sizeof(data)):S_FALSE;+ Payload actual{};DWORD returned=0;+ const auto get=ps->Get(property,2,&actual.enable,sizeof(actual)-sizeof(actual.property),&actual,sizeof(actual),&returned);+ const bool readable=SUCCEEDED(get)&&returned>=sizeof(actual)&&actual.enable<=1;+ log::info("capture-tonemap",std::format("AVerMedia request={} setHr=0x{:X} getHr=0x{:X} returned={} hardwareTonemap={} readbackKnown={} (P010/P016: passthrough requested; other formats: device state left unchanged, read only)",passthrough?"disable":"none",unsigned(set),unsigned(get),returned,actual.enable,readable));+ if(passthrough&&(FAILED(set)||(readable&&actual.enable!=data.enable)))log::warn("capture-tonemap","hardware tonemap request not confirmed; driver state may remain from another capture app");+}// MPEG2VIDEOINFO carries the codec's sequence header (SPS/PPS) for compressed// capture formats. Drivers are inconsistent: some store Annex-B with start// codes, some store 4-byte length-prefixed NAL units, some an@@ -222,6 +250,20 @@ bool parseCapturePath(std::wstring_view path,CaptureSelection& selection){selection.videoIndex=videoIndex;selection.format=format;selection.audio=audio;selection.colorOverride=fields>=4?colorOverride:0;return true;}}+// One native sample into a mailbox frame. Upload-backed frames+// (CaptureUploadFrame.h) are written once, straight into GPU upload memory, or+// into their CPU planes while the GPU still reads the buffer; planar I420/YV12+// is interleaved into the frame's NV12 layout here instead of in the graph.+static bool writeCaptureFrame(const CaptureMediaLayout& layout,const uint8_t* data,size_t bytes,AVFrame& frame,bool flipRows){+ pipeline::selectCaptureUploadTarget(frame);+ const bool flip=layout.bottomUp!=flipRows;+ if(layout.planes==3&&frame.format==AV_PIX_FMT_NV12&&pipeline::captureUploadFrame(&frame)){+ if(!data||bytes<layout.sampleBytes)return false;+ pipeline::interleaveCaptureI420(frame,data,layout.stride,data+layout.chromaOffset,data+layout.secondChromaOffset,layout.chromaStride,layout.width,layout.height,flip);+ }else if(!copyCaptureSample(layout,data,bytes,frame,flipRows))return false;+ pipeline::sampleCaptureUploadProxy(frame,data,layout.stride,flip);+ return true;+}struct CaptureCardSource::Impl:ISampleGrabberCB {using Clock=std::chrono::steady_clock;std::atomic<ULONG> refs{1};std::mutex mutex;std::condition_variable wake;@@ -297,8 +339,14 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {// Decode worker: keeps the DirectShow callback cheap (payload copy only)// and lets the decode overlap with graph work. The worker owns workerFrame// and swaps it into the mailbox once a frame is ready.- struct CompressedSample{std::vector<uint8_t> payload;double time=0;Clock::time_point arrival;REFERENCE_TIME start=0,end=0;bool completeTime=false,bad=false,reset=false;};+ struct CompressedSample{std::vector<uint8_t> payload;double time=0;Clock::time_point arrival;REFERENCE_TIME start=0,end=0;bool completeTime=false,bad=false,reset=false;uint64_t order=0;};std::deque<CompressedSample> compressedQueue;size_t compressedQueueLimit=3;+ // MJPEG is intra-only, so several decoders work on consecutive payloads at+ // once (mjpegLoop). One software decoder manages about 110 fps at 1440p;+ // at 144 fps the queue stayed full and every frame waited ~18 ms for its+ // turn. A frame that finishes after a newer one was published is dropped.+ bool mjpegParallel=false;uint64_t compressedOrder=0,lastPublishedOrder=0,reorderDrops=0;+ std::vector<std::unique_ptr<CaptureCompressedDecoder>> extraDecoders;std::vector<std::thread> extraDecodeThreads;// Recycled payload buffers: the callback used to allocate a fresh vector// per sample under the mailbox lock (MJPEG 4K = several MB); the worker// returns the buffer after decode (sweep 2026-09-22 C4).@@ -323,6 +371,42 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {// Decode worker loop: pop a compressed payload, decode it with our own// backend (software MJPEG / D3D12VA for H.264/HEVC/AV1/VP9), then hand the// result to the mailbox. No source lock is held during decoding.+ void mjpegLoop(CaptureCompressedDecoder& decoder){+ for(;;){+ CompressedSample sample;AVFrame* target=nullptr;+ {+ std::unique_lock lock(mutex);+ decodeWake.wait(lock,[&]{return decodeStop||(!compressedQueue.empty()&&!compressedFree.empty());});+ if(decodeStop)return;+ sample=std::move(compressedQueue.front());compressedQueue.pop_front();+ target=compressedFree.back();compressedFree.pop_back();+ }+ // Upload-backed target: written once, straight into GPU upload memory.+ pipeline::selectCaptureUploadTarget(*target);+ AVFrame* decodedFrame=nullptr;bool hardware=false;+ const bool produced=decoder.decode(sample.payload.data(),sample.payload.size(),int64_t(sample.time*1e7),target,&decodedFrame,hardware)&&!hardware;+ {+ std::lock_guard lock(mutex);+ if(sample.payload.capacity())returnPayload(std::move(sample.payload));+ if(!produced){++compressedErrors;compressedFree.push_back(target);continue;}+ if(sample.order<=lastPublishedOrder){+ // A newer picture is already in the mailbox.+ ++reorderDrops;++compressedDropped;++dropped;compressedFree.push_back(target);continue;+ }+ lastPublishedOrder=sample.order;+ if(pendingFrame){compressedFree.push_back(pendingFrame);if(pending)++dropped;}+ pendingFrame=target;pendingIsHardware=false;+ pendingDiscontinuity=(pending&&pendingDiscontinuity)||sample.bad;+ pending=true;pendingTime=sample.time;pendingArrival=sample.arrival;+ pendingDuration=captureDuration(sample.start,sample.end,sample.completeTime,nominalDuration100ns);+ ++compressedDecoded;+ if((compressedDecoded%600)==0)log::info("capture-decode",std::format("decoded={} errors={} queueDrops={} reorderDrops={} decodeMs={:.3f} convertMs={:.3f} workers={} backend={} (parallel MJPEG)",+ compressedDecoded,compressedErrors,compressedDropped,reorderDrops,decoder.decodeMsAverage(),decoder.convertMsAverage(),1+extraDecodeThreads.size(),decoder.backendName()));+ }+ wake.notify_one();decodeWake.notify_one();+ if(frameEvent)SetEvent(frameEvent);+ }+ }void decodeLoop(){std::deque<CompressedSample> metadata;bool recoveryBoundary=false;@@ -394,9 +478,12 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {pending=true;pendingTime=stamp.time;pendingArrival=stamp.arrival;pendingDuration=captureDuration(stamp.start,stamp.end,stamp.completeTime,nominalDuration100ns);++compressedDecoded;- if((compressedDecoded%600)==0)log::info("capture-decode",std::format("decoded={} errors={} queueDrops={} backend={} (decode worker)",compressedDecoded,compressedErrors,compressedDropped,compressedDecoder.backendName()));+ if((compressedDecoded%600)==0)log::info("capture-decode",std::format("decoded={} errors={} queueDrops={} decodeMs={:.3f} convertMs={:.3f} backend={} (decode worker)",compressedDecoded,compressedErrors,compressedDropped,compressedDecoder.decodeMsAverage(),compressedDecoder.convertMsAverage(),compressedDecoder.backendName()));}wake.notify_one();decodeWake.notify_one();+ // The engine waits on this event; the callback's signal fired before+ // the picture existed.+ if(frameEvent)SetEvent(frameEvent);}}HRESULT STDMETHODCALLTYPE SampleCB(double time,IMediaSample* sample)override{@@ -413,7 +500,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {AVFrame* staged=nullptr;bool stagedOk=false;if(valid&&!compressedPath){{std::lock_guard lock(mutex);if(stagingFrame&&!stagingBusy){stagingBusy=true;staged=stagingFrame;}}- if(staged)stagedOk=copyCaptureSample(layout,data,size_t(sample->GetActualDataLength()),*staged,verticalFlip.load());+ if(staged)stagedOk=writeCaptureFrame(layout,data,size_t(sample->GetActualDataLength()),*staged,verticalFlip.load());}{std::lock_guard lock(mutex);@@ -453,7 +540,12 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {const size_t bytes=size_t(sample->GetActualDataLength());CompressedSample entry;entry.payload=takePayload();entry.payload.assign(payload,payload+bytes);if(compressedQueue.size()>=compressedQueueLimit){- if(codec==CaptureCodec::Mjpeg){returnPayload(std::move(compressedQueue.front().payload));compressedQueue.pop_front();++compressedDropped;++dropped;entry.bad=true;}+ // MJPEG is intra-only: dropping a queued packet skips one picture and+ // leaves every other frame and its timestamp intact. It is counted+ // as a drop (bounded skip keeps NR/FG history), never as a+ // discontinuity - marking it bad reset the whole temporal history+ // on every overflow (field log: ~20 resets per second at 1440p144).+ if(codec==CaptureCodec::Mjpeg){returnPayload(std::move(compressedQueue.front().payload));compressedQueue.pop_front();++compressedDropped;++dropped;}else{compressedDropped+=compressedQueue.size();dropped+=compressedQueue.size();for(auto& queued:compressedQueue)returnPayload(std::move(queued.payload));@@ -462,6 +554,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {}}entry.time=time;entry.arrival=arrival;entry.start=sampleStart;entry.end=sampleEnd;entry.completeTime=sampleTime;+ entry.order=++compressedOrder;entry.bad=entry.bad||driverBreak||clockBreak;entry.reset=entry.reset||((driverBreak||clockBreak)&&codec!=CaptureCodec::Mjpeg);lastCallbackTime=time;@@ -476,7 +569,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {}else{// Staging frame unavailable (should not happen once// configured); keep the locked copy as a safe fallback.- if(!copyCaptureSample(layout,data,size_t(sample->GetActualDataLength()),*pendingFrame,verticalFlip.load())){callbackError=true;wake.notify_one();return S_OK;}+ if(!writeCaptureFrame(layout,data,size_t(sample->GetActualDataLength()),*pendingFrame,verticalFlip.load())){callbackError=true;wake.notify_one();return S_OK;}}if(pending)++dropped;// Inspect consecutive callbacks, not consecutive mailbox reads.@@ -620,6 +713,10 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.cle*interval=captureFrameInterval(selection.requestedFps);log::info("capture-rate",std::format("requestFps={:.6f} interval100ns={} deviceNegotiation=1 softwareLimiter=0",selection.requestedFps,*interval));}+ std::wstring devicePath=selection.videoPath;+ if(devicePath.empty()){const auto devices=monikers(false);if(index<devices.size())devicePath=monikerPath(devices[index].Get());}+ configureAverToneMap(p.device.Get(),devicePath,native->subtype.Data1==MAKEFOURCC('P','0','1','0')||native->subtype.Data1==MAKEFOURCC('P','0','1','6'));+ log::info("capture-device",std::format("path={} selectedFormat={} requestedFps={} nativeSubtype=0x{:X}",narrowForLog(devicePath),format,expectedFps,native->subtype.Data1));HRESULT hr=p.config->SetFormat(native);const GUID requestedSubtype=native->subtype;log::info("capture",std::format("SetFormat device={} nativeIndex={} subtype=0x{:08X} hr=0x{:08X}",index,format,native->subtype.Data1,uint32_t(hr)));freeType(native);if(FAILED(hr)){if(selection.requestedFps>0)error_=std::format(L"采集卡拒绝 {:.3f} FPS(0x{:08X});请改用设备支持的帧率,或填 0 恢复默认。",selection.requestedFps,uint32_t(hr));return false;}// Read the driver-negotiated type back. Native YUY2/NV12/RGB32 connects@@ -824,13 +921,31 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.cle}if(FAILED(p.graph.As(&p.control))||FAILED(p.graph.As(&p.events)))return false;if(p.grab&&(FAILED(p.grab->SetBufferSamples(FALSE))||FAILED(p.grab->SetCallback(&p,0))))return false;+ // Native capture with the graph's device: the three mailbox frames are+ // D3D12 upload buffers, so the callback's copy is the only CPU copy of a+ // frame (CaptureUploadFrame.h). Semiplanar and packed layouts keep their+ // format; planar I420/YV12 becomes NV12. Layouts that are converted per+ // pixel on the CPU (NV21, legacy rollback, 32-bit RGB) keep ordinary frames,+ // as does VEYRA_TEST_CAPTURE_CPU_FRAMES=1 for A/B runs.+ AVPixelFormat uploadFormat=AV_PIX_FMT_NONE;+ if(desc.d3d12Device&&!p.compressedPath&&GetEnvironmentVariableW(L"VEYRA_TEST_CAPTURE_CPU_FRAMES",nullptr,0)==0){+ const bool legacyYuy2=p.layout.format==AV_PIX_FMT_YUYV422&&(p.layout.packing==CapturePacking::Uyvy||p.layout.packing==CapturePacking::Yvyu);+ if(p.layout.planes==3&&p.layout.format==AV_PIX_FMT_YUV420P&&p.info.width%2==0&&p.info.height%2==0)uploadFormat=AV_PIX_FMT_NV12;+ else if(p.layout.planes==(pipeline::captureUploadPixelBytes(p.layout.format)&&(p.layout.format==AV_PIX_FMT_NV12||p.layout.format==AV_PIX_FMT_P010||p.layout.format==AV_PIX_FMT_P016)?2u:1u)&&+ p.layout.packing!=CapturePacking::Nv21&&!legacyYuy2)uploadFormat=p.layout.format;+ }+ const bool uploadFrames=uploadFormat!=AV_PIX_FMT_NONE;+ unsigned uploadBacked=0;for(auto** f:{&p.frame,&p.pendingFrame,&p.stagingFrame}){+ *f=uploadFrames?pipeline::allocCaptureUploadFrame(static_cast<ID3D12Device*>(desc.d3d12Device),uploadFormat,unsigned(p.info.width),unsigned(p.info.height)):nullptr;+ if(*f){++uploadBacked;continue;}*f=av_frame_alloc();if(!*f)return false;(*f)->format=p.layout.format;(*f)->width=p.info.width;(*f)->height=p.info.height;// 256-byte row alignment matches the graph's D3D12 upload pitch, so// the ingest copy is one memcpy per plane instead of one per row.if(av_frame_get_buffer(*f,256)<0)return false;}+ log::info("capture",std::format("mailbox frames uploadBacked={} of 3 layoutFormat={} frameFormat={} (single CPU copy when 3)",uploadBacked,int(p.layout.format),int(uploadFrames&&uploadBacked==3?uploadFormat:p.layout.format)));p.stagingBusy=false;if(!p.frameEvent)p.frameEvent=CreateEventW(nullptr,FALSE,FALSE,nullptr);if(compressedPath){@@ -841,6 +956,36 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.cle// larger pool was measured with two and three spares: the 4K18// read-age effect was not monotonic (23.6 vs 25.2 ms across runs), so// the extra memory buys nothing reproducible.+ const unsigned cores=std::thread::hardware_concurrency();+ p.mjpegParallel=p.codec==CaptureCodec::Mjpeg&&cores>=4&&GetEnvironmentVariableW(L"VEYRA_TEST_MJPEG_SINGLE",nullptr,0)==0;+ p.compressedOrder=p.lastPublishedOrder=p.reorderDrops=0;+ if(p.mjpegParallel){+ const unsigned wanted=std::clamp(cores/4,2u,4u);+ for(unsigned i=1;i<wanted;++i){+ auto decoder=std::make_unique<CaptureCompressedDecoder>();+ if(!decoder->open(p.codec,p.layout.width,p.layout.height,nullptr,0,nullptr,nullptr))break;+ p.extraDecoders.push_back(std::move(decoder));+ }+ // Every worker holds one target while it decodes; two more cover the+ // mailbox and the frame the reader owns. The ordinary mailbox frames+ // are not part of this pool.+ av_frame_free(&p.frame);av_frame_free(&p.pendingFrame);+ unsigned uploadTargets=0;+ for(size_t i=0;i<p.extraDecoders.size()+3;++i){+ AVFrame* frame=GetEnvironmentVariableW(L"VEYRA_TEST_CAPTURE_CPU_FRAMES",nullptr,0)==0?+ pipeline::allocCaptureUploadFrame(static_cast<ID3D12Device*>(desc.d3d12Device),AV_PIX_FMT_NV12,p.layout.width,p.layout.height):nullptr;+ if(frame)++uploadTargets;+ else{+ frame=av_frame_alloc();if(!frame)return false;+ frame->format=AV_PIX_FMT_NV12;frame->width=int(p.layout.width);frame->height=int(p.layout.height);+ if(av_frame_get_buffer(frame,32)<0){av_frame_free(&frame);return false;}+ }+ p.compressedFree.push_back(frame);+ }+ p.decodeStop=false;p.decodeThread=std::thread([&p]{p.mjpegLoop(p.compressedDecoder);});+ for(auto& decoder:p.extraDecoders)p.extraDecodeThreads.emplace_back([&p,raw=decoder.get()]{p.mjpegLoop(*raw);});+ log::info("capture-decode",std::format("parallel MJPEG decode workers={} targets={} uploadBacked={} queue={}",1+p.extraDecoders.size(),p.compressedFree.size(),uploadTargets,p.compressedQueueLimit));+ }else{for(int i=0;i<2;++i){AVFrame* frame=av_frame_alloc();if(!frame)return false;frame->format=AV_PIX_FMT_NV12;frame->width=int(p.layout.width);frame->height=int(p.layout.height);@@ -848,7 +993,8 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.cleif(i==0)p.workerFrame=frame;else p.compressedFree.push_back(frame);}p.decodeStop=false;p.decodeThread=std::thread([&p]{p.decodeLoop();});- log::info("capture-decode",std::format("decode worker started queue={} backend={} (single decode thread; the parallel pool is a later refinement)",p.compressedQueueLimit,p.compressedDecoder.backendName()));+ log::info("capture-decode",std::format("decode worker started queue={} backend={} (single decode thread)",p.compressedQueueLimit,p.compressedDecoder.backendName()));+ }}p.elgatoHdr=std::move(elgatoHdr);p.configured=true;@@ -1255,7 +1401,8 @@ SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,c// so it goes back into the decode pool and the worker continues.if(p.frame)p.compressedFree.push_back(p.frame);p.frame=p.pendingFrame;p.pendingFrame=nullptr;delivered=p.frame;- if(p.workerFrame==nullptr&&!p.compressedFree.empty()){p.workerFrame=p.compressedFree.back();p.compressedFree.pop_back();feedDecode=true;}+ if(p.mjpegParallel)feedDecode=true; // the released frame is a decode target again+ else if(p.workerFrame==nullptr&&!p.compressedFree.empty()){p.workerFrame=p.compressedFree.back();p.compressedFree.pop_back();feedDecode=true;}}else{// Native path keeps the original mailbox rotation: the frame the// caller releases becomes the next ingest target, and pendingFrame@@ -1271,7 +1418,7 @@ SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,cif(p.forceDiscontinuity){flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Discontinuity);p.forceDiscontinuity=false;}p.lastDrop=p.dropped;p.lastPts=time;++p.sequence;sequence=p.compressedPath?p.compressedDecoded:p.received;}- if(feedDecode)p.decodeWake.notify_one();+ if(feedDecode)p.decodeWake.notify_all();if(expiredHardware)av_frame_free(&expiredHardware);if(delivered==nullptr)return SourceReadStatus::Error;auto colorInfo=p.info.color;@@ -1297,6 +1444,8 @@ void CaptureCardSource::close()noexcept{if(p.audioPassthrough)p.audioPassthrough->close();p.events.Reset();p.control.Reset();p.grab.Reset();p.nullFilter.Reset();p.grabFilter.Reset();p.audioSink.Reset();p.audioFilter.Reset();p.config.Reset();p.device.Reset();p.builder.Reset();p.graph.Reset();p.referenceClock.Reset();p.audioSession.reset();p.audioPassthrough.reset();if(p.decodeThread.joinable()){{std::lock_guard lock(p.mutex);p.decodeStop=true;p.compressedQueue.clear();p.payloadPool.clear();}p.decodeWake.notify_all();p.decodeThread.join();}+ for(auto& thread:p.extraDecodeThreads)if(thread.joinable())thread.join();+ p.extraDecodeThreads.clear();p.extraDecoders.clear();p.mjpegParallel=false;if(p.workerFrame)av_frame_free(&p.workerFrame);for(auto*& frame:p.compressedFree)if(frame)av_frame_free(&frame);p.compressedFree.clear();diff --git a/src/source/CaptureCompressedDecoder.cpp b/src/source/CaptureCompressedDecoder.cppindex 5392b40d..b06f663a 100644--- a/src/source/CaptureCompressedDecoder.cpp+++ b/src/source/CaptureCompressedDecoder.cpp@@ -7,11 +7,14 @@ extern "C" {#include <libswscale/swscale.h>}+#include <chrono>#include <cstring>+#include <emmintrin.h>#include <format>#include "veyra/Log.h"#include "veyra/media/FFmpegVideoDecoder.h"+#include "veyra/pipeline/CaptureUploadFrame.h"namespace veyra::source {@@ -61,9 +64,62 @@ struct CaptureCompressedDecoder::Impl {bool depthWarningLogged = false;std::string error;uint64_t frames = 0, failures = 0, fallbacks = 0;+ double decodeMs = 0, convertMs = 0;~Impl() { close(); }+ // MJPEG: full-range 4:2:2 / 4:2:0 planes of the target size go straight to+ // NV12 (luma row copies; chroma rows averaged in pairs for 4:2:2, then+ // interleaved). swscale's generic scaler did the same reformat several+ // times slower, and this writer never reads the target, so the target may+ // be write-combined GPU upload memory.+ bool planarToNv12(const AVFrame& frame, AVFrame* target)+ {+ const bool is422 = frame.format == AV_PIX_FMT_YUVJ422P || frame.format == AV_PIX_FMT_YUV422P;+ const bool is420 = frame.format == AV_PIX_FMT_YUVJ420P || frame.format == AV_PIX_FMT_YUV420P;+ if (codec != CaptureCodec::Mjpeg || !(is422 || is420) || frame.width != int(width) || frame.height != int(height) ||+ width % 2 || height % 2 || !frame.data[0] || !frame.data[1] || !frame.data[2] || !target->data[0] || !target->data[1] ||+ target->linesize[0] < int(width) || target->linesize[1] < int(width)) return false;+ for (unsigned y = 0; y < height; ++y)+ std::memcpy(target->data[0] + ptrdiff_t(y) * target->linesize[0], frame.data[0] + ptrdiff_t(y) * frame.linesize[0], width);+ const unsigned chromaWidth = width / 2;+ for (unsigned row = 0; row < height / 2; ++row) {+ const unsigned sourceRow = is422 ? row * 2 : row;+ const uint8_t* u0 = frame.data[1] + ptrdiff_t(sourceRow) * frame.linesize[1];+ const uint8_t* v0 = frame.data[2] + ptrdiff_t(sourceRow) * frame.linesize[2];+ const uint8_t* u1 = is422 ? u0 + frame.linesize[1] : u0;+ const uint8_t* v1 = is422 ? v0 + frame.linesize[2] : v0;+ uint8_t* out = target->data[1] + ptrdiff_t(row) * target->linesize[1];+ unsigned x = 0;+ for (; x + 16 <= chromaWidth; x += 16) {+ const __m128i u = _mm_avg_epu8(_mm_loadu_si128(reinterpret_cast<const __m128i*>(u0 + x)), _mm_loadu_si128(reinterpret_cast<const __m128i*>(u1 + x)));+ const __m128i v = _mm_avg_epu8(_mm_loadu_si128(reinterpret_cast<const __m128i*>(v0 + x)), _mm_loadu_si128(reinterpret_cast<const __m128i*>(v1 + x)));+ _mm_storeu_si128(reinterpret_cast<__m128i*>(out + 2 * x), _mm_unpacklo_epi8(u, v));+ _mm_storeu_si128(reinterpret_cast<__m128i*>(out + 2 * x + 16), _mm_unpackhi_epi8(u, v));+ }+ for (; x < chromaWidth; ++x) {+ out[2 * x] = uint8_t((unsigned(u0[x]) + u1[x] + 1) >> 1);+ out[2 * x + 1] = uint8_t((unsigned(v0[x]) + v1[x] + 1) >> 1);+ }+ }+ pipeline::sampleCaptureUploadProxy(*target, frame.data[0], size_t(frame.linesize[0]), false);+ return true;+ }++ void copyFrameProperties(const AVFrame& frame, AVFrame* target, bool targetFullRange)+ {+ target->pts = frame.pts;+ target->best_effort_timestamp = frame.best_effort_timestamp;+ target->pkt_dts = frame.pkt_dts;+ target->duration = frame.duration;+ target->time_base = frame.time_base;+ target->flags = frame.flags;+ target->colorspace = frame.colorspace;+ target->color_primaries = frame.color_primaries;+ target->color_trc = frame.color_trc;+ target->color_range = targetFullRange ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;+ }+void close(){if (sws) { sws_freeContext(sws); sws = nullptr; }@@ -74,6 +130,7 @@ struct CaptureCompressedDecoder::Impl {hardwareRequested = hardware = hardwareChecked = waiting = false;depthWarningLogged = false;frames = failures = fallbacks = 0;+ decodeMs = convertMs = 0;error.clear();}@@ -97,6 +154,9 @@ struct CaptureCompressedDecoder::Impl {captureCodecKey(codec), description->comp[0].depth));}}+ if (planarToNv12(frame, target)) { copyFrameProperties(frame, target, true); return true; }+ // swscale cannot supply the analysis pixels of an upload-backed target.+ pipeline::useCaptureUploadCpuPlanes(*target);sws = sws_getCachedContext(sws, frame.width, frame.height, sourceFormat,int(width), int(height), AV_PIX_FMT_NV12, SWS_BILINEAR, nullptr, nullptr, nullptr);if (sws == nullptr) {@@ -118,16 +178,7 @@ struct CaptureCompressedDecoder::Impl {++failures;return false;}- target->pts = frame.pts;- target->best_effort_timestamp = frame.best_effort_timestamp;- target->pkt_dts = frame.pkt_dts;- target->duration = frame.duration;- target->time_base = frame.time_base;- target->flags = frame.flags;- target->colorspace = frame.colorspace;- target->color_primaries = frame.color_primaries;- target->color_trc = frame.color_trc;- target->color_range = targetFullRange ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;+ copyFrameProperties(frame, target, targetFullRange != 0);return true;}};@@ -204,6 +255,11 @@ bool CaptureCompressedDecoder::decode(const uint8_t* data, size_t bytes, int64_t// Two attempts at most: the second one re-sends the same payload after a// hardware decoder whose first frame cannot be imported has been replaced// by the software decoder.+ const auto started = std::chrono::steady_clock::now();+ const auto average = [](double& value, std::chrono::steady_clock::time_point from, std::chrono::steady_clock::time_point to) {+ const double ms = std::chrono::duration<double, std::milli>(to - from).count();+ value = value > 0 ? value * 0.95 + ms * 0.05 : ms;+ };for (int attempt = 0; attempt < 2; ++attempt) {if (!receiveOnly) {AVPacket* packet = av_packet_alloc();@@ -266,7 +322,10 @@ bool CaptureCompressedDecoder::decode(const uint8_t* data, size_t bytes, int64_tp.error.clear();return true;}+ const auto decoded = std::chrono::steady_clock::now();if (!p.convertToNv12(*frame, nv12Target)) return false;+ average(p.decodeMs, started, decoded);+ average(p.convertMs, decoded, std::chrono::steady_clock::now());*out = nv12Target;hardware = false;++p.frames;@@ -292,6 +351,8 @@ const std::string& CaptureCompressedDecoder::lastError() const { return p_->errouint64_t CaptureCompressedDecoder::framesDecoded() const { return p_->frames; }uint64_t CaptureCompressedDecoder::decodeFailures() const { return p_->failures; }uint64_t CaptureCompressedDecoder::hardwareFallbacks() const { return p_->fallbacks; }+double CaptureCompressedDecoder::decodeMsAverage() const { return p_->decodeMs; }+double CaptureCompressedDecoder::convertMsAverage() const { return p_->convertMs; }void CaptureCompressedDecoder::close() { p_->close(); }} // namespace veyra::sourcediff --git a/src/source/MediaFileSource.cpp b/src/source/MediaFileSource.cppindex fb0fb308..10f9e610 100644--- a/src/source/MediaFileSource.cpp+++ b/src/source/MediaFileSource.cpp@@ -52,6 +52,11 @@ bool MediaFileSource::fallbackToSoftware(std::string_view reason)if (!decoder_.hardwareActive() || path_.empty()) {return false;}+ if (requireHardwareDecode_) {+ veyra::log::error("source-file", std::format(+ "hardware decode required by the user setting; refusing the software fallback (reason={})", reason));+ return false;+ }// Mid-stream failures (driver/pool errors after frames were delivered)// reopen in software and seek back to the last delivered PTS; the caller// sees a Discontinuity flag so temporal history resets (sweep B5).@@ -156,6 +161,7 @@ bool MediaFileSource::open(const SourceOpenDesc& desc)close();path_ = desc.path;preferHardwareDecode_ = desc.preferHardwareDecode && desc.d3d12Device != nullptr && desc.d3d12Queue != nullptr;+ requireHardwareDecode_ = desc.requireHardwareDecode;if (!demuxer_.open(desc.path)) {veyra::log::error("source-file", "demuxer open failed");return false;@@ -195,6 +201,10 @@ bool MediaFileSource::open(const SourceOpenDesc& desc)}}}+ if (!decoderOpen && desc.requireHardwareDecode) {+ veyra::log::error("source-file", "hardware decode required by the user setting and not available; not falling back to software");+ return false;+ }if (!decoderOpen) {decoderOpen = decoder_.openSoftware(params, demuxer_.videoTimeBaseNum(),demuxer_.videoTimeBaseDen(), softwareDecodeThreads(params->width, params->height));@@ -485,6 +495,7 @@ void MediaFileSource::close() noexceptinfo_ = SourceInfo{};path_.clear();preferHardwareDecode_ = false;+ requireHardwareDecode_ = false;}} // namespace veyra::sourcediff --git a/src/ui/PlayerUiFacade.cpp b/src/ui/PlayerUiFacade.cppindex e52721d8..0bb866d8 100644--- a/src/ui/PlayerUiFacade.cpp+++ b/src/ui/PlayerUiFacade.cpp@@ -1,12 +1,14 @@#include "veyra/ui/PlayerUiFacade.h"#include "veyra/RuntimePaths.h"+#include "veyra/Log.h"#include "veyra/engine/PresetStore.h"#include <windows.h>#include <algorithm>#include <fstream>+#include <format>#include <iomanip>#include <sstream>@@ -53,12 +55,40 @@ bool sameSnapshot(const veyra::engine::PlayerSnapshot& a, const veyra::engine::PPlayerUiFacade::PlayerUiFacade(veyra::engine::EngineController& engine, std::filesystem::path dataDirectory): engine_(engine),presets_((dataDirectory.empty() ? veyra::runtime::localDataDirectory() : dataDirectory) / L"presets.v1"),- dataDirectory_(dataDirectory.empty() ? veyra::runtime::localDataDirectory() : dataDirectory) {}+ dataDirectory_(dataDirectory.empty() ? veyra::runtime::localDataDirectory() : dataDirectory),+ chainSessionStore_(dataDirectory_ / L"chain-session.v1") {}++bool PlayerUiFacade::loadChainSession(veyra::engine::ChainSession& session) {+ const bool loaded = chainSessionStore_.load(session);+ error_ = chainSessionStore_.error();+ return loaded;+}++bool PlayerUiFacade::saveChainSession(const veyra::engine::ChainSession& session) {+ if (chainSessionStore_.save(session)) return true;+ error_ = chainSessionStore_.error(); return false;+}PlayerUiFacade::Frame PlayerUiFacade::poll() {// The engine owns the snapshot lock; taking it here and comparing keeps the// UI free of the read-modify pattern it used to do at 4 Hz.const auto snapshot = engine_.snapshot();+ if(pendingNrRevision_&&snapshot.rejectedRevision==pendingNrRevision_&&pending_.nrRuntime==requestedNrRuntime_) {+ pending_.nrRuntime=snapshot.desired.nrRuntime;pendingNrRevision_=0;+ for(uint32_t i=0;i<pending_.nrLayerCount&&i<pending_.nrLayers.size();++i)+ pending_.nrLayers[i].runtime=pending_.nrRuntime;+ veyra::log::info("ui-nr-rollback",std::format("rejectedRevision={} restoredRuntime={}",snapshot.rejectedRevision,veyra::engine::nrRuntimeName(pending_.nrRuntime)));+ }+ // A GPU/provider failure arrives after command admission. Match the exact+ // accepted revision so a stale rejection cannot overwrite a newer choice.+ // Reconcile only the FG pair; unrelated editable controls stay untouched.+ if(pendingFgRevision_&&snapshot.rejectedRevision==pendingFgRevision_&&+ pending_.frameGenerationBackend==requestedFgBackend_&&pending_.multiplier==requestedFgMultiplier_){+ pending_.frameGenerationBackend=snapshot.desired.frameGenerationBackend;+ pending_.multiplier=snapshot.desired.multiplier;pendingFgRevision_=0;+ veyra::log::info("ui-fg-rollback",std::format("rejectedRevision={} restoredBackend={} restoredMultiplier={}",+ snapshot.rejectedRevision,int(pending_.frameGenerationBackend),pending_.multiplier));+ }Frame frame;frame.snapshot = snapshot;frame.changed = !haveLast_ || !sameSnapshot(snapshot, last_);@@ -71,9 +101,18 @@ PlayerUiFacade::Frame PlayerUiFacade::poll() {return frame;}-bool PlayerUiFacade::applySettings(const veyra::engine::EnhancementSettings& settings) {+bool PlayerUiFacade::applySettings(const veyra::engine::EnhancementSettings& settings,+ std::optional<veyra::engine::ChainRuntimeOrder> order) {+ uint64_t acceptedRevision=0;+ if (!engine_.requestSettings(settings, order,&acceptedRevision)) return false;+ veyra::log::info("ui-settings-request", std::format(+ "accepted srTarget={} quality={} fgBackend={} flowBackend={}",+ int(settings.srTarget), settings.videoSrQuality, int(settings.frameGenerationBackend), int(settings.opticalFlowBackend)));pending_ = settings;- return engine_.requestSettings(settings);+ pendingFgRevision_=acceptedRevision;+ pendingNrRevision_=acceptedRevision;requestedNrRuntime_=settings.nrRuntime;+ requestedFgBackend_=settings.frameGenerationBackend;requestedFgMultiplier_=settings.multiplier;+ return true;}bool PlayerUiFacade::applying() const {@@ -101,7 +140,10 @@ bool PlayerUiFacade::importLegacyStores() {// A corrupt file stays loaded-as-corrupt, and the library then refuses to save.if (!presetsLoaded_) {presetsLoaded_ = true;+ // 2.0 ships no built-in presets (user decision 2026-09-29).+ presets_.setIncludeBuiltins(false);if (!presets_.load()) { error_ = presets_.error(); return false; }+ error_ = presets_.error(); // Successful legacy migration carries an explicit notice.}// The old files are read-only inputs: they stay on disk untouched so a// downgrade still finds them. Their positional schema is owned bydiff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cppindex bfde7c2f..fe5e9be2 100644--- a/src/ui/QmlPlayerBridge.cpp+++ b/src/ui/QmlPlayerBridge.cpp@@ -7,6 +7,11 @@#include <QDir>#include <QFileDialog>#include <QFileInfo>+#include <QDesktopServices>+#include <QStandardPaths>+#include <QKeyEvent>+#include <QKeySequence>+#include <QCoreApplication>#include <QClipboard>#include <QGuiApplication>#include <QJsonDocument>@@ -15,13 +20,65 @@#include <QHash>#include <QFile>#include <QTimer>+#include <QBuffer>+#include <QImage>#include <algorithm>#include <cmath>+#include <limits>+#include <optional>+#include <vector>#include "veyra/Log.h"#include "veyra/RuntimePaths.h"+#include "veyra/engine/ColorLookStore.h"+#include "veyra/engine/ColorLut.h"+#include "veyra/engine/Subtitles.h"+#include "veyra/sink/WasapiAudioSink.h"+#include "veyra/source/CaptureFormatSelection.h"+#include "veyra/source/CaptureFormatRank.h"+#include "veyra/source/CaptureColorOverride.h"+#include "veyra/source/CaptureFrameRate.h"+#include "CapturePreferenceStore.h"+#ifdef VEYRA_ENABLE_REMOTEPLAY+// SDL3-static's system libraries (see CMakeLists: kept off the link line).+#pragma comment(lib, "winmm.lib")+#pragma comment(lib, "imm32.lib")+#pragma comment(lib, "version.lib")+#pragma comment(lib, "setupapi.lib")+#pragma comment(lib, "dinput8.lib")+#include "veyra/remoteplay/ControllerInput.h"+#include "veyra/remoteplay/Discovery.h"+#include "veyra/remoteplay/ProfileStore.h"+#include "veyra/remoteplay/PsnAuth.h"+#include "veyra/source/RemotePlaySource.h"+#endif+#include <future>+#include <functional>+#include <map>+#include <deque>+#include "SubtitleOverlay.h"+// GDI+ is only started here (the overlay draws with it); its headers expect+// min/max, which NOMINMAX builds do not define as macros.+#include <objidl.h>+namespace Gdiplus { using std::min; using std::max; }+#include <gdiplus.h>+#pragma comment(lib, "gdiplus.lib")+// 1.4.4's live status rules (正常 / 补帧调度降档 / 输出未达标 / 输入帧率不足).+#include "LiveStatusHistory.h"+// GPU utilization for the performance orb: the Windows "GPU Engine" counters,+// the same source Task Manager reads.+#include <pdh.h>+#include <pdhmsg.h>+#pragma comment(lib, "pdh.lib")+#include <atomic>+#include <mutex>+#include <thread>+#include "veyra/pipeline/ColorGradeTables.h"#include "veyra/ui/PlaybackPowerGuard.h"+#include "veyra/gfx/XessMfgUnlock.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include "veyra/ngx/NrArchitecturePolicy.h"#include "veyra/source/CaptureCardSource.h"#include "veyra/source/ScreenCaptureSource.h"@@ -55,12 +112,77 @@ struct QmlPlayerBridge::Impl {// The chain the UI edits, kept in step with the facade's pending settings.engine::EffectChain chain;+ engine::EffectChain acceptedChain;+ engine::NodeGraphLayout layout;+ engine::ChainGlobalSettings draftGlobals;+ const engine::EffectChain& activeRuntime() const {+ return chain.mode == engine::ChainMode::Node ? acceptedChain : chain;+ }+ void initializeDefaultNodePositions() {+ if (chain.mode != engine::ChainMode::Node) return;+ for (uint32_t i = 0; i < chain.nodeCount; ++i)+ if (chain.nodes[i].viewX == 0 && chain.nodes[i].viewY == 0) {+ chain.nodes[i].viewX = float(i % 4) * 260;+ chain.nodes[i].viewY = float(i / 4) * 300;+ }+ }+ void restoreConfiguration(const engine::ChainConfiguration& c) {+ draftGlobals = c.editor && c.editor->globals ? *c.editor->globals :+ static_cast<const engine::ChainGlobalSettings&>(c);+ acceptedChain = c.chain;+ chain = c.editor ? c.editor->nodes : c.chain;+ if (c.editor) layout = c.editor->layout;+ else if (chain.mode == engine::ChainMode::Node) layout.initialize(chain);+ selectedNr = c.selectedNr; selectedColour = c.selectedColour;+ // Resolve the old QML-only layout fallback once so duplication, wires+ // and saved coordinates use the same physical rectangles.+ if (!c.editor) initializeDefaultNodePositions();+ }engine::ChainValidation validation;+ engine::ChainSession session;+ engine::ChainSession savedSession;+ QTimer* sessionSaveTimer = nullptr;+ int selectedNr=-1;+ int nrIndex() const {+ if(selectedNr>=0&&uint32_t(selectedNr)<chain.nodeCount&&+ chain.nodes[selectedNr].type==engine::EffectType::NrEnhance)return selectedNr;+ for(uint32_t i=0;i<chain.nodeCount;++i)if(chain.nodes[i].type==engine::EffectType::NrEnhance)return int(i);+ return -1;+ }+ engine::ChainNode* nrNode(){const int i=nrIndex();return i>=0?&chain.nodes[i]:nullptr;}+ int selectedColour=-1;+ int colourIndex() const {+ if(selectedColour>=0&&uint32_t(selectedColour)<chain.nodeCount&&+ chain.nodes[selectedColour].type==engine::EffectType::Color)return selectedColour;+ for(uint32_t i=0;i<chain.nodeCount;++i)if(chain.nodes[i].type==engine::EffectType::Color)return int(i);+ return -1;+ }// The window the engine presents into, and the last file the UI opened.HWND videoWindow = nullptr;std::wstring sourceLabel;int thumbnailGeneration = 0;+ // The live source kind and label ("" for a file), for the page headers.+ QString liveKind, liveLabel;+ // A live open waiting for the 极简 switch to settle (openAfterCinema); the+ // generation lets a newer open or a stop cancel it.+ int liveOpenGen = 0;+ QString pendingLiveText;+ // 调色 history: each commit pushes the layer's previous state; a slider+ // drag (edits under 600 ms apart on one layer) is one step.+ struct ColourStep { int index = -1; engine::ColorSettings colour{}; };+ std::vector<ColourStep> colourUndo, colourRedo;+ std::optional<engine::ColorSettings> colourClip;+ qint64 colourLastPushMs = 0;+ int colourLastIndex = -1;+ bool colourReplaying = false;+ // Export queue rows as the UI added them, tracked against the manager's+ // snapshot by output path (the manager itself only reports a count).+ struct ExportRow { std::wstring input, output; QString state; double progress = 0; QString note; };+ std::vector<ExportRow> exportRows;+ // Poster data URL cache, per session.+ uint64_t posterSession = 0;+ QString posterUrl;// Keeps the display and system awake while a video plays (AppShell rule: running,// not failed, not a still image, transport Playing). Acquired and released on@@ -94,16 +216,256 @@ struct QmlPlayerBridge::Impl {QTimer* timer = nullptr;+ // Canvas positions of the fixed input / optical-flow / output boxes. They are+ // editor furniture, not chain nodes, so they live beside the preferences.+ std::filesystem::path anchorsFile;+ QVariantMap anchors;+ // Where the user's own files live (the facade resolves the same default).+ std::filesystem::path dataDir;+ // --- subtitles (ported from the Win32 shell, same semantics) ---+ std::unique_ptr<engine::SubtitleLoader> subLoader;+ uint64_t subGeneration = 0;+ std::vector<engine::SubtitleTrack> subTracks; // external files first, then the loader's+ size_t subExternal = 0; // user-loaded files at the front+ size_t subLoaded = 0; // loader tracks currently held+ int subPrimary = -1, subSecondary = -1;+ bool subPrimaryChosen = false, subSecondaryChosen = false;+ QString subStatus;+ QString subText;+ int subBottomInset = 0;+ HWND subOverlay = nullptr;+ bool subOverlayFailed = false;+ std::wstring subMedia;+ std::atomic<bool> subAligning{false}, subAlignReady{false};+ std::atomic<int> subAlignOffset{0};+ std::mutex subAlignMutex;+ std::wstring subAlignDetail;+ uint64_t subAlignGeneration = 0;+ int subAlignTrack = -1;+ // Declared after everything the worker touches, so it is joined first.+ std::jthread subAlignWorker;+ QVariantMap prefs;+ QString lastScreenshot;+ bool holdKeyDown = false;+ int positionTicks = 0;+ // A reopened file resumes here once its session is running.+ uint64_t resumeSession = 0;+ double resumeAt = 0;+ std::vector<sink::RenderEndpoint> audioEndpoints;+ // --- capture connection (P4-e) ---+ struct CaptureQuery { int kind = 0; std::wstring device; std::vector<source::CaptureDevice> video, audio; std::vector<source::CaptureFormat> formats; };+ std::future<CaptureQuery> captureQuery;+ bool captureBusy = false, captureListed = false, captureResumePending = false;+ int captureQueryKind = 0; // 0 device list, 1 formats, 2 formats then connect (continue)+ std::vector<source::CaptureDevice> captureVideo, captureAudio;+ std::vector<source::CaptureFormat> captureFormatList;+ std::wstring captureFormatKey;+ int captureAudioChoice = source::kCaptureAudioDisabled;+ unsigned captureColor = 0;+ double captureFps = 0;+ QString captureStatus;+ ui::CapturePreferences capturePrefs;+ // --- PS5 Remote Play ---+ QVariantMap ps5Form;+ QString ps5Status;+ std::wstring ps5Profile; // file name inside profileDirectory()+ QVariantList ps5ProfileList;+ uint64_t psnLoginStarted = 0;+ bool ps5Watching = false;+ struct Ps5Outcome { std::wstring message; std::vector<std::pair<std::string, std::string>> hosts; std::wstring savedPath; std::string account; bool refreshProfiles = false; };+ std::mutex ps5Mutex;+ Ps5Outcome ps5Outcome;+ std::atomic<bool> ps5Done{false};+ bool ps5Busy = false;+ QTimer* controllerTimer = nullptr;+#ifdef VEYRA_ENABLE_REMOTEPLAY+ remoteplay::ControllerInput controller;+#endif+ std::jthread ps5Worker; // last: joined before what it touches+ // --- screen capture ---+ std::vector<source::ScreenCaptureTarget> screenList;+ bool screenFillActive = false;+ QSize screenFitClient, screenFitImage;+ // --- image batch ---+ QStringList imageFiles;+ QString imageFolder, imageTarget, imageStatus;+ int imageIndex = -1, imageDone = 0, imageFailures = 0, imageWaits = 0;+ uint64_t imageSession = 0;+ enum class ImagePhase { Idle, Opening, Saving } imagePhase = ImagePhase::Idle;+ sink::ActiveRenderEndpoint audioActive;+ int audioPollTicks = 0;+ // --- protection drawing (#8) ---+ QString protDraw; // "" | rect | ellipse+ HWND protOverlay = nullptr;+ // --- performance orbs / status light (#13) ---+ ui::live_status::DashboardHistory history;+ int historyTicks = 0;+ QString runStatus, runLevel, runDetail;+ std::atomic<double> gpuUtil{-1.0};+ double gpuPublished = -2.0;+ double rateRatio = -1.0;+ std::deque<double> frameTimes; // frame interval ms, newest last+ // --- design gap: presentation, compare, aspect ---+ engine::PresentationSettings presentation;+ int compareMode = 0;+ bool compareBase = false;+ double compareSplit = 0.5;+ int aspectMode = 0, aspectApplied = 0;+ uint64_t aspectSession = 0;+ std::jthread gpuSampler; // joined before gpuUtil goes away+ std::filesystem::path prefsFile() const { return dataDir / L"qml-preferences.v1.json"; }+ void loadPrefs() {+ QFile file(QString::fromStdWString(prefsFile().wstring()));+ if (!file.exists()) return;+ if (!file.open(QIODevice::ReadOnly)) { veyra::log::warn("ui-prefs", "qml preferences unreadable; defaults used"); return; }+ QJsonParseError error{};+ const auto doc = QJsonDocument::fromJson(file.readAll(), &error);+ if (error.error != QJsonParseError::NoError || !doc.isObject()) {+ veyra::log::warn("ui-prefs", "qml preferences damaged; defaults used, file kept");+ return;+ }+ prefs = doc.object().toVariantMap();+ }+ bool savePrefs() {+ const QString path = QString::fromStdWString(prefsFile().wstring());+ // A fresh data directory may not exist yet: the first preference saved+ // on a new profile used to fail and was silently kept only in memory.+ std::error_code ec;+ std::filesystem::create_directories(prefsFile().parent_path(), ec);+ QFile file(path + QStringLiteral(".tmp"));+ if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) return false;+ const auto bytes = QJsonDocument(QJsonObject::fromVariantMap(prefs)).toJson(QJsonDocument::Indented);+ if (file.write(bytes) != bytes.size()) { file.close(); file.remove(); return false; }+ file.close();+ QFile::remove(path);+ return QFile::rename(path + QStringLiteral(".tmp"), path);+ }+ int prefInt(const char* key, int fallback) const { return prefs.contains(key) ? prefs.value(key).toInt() : fallback; }+ bool prefBool(const char* key, bool fallback) const { return prefs.contains(key) ? prefs.value(key).toBool() : fallback; }+ QString prefString(const char* key) const { return prefs.value(key).toString(); }Impl(engine::EngineController& e, std::filesystem::path dataDirectory)- : engine(e), facade(e, std::move(dataDirectory)) {+ : engine(e), facade(e, dataDirectory),+ dataDir(dataDirectory.empty() ? runtime::localDataDirectory() : dataDirectory) {+ if (!dataDirectory.empty()) anchorsFile = dataDirectory / L"node-anchors.json";+ if (!anchorsFile.empty()) {+ QFile file(QString::fromStdWString(anchorsFile.wstring()));+ if (file.open(QIODevice::ReadOnly)) anchors = QJsonDocument::fromJson(file.readAll()).object().toVariantMap();+ }+ // Same high-performance DXGI ordering as the engine. This only seeds a+ // fresh session; loading saved settings below preserves manual choices.+ gfx::ComPtr<IDXGIFactory6> factory;+ if(SUCCEEDED(CreateDXGIFactory2(0,IID_PPV_ARGS(&factory)))) {+ gfx::ComPtr<IDXGIAdapter1> adapter;+ for(UINT i=0;SUCCEEDED(factory->EnumAdapterByGpuPreference(i,DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE,IID_PPV_ARGS(&adapter)));++i) {+ DXGI_ADAPTER_DESC1 desc{};+ if(FAILED(adapter->GetDesc1(&desc))||(desc.Flags&DXGI_ADAPTER_FLAG_SOFTWARE))continue;+ auto initial=facade.pendingSettings();+ initial.nrRuntime=ngx::preferSfNr(desc.VendorId,desc.Description)?engine::NrRuntime::Ampere:engine::NrRuntime::Original;+ facade.setPending(initial);+ veyra::log::info("nr-default",std::format("adapter={} selected={}",utf8Of(std::wstring(desc.Description)).toStdString(),engine::nrRuntimeName(initial.nrRuntime)));+ break;+ }+ }chain = engine::toChain(facade.pendingSettings());+ acceptedChain = chain;+ draftGlobals = engine::ChainGlobalSettings::capture(facade.pendingSettings());+ session = engine::ChainSession::initial(facade.pendingSettings());+ savedSession = session;validation = engine::validateChain(chain);options = engine::PlayerOptions::from(facade.pendingSettings());}- void poll() {+ std::optional<engine::EnhancementSettings> exportSettings(QString& error) const {+ if (chain.mode == engine::ChainMode::Node) {+ error = QObject::tr("节点链尚未接入导出执行器,请切换列表模式后导出");+ return std::nullopt;+ }+ auto settings = facade.pendingSettings();+ engine::fromChain(chain, settings);+ if (!exportPresetName.empty()) {+ const auto& entries = facade.presets().entries();+ const auto preset = std::find_if(entries.begin(), entries.end(), [this](const auto& entry) {+ return entry.name == exportPresetName;+ });+ if (preset == entries.end()) {+ error = QObject::tr("导出预设已不存在,请重新选择");+ return std::nullopt;+ }+ if (preset->kind != engine::ChainMode::List) {+ error = QObject::tr("节点预设尚未接入导出执行器");+ return std::nullopt;+ }+ engine::PresetLibrary::apply(*preset, settings);+ }+ settings.exportBitrateMbps = exportBitrateMbps;+ if (exportResolutionIndex >= 0) {+ settings.sr = exportResolutionIndex != 0;+ if (settings.sr) {+ switch (exportResolutionIndex) {+ case 1: settings.srTarget = pipeline::SrTarget::Qhd; break;+ case 2: settings.srTarget = pipeline::SrTarget::Uhd4K; break;+ case 3: settings.srTarget = pipeline::SrTarget::Uhd8K; break;+ case 4: settings.srTarget = pipeline::SrTarget::Uhd5K; break;+ case 5: settings.srTarget = pipeline::SrTarget::Uhd6K; break;+ case 6: settings.srTarget = pipeline::SrTarget::Uhd7K; break;+ default: break;+ }+ }+ }+ if (exportRateControl != sink::ExportRateControl::Cq && !exportBitrateMbps) {+ error = QObject::tr("CBR/VBR 需要指定码率");+ return std::nullopt;+ }+ if (!settings.validate().empty()) {+ error = QObject::tr("导出设置无效");+ return std::nullopt;+ }+ return settings;+ }++ engine::ChainSession currentSession() const {+ auto current = session;+ current.active = chain.mode;+ current.initialized[size_t(chain.mode)] = true;+ current.configurations[size_t(chain.mode)] = engine::ChainConfiguration::capture(+ activeRuntime(), facade.pendingSettings(), nrIndex(), colourIndex());+ if (chain.mode == engine::ChainMode::Node) {+ auto document = std::make_shared<engine::NodeEditorDocument>();+ document->nodes = chain; document->layout = layout; document->globals = draftGlobals;+ current.configurations[size_t(chain.mode)].editor = std::move(document);+ }+ return current;+ }++ bool persistSession() {+ const auto current = currentSession();+ if (current == savedSession) return true;+ if (!facade.saveChainSession(current)) return false;+ session = savedSession = current;+ return true;+ }++ bool poll() {+ const auto before=facade.pendingSettings();auto frame = facade.poll();- if (!frame.changed && haveSnapshot) return;+ const auto restored=facade.pendingSettings();+ const bool fgRollback=before.frameGenerationBackend!=restored.frameGenerationBackend||before.multiplier!=restored.multiplier;+ const bool nrRollback=before.nrRuntime!=restored.nrRuntime;+ if(nrRollback) {+ for(auto* c:{&chain,&acceptedChain})for(uint32_t i=0;i<c->nodeCount;++i)+ if(c->nodes[i].type==engine::EffectType::NrEnhance)c->nodes[i].nr.runtime=restored.nrRuntime;+ }+ if(fgRollback){+ const auto restoreFg=[&](engine::EffectChain& value){+ if(restored.multiplier>1)value.fgMultiplier=restored.multiplier;+ for(uint32_t i=0;i<value.nodeCount;++i)+ if(value.nodes[i].type==engine::EffectType::FrameGeneration)value.nodes[i].enabled=restored.multiplier>1;+ };+ restoreFg(chain);restoreFg(acceptedChain);+ if(draftGlobals.fgBackend==before.frameGenerationBackend)draftGlobals.fgBackend=restored.frameGenerationBackend;+ options=engine::PlayerOptions::from(restored,engine::runtimeOrder(acceptedChain));+ }+ if (!frame.changed && haveSnapshot) return fgRollback||nrRollback;snapshot = frame.snapshot;publishedRevision = frame.revision;haveSnapshot = true;@@ -112,36 +474,254 @@ struct QmlPlayerBridge::Impl {snapshot.transport == engine::TransportState::Empty ||snapshot.transport == engine::TransportState::Stopping))openingSource = false;+ return fgRollback||nrRollback;}// The chain is the source of truth for the stage settings; every commit// writes it back over the struct so the two can never disagree.- void commit(engine::EnhancementSettings settings) {- engine::fromChain(chain, settings);- facade.setPending(settings);- facade.applySettings(settings);- options = engine::PlayerOptions::from(settings);+ bool commit(engine::EnhancementSettings settings) {+ if (chain.mode == engine::ChainMode::Node) {+ const auto previous = facade.pendingSettings();+ const auto oldGlobals = draftGlobals;+ draftGlobals = engine::ChainGlobalSettings::capture(settings);+ // Non-node controls (e.g. audio) may still change while a wire is+ // incomplete. Keep runtime globals separate from that transaction.+ engine::ChainGlobalSettings::capture(previous).apply(settings);+ facade.setPending(settings);+ if (revalidate(true, &previous)) return true;+ draftGlobals = oldGlobals; facade.setPending(previous);+ revalidate();+ return false;+ }+ const auto& runtime = activeRuntime();+ engine::fromChain(runtime, settings);+ if(!facade.applySettings(settings,engine::runtimeOrder(runtime)))return false;+ options = engine::PlayerOptions::from(settings,engine::runtimeOrder(runtime));+ return true;}- void revalidate() {- validation = engine::validateChain(chain);+ bool revalidate(bool apply=false, const engine::EnhancementSettings* prior=nullptr) {+ auto projected = std::make_unique<engine::EffectChain>(chain);+ bool incomplete = false;+ if (chain.mode == engine::ChainMode::Node) {+ validation = layout.validate(chain);+ if (!validation.accepted) return false;+ // Even detached controls must obey the persistent parameter contract.+ auto check = std::make_unique<engine::ChainConfiguration>(+ engine::ChainConfiguration::capture(acceptedChain, facade.pendingSettings()));+ auto document = std::make_shared<engine::NodeEditorDocument>();+ document->nodes = chain; document->layout = layout; document->globals = draftGlobals; check->editor = document;+ if (!check->valid()) { validation = {false, "节点参数无效,未提交"}; return false; }+ validation = layout.project(chain, *projected);+ if (!validation.accepted) {+ uint32_t end = layout.inputNext;+ while (end > engine::NodeGraphLayout::Output)+ end = layout.next[size_t(layout.indexOf(chain, end))];+ // Incomplete wires are editable/savable. A complete but illegal+ // path is rejected atomically by the caller, never auto-sorted.+ if (end != engine::NodeGraphLayout::Input) return false;+ *projected = acceptedChain; incomplete = true;+ }+ } else validation = engine::validateChain(chain);+ if(!validation.accepted && !incomplete)return false;+ const auto previous = prior ? *prior : facade.pendingSettings();auto s = facade.pendingSettings();- engine::fromChain(chain, s);- facade.setPending(s);- options = engine::PlayerOptions::from(s);+ if (chain.mode == engine::ChainMode::Node && !incomplete) {+ draftGlobals.apply(s);+ // A detached singleton owns editable values, not live resources.+ if (!projected->firstOf(engine::EffectType::SuperResolution)) {+ s.srTarget = previous.srTarget; s.videoSrQuality = previous.videoSrQuality;+ }+ if (!projected->firstOf(engine::EffectType::FrameGeneration))+ s.frameGenerationBackend = previous.frameGenerationBackend;+ }+ engine::fromChain(*projected, s);+ if(const auto error=s.validate();!error.empty()){+ veyra::log::error("qml-settings",error);+ validation={false,"效果参数无效,未提交;详见诊断日志"};return false;+ }+ const auto order = engine::runtimeOrder(*projected);+ const bool changed = s != previous || order != engine::runtimeOrder(acceptedChain);+ if(apply && changed && !facade.applySettings(s,order)){+ facade.setPending(previous);+ validation={false,"引擎未接受设置,已保留原状态"};+ return false;+ }+ if(!apply || !changed)facade.setPending(s);+ acceptedChain = *projected;+ options = engine::PlayerOptions::from(s,order);+ return true;}};+namespace {+bool prepareStartupPreset(const engine::PresetEntry& entry, engine::ChainSession& session,+ engine::EnhancementSettings& settings, QString& error) {+ if (!session.select(entry.kind)) {+ error = QObject::tr("默认预设的编辑模式无效");+ return false;+ }+ auto& configuration = session.configurations[size_t(entry.kind)];+ configuration.apply(settings);+ if (entry.kind == engine::ChainMode::List) {+ auto chain = configuration.chain;+ const auto result = engine::PresetLibrary::applyToChain(entry, chain, settings);+ if (!result.accepted) { error = utf8Of(result.message); return false; }+ configuration = engine::ChainConfiguration::capture(chain, settings);+ } else {+ engine::NodeEditorDocument document;+ if (configuration.editor) document = *configuration.editor;+ else {+ document.nodes = configuration.chain;+ const auto result = document.layout.initialize(document.nodes);+ if (!result.accepted) { error = utf8Of(result.message); return false; }+ }+ if (!document.globals)+ document.globals = static_cast<const engine::ChainGlobalSettings&>(configuration);+ auto draftSettings = settings;+ const auto result = engine::PresetLibrary::applyToEditor(entry, document, draftSettings);+ if (!result.accepted) { error = utf8Of(result.message); return false; }+ auto runtime = configuration.chain;+ const auto projected = document.layout.project(document.nodes, runtime);+ if (!projected.accepted) {+ uint32_t end = document.layout.inputNext;+ while (end > engine::NodeGraphLayout::Output)+ end = document.layout.next[size_t(document.layout.indexOf(document.nodes, end))];+ if (end != engine::NodeGraphLayout::Input) { error = utf8Of(projected.message); return false; }+ runtime = configuration.chain;+ } else {+ document.globals->apply(settings);+ engine::fromChain(runtime, settings);+ }+ settings.audioSync = draftSettings.audioSync;+ settings.audioOffsetMs = draftSettings.audioOffsetMs;+ configuration = engine::ChainConfiguration::capture(runtime, settings);+ configuration.editor = std::make_shared<engine::NodeEditorDocument>(std::move(document));+ }+ if (!session.valid() || !settings.validate().empty()) {+ error = QObject::tr("默认预设参数无效,已保留恢复会话");+ return false;+ }+ return true;+}+} // namespace+QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesystem::path dataDirectory,QObject* parent): QObject(parent), impl_(std::make_unique<Impl>(engine, std::move(dataDirectory))) {- impl_->facade.importLegacyStores();+ connect(this,&QmlPlayerBridge::snapshotChanged,this,&QmlPlayerBridge::fgChoicesChanged);+ connect(this,&QmlPlayerBridge::settingsChanged,this,&QmlPlayerBridge::fgChoicesChanged);+ impl_->loadPrefs();+ if (qApp) qApp->installEventFilter(this);+ // Before anything opens: the renderer reads the output choice at start().+ applyPreference(QStringLiteral("audioDevice"));+ applyPreference(QStringLiteral("audioForceStereo"));+ const bool presetsLoaded = impl_->facade.importLegacyStores();+ const auto presetNotice = utf8Of(impl_->facade.error());+ if (!presetNotice.isEmpty())+ QTimer::singleShot(0, this, [this, presetNotice, presetsLoaded] { emit notice(presetNotice, !presetsLoaded); });// Recent files, the last capture session and the shell preferences are saved// on every change; without this load they were written but never read back,// so every restart came up with an empty history. A damaged file is logged// and the defaults stand.if (!impl_->facade.loadPreferences())veyra::log::error("ui", "preferences not loaded: " + utf8Of(impl_->facade.error()).toStdString());+ auto restored = impl_->session;+ QString restoreError;+ if (!impl_->facade.loadChainSession(restored)) {+ restoreError = utf8Of(impl_->facade.error());+ } else {+ const auto migrationNotice = utf8Of(impl_->facade.error());+ if (!migrationNotice.isEmpty())+ QTimer::singleShot(0, this, [this, migrationNotice] { emit notice(migrationNotice, false); });+ auto settings = impl_->facade.pendingSettings();+ const auto& configuration = restored.configurations[size_t(restored.active)];+ configuration.apply(settings);+ const auto previous = impl_->facade.pendingSettings();+ if (settings.validate().empty() && impl_->facade.applySettings(settings,engine::runtimeOrder(configuration.chain))) {+ impl_->session = impl_->savedSession = restored;+ impl_->restoreConfiguration(configuration);+ impl_->options = engine::PlayerOptions::from(settings,engine::runtimeOrder(impl_->activeRuntime()));+ impl_->revalidate();+ } else {+ impl_->facade.setPending(previous);+ restoreError = tr("模式会话未被引擎接受,保留初始状态");+ }+ }+ if (!restoreError.isEmpty()) {+ veyra::log::error("ui-session", restoreError.toStdString());+ QTimer::singleShot(0, this, [this, restoreError] { emit notice(restoreError, true); });+ } else if (presetsLoaded) {+ const auto defaultIndex = impl_->facade.presets().defaultIndex();+ if (defaultIndex) {+ const auto before = impl_->currentSession();+ auto candidate = before;+ auto settings = impl_->facade.pendingSettings();+ QString error;+ const auto& entry = impl_->facade.presets().entries()[*defaultIndex];+ if (!prepareStartupPreset(entry, candidate, settings, error)) {+ veyra::log::error("ui-preset", error.toStdString());+ } else if (!impl_->facade.applySettings(settings,+ engine::runtimeOrder(candidate.configurations[size_t(candidate.active)].chain))) {+ error = tr("引擎未接受默认预设,已保留恢复会话");+ } else {+ impl_->session = candidate;+ impl_->restoreConfiguration(candidate.configurations[size_t(candidate.active)]);+ impl_->revalidate();+ impl_->options = engine::PlayerOptions::from(settings, engine::runtimeOrder(impl_->activeRuntime()));+ if (candidate != before && !impl_->facade.saveChainSession(candidate))+ error = tr("默认预设已应用,但会话保存失败:") + utf8Of(impl_->facade.error());+ else impl_->savedSession = candidate;+ }+ if (!error.isEmpty())+ QTimer::singleShot(0, this, [this, error] { emit notice(error, true); });+ }+ }+ // Sound sync is a player setting, not part of either chain: it is kept in+ // the shell preferences and restored here, after the session.+ {+ auto s = impl_->facade.pendingSettings();+ const auto& p = impl_->prefs;+ bool changed = false;+ if (p.contains(QStringLiteral("audioSync"))) {+ const int m = p.value(QStringLiteral("audioSync")).toInt();+ if (m >= 0 && m <= 2 && int(s.audioSync) != m) { s.audioSync = static_cast<engine::AudioSyncMode>(m); changed = true; }+ }+ if (p.contains(QStringLiteral("audioOffsetMs"))) {+ const int ms = p.value(QStringLiteral("audioOffsetMs")).toInt();+ if (ms >= -250 && ms <= 250 && s.audioOffsetMs != ms) { s.audioOffsetMs = ms; changed = true; }+ }+ if (p.contains(QStringLiteral("contentRate"))) {+ const int rate = p.value(QStringLiteral("contentRate")).toInt();+ if (rate >= 0 && rate <= int(engine::ContentRate::Capture60To30) && int(s.content) != rate) { s.content = static_cast<engine::ContentRate>(rate); changed = true; }+ }+ if (changed && !impl_->commit(std::move(s))) veyra::log::warn("ui-prefs", "saved sound sync not accepted");+ }+ // Presentation (低延迟队列 / 显示同步 / 输出上限) and the picture aspect.+ {+ const auto saved = impl_->prefs.value(QStringLiteral("presentation")).toMap();+ auto& pr = impl_->presentation;+ if (!saved.isEmpty()) {+ pr.enabled = saved.value(QStringLiteral("lowQueue")).toBool();+ pr.display = static_cast<engine::DisplaySync>(std::clamp(saved.value(QStringLiteral("display")).toInt(), 0, 2));+ pr.outputRate = static_cast<engine::OutputRateMode>(std::clamp(saved.value(QStringLiteral("outputRate")).toInt(), 0, 2));+ pr.customFps = std::clamp(saved.value(QStringLiteral("customFps"), 60.0).toDouble(), 1.0, 1000.0);+ }+ if (pr.valid()) impl_->engine.requestPresentation(pr);+ impl_->aspectMode = std::clamp(impl_->prefs.value(QStringLiteral("aspect")).toInt(), 0, 6);+ }+ impl_->sessionSaveTimer = new QTimer(this);+ impl_->sessionSaveTimer->setSingleShot(true);+ impl_->sessionSaveTimer->setInterval(300);+ const auto scheduleSave = [this] { impl_->sessionSaveTimer->start(); };+ connect(this, &QmlPlayerBridge::chainChanged, this, scheduleSave);+ connect(this, &QmlPlayerBridge::settingsChanged, this, scheduleSave);+ connect(impl_->sessionSaveTimer, &QTimer::timeout, this, [this] {+ if (!impl_->persistSession()) {+ veyra::log::error("ui-session", utf8Of(impl_->facade.error()).toStdString());+ emit notice(tr("当前修改尚未保存:") + utf8Of(impl_->facade.error()), true);+ }+ });// 60 Hz ceiling, and it does nothing at all when the snapshot is unchanged.impl_->timer = new QTimer(this);connect(impl_->timer, &QTimer::timeout, this, [this] {@@ -152,7 +732,49 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesystconst bool wasFailed = impl_->snapshot.failed;const auto wasTransport = impl_->snapshot.transport;const uint64_t wasSession = impl_->snapshot.sessionId;- impl_->poll();+ if(impl_->poll()){emit settingsChanged();emit chainChanged();}+ tickSubtitles();+ tickImageBatch();+ tickCapture();+ tickPs5();+ // Geometry uses the source DAR and the same transform as mouse/compare.+ if (impl_->snapshot.running && impl_->videoWindow) {+ const bool fresh = impl_->aspectSession != impl_->snapshot.sessionId;+ impl_->aspectSession = impl_->snapshot.sessionId;+ applyAspect(fresh);+ }+ {+ const auto& s = impl_->snapshot;+ if (impl_->resumeSession && s.sessionId == impl_->resumeSession && s.running && s.duration > 0) {+ const double at = impl_->resumeAt;+ impl_->resumeSession = 0;+ if (at > 5 && at < s.duration - 10) {+ seekTo(at);+ veyra::log::info("ui-resume", std::format("resumed at {:.1f}s", at));+ emit notice(tr("已从上次位置 %1 继续").arg(formatTime(at)), false);+ }+ }+ if (++impl_->positionTicks >= 120) { impl_->positionTicks = 0; rememberPosition(false); }+ }+ // Status light: 1.4.4 sampled its dashboard history every 250 ms.+ if (++impl_->historyTicks >= 16) {+ impl_->historyTicks = 0;+ updateRunStatus();+ }+ // The renderer reopens on its own thread (device change, fallback); pick+ // up what it opened about twice a second.+ if (++impl_->audioPollTicks >= 30) {+ impl_->audioPollTicks = 0;+ const auto active = sink::activeRenderEndpoint();+ if (active.valid != impl_->audioActive.valid || active.id != impl_->audioActive.id ||+ active.fallback != impl_->audioActive.fallback || active.channels != impl_->audioActive.channels ||+ active.downmix != impl_->audioActive.downmix) {+ const bool fellBack = active.fallback && !impl_->audioActive.fallback;+ impl_->audioActive = active;+ emit audioDevicesChanged();+ if (fellBack) emit notice(tr("所选音频设备不可用,已切到系统默认设备"), true);+ }+ }if (!had || impl_->publishedRevision != before) {const auto& s = impl_->snapshot;if (!had || wasSession != s.sessionId || wasTransport != s.transport ||@@ -162,16 +784,35 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesysts.sessionId, int(s.transport), s.running, s.image, s.failed,impl_->openingSource, impl_->publishedRevision));impl_->power.update(s.running && !s.failed && !s.image && s.transport == engine::TransportState::Playing);+ if (had && !wasFailed && s.failed && !s.capture && !s.remotePlay &&+ impl_->prefString("decode") == QLatin1String("hardware"))+ emit notice(tr("已设为“强制硬解”,这个文件无法用硬件解码打开;可在 设置 → 播放 改回“自动”"), true);+ // A live source that fails says why, and the user is taken back to the+ // start page: the reason used to land only in the (closed) PS5 panel,+ // leaving a black cinema strip that looked like a minimised window.+ if (had && !wasFailed && s.failed && (s.capture || s.remotePlay)) {+ const QString why = QString::fromStdWString(s.status);+ veyra::log::warn("ui-live-failed", std::format("remote={} status={}", s.remotePlay, why.toStdString()));+ emit notice(why.isEmpty() ? (s.remotePlay ? tr("PS5 串流没有连上") : tr("采集没有开始")) : why, true);+ if (impl_->currentPage == QLatin1String("min")) emit navigate(QStringLiteral("home"));+ }emit snapshotChanged();}// An export in flight needs its own poll; it is a separate job and its// snapshot is not part of the player snapshot.- if (impl_->exportSnapshot.active()) pollExport();+ if (impl_->exportSnapshot.active() || impl_->exportSnapshot.queued > 0) pollExport();});impl_->timer->start(16);+ startGpuSampler();}-QmlPlayerBridge::~QmlPlayerBridge() = default;+QmlPlayerBridge::~QmlPlayerBridge() {+ if (qApp) qApp->removeEventFilter(this);+ rememberPosition(true);+ if (impl_->sessionSaveTimer) impl_->sessionSaveTimer->stop();+ if (!impl_->persistSession())+ veyra::log::error("ui-session", utf8Of(impl_->facade.error()).toStdString());+}// --- professional-page readouts ---------------------------------------------@@ -179,12 +820,10 @@ QmlPlayerBridge::~QmlPlayerBridge() = default;// the getter says so and the UI shows an explicit "unmeasured" rather than a// zero or a stand-in.QString QmlPlayerBridge::outputSummary() const {- // The engine publishes the source extent and the preview scale, not the final- // working extent, so the honest answer is the source size at the reported- // scale factor. Nothing here invents a resolution the graph did not produce.const auto& s = impl_->snapshot;- if (s.sourceWidth == 0 || s.sourceHeight == 0) return {};- return QStringLiteral("%1x%2").arg(s.sourceWidth).arg(s.sourceHeight);+ const auto& plan = s.metrics.resolution;+ if (!s.running || !plan.output.valid() || plan.settingsRevision != s.applied.revision) return {};+ return QStringLiteral("%1x%2").arg(plan.output.width).arg(plan.output.height);}// A display rate is only real when the system's display event can be read. No@@ -195,9 +834,16 @@ double QmlPlayerBridge::displayFps() const { return 0.0; }bool QmlPlayerBridge::displayFpsKnown() const { return false; }double QmlPlayerBridge::queuedFrames() const {- // Preview frames the scheduler chose not to present, as a running count. This- // is in-process scheduling, NOT screen latency, and the UI labels it so.- return double(impl_->snapshot.previewSkipped);+ // Valid output opportunities held by presenter jobs, not cumulative skips+ // and not the OS/display queue. Zero is meaningful only with a live window.+ return queuedFramesKnown() ? double(impl_->snapshot.metrics.flow.pendingOutputFrames) : 0.0;+}+bool QmlPlayerBridge::queuedFramesKnown() const {+ const auto& s = impl_->snapshot;+ const auto& flow = s.metrics.flow;+ return s.running && !s.image && s.sessionId != 0 &&+ flow.latest.sessionId == s.sessionId && flow.lastReady100ns > 0 &&+ flow.latest.frame.settingsRevision == s.applied.revision;}int QmlPlayerBridge::skippedFrames() const { return int(impl_->snapshot.previewSkipped); }@@ -210,31 +856,138 @@ QString QmlPlayerBridge::flowBackend() const {return QStringLiteral("GPU 光流");}+int QmlPlayerBridge::opticalFlowChoice() const { return int(settings().opticalFlowBackend); }+bool QmlPlayerBridge::setOpticalFlowChoice(int backend) {+ if(backend<0||backend>2)return false;+ const auto before=settings();auto next=before;+ next.opticalFlowBackend=engine::OpticalFlowBackend(backend);+ if(next.opticalFlowBackend==before.opticalFlowBackend)return true;+ if(!impl_->commit(next)){+ emit notice(tr("引擎未接受光流配置,原设置保留"),true);return false;+ }+ emit settingsChanged();return true;+}+QVariantList QmlPlayerBridge::stageTimings() const {- // The engine publishes CPU-side percentiles per phase, not per-GPU-stage- // timings, so the three signals it does publish are what is shown. A stage- // with no sample reports as unmeasured instead of a zero-length bar.+ // Consume the existing GPU timestamp aggregates. Repeated NR layers share+ // a timestamp slot: this is stage sampling, NOT per-node attribution.+ // XeSS-internal FG is not measured by the graph's DLSS FG batch query.const auto& s = impl_->snapshot;QVariantList out;- struct Row { const char* label; double ms; const char* color; bool measured; };+ using Stage = diagnostics::GpuStage;+ struct Row { const char* label; Stage stage; const char* color; };const Row rows[] = {- {"调度", s.schedulingWaitP95Ms, "#6EA8FF", s.schedulingWaitP95Ms > 0.0},- {"处理", s.processCpuP95Ms, "#FF8A3D", s.processCpuP95Ms > 0.0},- {"呈现", s.presentCpuP95Ms, "#3DDC84", s.presentCpuP95Ms > 0.0},+ {"输入", Stage::Color, "#A8A8B8"},+ {"超分", Stage::Sr, "#6EA8FF"},+ {"光流", Stage::Flow, "#9A85FF"},+ {"NR采样", Stage::Nr, "#FF8A3D"},+ {"残差", Stage::Residual, "#E7B868"},+ {"DLSS FG", Stage::FgBatch, "#3DDC84"},+ {"HDR", Stage::VideoHdr, "#E58BD9"},+ {"呈现", Stage::Blit, "#58CAD4"},};const double budget = stageBudgetMs();for (const auto& r : rows) {+ const auto& sample = s.metrics.flow.gpuTiming[size_t(r.stage)];+ const bool measured = queuedFramesKnown() && sample.samples > 0 &&+ sample.p95 && std::isfinite(*sample.p95) && *sample.p95 >= 0.0;+ const double ms = measured ? *sample.p95 : 0.0;QVariantMap item;item["label"] = QString::fromUtf8(r.label);- item["ms"] = r.ms;- item["measured"] = r.measured;+ item["ms"] = ms;+ item["measured"] = measured;+ item["samples"] = measured ? QVariant::fromValue<qulonglong>(sample.samples) : QVariant::fromValue<qulonglong>(0);+ item["domain"] = QStringLiteral("GPU timestamp P95");item["color"] = QString::fromUtf8(r.color);- item["fraction"] = (r.measured && budget > 0.01) ? r.ms / budget : 0.0;+ item["fraction"] = (measured && budget > 0.01) ? ms / budget : 0.0;out << item;}return out;}+QVariantMap QmlPlayerBridge::nodeTimings() const {+ // Per-node GPU timestamp P95, keyed by the card id chain() publishes. An+ // editor node borrows a number only when the wired path it sits on is the+ // chain actually running; drafts, detached and disabled nodes never do.+ using Stage = diagnostics::GpuStage;+ const auto& c = impl_->chain;+ const auto& flow = impl_->snapshot.metrics.flow;+ const bool node = c.mode == engine::ChainMode::Node;+ std::vector<int> path;+ bool draft = false;+ if (!node) {+ for (uint32_t i = 0; i < c.nodeCount; ++i) path.push_back(int(i));+ } else {+ uint32_t id = impl_->layout.inputNext;+ while (id > engine::NodeGraphLayout::Output && path.size() <= c.nodeCount) {+ const int index = impl_->layout.indexOf(c, id);+ if (index < 0) break;+ path.push_back(index);+ id = impl_->layout.next[size_t(index)];+ }+ engine::EffectChain projected;+ draft = id != engine::NodeGraphLayout::Output || !impl_->layout.project(c, projected).accepted ||+ engine::runtimeOrder(projected) != engine::runtimeOrder(impl_->acceptedChain);+ if (draft) path.clear();+ }+ const bool live = queuedFramesKnown();+ const bool xess = fgBackendName() == QLatin1String("xess");+ QVariantMap out;+ auto publish = [&](uint32_t i, const QString& state, std::optional<Stage> stage) {+ QVariantMap item{{"state", state}, {"ms", 0.0}, {"samples", QVariant::fromValue<qulonglong>(0)}};+ if (stage) {+ const auto& sample = flow.gpuTiming[size_t(*stage)];+ if (live && sample.samples > 0 && sample.p95 && std::isfinite(*sample.p95) && *sample.p95 >= 0.0) {+ item["state"] = QStringLiteral("measured");+ item["ms"] = *sample.p95;+ item["samples"] = QVariant::fromValue<qulonglong>(sample.samples);+ }+ }+ const QVariant key = node ? QVariant(impl_->layout.ids[i]) : QVariant(i + 2);+ out[key.toString()] = item;+ };+ std::vector<bool> onPath(c.nodeCount, false);+ for (const int i : path) onPath[size_t(i)] = true;+ for (uint32_t i = 0; i < c.nodeCount; ++i)+ if (!onPath[i]) publish(i, draft ? QStringLiteral("draft") : QStringLiteral("idle"), std::nullopt);+ unsigned enabledNr = 0, colour = 0;+ for (const int index : path) {+ const auto i = uint32_t(index);+ const auto& n = c.nodes[i];+ std::optional<Stage> stage;+ QString waiting = live ? QStringLiteral("pending") : QStringLiteral("stopped");+ switch (n.type) {+ case engine::EffectType::NrEnhance:+ if (n.enabled && enabledNr < diagnostics::kTimedNrLayers) stage = diagnostics::nrLayerStage(enabledNr);+ if (n.enabled) ++enabledNr;+ break;+ case engine::EffectType::Color:+ // Parameter 0 before any SR/NR is fused into the input conversion+ // shader: it has no separable GPU span of its own.+ if (colour < diagnostics::kTimedColorNodes) stage = diagnostics::colorNodeStage(colour);+ if (colour == 0) waiting = live ? QStringLiteral("fused") : waiting;+ ++colour;+ break;+ case engine::EffectType::SuperResolution: stage = Stage::Sr; break;+ case engine::EffectType::VideoHdr:+ stage = Stage::VideoHdr;+ // SDR display path: the node is wired but TrueHDR is not built.+ if (live && !impl_->snapshot.videoHdrActive) waiting = QStringLiteral("hdr-sdr");+ break;+ case engine::EffectType::FrameGeneration:+ if (xess) waiting = QStringLiteral("sdk"); else stage = Stage::FgBatch;+ // Realtime admission declined the pairs inside this window.+ if (!xess && live && flow.counters.fgSkippedBeforeEval > 0 && flow.counters.fgEvaluated < flow.counters.fgCandidate)+ waiting = QStringLiteral("fg-skipped");+ break;+ default: waiting = QStringLiteral("untimed"); break;+ }+ if (!n.enabled) { publish(i, QStringLiteral("disabled"), std::nullopt); continue; }+ publish(i, waiting, stage);+ }+ return out;+}+double QmlPlayerBridge::stageBudgetMs() const {// One source period: the budget a stage has to stay inside. Zero when the// source rate is unknown, which the UI shows as unmeasured.@@ -245,50 +998,113 @@ double QmlPlayerBridge::stageBudgetMs() const {double QmlPlayerBridge::scheduleP95Ms() const { return impl_->snapshot.schedulingWaitP95Ms; }double QmlPlayerBridge::chainTotalMs() const {- // Sum of the phases the engine measured. Zero means nothing measured yet, and- // the UI shows "未测" rather than a zero that would read as instant.- const auto& s = impl_->snapshot;- const double total = s.schedulingWaitP95Ms + s.processCpuP95Ms + s.presentCpuP95Ms;- return total > 0.0 ? total : 0.0;+ // Engine merges same-frame measured intervals before aggregation. Never+ // sum unrelated percentiles. This excludes uninstrumented stages/nodes.+ return chainTotalMsKnown() ? *impl_->snapshot.metrics.flow.enhancementProcessing.p95 : 0.0;+}+bool QmlPlayerBridge::chainTotalMsKnown() const {+ const auto& sample = impl_->snapshot.metrics.flow.enhancementProcessing;+ return queuedFramesKnown() && sample.samples > 0 && sample.p95 &&+ std::isfinite(*sample.p95) && *sample.p95 >= 0.0;}// --- frame generation --------------------------------------------------------QString QmlPlayerBridge::fgBackendName() const {- return impl_->facade.pendingSettings().frameGenerationBackend- == engine::FrameGenerationBackend::XeSS- ? QStringLiteral("xess") : QStringLiteral("dlss");+ switch(settings().frameGenerationBackend){+ case engine::FrameGenerationBackend::Dlss:return QStringLiteral("dlss");+ case engine::FrameGenerationBackend::XeSS:return QStringLiteral("xess");+ case engine::FrameGenerationBackend::Fsr:return QStringLiteral("fsr3");+ case engine::FrameGenerationBackend::Fsr4:return QStringLiteral("fsr4");+ }+ return {};+}+QVariantList QmlPlayerBridge::fgBackendChoices() const {+ return {+ QVariantMap{{"id","dlss"},{"label",tr("DLSS 帧生成")}},+ QVariantMap{{"id","xess"},{"label",tr("Intel XeSS · 实验")}},+ QVariantMap{{"id","fsr3"},{"label",tr("FSR 3.1 · 2X")}},+ QVariantMap{{"id","fsr4"},{"label",tr("FSR 4 ML · RX 9000 · 实验")}}+ };+}+QString QmlPlayerBridge::fgProviderText() const {+ const auto& s=impl_->snapshot;+ if(engine::fsrFrameGeneration(s.applied.frameGenerationBackend)&&s.applied.multiplier>1&&!s.fsrProviderVersion.empty())+ return tr("实际运行:FSR %1 · 2X").arg(QString::fromStdString(s.fsrProviderVersion));+ if(fgBackendName()==QLatin1String("fsr4"))return tr("FSR 4 ML 需要支持的 RX 9000 和驱动;实卡待验");+ if(fgBackendName()==QLatin1String("fsr3"))return tr("FSR 3.1 跨厂商补帧 · 最高 2X");+ if(fgBackendName()==QLatin1String("xess"))+ return fgMaxMultiplier()<4?tr("当前 XeSS 模块未匹配 3X / 4X 解锁版本;2X 可用,请在组件页核对版本"):+ tr("2X 为原生路径,3X / 4X 为实验解锁;失败原因见诊断");+ return tr("NVIDIA RTX 补帧;倍率以运行库实际能力为准");+}+// XeSS ceiling (SettingsWindow): 4X with the audited unlock provider, else 2X,+// or a running session's reported interpolation count above 2X.+static int xessCeiling(const engine::PlayerSnapshot& s) {+ static const bool audited = gfx::XessMfgUnlock::providerIsAudited(+ (runtime::localDataDirectory() / L"intel" / L"experimental" / L"libxess_fg.dll").wstring());+ int cap = audited ? 4 : 2;+ // A running context reports the count it was CREATED with (3X -> 2), not+ // what the provider allows: it may raise the ceiling, never lower it.+ // Lowering it made 4X vanish after picking 3X until the backend was reset.+ // The highest ceiling any context has reported this run stays offered:+ // a later context created at 2X reports 1 and must not hide 3X/4X again.+ static int seen = 0;+ if (s.xessMaxInterpolatedFrames > 1) seen = std::max(seen, std::clamp(s.xessMaxInterpolatedFrames + 1, 2, 4));+ return std::max(cap, seen);}void QmlPlayerBridge::setFgBackendName(const QString& value) {+ if(value!=QLatin1String("dlss")&&value!=QLatin1String("xess")&&value!=QLatin1String("fsr3")&&value!=QLatin1String("fsr4")){emit notice(tr("未知补帧后端"),true);return;}auto s = settings();const auto want = value == QLatin1String("xess") ? engine::FrameGenerationBackend::XeSS- : engine::FrameGenerationBackend::Dlss;+ : value == QLatin1String("fsr3") ? engine::FrameGenerationBackend::Fsr+ : value == QLatin1String("fsr4") ? engine::FrameGenerationBackend::Fsr4+ : engine::FrameGenerationBackend::Dlss;if (s.frameGenerationBackend == want) return;s.frameGenerationBackend = want;- impl_->commit(std::move(s));+ // A DLSS multiplier above XeSS's ceiling used to make the switch fail+ // silently in effect (the backend stayed DLSS). Clamp to the ceiling instead.+ auto& chain = impl_->chain;+ const auto beforeMultiplier = chain.fgMultiplier;+ const int cap = want == engine::FrameGenerationBackend::XeSS ? xessCeiling(impl_->snapshot)+ : engine::fsrFrameGeneration(want) ? 2 : 6;+ const bool clamped = chain.fgMultiplier > uint32_t(cap);+ if (clamped) chain.fgMultiplier = uint32_t(cap);+ if(!impl_->commit(s)){+ chain.fgMultiplier = beforeMultiplier;+ emit notice(tr("补帧后端切换未被接受,原设置保留"),true);return;+ }+ if (clamped) emit notice(tr("所选补帧后端最高 %1X,倍率已调整为 %1X").arg(cap), false);emit settingsChanged();+ emit chainChanged();}int QmlPlayerBridge::fgMaxMultiplier() const {- // Start from 2, the multiplier every path supports, and raise it only on a- // capability the engine actually reported.+ // AppShell/SettingsWindow rules. Capabilities report GENERATED frames, so the+ // multiplier ceiling is that count + 1 (DLSS MultiFrameCountMax 5 = 6X on+ // Blackwell, 1 = 2X on Ada). Unknown DLSS capability offers the full list; a+ // new context validates it. XeSS: 4X with the audited unlock provider, else+ // 2X, or what a running session already reported above 2X.const auto& s = impl_->snapshot;- int best = 2;- if (s.fgCapabilityKnown) best = std::max(best, s.fgMultiFrameMax);- if (s.xessMaxInterpolatedFrames > 0) best = std::max(best, s.xessMaxInterpolatedFrames + 1);- if (s.fsrMaxGeneratedFrames > 0) best = std::max(best, s.fsrMaxGeneratedFrames + 1);- return std::min(best, 6);+ if(engine::fsrFrameGeneration(settings().frameGenerationBackend))return 2;+ if (settings().frameGenerationBackend == engine::FrameGenerationBackend::XeSS)+ return xessCeiling(s);+ if (s.fgCapabilityKnown && s.fgMultiFrameMax > 0) return std::clamp(s.fgMultiFrameMax + 1, 2, 6);+ return 6;}QVariantList QmlPlayerBridge::fgMultiplierChoices() const {// Only multipliers the chosen backend supports are offered: DLSS reaches 6X on// capable hardware, XeSS stops at 4X. Offering a value the provider would// refuse is the same lie as a dead control.- const bool xess = impl_->facade.pendingSettings().frameGenerationBackend+ const bool xess = settings().frameGenerationBackend== engine::FrameGenerationBackend::XeSS;const int ceiling = xess ? std::min(fgMaxMultiplier(), 4) : fgMaxMultiplier();QVariantList out;- for (int m = 2; m <= ceiling; ++m) {+ // Only the engine's legal multipliers (kFgMultiplierChoices: no 5X).+ for (const auto choice : engine::kFgMultiplierChoices) {+ const int m = int(choice);+ if (m < 2 || m > ceiling) continue;QVariantMap item;item["id"] = QString::number(m);item["label"] = QString::number(m) + QStringLiteral("X");@@ -297,56 +1113,44 @@ QVariantList QmlPlayerBridge::fgMultiplierChoices() const {return out;}-bool QmlPlayerBridge::fgStrict() const { return impl_->facade.pendingSettings().fgStrictAdmission; }+bool QmlPlayerBridge::fgStrict() const { return impl_->chain.fgStrictAdmission; }void QmlPlayerBridge::setFgStrict(bool value) {- auto s = settings();- if (s.fgStrictAdmission == value) return;- s.fgStrictAdmission = value;- impl_->commit(std::move(s));+ if (impl_->chain.fgStrictAdmission == value) return;+ impl_->chain.fgStrictAdmission = value;+ if (!impl_->revalidate(true)) {+ const auto error = impl_->validation.message;+ impl_->chain.fgStrictAdmission = !value; impl_->revalidate();+ emit notice(utf8Of(error), true);+ }emit settingsChanged();+ emit chainChanged();}-bool QmlPlayerBridge::fgLowQueue() const { return impl_->facade.pendingSettings().lowLatency; }+// 低延迟队列 is the presentation queue (1.4.4 PresentationSettings.enabled),+// not EnhancementSettings::lowLatency, which means "NR before SR".+bool QmlPlayerBridge::fgLowQueue() const { return impl_->presentation.enabled; }void QmlPlayerBridge::setFgLowQueue(bool value) {- auto s = settings();- if (s.lowLatency == value) return;- s.lowLatency = value;- impl_->commit(std::move(s));- emit settingsChanged();+ if (impl_->presentation.enabled == value) return;+ impl_->presentation.enabled = value;+ applyPresentation();}// --- colour -------------------------------------------------------------------double QmlPlayerBridge::colorExposure() const { return settings().color.exposure; }+double QmlPlayerBridge::colorExposure() const { return selectedColourSettings().exposure; }void QmlPlayerBridge::setColorExposure(double v) {- auto s = settings();- if (double(s.color.exposure) == v) return;- s.color.exposure = float(v);- impl_->commit(std::move(s));- emit settingsChanged();+ setColourParameter(QStringLiteral("exposure"),v);}-double QmlPlayerBridge::colorContrast() const { return settings().color.contrast; }+double QmlPlayerBridge::colorContrast() const { return selectedColourSettings().contrast; }void QmlPlayerBridge::setColorContrast(double v) {- auto s = settings();- if (double(s.color.contrast) == v) return;- s.color.contrast = float(v);- impl_->commit(std::move(s));- emit settingsChanged();+ setColourParameter(QStringLiteral("contrast"),v);}-double QmlPlayerBridge::colorSaturation() const { return settings().color.saturation; }+double QmlPlayerBridge::colorSaturation() const { return selectedColourSettings().saturation; }void QmlPlayerBridge::setColorSaturation(double v) {- auto s = settings();- if (double(s.color.saturation) == v) return;- s.color.saturation = float(v);- impl_->commit(std::move(s));- emit settingsChanged();+ setColourParameter(QStringLiteral("saturation"),v);}-double QmlPlayerBridge::colorTemperature() const { return settings().color.temperature; }+double QmlPlayerBridge::colorTemperature() const { return selectedColourSettings().temperature; }void QmlPlayerBridge::setColorTemperature(double v) {- auto s = settings();- if (double(s.color.temperature) == v) return;- s.color.temperature = float(v);- impl_->commit(std::move(s));- emit settingsChanged();+ setColourParameter(QStringLiteral("temperature"),v);}void QmlPlayerBridge::resetCurrentPage() {@@ -355,13 +1159,35 @@ void QmlPlayerBridge::resetCurrentPage() {auto s = settings();s.nr = false; s.sr = false; s.multiplier = 1;s.lowLatency = false; s.nrTemporal = false;+ s.nrLayers = {}; s.nrLayerCount = 0;s.model = engine::NrSettings{};s.residual = engine::ResidualSettings{};s.protection = engine::ProtectionSettings{};s.color = engine::ColorSettings{};+ s.additionalColors = {}; s.additionalColorCount = 0;s.videoHdr = engine::VideoHdrSettings{};- impl_->commit(std::move(s));+ const auto before=impl_->chain; const auto selected=impl_->selectedNr;+ const auto oldLayout = impl_->layout;+ const auto selectedColour=impl_->selectedColour;+ impl_->chain=engine::toChain(s); impl_->selectedNr=-1; impl_->selectedColour=-1;+ impl_->chain.mode = before.mode;+ if (before.mode == engine::ChainMode::Node) {+ engine::removeLegacyNodeProtection(impl_->chain);+ const auto initialized = impl_->layout.initialize(impl_->chain);+ if (!initialized.accepted) {+ impl_->chain = before; impl_->layout = oldLayout;+ impl_->selectedNr = selected; impl_->selectedColour = selectedColour;+ emit notice(utf8Of(initialized.message), true); return;+ }+ impl_->initializeDefaultNodePositions();+ }+ if(!impl_->revalidate(true)){+ const auto error=impl_->validation.message;+ impl_->chain=before;impl_->layout=oldLayout;impl_->selectedNr=selected;impl_->selectedColour=selectedColour;impl_->revalidate();+ emit notice(utf8Of(error),true);+ }emit settingsChanged();+ emit chainChanged();}@@ -382,12 +1208,19 @@ QString QmlPlayerBridge::defaultPageLabel() const {const QString page = defaultPage();if (page == QLatin1String("min")) return tr("极简模式");if (page == QLatin1String("pro")) return tr("专业模式");+ if (page == QLatin1String("last")) return tr("上次");return tr("首页");}QString QmlPlayerBridge::initialPage() const {- // The saved preference unless a test override was set.- return impl_->initialPageOverride.isEmpty() ? defaultPage() : impl_->initialPageOverride;+ // The saved preference unless a test override was set; "last" reopens the+ // page the previous session ended on.+ if (!impl_->initialPageOverride.isEmpty()) return impl_->initialPageOverride;+ if (defaultPage() == QLatin1String("last")) {+ const QString last = impl_->prefString("lastPage");+ return last.isEmpty() ? QStringLiteral("home") : last;+ }+ return defaultPage();}void QmlPlayerBridge::setInitialPage(const QString& value) {impl_->initialPageOverride = value;@@ -395,7 +1228,14 @@ void QmlPlayerBridge::setInitialPage(const QString& value) {}QString QmlPlayerBridge::currentPage() const { return impl_->currentPage; }-void QmlPlayerBridge::setCurrentPage(const QString& value) { impl_->currentPage = value; }+void QmlPlayerBridge::setCurrentPage(const QString& value) {+ impl_->currentPage = value;+ static const QStringList remembered{"home", "min", "pro", "node", "set", "exp"};+ if (remembered.contains(value) && impl_->prefString("lastPage") != value) {+ impl_->prefs["lastPage"] = value == QLatin1String("node") ? QStringLiteral("pro") : value;+ impl_->savePrefs();+ }+}QString QmlPlayerBridge::remotePlayState() const {// The engine's own remote-play state word, or empty when there is none. No@@ -420,10 +1260,21 @@ QVariantList QmlPlayerBridge::componentList() const {const auto object = value.toObject();QVariantMap item;item["name"] = object.value(QStringLiteral("name")).toString();- const QString version = object.value(QStringLiteral("version")).toString();- const QString signature = object.value(QStringLiteral("signature")).toString();+ // Release manifests write fileVersion/authenticode; keep the short keys too.+ auto field = [&](const char* primary, const char* fallback) {+ const QString text = object.value(QLatin1String(primary)).toString();+ return text.isEmpty() ? object.value(QLatin1String(fallback)).toString() : text;+ };+ const QString version = field("version", "fileVersion");+ const QString signature = field("signature", "authenticode");const bool experimental = object.value(QStringLiteral("experimental")).toBool();- item["detail"] = QStringList{version, signature}.join(QStringLiteral(" · "));+ // Several runtimes share a file name (the NR slots); the folder tells them apart.+ const QString path = object.value(QStringLiteral("path")).toString();+ const QString folder = path.section(QLatin1Char('/'), 0, -2);+ QStringList detail;+ for (const QString& part : {version, signature, folder})+ if (!part.isEmpty()) detail << part;+ item["detail"] = detail.join(QStringLiteral(" · "));item["loaded"] = object.value(QStringLiteral("loaded")).toBool(true);item["experimental"] = experimental;if (!item["name"].toString().isEmpty()) out << item;@@ -447,25 +1298,225 @@ void QmlPlayerBridge::copyDiagnostics() {// --- capture dialog ----------------------------------------------------------QVariantList QmlPlayerBridge::captureDevices() const {- // The source's own enumeration. An empty list means the machine reports no- // capture devices, and the dialog says so rather than listing examples.+ // The source's own enumeration (asynchronous, see refreshCaptureDevices). An+ // empty list means the machine reports no capture devices.QVariantList out;- for (const auto& name : source::CaptureCardSource::devices(false)) {- QVariantMap item;- item["id"] = utf8Of(name);- item["label"] = utf8Of(name);- out << item;- }+ for (const auto& d : impl_->captureVideo)+ out << QVariantMap{{"id", utf8Of(d.path)}, {"label", utf8Of(d.name)}, {"embeddedAudio", d.hasEmbeddedAudio}};return out;}QString QmlPlayerBridge::captureDeviceId() const { return utf8Of(impl_->captureDevice); }void QmlPlayerBridge::setCaptureDeviceId(const QString& value) {+ if (impl_->captureDevice == wideOf(value)) return;impl_->captureDevice = wideOf(value);+ impl_->captureFormatList.clear(); impl_->captureFormatKey.clear();+ // Colour follows the device, as in 1.4.4; audio returns to "none" unless it+ // is the remembered device.+ impl_->captureColor = impl_->capturePrefs.colorForDevice(impl_->captureDevice);+ if (impl_->captureDevice != impl_->capturePrefs.videoPath) impl_->captureAudioChoice = source::kCaptureAudioDisabled;+ if (!impl_->captureDevice.empty()) queryCapture(1, impl_->captureDevice);emit captureChanged();}QString QmlPlayerBridge::captureDeviceLabel() const {- const QString id = captureDeviceId();- return id.isEmpty() ? tr("未选择设备") : id;+ for (const auto& d : impl_->captureVideo) if (d.path == impl_->captureDevice) return utf8Of(d.name);+ return impl_->captureDevice.empty() ? tr("未选择设备") : tr("设备未连接");+}+QVariantList QmlPlayerBridge::captureFormats() const {+ QVariantList out;+ for (const auto& f : impl_->captureFormatList)+ out << QVariantMap{{"id", utf8Of(f.key)}, {"label", utf8Of(f.label)}, {"tier", f.tier},+ {"costHint", source::captureFormatNeedsCostHint(static_cast<source::CaptureFormatTier>(f.tier))}};+ return out;+}+QString QmlPlayerBridge::captureFormatKey() const { return utf8Of(impl_->captureFormatKey); }+void QmlPlayerBridge::setCaptureFormatKey(const QString& key) {+ if (impl_->captureFormatKey == wideOf(key)) return;+ impl_->captureFormatKey = wideOf(key);+ emit captureChanged();+}+QVariantList QmlPlayerBridge::captureAudioInputs() const {+ // Only what the user picks explicitly is ever opened (1.4.4 rule).+ QVariantList out{QVariantMap{{"id", source::kCaptureAudioDisabled}, {"label", tr("不监听音频")}}};+ for (const auto& d : impl_->captureVideo)+ if (d.path == impl_->captureDevice)+ out << QVariantMap{{"id", source::kCaptureAudioFromVideoDevice},+ {"label", d.hasEmbeddedAudio ? tr("视频设备内置音频(已检测)") : tr("尝试视频设备内置音频")}};+ for (size_t i = 0; i < impl_->captureAudio.size(); ++i)+ out << QVariantMap{{"id", int(i)}, {"label", QStringLiteral("[%1] %2").arg(impl_->captureAudio[i].wasapi ? QStringLiteral("WASAPI") : QStringLiteral("DirectShow"), utf8Of(impl_->captureAudio[i].name))}};+ return out;+}+int QmlPlayerBridge::captureAudioChoice() const { return impl_->captureAudioChoice; }+void QmlPlayerBridge::setCaptureAudioChoice(int choice) {+ if (choice < source::kCaptureAudioFromVideoDevice || choice >= int(impl_->captureAudio.size())) return;+ impl_->captureAudioChoice = choice; emit captureChanged();+}+int QmlPlayerBridge::captureColorSpace() const { return int(source::captureColorSpace(impl_->captureColor)); }+void QmlPlayerBridge::setCaptureColorSpace(int value) {+ if (value < 0 || value > 3) return;+ impl_->captureColor = source::captureColorOverride(unsigned(value), source::captureColorRange(impl_->captureColor)); emit captureChanged();+}+int QmlPlayerBridge::captureColorRange() const { return int(source::captureColorRange(impl_->captureColor)); }+void QmlPlayerBridge::setCaptureColorRange(int value) {+ if (value < 0 || value > 2) return;+ impl_->captureColor = source::captureColorOverride(source::captureColorSpace(impl_->captureColor), unsigned(value)); emit captureChanged();+}+double QmlPlayerBridge::captureRequestedFps() const { return impl_->captureFps; }+void QmlPlayerBridge::setCaptureRequestedFps(double value) {+ if (!source::validCaptureFrameRate(value)) { emit notice(tr("采集帧率请输入 1–1000 的数字(可带小数),或 0 沿用设备默认"), true); return; }+ impl_->captureFps = value; emit captureChanged();+}+int QmlPlayerBridge::captureAudioIngress() const { return int(settings().captureAudio); }+void QmlPlayerBridge::setCaptureAudioIngress(int value) {+ if (value < 0 || value > 2) return;+ auto s = settings(); s.captureAudio = static_cast<engine::CaptureAudioIngress>(value);+ impl_->commit(std::move(s)); emit settingsChanged();+}+int QmlPlayerBridge::captureBufferMode() const { return int(settings().captureBuffer); }+void QmlPlayerBridge::setCaptureBufferMode(int value) {+ if (value < 0 || value > 2) return;+ auto s = settings(); s.captureBuffer = static_cast<source::CaptureBufferMode>(value);+ impl_->commit(std::move(s)); emit settingsChanged();+}+bool QmlPlayerBridge::captureQueryBusy() const { return impl_->captureBusy; }+QString QmlPlayerBridge::captureStatus() const { return impl_->captureStatus; }+void QmlPlayerBridge::refreshCaptureDevices() {+ impl_->capturePrefs = ui::CapturePreferenceStore(impl_->dataDir).load();+ queryCapture(0, {});+}+void QmlPlayerBridge::queryCapture(int kind, std::wstring device) {+ auto& i = *impl_;+ if (i.captureBusy) { if (kind == 0) i.captureStatus = tr("正在查询设备…"); return; }+ i.captureBusy = true; i.captureQueryKind = kind;+ i.captureStatus = kind == 0 ? tr("正在查询采集设备…当前播放继续") : tr("正在读取设备支持的格式…");+ i.captureQuery = std::async(std::launch::async, [kind, device] {+ CoInitializeEx(nullptr, COINIT_MULTITHREADED);+ Impl::CaptureQuery q; q.kind = kind; q.device = device;+ try {+ if (kind == 0) { q.video = source::CaptureCardSource::deviceDetails(); q.audio = source::CaptureCardSource::deviceDetails(true); }+ else {+ if (kind == 2) { q.video = source::CaptureCardSource::deviceDetails(); q.audio = source::CaptureCardSource::deviceDetails(true); }+ q.formats = source::CaptureCardSource::formatsByPath(device);+ }+ } catch (...) {}+ CoUninitialize();+ return q;+ });+ emit captureChanged();+}+void QmlPlayerBridge::tickCapture() {+ auto& i = *impl_;+ if (!i.captureBusy || i.captureQuery.wait_for(std::chrono::seconds(0)) != std::future_status::ready) return;+ auto q = i.captureQuery.get();+ i.captureBusy = false;+ if (q.kind == 0 || q.kind == 2) { i.captureVideo = std::move(q.video); i.captureAudio = std::move(q.audio); i.captureListed = true; }+ if (q.kind == 0) {+ veyra::log::info("capture-ui", std::format("devices video={} audio={}", i.captureVideo.size(), i.captureAudio.size()));+ // Restore the remembered device; otherwise the first one. Never guess audio.+ std::wstring pick;+ for (const auto& d : i.captureVideo) if (d.path == i.capturePrefs.videoPath) pick = d.path;+ if (pick.empty() && !i.captureVideo.empty() && i.capturePrefs.videoPath.empty()) pick = i.captureVideo.front().path;+ i.captureStatus = i.captureVideo.empty() ? tr("未找到采集设备。连接后点击刷新。")+ : pick.empty() ? tr("上次采集设备未连接。插回后刷新,或手动选择其他设备。") : QString();+ if (!pick.empty()) {+ i.captureDevice.clear();+ setCaptureDeviceId(utf8Of(pick));+ if (pick == i.capturePrefs.videoPath) {+ i.captureFps = i.capturePrefs.requestedFps;+ const int mode = i.capturePrefs.audioMode;+ if (mode == source::kCaptureAudioFromVideoDevice) i.captureAudioChoice = mode;+ else if (!i.capturePrefs.audioPath.empty()) {+ i.captureAudioChoice = source::kCaptureAudioDisabled;+ for (size_t k = 0; k < i.captureAudio.size(); ++k)+ if (i.captureAudio[k].path == i.capturePrefs.audioPath &&+ i.captureAudio[k].wasapi == (mode == source::kCaptureAudioWasapi)) i.captureAudioChoice = int(k);+ } else i.captureAudioChoice = source::kCaptureAudioDisabled;+ }+ }+ emit captureChanged();+ return;+ }+ if (q.device != i.captureDevice) { emit captureChanged(); return; } // stale answer+ i.captureFormatList = std::move(q.formats);+ const bool remembered = i.captureDevice == i.capturePrefs.videoPath;+ i.captureFormatKey.clear();+ if (remembered && !i.capturePrefs.formatKey.empty()) {+ for (const auto& f : i.captureFormatList) if (f.key == i.capturePrefs.formatKey) i.captureFormatKey = f.key;+ } else if (!i.captureFormatList.empty()) i.captureFormatKey = i.captureFormatList.front().key;+ i.captureStatus = i.captureFormatList.empty() ? tr("未读到有效的 4K 以内采集格式,或设备正被其他应用占用。")+ : i.captureFormatKey.empty() ? tr("上次格式已不可用,请重新选择格式。")+ : tr("连接后使用当前增强设置。格式与音频变更需要重新连接。");+ veyra::log::info("capture-ui", std::format("formats={} selected={}", i.captureFormatList.size(), !i.captureFormatKey.empty()));+ emit captureChanged();+ if (q.kind == 2) {+ if (i.captureFormatKey.empty()) emit notice(tr("上次的采集格式不可用,请在采集卡面板重新选择"), true);+ else startCaptureSession();+ }+}+bool QmlPlayerBridge::startCaptureSession() {+ auto& i = *impl_;+ if (i.captureBusy) { emit notice(tr("设备查询还没有完成"), true); return false; }+ int device = -1;+ for (size_t k = 0; k < i.captureVideo.size(); ++k) if (i.captureVideo[k].path == i.captureDevice) device = int(k);+ const auto* format = source::selectCaptureFormat(i.captureFormatList, -1, i.captureFormatKey);+ if (device < 0 || !format) { emit notice(tr("请先选择采集设备和格式"), true); return false; }+ const int audio = i.captureAudioChoice;+ const source::CaptureDevice* audioDevice = audio >= 0 && size_t(audio) < i.captureAudio.size() ? &i.captureAudio[size_t(audio)] : nullptr;+ const auto path = source::CaptureCardSource::makeCapturePath(unsigned(device), i.captureVideo[size_t(device)], format->index, audio,+ audioDevice, i.captureColor, i.captureFps, format->key);+ if (path.empty()) { emit notice(tr("无法生成采集连接参数"), true); return false; }+ auto colors = i.capturePrefs.deviceColors; colors[i.captureDevice] = i.captureColor;+ i.capturePrefs = {i.captureDevice, format->key, audioDevice ? audioDevice->path : std::wstring{},+ audioDevice ? (audioDevice->wasapi ? source::kCaptureAudioWasapi : 0) : audio, i.captureColor,+ i.capturePrefs.formatHintDismissed, i.captureFps, std::move(colors)};+ if (!ui::CapturePreferenceStore(i.dataDir).save(i.capturePrefs)) veyra::log::warn("capture-ui", "capture selection not saved");+ i.facade.noteCaptureSession({i.captureDevice, format->key, i.facade.presets().entries().empty() ? std::wstring{} : wideOf(currentPresetName()),+ i.captureFps > 0 ? i.captureFps : format->fps, true});+ veyra::log::info("capture-ui", std::format("connect format={} audio={} color={} fps={}", QString::fromStdWString(format->label).toStdString(), audio, i.captureColor, i.captureFps));+ i.prefs["captureDeviceName"] = utf8Of(i.captureVideo[size_t(device)].name);+ rememberSource(QStringLiteral("capture"), utf8Of(i.captureVideo[size_t(device)].name));+ i.prefs["captureFormatLabel"] = utf8Of(format->label);+ i.savePrefs();+ openSourceUri(path, i.captureVideo[size_t(device)].name);+ emit snapshotChanged();+ return true;+}+void QmlPlayerBridge::openSourceUri(const std::wstring& uri, const std::wstring& label) {+ rememberPosition(true);+ impl_->openingSource = true;+ impl_->openingSessionId = 0;+ impl_->sourceLabel = label;+ impl_->resumeSession = 0;+ impl_->screenFillActive = false;+ const bool screen = uri.find(L"screen") != std::wstring::npos;+ openAfterCinema(screen ? tr("正在开始屏幕捕获…") : tr("正在打开采集设备 · %1").arg(utf8Of(label)), [this, uri] {+ if (impl_->preOpen) impl_->preOpen();+ impl_->engine.previewView({});+ impl_->engine.open(impl_->videoWindow, uri, impl_->options);+ impl_->openingSessionId = impl_->engine.snapshot().sessionId;+ refreshSubtitles({});+ });+}++void QmlPlayerBridge::openAfterCinema(const QString& pending, std::function<void()> open) {+ const int gen = ++impl_->liveOpenGen;+ const bool fromHome = impl_->currentPage.isEmpty() || impl_->currentPage == QLatin1String("home");+ if (!fromHome) { impl_->pendingLiveText.clear(); open(); return; }+ // User report 2026-09-29: the window blacked out and jumped into 极简 when+ // the engine opened in the same instant as the page switch and the window's+ // height spring. Switch first, say that it is connecting, then open once+ // the page (.22s out + 150 ms + rise) and the .7s height spring have settled.+ emit navigate(QStringLiteral("min"));+ impl_->pendingLiveText = pending;+ emit snapshotChanged();+ const int delay = reducedMotion() ? 0 : 820;+ veyra::log::info("ui-live-open", std::format("deferred ms={} gen={}", delay, gen));+ QTimer::singleShot(delay, this, [this, gen, open = std::move(open)] {+ if (gen != impl_->liveOpenGen) { veyra::log::info("ui-live-open", std::format("superseded gen={}", gen)); return; }+ impl_->pendingLiveText.clear();+ veyra::log::info("ui-live-open", std::format("open gen={}", gen));+ open();+ emit snapshotChanged();+ });}// Force-SDR and vertical flip are real settings the engine already carries, so@@ -489,23 +1540,71 @@ void QmlPlayerBridge::setCaptureFlipVertical(bool value) {// --- screen capture ----------------------------------------------------------QVariantList QmlPlayerBridge::screenTargets() const {- // Enumerated from the source, both kinds, so the dialog can offer windows and- // monitors from what the machine actually has.+ // Enumerated from the source for the chosen kind; cached until refreshed so a+ // binding re-evaluation does not walk every window again.QVariantList out;- for (auto kind : {source::ScreenTargetKind::Window, source::ScreenTargetKind::Monitor}) {- for (const auto& target : source::ScreenCaptureSource::targets(kind)) {- QVariantMap item;- item["id"] = QString::number(target.handle);- QString label = QString::fromWCharArray(target.name.c_str());- if (target.width > 0)- label += QStringLiteral(" · %1x%2").arg(target.width).arg(target.height);- if (target.refresh > 0) label += QStringLiteral(" · %1Hz").arg(target.refresh);- item["label"] = label;- out << item;- }+ for (const auto& target : impl_->screenList) {+ QVariantMap item;+ item["id"] = QString::number(target.handle);+ QString label = QString::fromWCharArray(target.name.c_str());+ if (target.width > 0)+ label += QStringLiteral(" · %1x%2").arg(target.width).arg(target.height);+ if (target.refresh > 0) label += QStringLiteral(" · %1Hz").arg(target.refresh);+ item["label"] = label;+ item["width"] = int(target.width);+ item["height"] = int(target.height);+ out << item;}return out;}+QVariantMap QmlPlayerBridge::screenOptions() const {+ QVariantMap d{{"kind", 0}, {"method", 0}, {"fps", 0}, {"cursor", true}, {"fill", false},+ {"left", 0}, {"top", 0}, {"right", 0}, {"bottom", 0}};+ const auto saved = impl_->prefs.value("screen").toMap();+ for (auto it = saved.begin(); it != saved.end(); ++it) if (d.contains(it.key())) d[it.key()] = it.value();+ if (d.value("kind").toInt() == 0) d["method"] = 0; // DXGI is monitors only+ if (d.value("method").toInt() == 1) d["cursor"] = false; // and has no pointer+ return d;+}+bool QmlPlayerBridge::setScreenOption(const QString& key, const QVariant& value) {+ static const QHash<QString, std::pair<int, int>> ranges{{"kind", {0, 1}}, {"method", {0, 1}}, {"fps", {0, 5}},+ {"left", {0, 16384}}, {"top", {0, 16384}}, {"right", {0, 16384}}, {"bottom", {0, 16384}}};+ auto saved = impl_->prefs.value("screen").toMap();+ if (ranges.contains(key)) {+ bool ok = false; const int n = value.toInt(&ok);+ const auto [low, high] = ranges.value(key);+ if (!ok || n < low || n > high) { emit notice(tr("数值超出范围"), true); return false; }+ saved[key] = n;+ } else if (key == QLatin1String("cursor") || key == QLatin1String("fill")) {+ saved[key] = value.toBool();+ } else return false;+ impl_->prefs["screen"] = saved;+ impl_->savePrefs();+ if (key == QLatin1String("kind")) { impl_->screenTarget.clear(); refreshCaptureTargets(); }+ emit captureChanged();+ return true;+}+bool QmlPlayerBridge::startScreenCapture() {+ const auto o = screenOptions();+ source::ScreenCaptureOptions value;+ bool found = false;+ for (const auto& t : impl_->screenList)+ if (QString::number(t.handle) == impl_->screenTarget) { value.kind = t.kind; value.target = t.handle; found = true; }+ if (!found) { emit notice(tr("先选择一个捕获目标"), true); return false; }+ constexpr unsigned rates[] = {0, 30, 60, 120, 144, 240};+ value.method = source::ScreenCaptureMethod(o.value("method").toInt());+ value.fps = rates[std::clamp(o.value("fps").toInt(), 0, 5)];+ value.cursor = o.value("cursor").toBool();+ value.left = o.value("left").toUInt(); value.top = o.value("top").toUInt();+ value.right = o.value("right").toUInt(); value.bottom = o.value("bottom").toUInt();+ veyra::log::info("screen-ui", std::format("start kind={} method={} fps={} cursor={} crop={},{},{},{} fill={}", int(value.kind), int(value.method),+ value.fps, value.cursor, value.left, value.top, value.right, value.bottom, o.value("fill").toBool()));+ openSourceUri(value.uri(), wideOf(screenTargetLabel()));+ impl_->screenFillActive = o.value("fill").toBool();+ impl_->screenFitClient = impl_->screenFitImage = QSize();+ rememberSource(QStringLiteral("screen"), screenTargetLabel());+ return true;+}QString QmlPlayerBridge::screenTargetId() const { return impl_->screenTarget; }void QmlPlayerBridge::setScreenTargetId(const QString& value) {impl_->screenTarget = value;@@ -521,11 +1620,401 @@ QString QmlPlayerBridge::screenTargetLabel() const {return tr("目标已失效");}void QmlPlayerBridge::refreshCaptureTargets() {- // Re-enumeration is what the dialog's refresh does; the lists are read fresh on- // every call, so this only has to tell the UI to ask again.+ const int kind = screenOptions().value("kind").toInt();+ impl_->screenList = source::ScreenCaptureSource::targets(kind == 1 ? source::ScreenTargetKind::Monitor : source::ScreenTargetKind::Window);+ bool stillThere = false;+ for (const auto& t : impl_->screenList) stillThere = stillThere || QString::number(t.handle) == impl_->screenTarget;+ if (!stillThere) impl_->screenTarget = impl_->screenList.empty() ? QString() : QString::number(impl_->screenList.front().handle);emit captureChanged();}+// --- PS5 Remote Play (P4-e) ---------------------------------------------------+namespace {+constexpr uint32_t kPs5Bitrates[] = {5000, 10000, 15000, 20000, 30000, 50000, 80000, 100000};+#ifdef VEYRA_ENABLE_REMOTEPLAY+std::filesystem::path ps5Settings() { return remoteplay::profileDirectory() / L"settings.ini"; }+#endif+}+QVariantMap QmlPlayerBridge::ps5() const {+ QVariantMap out = impl_->ps5Form;+ out["status"] = impl_->ps5Status;+ out["busy"] = impl_->ps5Busy;+ out["profile"] = QString::fromStdWString(impl_->ps5Profile);+#ifdef VEYRA_ENABLE_REMOTEPLAY+ out["available"] = true;+ out["psnReady"] = remoteplay::loadPsnAuthorization().has_value();+ const auto& s = impl_->snapshot;+ out["active"] = s.remotePlay && (s.running || s.transport == engine::TransportState::Opening || s.transport == engine::TransportState::Stopping);+ const auto c = impl_->controller.capabilities();+ out["controller"] = c.connected;+ out["gyro"] = c.gyro && c.accel;+ out["calibrating"] = c.calibrating;+#else+ out["available"] = false;+#endif+ return out;+}+QVariantList QmlPlayerBridge::ps5Profiles() const { return impl_->ps5ProfileList; }+void QmlPlayerBridge::ps5Load() {+#ifdef VEYRA_ENABLE_REMOTEPLAY+ auto& i = *impl_;+ try {+ const auto directory = remoteplay::profileDirectory();+ if (i.ps5Profile.empty()) {+ wchar_t last[80]{};+ GetPrivateProfileStringW(L"RemotePlay", L"LastProfile", L"", last, 80, ps5Settings().c_str());+ const std::wstring name = last;+ if (!name.empty() && name.find_first_of(L"/\\:") == std::wstring::npos) i.ps5Profile = name;+ }+ i.ps5ProfileList.clear();+ unsigned failures = 0;+ auto add = [&](const std::filesystem::path& path) {+ remoteplay::ProfileLoadError error{};+ auto saved = remoteplay::loadProfile(path, &error);+ if (saved) i.ps5ProfileList << QVariantMap{{"id", QString::fromStdWString(path.filename().wstring())},+ {"label", QString::fromStdString(saved->host)}};+ else if (error != remoteplay::ProfileLoadError::Missing) ++failures;+ };+ add(directory / "remoteplay-profile.dat");+ std::error_code ec; size_t scanned = 0;+ for (std::filesystem::directory_iterator it(directory, ec), end; !ec && it != end && i.ps5ProfileList.size() < 64 && scanned < 256; it.increment(ec), ++scanned) {+ const auto id = it->path().stem().wstring();+ if (it->path().extension() == ".dat" && id.size() == 32 &&+ std::all_of(id.begin(), id.end(), [](wchar_t c) { return (c >= L'0' && c <= L'9') || (c >= L'a' && c <= L'f'); }))+ add(it->path());+ }+ bool known = false;+ for (const auto& p : i.ps5ProfileList) known = known || p.toMap().value("id").toString() == QString::fromStdWString(i.ps5Profile);+ if (!known) i.ps5Profile = i.ps5ProfileList.isEmpty() ? std::wstring{} : i.ps5ProfileList.front().toMap().value("id").toString().toStdWString();+ // Form defaults, then the selected pairing's own values.+ i.ps5Form = QVariantMap{{"host", QString()}, {"account", QString()}, {"quality", 3}, {"codec", 0}, {"bitrate", 2}, {"viewOnly", false},+ {"decode", int(std::min(2u, GetPrivateProfileIntW(L"RemotePlay", L"DecodeMode", 0, ps5Settings().c_str())))},+ {"sampling", int(std::min(1u, GetPrivateProfileIntW(L"RemotePlay", L"FineSampling", 1, ps5Settings().c_str())))}};+ if (!i.ps5Profile.empty())+ if (auto saved = remoteplay::loadProfile(directory / i.ps5Profile)) {+ i.ps5Form["host"] = QString::fromStdString(saved->host);+ i.ps5Form["account"] = QString::fromStdString(remoteplay::accountIdToBase64(saved->credentials.accountId));+ i.ps5Form["quality"] = (saved->video.height == 1080 ? 2 : 0) + (saved->video.fps == 60 ? 1 : 0);+ i.ps5Form["codec"] = int(saved->video.codec);+ const auto found = std::find(std::begin(kPs5Bitrates), std::end(kPs5Bitrates), saved->video.bitrateKbps);+ i.ps5Form["bitrate"] = found == std::end(kPs5Bitrates) ? 2 : int(found - std::begin(kPs5Bitrates));+ i.ps5Form["viewOnly"] = saved->viewOnly;+ }+ if (i.ps5Status.isEmpty())+ i.ps5Status = failures ? tr("有配对存档无法读取或解密,详情见日志。请使用原 Windows 账户;不要删除原件。")+ : !i.ps5Profile.empty() ? tr("已加载保存的主机,直接点“连接”,无需重新填写 8 位配对码。")+ : tr("首次使用:PS5 设置 → 系统 → 远程游玩 → 关联设备,填写账号 ID 与 8 位配对码后配对。");+ veyra::log::info("remoteplay-ui", std::format("profiles={} readFailures={}", i.ps5ProfileList.size(), failures));+ } catch (...) {+ impl_->ps5Status = tr("无法读取远程游玩目录;原有配对文件不会被改动。");+ }+#else+ impl_->ps5Status = tr("此版本未包含 PS5 远程游玩组件。");+#endif+ emit ps5Changed();+}+bool QmlPlayerBridge::ps5Set(const QString& key, const QVariant& value) {+ static const QHash<QString, std::pair<int, int>> ranges{{"quality", {0, 3}}, {"codec", {0, 2}}, {"bitrate", {0, 7}}, {"decode", {0, 2}}, {"sampling", {0, 1}}};+ if (ranges.contains(key)) {+ bool ok = false; const int n = value.toInt(&ok); const auto [low, high] = ranges.value(key);+ if (!ok || n < low || n > high) return false;+ impl_->ps5Form[key] = n;+ } else if (key == QLatin1String("viewOnly")) impl_->ps5Form[key] = value.toBool();+ else if (key == QLatin1String("host") || key == QLatin1String("account")) impl_->ps5Form[key] = value.toString().trimmed();+ else return false;+ emit ps5Changed();+ return true;+}+void QmlPlayerBridge::ps5SelectProfile(const QString& id) {+#ifdef VEYRA_ENABLE_REMOTEPLAY+ if (impl_->ps5Busy) return;+ impl_->ps5Profile = id.toStdWString();+ WritePrivateProfileStringW(L"RemotePlay", L"LastProfile", impl_->ps5Profile.c_str(), ps5Settings().c_str());+ impl_->ps5Status.clear();+ ps5Load();+#else+ Q_UNUSED(id);+#endif+}+#ifdef VEYRA_ENABLE_REMOTEPLAY+namespace {+remoteplay::VideoProfile ps5Video(const QVariantMap& f) {+ remoteplay::VideoProfile p; const int q = f.value("quality").toInt();+ p.width = q < 2 ? 1280 : 1920; p.height = q < 2 ? 720 : 1080; p.fps = (q == 0 || q == 2) ? 30 : 60;+ p.codec = static_cast<remoteplay::Codec>(std::clamp(f.value("codec").toInt(), 0, 2));+ p.bitrateKbps = kPs5Bitrates[std::clamp(f.value("bitrate").toInt(), 0, 7)];+ return p;+}+std::string asciiOnly(const QString& s) {+ std::string out;+ for (const QChar c : s) { if (c.unicode() > 127) return {}; out.push_back(char(c.unicode())); }+ return out;+}+}+#endif+// One worker at a time, as the 1.4.4 panel; results are picked up in tickPs5().+#define VEYRA_PS5_LAUNCH(body) \+ do { if (impl_->ps5Busy) return; if (impl_->ps5Worker.joinable()) impl_->ps5Worker.join(); \+ impl_->ps5Busy = true; impl_->ps5Done = false; impl_->ps5Status = tr("正在处理…可随时取消"); emit ps5Changed(); \+ impl_->ps5Worker = std::jthread([this, fn = std::move(body)](std::stop_token stop) mutable { \+ Impl::Ps5Outcome result; \+ try { result = fn(stop); } catch (...) { result.message = L"操作失败;请检查网络、输入和可用磁盘空间。"; } \+ { std::lock_guard lock(impl_->ps5Mutex); impl_->ps5Outcome = std::move(result); } impl_->ps5Done = true; }); } while (0)+void QmlPlayerBridge::ps5Scan() {+#ifdef VEYRA_ENABLE_REMOTEPLAY+ auto work = [](std::stop_token stop) {+ Impl::Ps5Outcome out; auto report = remoteplay::discoverLocalPs5(stop);+ for (const auto& line : report.diagnostics) veyra::log::info("remoteplay-discovery", line);+ for (auto& h : report.hosts) {+ std::string id = h.consoleId;+ std::transform(id.begin(), id.end(), id.begin(), [](unsigned char c) { return char(std::tolower(c)); });+ out.hosts.push_back({h.host, id});+ }+ out.message = stop.stop_requested() ? L"已取消查找" : out.hosts.empty()+ ? (report.error ? std::format(L"主机搜索发生错误({}),详情见日志;可手填 IP。", report.error) : L"搜索完成,未发现 PS5;确认同一局域网,或手动填写 IP。")+ : std::format(L"发现 {} 台 PS5。", out.hosts.size());+ return out;+ };+ VEYRA_PS5_LAUNCH(work);+#endif+}+void QmlPlayerBridge::ps5Pair(const QString& pinText) {+#ifdef VEYRA_ENABLE_REMOTEPLAY+ auto host = asciiOnly(impl_->ps5Form.value("host").toString()), id = asciiOnly(impl_->ps5Form.value("account").toString()), pin = asciiOnly(pinText);+ auto account = remoteplay::accountIdFromBase64(id); if (!account) account = remoteplay::accountIdFromDecimal(id);+ if (!remoteplay::validHost(host) || !account || !remoteplay::parsePairingPin(pin)) {+ impl_->ps5Status = tr("请填写有效主机地址、Account ID 和 8 位配对码。"); emit ps5Changed(); return;+ }+ // Same host + account reuses its file; otherwise a fresh random name.+ std::filesystem::path target;+ for (const auto& p : impl_->ps5ProfileList) {+ const auto path = remoteplay::profileDirectory() / p.toMap().value("id").toString().toStdWString();+ if (auto saved = remoteplay::loadProfile(path); saved && saved->host == host && saved->credentials.accountId == *account) target = path;+ }+ if (target.empty()) {+ GUID guid{}; if (FAILED(CoCreateGuid(&guid))) { impl_->ps5Status = tr("无法分配配对存档,请重试。"); emit ps5Changed(); return; }+ std::string name; const auto* bytes = reinterpret_cast<const unsigned char*>(&guid);+ for (size_t k = 0; k < sizeof(guid); ++k) name += std::format("{:02x}", bytes[k]);+ target = remoteplay::profileDirectory() / (name + ".dat");+ }+ const auto format = ps5Video(impl_->ps5Form);+ auto work = [host = std::move(host), account = *account, pin = std::move(pin), format, target](std::stop_token stop) mutable {+ auto result = remoteplay::pairLocalPs5(host, account, pin, stop); SecureZeroMemory(pin.data(), pin.size());+ Impl::Ps5Outcome out;+ if (result.result.ok && !stop.stop_requested()) {+ remoteplay::NativeConnectRequest request; request.host = host; request.video = format; request.credentials = std::move(result.credentials);+ for (auto byte : result.mac) request.consoleId += std::format("{:02x}", byte);+ if (request.consoleId == "000000000000") request.consoleId.clear();+ if (remoteplay::saveProfile(target, request)) { out.savedPath = target.filename().wstring(); out.message = L"配对成功并已加密保存;现在可以连接。"; }+ else out.message = L"配对成功,但保存失败;请检查用户目录权限。";+ } else out.message = result.canceled || stop.stop_requested() ? L"已取消配对" : std::format(L"配对失败({}),检查 PS5 配对码、Account ID 与网络。", result.result.code);+ return out;+ };+ VEYRA_PS5_LAUNCH(work);+#else+ Q_UNUSED(pinText);+#endif+}+bool QmlPlayerBridge::ps5Connect() {+#ifdef VEYRA_ENABLE_REMOTEPLAY+ auto& i = *impl_;+ if (i.ps5Busy) return false;+ const auto path = i.ps5Profile.empty() ? std::filesystem::path{} : remoteplay::profileDirectory() / i.ps5Profile;+ auto saved = path.empty() ? std::nullopt : remoteplay::loadProfile(path);+ const auto host = asciiOnly(i.ps5Form.value("host").toString());+ if (!saved || !remoteplay::validHost(host)) { i.ps5Status = tr("请先完成配对,并填写有效主机地址。"); emit ps5Changed(); return false; }+ saved->host = host; saved->video = ps5Video(i.ps5Form); saved->viewOnly = i.ps5Form.value("viewOnly").toBool();+ if (!remoteplay::saveProfile(path, *saved)) { i.ps5Status = tr("保存连接设置失败,请检查目录权限。"); emit ps5Changed(); return false; }+ source::RemotePlayConnectDesc desc; desc.request = std::move(*saved);+ const int decode = std::clamp(i.ps5Form.value("decode").toInt(), 0, 2);+ desc.decodeMode = static_cast<source::RemotePlayConnectDesc::DecodeMode>(decode);+ desc.highQualitySampling = i.ps5Form.value("sampling").toInt() == 1;+ WritePrivateProfileStringW(L"RemotePlay", L"DecodeMode", std::to_wstring(decode).c_str(), ps5Settings().c_str());+ WritePrivateProfileStringW(L"RemotePlay", L"FineSampling", desc.highQualitySampling ? L"1" : L"0", ps5Settings().c_str());+ const bool viewOnly = desc.request.viewOnly;+ rememberPosition(true);+ i.openingSource = true; i.sourceLabel = L"PS5 · " + std::wstring(host.begin(), host.end()); i.resumeSession = 0; i.screenFillActive = false;+ auto request = std::make_shared<source::RemotePlayConnectDesc>(std::move(desc));+ openAfterCinema(tr("正在连接 PS5 · %1").arg(QString::fromStdString(host)), [this, request, viewOnly] {+ auto& i = *impl_;+ if (i.preOpen) i.preOpen();+ i.engine.previewView({});+ i.engine.openRemotePlay(i.videoWindow, std::move(*request), i.options);+ i.openingSessionId = i.engine.snapshot().sessionId;+ refreshSubtitles({});+ // Controller forwarding at 8 ms, as 1.4.4; view-only leaves the pad to the PS5.+ // Started with the session: the poll stops the pad when no session runs.+ if (!viewOnly) {+ if (!i.controller.start()) veyra::log::warn("remoteplay-input", "SDL gamepad initialization failed");+ if (!i.controllerTimer) {+ i.controllerTimer = new QTimer(this);+ connect(i.controllerTimer, &QTimer::timeout, this, [this] {+ auto& j = *impl_;+ const auto s = j.engine.snapshot();+ if (s.remotePlay && (s.running || s.transport == engine::TransportState::Opening)) {+ const bool focused = QGuiApplication::focusWindow() != nullptr;+ j.engine.remotePlayController(j.controller.poll(focused));+ j.controller.feedback(j.engine.remotePlayFeedback(), focused);+ } else {+ j.engine.remotePlayController({}); j.controller.stop(); j.controllerTimer->stop();+ }+ });+ }+ i.controllerTimer->start(8);+ } else {+ if (i.controllerTimer) i.controllerTimer->stop();+ i.controller.stop();+ }+ });+ i.ps5Watching = true;+ rememberSource(QStringLiteral("ps5"), QString::fromStdString(host));+ i.ps5Status = tr("连接已开始。需要登录 PIN 时在下方提交。关闭面板不停止串流。");+ veyra::log::info("remoteplay-ui", std::format("connect quality={} codec={} bitrate={} decode={} viewOnly={}",+ i.ps5Form.value("quality").toInt(), i.ps5Form.value("codec").toInt(), i.ps5Form.value("bitrate").toInt(), decode, viewOnly));+ emit ps5Changed();+ return true;+#else+ return false;+#endif+}+void QmlPlayerBridge::ps5Wake() {+#ifdef VEYRA_ENABLE_REMOTEPLAY+ auto saved = impl_->ps5Profile.empty() ? std::nullopt : remoteplay::loadProfile(remoteplay::profileDirectory() / impl_->ps5Profile);+ if (!saved) { impl_->ps5Status = tr("需要先配对才能唤醒。"); emit ps5Changed(); return; }+ saved->host = asciiOnly(impl_->ps5Form.value("host").toString());+ auto work = [request = std::move(*saved)](std::stop_token stop) {+ Impl::Ps5Outcome out; if (stop.stop_requested()) { out.message = L"已取消唤醒"; return out; }+ auto r = remoteplay::wakeLocalPs5(request);+ out.message = r.ok ? L"已发送唤醒请求,等待 PS5 开机后再连接。" : std::format(L"唤醒失败({});确认 PS5 处于待机而不是关机。", r.code);+ return out;+ };+ VEYRA_PS5_LAUNCH(work);+#endif+}+void QmlPlayerBridge::ps5Forget() {+#ifdef VEYRA_ENABLE_REMOTEPLAY+ if (impl_->ps5Busy || impl_->ps5Profile.empty()) return;+ std::error_code ec;+ const bool removed = std::filesystem::remove(remoteplay::profileDirectory() / impl_->ps5Profile, ec);+ impl_->ps5Status = removed ? tr("配对已删除。现有串流会保留;下次连接需选择其他主机或重新配对。") : tr("删除失败,请检查目录权限。");+ if (removed) impl_->ps5Profile.clear();+ ps5Load();+#endif+}+void QmlPlayerBridge::ps5PsnLogin() {+#ifdef VEYRA_ENABLE_REMOTEPLAY+ if (QDesktopServices::openUrl(QUrl(QString::fromStdWString(remoteplay::psnLoginUrl())))) {+ impl_->psnLoginStarted = GetTickCount64();+ impl_->ps5Status = tr("在 Sony 网页完成登录,复制最终回调地址,再点“提交登录结果”。");+ } else impl_->ps5Status = tr("无法打开浏览器,请检查默认浏览器设置。");+ emit ps5Changed();+#endif+}+void QmlPlayerBridge::ps5PsnComplete() {+#ifdef VEYRA_ENABLE_REMOTEPLAY+ if (impl_->ps5Busy) return;+ if (!impl_->psnLoginStarted || GetTickCount64() - impl_->psnLoginStarted > 600000) {+ impl_->ps5Status = tr("请先点登录 PSN,完成网页授权后再提交。"); emit ps5Changed(); return;+ }+ std::wstring callback = QGuiApplication::clipboard() ? QGuiApplication::clipboard()->text().left(8192).toStdWString() : std::wstring{};+ if (!remoteplay::validPsnCallback(callback)) {+ SecureZeroMemory(callback.data(), callback.size() * sizeof(wchar_t));+ impl_->ps5Status = tr("剪贴板不是有效的 Sony 授权回调地址。请复制登录完成后的完整 URL。"); emit ps5Changed(); return;+ }+ impl_->psnLoginStarted = 0;+ auto work = [callback = std::move(callback)](std::stop_token stop) mutable {+ auto result = remoteplay::authorizePsn(std::move(callback), stop); Impl::Ps5Outcome out;+ if (result.account) out.account = remoteplay::accountIdToBase64(*result.account);+ out.message = result.ok ? L"PSN 登录已保存,Account ID 已填入。首次仍需配对;已配对主机直接连接。"+ : std::format(L"PSN 授权失败({});原有配对不受影响,可重新登录。", result.error);+ return out;+ };+ VEYRA_PS5_LAUNCH(work);+#endif+}+void QmlPlayerBridge::ps5PsnForget() {+#ifdef VEYRA_ENABLE_REMOTEPLAY+ if (impl_->ps5Busy) return;+ impl_->ps5Status = remoteplay::forgetPsnAuthorization() ? tr("PSN 授权已删除,局域网配对保留。") : tr("删除授权失败,请检查目录权限。");+ emit ps5Changed();+#endif+}+void QmlPlayerBridge::ps5SendLoginPin(const QString& pin) {+ const auto text = pin.trimmed();+ if (text.isEmpty() || !std::all_of(text.begin(), text.end(), [](QChar c) { return c.isDigit(); })) {+ impl_->ps5Status = tr("登录 PIN 必须为数字。"); emit ps5Changed(); return;+ }+ impl_->engine.remotePlayLoginPin(text.toStdString());+}+void QmlPlayerBridge::ps5Cancel() {+ if (impl_->ps5Busy && impl_->ps5Worker.joinable()) { impl_->ps5Worker.request_stop(); return; }+ if (impl_->snapshot.remotePlay) stopPlayback();+}+void QmlPlayerBridge::ps5Calibrate() {+#ifdef VEYRA_ENABLE_REMOTEPLAY+ impl_->ps5Status = impl_->controller.calibrate() ? tr("将手柄平放并保持静止:采集 120 个稳定样本完成校准;10 秒内不稳定则保留原校准。")+ : tr("请先连接串流及带陀螺仪的电脑手柄。仅观看模式不使用电脑手柄。");+ emit ps5Changed();+#endif+}+void QmlPlayerBridge::tickPs5() {+ auto& i = *impl_;+ bool changed = false;+ if (i.ps5Busy && i.ps5Done.load()) {+ if (i.ps5Worker.joinable()) i.ps5Worker.join();+ i.ps5Busy = false;+ Impl::Ps5Outcome r; { std::lock_guard lock(i.ps5Mutex); r = std::move(i.ps5Outcome); }+ i.ps5Status = QString::fromStdWString(r.message);+ if (!r.account.empty()) i.ps5Form["account"] = QString::fromStdString(r.account);+#ifdef VEYRA_ENABLE_REMOTEPLAY+ if (!r.savedPath.empty()) {+ i.ps5Profile = r.savedPath;+ WritePrivateProfileStringW(L"RemotePlay", L"LastProfile", i.ps5Profile.c_str(), ps5Settings().c_str());+ const auto status = i.ps5Status; ps5Load(); i.ps5Status = status;+ }+ if (!r.hosts.empty()) {+ // A found console updates the selected pairing's address only when its+ // id matches (or the legacy profile had no id and the same host).+ const auto path = i.ps5Profile.empty() ? std::filesystem::path{} : remoteplay::profileDirectory() / i.ps5Profile;+ auto selected = path.empty() ? std::nullopt : remoteplay::loadProfile(path);+ bool matched = false;+ if (selected) for (const auto& [host, id] : r.hosts) {+ if ((!selected->consoleId.empty() && selected->consoleId == id) || (selected->consoleId.empty() && selected->host == host)) {+ selected->host = host; if (id.size() == 12) selected->consoleId = id;+ if (remoteplay::saveProfile(path, *selected)) { i.ps5Form["host"] = QString::fromStdString(host); matched = true; }+ break;+ }+ }+ if (!selected && r.hosts.size() == 1) i.ps5Form["host"] = QString::fromStdString(r.hosts.front().first);+ else if (selected && !matched) i.ps5Status = tr("发现主机,但无法确认是已配对的这一台。保留原地址,可核对后手动修改。");+ else if (!selected && r.hosts.size() > 1) i.ps5Status = tr("发现多台 PS5,请填写要配对的主机 IP,避免选错主机。");+ }+#endif+ changed = true;+ }+#ifdef VEYRA_ENABLE_REMOTEPLAY+ if (i.ps5Watching && !i.ps5Busy) {+ const auto& s = i.snapshot;+ const bool active = s.remotePlay && (s.running || s.transport == engine::TransportState::Opening || s.transport == engine::TransportState::Stopping);+ QString message = QString::fromStdWString(s.failed ? s.status : s.remoteRecovering ? s.remoteRecoveryMessage+ : s.remotePlay && s.running ? std::wstring(L"PS5 画面已进入播放;关闭此面板不停止串流。") : active ? s.status : std::wstring(L"PS5 串流已停止,可以重新连接。"));+ if (s.remotePlay && s.running && !s.failed && !s.remoteRecovering) {+ const auto& r = s.remoteStream; const auto& p = r.requestedProfile;+ message = QString::fromStdWString(std::format(L"生效:{}p / {} fps / {} / 请求 {} Mbps · 实收视频 {:.1f} Mbps", p.height, p.fps,+ p.codec == remoteplay::Codec::H264 ? L"H.264" : p.codec == remoteplay::Codec::H265Hdr ? L"H.265 HDR" : L"H.265", p.bitrateKbps / 1000, r.videoMbps));+ const auto c = i.controller.capabilities();+ if (i.ps5Form.value("viewOnly").toBool()) message += tr("\n仅观看:电脑输入已关闭,手柄由 PS5 处理。");+ else if (!c.connected) message += tr("\n未检测到电脑手柄。");+ else message += QString::fromStdWString(std::format(L"\n陀螺仪 {} · 触摸板 {} · 扳机 {} · 触觉 {}{}", c.gyro && c.accel ? L"已启用" : L"不可用",+ c.touch ? L"可用" : L"不可用", c.triggers ? L"已接入" : L"不可用", c.haptics ? L"端点已打开" : L"未打开", c.calibrating ? L" · 校准中" : L""));+ }+ if (message != i.ps5Status) { i.ps5Status = message; changed = true; }+ if (!active && !s.remotePlay) i.ps5Watching = false;+ }+#endif+ if (changed) emit ps5Changed();+}+// --- ps5 dialog --------------------------------------------------------------QString QmlPlayerBridge::remotePlayHost() const { return impl_->remotePlayHost; }void QmlPlayerBridge::setRemotePlayHost(const QString& value) {@@ -571,9 +2060,9 @@ const ColourParam kColourParams[] = {{"paramLights", "参数化亮调", "曲线", -100, 100, 1},{"paramDarks", "参数化暗调", "曲线", -100, 100, 1},{"paramShadows", "参数化阴影", "曲线", -100, 100, 1},- {"splitHighlights","分离高光", "颜色分级", -100, 100, 1},- {"splitMidtones", "分离中间调", "颜色分级", -100, 100, 1},- {"splitShadows", "分离阴影", "颜色分级", -100, 100, 1},+ {"splitHighlights","分离高光", "曲线", -100, 100, 1},+ {"splitMidtones", "分离中间调", "曲线", -100, 100, 1},+ {"splitShadows", "分离阴影", "曲线", -100, 100, 1},{"gradingBlending","混合", "颜色分级", 0, 100, 1},{"gradingBalance","平衡", "颜色分级", -100, 100, 1},{"calibrationShadowTint","阴影色调","校准", -100, 100, 1},@@ -606,12 +2095,35 @@ float* colourScalar(engine::ColorSettings& c, const char* name) {if (n == "gradingBalance") return &c.gradingBalance;if (n == "calibrationShadowTint") return &c.calibrationShadowTint;if (n == "lutStrength") return &c.lutStrength;+ // Array parameters retain the existing engine units; no UI-only mirrors.+ const auto parts=QString::fromUtf8(name).split('.');+ bool ok=false;+ const int index=parts.size()>=2?parts[1].toInt(&ok):-1;+ if(!ok||index<0)return nullptr;+ if(parts.size()==2){+ if(index<engine::kColorMixerBands){+ if(parts[0]=="mixerHue")return &c.mixerHue[index];+ if(parts[0]=="mixerSaturation")return &c.mixerSaturation[index];+ if(parts[0]=="mixerLuminance")return &c.mixerLuminance[index];+ if(parts[0]=="blackWhiteMix")return &c.blackWhiteMix[index];+ }+ if(index<3){+ if(parts[0]=="calibrationHue")return &c.calibrationHue[index];+ if(parts[0]=="calibrationSaturation")return &c.calibrationSaturation[index];+ }+ }+ if(parts.size()==3&&parts[0]=="grading"&&index<engine::kColorGradingZones){+ if(parts[2]=="hue")return &c.grading[index].hue;+ if(parts[2]=="saturation")return &c.grading[index].saturation;+ if(parts[2]=="luminance")return &c.grading[index].luminance;+ }return nullptr;}} // namespaceQVariantList QmlPlayerBridge::colourParameters() const {QVariantList out;+ engine::ColorSettings defaults;for (const auto& p : kColourParams) {QVariantMap item;item["name"] = QString::fromUtf8(p.name);@@ -620,6 +2132,7 @@ QVariantList QmlPlayerBridge::colourParameters() const {item["min"] = double(p.minimum);item["max"] = double(p.maximum);item["step"] = double(p.step);+ if (const auto* value = colourScalar(defaults, p.name)) item["defaultValue"] = double(*value);// Centred controls read their fill from the middle, as the design's sliders// do for anything that can go either way.item["center"] = p.minimum < 0 && p.maximum > 0;@@ -655,37 +2168,648 @@ QVariantList QmlPlayerBridge::colourGroups() const {}double QmlPlayerBridge::colourParameter(const QString& name) const {- auto c = settings().color;+ auto c = selectedColourSettings();const auto utf8 = name.toUtf8();if (float* field = colourScalar(c, utf8.constData())) return double(*field);return 0.0;}bool QmlPlayerBridge::setColourParameter(const QString& name, double value) {- auto s = settings();+ if(!std::isfinite(value)){emit notice(tr("调色值必须是有限数值"),true);return false;}+ auto c = selectedColourSettings();const auto utf8 = name.toUtf8();- float* field = colourScalar(s.color, utf8.constData());+ float* field = colourScalar(c, utf8.constData());if (field == nullptr) return false;const float next = float(value);if (*field == next) return true;*field = next;- // Colour is live in the engine: it uploads per frame, so this never rebuilds the- // graph and does not need a rebuild check.- impl_->commit(std::move(s));- emit settingsChanged();- return true;+ return commitColour(c);}bool QmlPlayerBridge::resetColourParameter(const QString& name) {- auto s = settings();+ engine::ColorSettings defaults;const auto utf8 = name.toUtf8();- float* field = colourScalar(s.color, utf8.constData());+ float* field = colourScalar(defaults, utf8.constData());if (field == nullptr) return false;- *field = 0.0f;- impl_->commit(std::move(s));- emit settingsChanged();+ return setColourParameter(name,*field);+}++int QmlPlayerBridge::selectedColourLayer() const {return impl_->colourIndex();}+void QmlPlayerBridge::setSelectedColourLayer(int index){+ if(index<0||uint32_t(index)>=impl_->chain.nodeCount||+ impl_->chain.nodes[index].type!=engine::EffectType::Color||impl_->selectedColour==index)return;+ impl_->selectedColour=index;emit settingsChanged();+}+engine::ColorSettings QmlPlayerBridge::selectedColourSettings() const {+ const int index=impl_->colourIndex();+ if(index<0)return {};+ auto colour=impl_->chain.nodes[index].color;+ colour.enabled=impl_->chain.nodes[index].enabled;+ return colour;+}+bool QmlPlayerBridge::commitColour(const engine::ColorSettings& colour){+ const int index=impl_->colourIndex();+ if(index<0){emit notice(tr("处理链中没有调色节点,未更改设置"),true);return false;}+ if(const auto error=colour.validate();!error.empty()){+ emit notice(tr("调色参数被拒绝:%1").arg(utf8Of(error)),true);return false;+ }+ auto& node=impl_->chain.nodes[index];+ if(node.color==colour&&node.enabled==colour.enabled)return true;+ const auto previous=node;+ node.color=colour;node.enabled=colour.enabled;+ if(!impl_->revalidate(true)){+ const auto error=impl_->validation.message;node=previous;impl_->revalidate();+ emit notice(utf8Of(error),true);emit settingsChanged();return false;+ }+ if(!impl_->colourReplaying){+ const qint64 now=QDateTime::currentMSecsSinceEpoch();+ const bool sameDrag=index==impl_->colourLastIndex&&now-impl_->colourLastPushMs<600&&!impl_->colourUndo.empty();+ if(!sameDrag){+ auto before=previous.color;before.enabled=previous.enabled;+ impl_->colourUndo.push_back({index,before});+ if(impl_->colourUndo.size()>64)impl_->colourUndo.erase(impl_->colourUndo.begin());+ }+ impl_->colourLastPushMs=now;impl_->colourLastIndex=index;impl_->colourRedo.clear();+ }+ emit settingsChanged();emit chainChanged();return true;+}+QVariantMap QmlPlayerBridge::colourState() const { return colourStateAt(impl_->colourIndex()); }+// Any colour node's full state, so several node cards can show their own+// values at once; edits still go through the selected-layer setters.+QVariantMap QmlPlayerBridge::colourStateAt(int index) const {+ engine::ColorSettings c{};+ if(index>=0&&uint32_t(index)<impl_->chain.nodeCount&&impl_->chain.nodes[index].type==engine::EffectType::Color){+ c=impl_->chain.nodes[index].color;c.enabled=impl_->chain.nodes[index].enabled;+ }else index=-1;+ QVariantMap out;+ out["index"]=index;out["enabled"]=c.enabled;+ out["blackWhite"]=c.blackWhite;out["groupBypassMask"]=int(c.groupBypassMask);+ for(const auto& p:kColourParams)out[QString::fromUtf8(p.name)]=double(*colourScalar(c,p.name));+ const auto list=[](const auto& values){QVariantList out;for(const auto v:values)out<<double(v);return out;};+ out["mixerHue"]=list(c.mixerHue);out["mixerSaturation"]=list(c.mixerSaturation);+ out["mixerLuminance"]=list(c.mixerLuminance);out["blackWhiteMix"]=list(c.blackWhiteMix);+ out["calibrationHue"]=list(c.calibrationHue);out["calibrationSaturation"]=list(c.calibrationSaturation);+ QVariantList curves,wheels,samples;+ for(const auto& curve:c.curves){+ QVariantList points;+ for(int i=0;i<curve.count;++i)points<<QVariantMap{{"x",double(curve.points[i].x)},{"y",double(curve.points[i].y)}};+ curves<<QVariant(points);+ QVariantList values;+ for(int i=0;i<=128;++i)values<<double(pipeline::ColorGradeTables::curveValue(curve,float(i)/128.0f));+ samples<<QVariant(values);+ }+ for(const auto& wheel:c.grading)wheels<<QVariantMap{{"hue",double(wheel.hue)},+ {"saturation",double(wheel.saturation)},{"luminance",double(wheel.luminance)}};+ out["curves"]=curves;out["curveSamples"]=samples;out["grading"]=wheels;+ out["lutName"]=QString::fromStdWString(c.lutNameString());out["lutInputSpace"]=c.lutInputSpace;+ return out;+}+bool QmlPlayerBridge::setColourCurve(int channel,const QVariantList& points){+ if(channel<0||channel>=4||points.size()<2||points.size()>engine::kColorCurvePoints)return false;+ auto c=selectedColourSettings();auto& curve=c.curves[channel];curve.reset();curve.count=int(points.size());+ for(int i=0;i<curve.count;++i){+ const auto point=points[i].toMap();bool xok=false,yok=false;+ const double x=point.value("x").toDouble(&xok),y=point.value("y").toDouble(&yok);+ if(!xok||!yok||!std::isfinite(x)||!std::isfinite(y))return false;+ curve.points[i]={float(x),float(y)};+ }+ return commitColour(c);+}+bool QmlPlayerBridge::setColourOption(const QString& name,int value){+ auto c=selectedColourSettings();+ if(name=="blackWhite"&&(value==0||value==1))c.blackWhite=value!=0;+ else if(name=="groupBypassMask"&&value>=0&&value<128)c.groupBypassMask=uint32_t(value);+ else if(name=="lutInputSpace"&&value>=0&&value<=2)c.lutInputSpace=value;+ else return false;+ return commitColour(c);+}+bool QmlPlayerBridge::setColourWheel(int zone,double hue,double saturation,double luminance){+ if(zone<0||zone>=engine::kColorGradingZones||!std::isfinite(hue)||+ !std::isfinite(saturation)||!std::isfinite(luminance))return false;+ auto c=selectedColourSettings();c.grading[zone]={float(hue),float(saturation),float(luminance)};+ return commitColour(c);+}+bool QmlPlayerBridge::resetColourGroup(int group){+ auto c=selectedColourSettings();const engine::ColorSettings d;+ switch(group){+ case -1:{const bool enabled=c.enabled;c=d;c.enabled=enabled;break;}+ case 0:c.exposure=c.contrast=c.highlights=c.shadows=c.whites=c.blacks=0;break;+ case 1:c.temperature=c.tint=c.vibrance=c.saturation=0;break;+ case 2:c.paramHighlights=c.paramLights=c.paramDarks=c.paramShadows=0;c.curves=d.curves;+ c.splitHighlights=c.splitMidtones=c.splitShadows=0;break;+ case 3:c.mixerHue=d.mixerHue;c.mixerSaturation=d.mixerSaturation;c.mixerLuminance=d.mixerLuminance;+ c.blackWhite=d.blackWhite;c.blackWhiteMix=d.blackWhiteMix;break;+ case 4:c.grading=d.grading;c.gradingBlending=d.gradingBlending;c.gradingBalance=0;break;+ case 5:c.calibrationShadowTint=0;c.calibrationHue=d.calibrationHue;c.calibrationSaturation=d.calibrationSaturation;break;+ case 6:c.clearLut();c.lutStrength=d.lutStrength;c.lutInputSpace=d.lutInputSpace;break;+ case 7:c.texture=c.clarity=c.dehaze=0;break;+ default:return false;+ }+ if(group>=0&&group<7)c.groupBypassMask&=~(1u<<group);+ return commitColour(c);+}++// --- LUT library and colour looks (P4-g) ------------------------------------+// LUTs go to the folder the engine and the export worker resolve by name+// (runtime_local/luts); looks are user data beside the presets.+QVariantList QmlPlayerBridge::lutLibrary() const {+ QVariantList out;+ const engine::ColorLutStore store(runtime::localDataDirectory());+ for (const auto& name : store.list()) out << QString::fromStdWString(name);+ return out;+}+QVariantList QmlPlayerBridge::colourLooks() const {+ engine::ColorLookStore store(impl_->dataDir);+ QVariantList out;+ if (!store.load()) return out;+ for (size_t i = 0; i < store.entries().size(); ++i) {+ const auto& look = store.entries()[i];+ out << QVariantMap{{"index", int(i)}, {"name", QString::fromStdWString(look.name)},+ {"lut", QString::fromStdWString(look.color.lutNameString())}};+ }+ return out;+}+void QmlPlayerBridge::importLutDialog() {+ const QString path = QFileDialog::getOpenFileName(nullptr, tr("导入 .cube LUT"), QString(),+ tr("Cube LUT (*.cube);;所有文件 (*.*)"));+ if (!path.isEmpty()) importLut(path);+}+bool QmlPlayerBridge::importLut(const QString& path) {+ if (impl_->colourIndex() < 0) { emit notice(tr("处理链中没有调色节点,无法使用 LUT"), true); return false; }+ const engine::ColorLutStore store(runtime::localDataDirectory());+ std::wstring name; std::string error;+ if (!store.importFile(std::filesystem::path(path.toStdWString()), name, error) || name.empty()) {+ veyra::log::warn("ui-colour", std::format("lut import rejected path={} error={}", path.toStdString(), error));+ emit notice(tr("LUT 导入失败:%1").arg(QString::fromStdString(error)), true);+ return false;+ }+ veyra::log::info("ui-colour", std::format("lut imported name={}", QString::fromStdWString(name).toStdString()));+ emit colourLibraryChanged();+ const bool applied = setColourLut(QString::fromStdWString(name));+ if (applied) emit notice(tr("已导入并使用 LUT:%1").arg(QString::fromStdWString(name)), false);+ return applied;+}+bool QmlPlayerBridge::setColourLut(const QString& name) {+ auto c = selectedColourSettings();+ if (name.isEmpty()) { c.clearLut(); return commitColour(c); }+ const engine::ColorLutStore store(runtime::localDataDirectory());+ engine::ColorLutData data;+ if (!store.validName(name.toStdWString()) || !store.resolve(name.toStdWString(), data) || !data.valid()) {+ emit notice(tr("LUT 不可用:%1").arg(name), true);+ return false;+ }+ if (!c.setLutName(name.toStdWString())) { emit notice(tr("LUT 名称过长"), true); return false; }+ if (c.lutStrength <= 0.0f) c.lutStrength = 100.0f;+ c.enabled = true;+ return commitColour(c);+}+bool QmlPlayerBridge::saveColourLook(const QString& name, bool replace) {+ const QString trimmed = name.trimmed();+ if (trimmed.isEmpty() || trimmed.size() > 48) { emit notice(tr("颜色预设名称需为 1–48 个字符"), true); return false; }+ if (impl_->colourIndex() < 0) { emit notice(tr("处理链中没有调色节点"), true); return false; }+ engine::ColorLookStore store(impl_->dataDir);+ if (!store.load()) { emit notice(tr("颜色预设库无法读取:%1").arg(QString::fromStdWString(store.error())), true); return false; }+ const bool exists = std::any_of(store.entries().begin(), store.entries().end(),+ [&](const auto& e) { return e.name == trimmed.toStdWString(); });+ if (exists && !replace) { emit notice(tr("已存在同名颜色预设"), true); return false; }+ auto colour = selectedColourSettings(); colour.enabled = true;+ if (!store.put(trimmed.toStdWString(), colour, replace) || !store.save()) {+ emit notice(tr("颜色预设保存失败:%1").arg(QString::fromStdWString(store.error())), true); return false;+ }+ veyra::log::info("ui-colour", std::format("look saved name={} layer={}", trimmed.toStdString(), impl_->colourIndex()));+ emit colourLibraryChanged();+ emit notice(tr("已保存颜色预设:%1").arg(trimmed), false);+ return true;+}+bool QmlPlayerBridge::applyColourLook(int index) {+ engine::ColorLookStore store(impl_->dataDir);+ if (!store.load() || index < 0 || size_t(index) >= store.entries().size()) {+ emit notice(tr("颜色预设不存在"), true); return false;+ }+ auto colour = store.entries()[size_t(index)].color; colour.enabled = true;+ if (colour.hasLut()) {+ const engine::ColorLutStore luts(runtime::localDataDirectory());+ engine::ColorLutData data;+ if (!luts.resolve(colour.lutNameString(), data)) {+ emit notice(tr("预设引用的 LUT 不存在:%1,未应用").arg(QString::fromStdWString(colour.lutNameString())), true);+ return false;+ }+ }+ const bool ok = commitColour(colour);+ veyra::log::info("ui-colour", std::format("look applied index={} layer={} ok={}", index, impl_->colourIndex(), ok));+ return ok;+}+bool QmlPlayerBridge::deleteColourLook(int index) {+ engine::ColorLookStore store(impl_->dataDir);+ if (!store.load() || index < 0 || !store.erase(size_t(index)) || !store.save()) {+ emit notice(tr("删除颜色预设失败"), true); return false;+ }+ emit colourLibraryChanged();+ return true;+}+void QmlPlayerBridge::importColourLookDialog() {+ const QString path = QFileDialog::getOpenFileName(nullptr, tr("导入颜色预设"), QString(),+ tr("Veyra 颜色预设 (*.vpcolor);;所有文件 (*.*)"));+ if (!path.isEmpty()) importColourLook(path);+}+bool QmlPlayerBridge::importColourLook(const QString& path) {+ engine::ColorLookStore store(impl_->dataDir);+ std::wstring name;+ if (!store.load() || !store.importFile(std::filesystem::path(path.toStdWString()), name)) {+ emit notice(tr("导入颜色预设失败:%1").arg(QString::fromStdWString(store.error())), true); return false;+ }+ emit colourLibraryChanged();+ emit notice(tr("已导入颜色预设:%1").arg(QString::fromStdWString(name)), false);+ return true;+}+void QmlPlayerBridge::exportColourLookDialog(int index) {+ const QString path = QFileDialog::getSaveFileName(nullptr, tr("导出颜色预设"), QString(),+ tr("Veyra 颜色预设 (*.vpcolor)"));+ if (!path.isEmpty()) exportColourLook(index, path);+}+bool QmlPlayerBridge::exportColourLook(int index, const QString& path) {+ engine::ColorLookStore store(impl_->dataDir);+ if (!store.load() || index < 0 || !store.exportFile(size_t(index), std::filesystem::path(path.toStdWString()))) {+ emit notice(tr("导出颜色预设失败:%1").arg(QString::fromStdWString(store.error())), true); return false;+ }+ emit notice(tr("已导出颜色预设"), false);+ return true;+}++// --- image export (P4-b) -----------------------------------------------------+bool QmlPlayerBridge::imageBatchActive() const { return impl_->imagePhase != Impl::ImagePhase::Idle; }+int QmlPlayerBridge::imageBatchDone() const { return impl_->imageDone; }+int QmlPlayerBridge::imageBatchTotal() const { return int(impl_->imageFiles.size()); }+int QmlPlayerBridge::imageBatchFailures() const { return impl_->imageFailures; }+QString QmlPlayerBridge::imageBatchStatus() const { return impl_->imageStatus; }+void QmlPlayerBridge::saveFrameDialog() {+ if (!hasSource()) { emit notice(tr("没有可保存的画面"), true); return; }+ if (impl_->chain.mode == engine::ChainMode::Node) {+ emit notice(tr("图片导出只接受列表模式;请切回列表模式再导出"), true); return;+ }+ const QString suggested = QDir(screenshotDirectory()).filePath(+ QFileInfo(QString::fromStdWString(impl_->sourceLabel)).completeBaseName() + QStringLiteral("-veyra.png"));+ const QString path = QFileDialog::getSaveFileName(nullptr, tr("导出当前画面"), suggested,+ tr("PNG 图片 (*.png);;JPEG 图片 (*.jpg)"));+ if (path.isEmpty()) return;+ if (QFileInfo::exists(path)) { emit notice(tr("目标文件已存在,请换一个文件名"), true); return; }+ impl_->engine.saveFrame(wideOf(QDir::toNativeSeparators(path)));+ emit notice(tr("正在保存:%1").arg(QDir::toNativeSeparators(path)), false);+}+void QmlPlayerBridge::exportImagesDialog() {+ const auto files = QFileDialog::getOpenFileNames(nullptr, tr("选择要处理的图片"), QString(),+ tr("图片 (*.png *.jpg *.jpeg)"));+ if (files.isEmpty()) return;+ const QString folder = QFileDialog::getExistingDirectory(nullptr, tr("保存到"), QFileInfo(files.front()).absolutePath());+ if (!folder.isEmpty()) startImageBatch(files, folder);+}+bool QmlPlayerBridge::startImageBatch(const QStringList& files, const QString& folder) {+ auto& i = *impl_;+ if (i.imagePhase != Impl::ImagePhase::Idle) { emit notice(tr("已有一批图片在处理"), true); return false; }+ if (i.chain.mode == engine::ChainMode::Node) {+ emit notice(tr("图片导出只接受列表模式;请切回列表模式再导出"), true); return false;+ }+ if (files.isEmpty() || !QFileInfo(folder).isDir()) { emit notice(tr("请选择图片和已存在的输出目录"), true); return false; }+ i.imageFiles = files; i.imageFolder = folder;+ i.imageIndex = -1; i.imageDone = 0; i.imageFailures = 0;+ i.imagePhase = Impl::ImagePhase::Opening; i.imageWaits = 0;+ veyra::log::info("image-batch", std::format("start files={} folder={}", files.size(), folder.toStdString()));+ emit imageBatchChanged();+ return true;+}+void QmlPlayerBridge::cancelImageBatch() {+ if (impl_->imagePhase == Impl::ImagePhase::Idle) return;+ impl_->imagePhase = Impl::ImagePhase::Idle;+ impl_->imageStatus = tr("已取消:完成 %1 / %2").arg(impl_->imageDone).arg(impl_->imageFiles.size());+ veyra::log::info("image-batch", "cancelled");+ emit imageBatchChanged();+}+void QmlPlayerBridge::tickImageBatch() {+ auto& i = *impl_;+ if (i.imagePhase == Impl::ImagePhase::Idle) return;+ auto fail = [&](const QString& why) {+ ++i.imageFailures;+ veyra::log::warn("image-batch", std::format("item failed index={} reason={}", i.imageIndex, why.toStdString()));+ emit notice(tr("图片未导出:%1(%2)").arg(QFileInfo(i.imageFiles[i.imageIndex]).fileName(), why), true);+ i.imagePhase = Impl::ImagePhase::Opening; i.imageSession = 0;+ };+ const auto& s = i.snapshot;+ if (i.imagePhase == Impl::ImagePhase::Opening && i.imageSession == 0) {+ // Next item.+ if (++i.imageIndex >= i.imageFiles.size()) {+ i.imagePhase = Impl::ImagePhase::Idle;+ i.imageStatus = tr("完成 %1 张,失败 %2 张").arg(i.imageDone).arg(i.imageFailures);+ veyra::log::info("image-batch", std::format("finished done={} failed={}", i.imageDone, i.imageFailures));+ emit imageBatchChanged();+ emit notice(i.imageStatus, i.imageFailures > 0);+ return;+ }+ const QString input = i.imageFiles[i.imageIndex];+ i.imageTarget = QDir(i.imageFolder).filePath(QFileInfo(input).completeBaseName() + QStringLiteral("-veyra.png"));+ i.imageStatus = tr("正在处理 %1 / %2:%3").arg(i.imageIndex + 1).arg(i.imageFiles.size()).arg(QFileInfo(input).fileName());+ emit imageBatchChanged();+ if (!QFileInfo(input).isFile()) { fail(tr("文件不存在")); return; }+ if (QFileInfo::exists(i.imageTarget)) { fail(tr("输出已存在,不覆盖")); return; }+ openPath(input);+ i.imageSession = i.openingSessionId ? i.openingSessionId : UINT64_MAX;+ i.imageWaits = 0;+ return;+ }+ ++i.imageWaits;+ if (i.imagePhase == Impl::ImagePhase::Opening) {+ if (s.sessionId == i.imageSession && s.failed) { fail(tr("无法打开")); return; }+ if (s.sessionId == i.imageSession && s.image && s.frames > 0 && !applying()) {+ impl_->engine.saveFrame(wideOf(QDir::toNativeSeparators(i.imageTarget)));+ i.imagePhase = Impl::ImagePhase::Saving; i.imageWaits = 0;+ } else if (i.imageWaits > 60 * 20) { fail(tr("打开超时")); }+ return;+ }+ // Saving: the engine writes on its own thread; HDR output becomes .jxr.+ QString written = i.imageTarget;+ if (!QFileInfo(written).isFile()) written = QFileInfo(i.imageTarget).path() + QLatin1Char('/') + QFileInfo(i.imageTarget).completeBaseName() + QStringLiteral(".jxr");+ if (QFileInfo(written).isFile() && QFileInfo(written).size() > 0) {+ ++i.imageDone;+ veyra::log::info("image-batch", std::format("saved index={} path={}", i.imageIndex, written.toStdString()));+ i.imagePhase = Impl::ImagePhase::Opening; i.imageSession = 0;+ emit imageBatchChanged();+ } else if (i.imageWaits > 60 * 15) {+ fail(tr("保存超时"));+ }+}++// --- subtitles (P4-c) --------------------------------------------------------+namespace {+const wchar_t* const kSubtitleFonts[] = {L"Microsoft YaHei UI", L"SimHei", L"SimSun", L"DengXian", L"Arial", L"Segoe UI"};+bool subtitleIsChinese(const engine::SubtitleTrack& t) {+ const auto has = [](const std::wstring& s, const wchar_t* k) { return s.find(k) != std::wstring::npos; };+ return has(t.language, L"chi") || has(t.language, L"zho") || has(t.language, L"zh") || has(t.name, L"中") ||+ has(t.name, L"简") || has(t.name, L"繁");+}+void ensureGdiplus() {+ static ULONG_PTR token = 0;+ if (token) return;+ Gdiplus::GdiplusStartupInput input;+ if (Gdiplus::GdiplusStartup(&token, &input, nullptr) != Gdiplus::Ok) token = 0;+}+}+void QmlPlayerBridge::refreshSubtitles(const std::wstring& media) {+ auto& i = *impl_;+ i.subTracks.clear(); i.subExternal = i.subLoaded = 0;+ i.subPrimary = i.subSecondary = -1; i.subPrimaryChosen = i.subSecondaryChosen = false;+ i.subStatus.clear(); i.subMedia = media;+ if (i.subAlignWorker.joinable()) { i.subAlignWorker.request_stop(); i.subAlignWorker = {}; }+ i.subAligning = false; i.subAlignReady = false;+ if (!i.subLoader) i.subLoader = std::make_unique<engine::SubtitleLoader>();+ i.subGeneration = i.subLoader->request(media);+ emit subtitlesChanged();+}+void QmlPlayerBridge::tickSubtitles() {+ auto& i = *impl_;+ bool changed = false;+ if (i.subLoader) {+ if (auto result = i.subLoader->poll(); result && result->generation == i.subGeneration) {+ // Replace the loader's tracks, keep user-loaded files and per-track offsets.+ const size_t count = result->tracks.size();+ for (size_t k = 0; k < std::min(i.subLoaded, count); ++k)+ result->tracks[k].offsetMs = i.subTracks[i.subExternal + k].offsetMs;+ i.subTracks.erase(i.subTracks.begin() + std::ptrdiff_t(i.subExternal),+ i.subTracks.begin() + std::ptrdiff_t(i.subExternal + i.subLoaded));+ i.subTracks.insert(i.subTracks.begin() + std::ptrdiff_t(i.subExternal),+ std::make_move_iterator(result->tracks.begin()), std::make_move_iterator(result->tracks.end()));+ i.subLoaded = count;+ int firstUsable = -1, firstChinese = -1;+ for (size_t k = 0; k < i.subTracks.size(); ++k) {+ if (!i.subTracks[k].usable()) continue;+ if (firstUsable < 0) firstUsable = int(k);+ if (firstChinese < 0 && subtitleIsChinese(i.subTracks[k])) firstChinese = int(k);+ }+ if (!i.subPrimaryChosen) i.subPrimary = firstChinese >= 0 ? firstChinese : firstUsable;+ if (!i.subSecondaryChosen && i.prefBool("subtitleSecondLanguage", false)) {+ int candidate = -1;+ for (size_t k = 0; k < i.subTracks.size(); ++k)+ if (i.subTracks[k].usable() && int(k) != i.subPrimary) { candidate = int(k); break; }+ i.subSecondary = candidate;+ }+ if (result->complete)+ for (const auto& t : i.subTracks)+ veyra::log::info("subtitle", std::format("track name={} codec={} embedded={} cues={} usable={}",+ QString::fromStdWString(t.name).toStdString(), QString::fromStdWString(t.codec).toStdString(),+ t.embedded ? 1 : 0, t.cues.size(), t.usable() ? 1 : 0));+ veyra::log::info("subtitle", std::format("tracks={} primary={} secondary={}", i.subTracks.size(), i.subPrimary, i.subSecondary));+ changed = true;+ }+ }+ if (i.subAlignReady.exchange(false) && i.subAlignGeneration == i.subGeneration &&+ i.subAlignTrack >= 0 && size_t(i.subAlignTrack) < i.subTracks.size()) {+ i.subTracks[size_t(i.subAlignTrack)].offsetMs = i.subAlignOffset.load();+ std::lock_guard lock(i.subAlignMutex);+ i.subStatus = tr("自动对齐:%1(Z/X 可微调)").arg(QString::fromStdWString(i.subAlignDetail));+ veyra::log::info("subtitle", std::format("auto align applied offsetMs={}", i.subAlignOffset.load()));+ changed = true;+ }+ if (i.subAligning.load() != (i.subStatus.startsWith(tr("正在自动对齐")))) changed = true;+ if (changed) emit subtitlesChanged();++ // Draw. The overlay is a layered child of the video window: it moves with the+ // picture and is clipped by the same window region as the video itself.+ if (!i.videoWindow || !IsWindow(i.videoWindow)) return;+ if (!i.subOverlay) {+ // A refused layered child (missing compatibility manifest, old OS) is+ // reported once; retrying every tick would only flood the log.+ if (i.subOverlayFailed) return;+ ensureGdiplus();+ i.subOverlay = createSubtitleOverlay(i.videoWindow);+ const DWORD error = i.subOverlay ? 0 : GetLastError();+ veyra::log::info("subtitle", std::format("overlay created ok={} err={}", i.subOverlay != nullptr, error));+ if (!i.subOverlay) { i.subOverlayFailed = true; return; }+ }+ RECT client{}; GetClientRect(i.videoWindow, &client);+ RECT current{}; GetClientRect(i.subOverlay, ¤t);+ if (current.right != client.right || current.bottom != client.bottom)+ SetWindowPos(i.subOverlay, HWND_TOP, 0, 0, client.right, client.bottom, SWP_NOACTIVATE);+ const auto& s = i.snapshot;+ std::vector<SubtitleLine> draw;+ const bool show = i.prefBool("subtitleEnabled", true) && (s.running && !s.image && !s.capture) && !i.subTracks.empty();+ if (show) {+ auto append = [&](int index, bool secondary) {+ if (index < 0 || size_t(index) >= i.subTracks.size()) return;+ const auto& track = i.subTracks[size_t(index)];+ if (!track.usable()) return;+ const double at = s.position + double(track.offsetMs) / 1000.0;+ for (const auto* cue : engine::cuesAt(track, at, 3)) {+ SubtitleLine line;+ line.text = cue->text; line.bitmap = cue->bitmap;+ line.style = track.styles.empty() ? engine::SubtitleStyle{}+ : track.styles[size_t(std::clamp(cue->style, 0, int(track.styles.size()) - 1))];+ if (cue->alignOverride) line.style.alignment = cue->alignOverride;+ line.alignOverride = cue->alignOverride;+ line.posX = cue->posX >= 0 ? cue->posX / std::max(1.0, track.scriptWidth) : -1.0;+ line.posY = cue->posY >= 0 ? cue->posY / std::max(1.0, track.scriptHeight) : -1.0;+ line.secondary = secondary;+ // Outline level 0..3: none / thin / normal / thick, over the track's own width.+ const int outline = i.prefInt("subtitleOutline", 2);+ if (outline == 0) line.style.outlineWidth = 0;+ else if (line.style.outlineWidth <= 0) line.style.outlineWidth = outline == 1 ? 1.0 : outline == 2 ? 2.0 : 3.5;+ else line.style.outlineWidth *= outline == 1 ? 0.6 : outline == 3 ? 1.6 : 1.0;+ draw.push_back(std::move(line));+ }+ };+ append(i.subSecondary, true); // the painter stacks bottom-up+ append(i.subPrimary, false);+ }+ SubtitleView view;+ view.scale = double(i.prefInt("subtitleSize", 22)) / 22.0;+ const int font = i.prefInt("subtitleFont", 0);+ view.fontOverride = font > 0 ? std::wstring(kSubtitleFonts[std::clamp(font, 0, 5)]) : std::wstring{};+ view.outline = i.prefInt("subtitleOutline", 2) > 0;+ view.background = i.prefBool("subtitleBackground", false);+ view.bottomMargin = i.prefInt("subtitleMargin", 0) + i.subBottomInset;+ view.targetLines = i.prefInt("subtitleLines", 2);+ view.fitToLines = i.prefBool("subtitleFit", false);+ view.preview = i.engine.previewView();+ view.videoWidth = s.metrics.resolution.output.width;+ view.videoHeight = s.metrics.resolution.output.height;+ updateSubtitleOverlay(i.subOverlay, draw, view);+ QString joined;+ for (const auto& line : draw) { if (!joined.isEmpty()) joined += QStringLiteral(" | "); joined += QString::fromStdWString(line.text); }+ if (joined != i.subText) {+ i.subText = joined;+ if (!joined.isEmpty()) veyra::log::info("subtitle-overlay", "text=" + joined.toStdString());+ emit subtitleTextChanged();+ }+}+QVariantList QmlPlayerBridge::subtitleTracks() const {+ QVariantList out;+ for (size_t k = 0; k < impl_->subTracks.size(); ++k) {+ const auto& t = impl_->subTracks[k];+ QString label = QString::fromStdWString(t.name);+ if (label.isEmpty()) label = QString::fromStdWString(t.language);+ if (label.isEmpty()) label = tr("字幕 %1").arg(k + 1);+ QString note = t.embedded ? tr("内嵌") : tr("外挂");+ if (!t.codec.empty()) note += QStringLiteral(" · ") + QString::fromStdWString(t.codec).toUpper();+ if (!t.usable()) note += QStringLiteral(" · ") + (t.note.empty() ? tr("不可用") : QString::fromStdWString(t.note));+ out << QVariantMap{{"index", int(k)}, {"label", label}, {"note", note}, {"usable", t.usable()},+ {"embedded", t.embedded}, {"cues", int(t.cues.size())}, {"offsetMs", t.offsetMs}};+ }+ return out;+}+int QmlPlayerBridge::subtitlePrimary() const { return impl_->subPrimary; }+void QmlPlayerBridge::setSubtitlePrimary(int index) {+ if (index < -1 || index >= int(impl_->subTracks.size())) return;+ if (index >= 0 && !impl_->subTracks[size_t(index)].usable()) { emit notice(tr("该字幕轨没有可显示的内容"), true); return; }+ impl_->subPrimaryChosen = true;+ if (impl_->subPrimary == index) return;+ impl_->subPrimary = index;+ if (impl_->subSecondary == index) impl_->subSecondary = -1;+ veyra::log::info("subtitle", std::format("primary={} secondary={}", impl_->subPrimary, impl_->subSecondary));+ emit subtitlesChanged();+}+int QmlPlayerBridge::subtitleSecondary() const { return impl_->subSecondary; }+void QmlPlayerBridge::setSubtitleSecondary(int index) {+ if (index < -1 || index >= int(impl_->subTracks.size())) return;+ if (index >= 0 && (!impl_->subTracks[size_t(index)].usable() || index == impl_->subPrimary)) return;+ impl_->subSecondaryChosen = true;+ if (impl_->subSecondary == index) return;+ impl_->subSecondary = index;+ veyra::log::info("subtitle", std::format("primary={} secondary={}", impl_->subPrimary, impl_->subSecondary));+ emit subtitlesChanged();+}+int QmlPlayerBridge::subtitleOffsetMs() const {+ const int p = impl_->subPrimary;+ return p >= 0 && size_t(p) < impl_->subTracks.size() ? impl_->subTracks[size_t(p)].offsetMs : 0;+}+void QmlPlayerBridge::setSubtitleOffsetMs(int ms) {+ const int p = impl_->subPrimary;+ if (p < 0 || size_t(p) >= impl_->subTracks.size()) return;+ auto& track = impl_->subTracks[size_t(p)];+ ms = std::clamp(ms, -30000, 30000);+ if (track.offsetMs == ms) return;+ track.offsetMs = ms;+ impl_->subStatus = tr("字幕延时 %1 ms").arg(ms);+ veyra::log::info("subtitle", std::format("offset track={} offsetMs={}", p, ms));+ emit subtitlesChanged();+}+QString QmlPlayerBridge::subtitleStatus() const { return impl_->subStatus; }+bool QmlPlayerBridge::subtitleAligning() const { return impl_->subAligning.load(); }+QString QmlPlayerBridge::subtitleText() const { return impl_->subText; }+int QmlPlayerBridge::subtitleBottomInset() const { return impl_->subBottomInset; }+void QmlPlayerBridge::setSubtitleBottomInset(int value) {+ value = std::clamp(value, 0, 400);+ if (impl_->subBottomInset == value) return;+ impl_->subBottomInset = value;+ emit subtitlesChanged();+}+void QmlPlayerBridge::loadSubtitleDialog() {+ const QString start = impl_->subMedia.empty() ? QString() : QFileInfo(QString::fromStdWString(impl_->subMedia)).absolutePath();+ const QString path = QFileDialog::getOpenFileName(nullptr, tr("加载外部字幕"), start,+ tr("字幕文件 (*.srt *.ass *.ssa *.vtt);;所有文件 (*.*)"));+ if (!path.isEmpty()) loadSubtitleFile(path);+}+bool QmlPlayerBridge::loadSubtitleFile(const QString& path) {+ engine::SubtitleTrack track;+ try { track = engine::loadSubtitleFile(wideOf(path)); } catch (...) {}+ if (!track.usable()) {+ veyra::log::warn("subtitle", "external file has no usable cues path=" + path.toStdString());+ emit notice(tr("字幕文件无法读取或没有字幕内容:%1").arg(QFileInfo(path).fileName()), true);+ return false;+ }+ if (track.name.empty()) track.name = QFileInfo(path).fileName().toStdWString();+ impl_->subTracks.insert(impl_->subTracks.begin(), std::move(track));+ ++impl_->subExternal;+ if (impl_->subPrimary >= 0) ++impl_->subPrimary;+ if (impl_->subSecondary >= 0) ++impl_->subSecondary;+ if (impl_->subAlignTrack >= 0) ++impl_->subAlignTrack;+ impl_->subPrimary = 0; impl_->subPrimaryChosen = true;+ if (impl_->subSecondary == 0) impl_->subSecondary = -1;+ impl_->subStatus = tr("已加载外部字幕:%1").arg(QFileInfo(path).fileName());+ veyra::log::info("subtitle", std::format("external loaded cues={} path={}", impl_->subTracks.front().cues.size(), path.toStdString()));+ emit subtitlesChanged();return true;}+void QmlPlayerBridge::nudgeSubtitle(int deltaMs) {+ if (impl_->subPrimary < 0) { emit notice(tr("没有正在显示的字幕"), true); return; }+ setSubtitleOffsetMs(subtitleOffsetMs() + deltaMs);+ emit notice(impl_->subStatus, false);+}+void QmlPlayerBridge::cycleSubtitle(bool secondary) {+ auto& i = *impl_;+ if (i.subTracks.empty()) { emit notice(tr("当前片源没有字幕"), true); return; }+ int slot = secondary ? i.subSecondary : i.subPrimary;+ for (size_t n = 0; n <= i.subTracks.size(); ++n) { // -1 -> 0 -> ... -> -1, skipping unusable+ slot = slot + 1 >= int(i.subTracks.size()) ? -1 : slot + 1;+ if (slot < 0 || (i.subTracks[size_t(slot)].usable() && !(secondary && slot == i.subPrimary))) break;+ }+ if (secondary) setSubtitleSecondary(slot); else setSubtitlePrimary(slot);+ const int now = secondary ? i.subSecondary : i.subPrimary;+ emit notice(now < 0 ? (secondary ? tr("副字幕已关闭") : tr("主字幕已关闭"))+ : (secondary ? tr("副字幕:%1") : tr("主字幕:%1")).arg(subtitleTracks()[now].toMap().value("label").toString()), false);+}+void QmlPlayerBridge::toggleSubtitles() {+ const bool on = !impl_->prefBool("subtitleEnabled", true);+ setPreference(QStringLiteral("subtitleEnabled"), on);+ emit notice(on ? tr("字幕:开") : tr("字幕:关"), false);+}+void QmlPlayerBridge::autoAlignSubtitle() {+ auto& i = *impl_;+ if (i.subAligning.load()) { emit notice(tr("已有一个自动对齐在进行"), true); return; }+ if (i.subMedia.empty() || i.subPrimary < 0 || !i.subTracks[size_t(i.subPrimary)].usable()) {+ emit notice(tr("没有可用的主字幕,无法自动对齐"), true); return;+ }+ const std::wstring media = i.subMedia;+ const auto track = i.subTracks[size_t(i.subPrimary)];+ i.subAlignGeneration = i.subGeneration; i.subAlignTrack = i.subPrimary;+ i.subAligning = true; i.subAlignReady = false;+ i.subStatus = tr("正在自动对齐:分析音轨(最多前 30 分钟)…");+ emit subtitlesChanged();+ i.subAlignWorker = std::jthread([&i, media, track](std::stop_token stop) {+ const auto result = engine::alignSubtitleToAudio(media, track, 30, stop);+ if (stop.stop_requested()) { i.subAligning = false; return; }+ { std::lock_guard lock(i.subAlignMutex); i.subAlignDetail = result.detail; }+ i.subAlignOffset = result.ok ? result.offsetMs : 0;+ i.subAlignReady = result.ok;+ i.subAligning = false;+ });+}void QmlPlayerBridge::attachVideoWindow(qulonglong nativeHandle) {impl_->videoWindow = reinterpret_cast<HWND>(nativeHandle);@@ -743,8 +2867,19 @@ double QmlPlayerBridge::sourceAspect() const {}// --- live performance --------------------------------------------------------double QmlPlayerBridge::submitFps() const { return impl_->snapshot.submissionFps.value_or(0.0); }-bool QmlPlayerBridge::submitFpsKnown() const { return impl_->snapshot.submissionFps.has_value(); }+// XeSS generates inside the provider: the engine only submits source frames,+// so its own rate would read 60 while the SDK presents 120. Show the provider's+// reported submissions for XeSS (AppShell: "SDK提交(非屏幕实测)").+static bool xessPresenting(const engine::PlayerSnapshot& s) {+ return s.fgActive && s.applied.frameGenerationBackend == engine::FrameGenerationBackend::XeSS &&+ s.metrics.flow.xessSdkSubmitFps > 0;+}+double QmlPlayerBridge::submitFps() const {+ const auto& s = impl_->snapshot;+ return xessPresenting(s) ? s.metrics.flow.xessSdkSubmitFps : s.submissionFps.value_or(0.0);+}+bool QmlPlayerBridge::submitFpsKnown() const { return xessPresenting(impl_->snapshot) || impl_->snapshot.submissionFps.has_value(); }+QString QmlPlayerBridge::submitFpsLabel() const { return xessPresenting(impl_->snapshot) ? tr("SDK 提交") : tr("提交"); }double QmlPlayerBridge::lateMs() const { return impl_->snapshot.lateMs; }double QmlPlayerBridge::lateP95Ms() const { return impl_->snapshot.lateP95Ms; }QString QmlPlayerBridge::metricsSummary() const {@@ -784,48 +2919,224 @@ QString QmlPlayerBridge::backendWarning() const { return utf8Of(impl_->snapshot.emit settingsChanged(); \}-VEYRA_BOOL_PROP(nrEnabled, setNrEnabled, nr)-VEYRA_BOOL_PROP(srEnabled, setSrEnabled, sr)-VEYRA_BOOL_PROP(lowLatency, setLowLatency, lowLatency)-VEYRA_BOOL_PROP(nrTemporal, setNrTemporal, nrTemporal)-VEYRA_BOOL_PROP(videoHdr, setVideoHdr, videoHdr.enabled)-VEYRA_BOOL_PROP(protectionEnabled, setProtectionEnabled, protection.enabled)-VEYRA_BOOL_PROP(colorEnabled, setColorEnabled, color.enabled)-VEYRA_NUM_PROP(fgMultiplier, setFgMultiplier, multiplier, int)VEYRA_NUM_PROP(videoSrQuality, setVideoSrQuality, videoSrQuality, int)-VEYRA_NUM_PROP(audioOffsetMs, setAudioOffsetMs, audioOffsetMs, int)-VEYRA_NUM_PROP(nrIntensity, setNrIntensity, model.intensity, double)-VEYRA_NUM_PROP(nrTone, setNrTone, model.tone, double)-VEYRA_NUM_PROP(nrStructure, setNrStructure, model.structure, double)-VEYRA_NUM_PROP(nrSkin, setNrSkin, model.skin, double)+int QmlPlayerBridge::audioOffsetMs() const { return settings().audioOffsetMs; }+void QmlPlayerBridge::setAudioOffsetMs(int value) {+ auto s = settings();+ if (s.audioOffsetMs == value) return;+ s.audioOffsetMs = value;+ if (!impl_->commit(std::move(s))) return;+ impl_->prefs[QStringLiteral("audioOffsetMs")] = value;+ if (!impl_->savePrefs()) veyra::log::warn("ui-prefs", "audio offset not saved");+ emit settingsChanged();+}#undef VEYRA_BOOL_PROP#undef VEYRA_NUM_PROP-// The two NR switches the engine keeps as small integers. Kept separate from-// the macro because the property is a bool and the field is not.-bool QmlPlayerBridge::nrAutoMask() const { return settings().model.autoMask != 0; }-void QmlPlayerBridge::setNrAutoMask(bool value) {- auto s = settings();- const int32_t want = value ? 1 : 0;- if (s.model.autoMask == want) return;- s.model.autoMask = want;- impl_->commit(std::move(s));- emit settingsChanged();+// Stage-owned properties must change the authoritative chain first. commit()+// projects that chain back to settings, so setting only a flat mirror is a no-op.+bool QmlPlayerBridge::srEnabled() const {+ const auto* node = impl_->chain.firstOf(engine::EffectType::SuperResolution);+ return node && node->enabled;+}+void QmlPlayerBridge::setSrEnabled(bool enabled) {+ for (uint32_t i = 0; i < impl_->chain.nodeCount; ++i)+ if (impl_->chain.nodes[i].type == engine::EffectType::SuperResolution) {+ setEffectEnabled(int(i), enabled); return;+ }+ if (enabled) emit notice(tr("请先添加超分节点"), true);+}+bool QmlPlayerBridge::videoHdr() const {+ const auto* node = impl_->chain.firstOf(engine::EffectType::VideoHdr);+ return node && node->enabled;+}+void QmlPlayerBridge::setVideoHdr(bool enabled) {+ for (uint32_t i = 0; i < impl_->chain.nodeCount; ++i)+ if (impl_->chain.nodes[i].type == engine::EffectType::VideoHdr) {+ setEffectEnabled(int(i), enabled); return;+ }+ if (enabled) emit notice(tr("请先添加 RTX Video HDR 节点"), true);+}+// RTX Video HDR tuning lives on the chain's HDR node, like NR parameters on+// NR nodes: the same values AppShell's settings sliders edited.+QVariantMap QmlPlayerBridge::videoHdrParams() const {+ for (uint32_t i = 0; i < impl_->chain.nodeCount; ++i)+ if (impl_->chain.nodes[i].type == engine::EffectType::VideoHdr) {+ const auto& v = impl_->chain.nodes[i].videoHdr;+ return {{"contrast", int(v.contrast)}, {"saturation", int(v.saturation)},+ {"middleGray", int(v.middleGray)}, {"peakNits", int(v.peakNits)}};+ }+ return {};+}+bool QmlPlayerBridge::setVideoHdrParameter(const QString& key, double value) {+ if (!std::isfinite(value) || value < 0) return false;+ for (uint32_t i = 0; i < impl_->chain.nodeCount; ++i) {+ auto& node = impl_->chain.nodes[i];+ if (node.type != engine::EffectType::VideoHdr) continue;+ const auto before = node;+ const auto v = unsigned(std::lround(value));+ if (key == "contrast") node.videoHdr.contrast = v;+ else if (key == "saturation") node.videoHdr.saturation = v;+ else if (key == "middleGray") node.videoHdr.middleGray = v;+ else if (key == "peakNits") node.videoHdr.peakNits = v;+ else return false;+ if (!node.videoHdr.valid()) { node = before; return false; }+ if (node == before) return true;+ const bool accepted = impl_->revalidate(true);+ if (!accepted) { const auto error = impl_->validation.message; node = before; impl_->revalidate(); emit notice(utf8Of(error), true); }+ emit settingsChanged(); emit chainChanged(); return accepted;+ }+ emit notice(tr("请先添加 RTX Video HDR 节点"), true);+ return false;+}+bool QmlPlayerBridge::fgEnabled() const {+ const auto* node = impl_->chain.firstOf(engine::EffectType::FrameGeneration);+ return node && node->enabled;+}+void QmlPlayerBridge::setFgEnabled(bool enabled) {+ for (uint32_t i = 0; i < impl_->chain.nodeCount; ++i)+ if (impl_->chain.nodes[i].type == engine::EffectType::FrameGeneration) {+ if (impl_->chain.nodes[i].enabled == enabled) return;+ // Turning on keeps the last chosen multiplier (at least 2X).+ if (enabled && impl_->chain.fgMultiplier < 2) impl_->chain.fgMultiplier = 2;+ setEffectEnabled(int(i), enabled); emit settingsChanged(); return;+ }+ if (enabled) emit notice(tr("请先添加补帧节点"), true);+}+int QmlPlayerBridge::fgMultiplier() const {+ const auto* node = impl_->chain.firstOf(engine::EffectType::FrameGeneration);+ return node && node->enabled ? int(impl_->chain.fgMultiplier) : 1;+}+void QmlPlayerBridge::setFgMultiplier(int multiplier) {+ const bool legal = std::find(std::begin(engine::kFgMultiplierChoices), std::end(engine::kFgMultiplierChoices),+ uint32_t(std::max(multiplier, 0))) != std::end(engine::kFgMultiplierChoices);+ if (!legal || multiplier > fgMaxMultiplier()) {+ emit notice(tr("补帧倍率超出当前后端范围"), true); return;+ }+ auto& chain = impl_->chain;+ auto* node = chain.firstOf(engine::EffectType::FrameGeneration);+ if (!node) { if (multiplier > 1) emit notice(tr("请先添加补帧节点"), true); return; }+ const bool enabled = multiplier > 1;+ if (node->enabled == enabled && (!enabled || chain.fgMultiplier == uint32_t(multiplier))) return;+ const auto beforeMultiplier = chain.fgMultiplier; const auto beforeEnabled = node->enabled;+ node->enabled = enabled; if (enabled) chain.fgMultiplier = uint32_t(multiplier);+ if (!impl_->revalidate(true)) {+ const auto error = impl_->validation.message;+ node->enabled = beforeEnabled; chain.fgMultiplier = beforeMultiplier; impl_->revalidate();+ emit notice(utf8Of(error), true);+ }+ emit settingsChanged(); emit chainChanged();+}++bool QmlPlayerBridge::colorEnabled() const {return selectedColourSettings().enabled;}+void QmlPlayerBridge::setColorEnabled(bool enabled){+ auto c=selectedColourSettings();c.enabled=enabled;commitColour(c);+}++bool QmlPlayerBridge::protectionEnabled() const { return settings().protection.enabled; }+void QmlPlayerBridge::setProtectionEnabled(bool enabled) {+ if (impl_->chain.mode != engine::ChainMode::List) {+ emit notice(tr("NR 保护区域仅在列表模式可用"), true); return;+ }+ for (uint32_t i=0; i<impl_->chain.nodeCount; ++i) {+ if (impl_->chain.nodes[i].type==engine::EffectType::Protection) {+ setEffectEnabled(int(i), enabled);+ return;+ }+ }+ emit notice(tr("处理链中没有 NR 保护节点,未更改设置"), true);+}++QVariantMap QmlPlayerBridge::protectionState() const {+ const auto p = settings().protection;+ const auto r = p.regions[0];+ return {{"left",double(r.left)},{"top",double(r.top)},+ {"right",double(r.right)},{"bottom",double(r.bottom)},+ {"feather",double(p.featherPixels)}};+}++bool QmlPlayerBridge::setProtectionRegion(double left,double top,double right,double bottom,double feather) {+ if (impl_->chain.mode != engine::ChainMode::List) return false;+ for (double v : {left,top,right,bottom,feather}) if (!std::isfinite(v)) return false;+ if (left<0 || top<0 || right>1 || bottom>1 || left>right || top>bottom || feather<0 || feather>64) return false;+ for (uint32_t i=0;i<impl_->chain.nodeCount;++i) {+ auto& node=impl_->chain.nodes[i];+ if (node.type!=engine::EffectType::Protection) continue;+ const auto before=node;+ // Explicit edits replace legacy multi-rectangle settings with the one global region.+ node.protection.regions={};+ node.protection.regions[0]={float(left),float(top),float(right),float(bottom)};+ node.protection.featherPixels=float(feather);+ if(node==before)return true;+ const bool accepted=impl_->revalidate(true);+ if(!accepted){const auto error=impl_->validation.message;node=before;impl_->revalidate();emit notice(utf8Of(error),true);}+ emit settingsChanged();emit chainChanged();return accepted;+ }+ return false;}-bool QmlPlayerBridge::nrUiCorrection() const { return settings().model.uiCorrection != 0; }-void QmlPlayerBridge::setNrUiCorrection(bool value) {++// The inspector edits the selected list node, not the first flat NR mirror.+#define VEYRA_NR_PROP(getter,setter,member,type) \+ type QmlPlayerBridge::getter() const { \+ const auto* n=impl_->nrNode(); const engine::ChainNode fallback{}; \+ return type((n?*n:fallback).member); \+ } \+ void QmlPlayerBridge::setter(type value){ \+ auto* n=impl_->nrNode(); if(!n||type(n->member)==value)return; \+ const auto before=*n; n->member=decltype(n->member)(value); \+ if(!impl_->revalidate(true)){ \+ const auto error=impl_->validation.message; *n=before; \+ impl_->revalidate();emit notice(utf8Of(error),true); \+ } \+ emit settingsChanged();emit chainChanged(); \+ }+VEYRA_NR_PROP(nrEnabled,setNrEnabled,enabled,bool)+VEYRA_NR_PROP(nrTemporal,setNrTemporal,nr.temporal,bool)+VEYRA_NR_PROP(nrIntensity,setNrIntensity,nr.model.intensity,double)+VEYRA_NR_PROP(nrTone,setNrTone,nr.model.tone,double)+VEYRA_NR_PROP(nrStructure,setNrStructure,nr.model.structure,double)+VEYRA_NR_PROP(nrSkin,setNrSkin,nr.model.skin,double)+VEYRA_NR_PROP(nrAutoMask,setNrAutoMask,nr.model.autoMask,bool)+VEYRA_NR_PROP(nrUiCorrection,setNrUiCorrection,nr.model.uiCorrection,bool)+VEYRA_NR_PROP(nrStyle,setNrStyle,nr.model.style,int)+#undef VEYRA_NR_PROP+int QmlPlayerBridge::selectedNrLayer() const{return impl_->nrIndex();}+void QmlPlayerBridge::setSelectedNrLayer(int index){+ if(index<0||uint32_t(index)>=impl_->chain.nodeCount||+ impl_->chain.nodes[index].type!=engine::EffectType::NrEnhance||index==impl_->selectedNr)return;+ impl_->selectedNr=index;emit settingsChanged();+}+bool QmlPlayerBridge::lowLatency() const{return settings().lowLatency;}+void QmlPlayerBridge::setLowLatency(bool value){+ const auto before=impl_->chain;+ for(uint32_t i=0;i<impl_->chain.nodeCount;++i)if(impl_->chain.nodes[i].type==engine::EffectType::NrEnhance)+ impl_->chain.nodes[i].nr.lowLatencyPairing=value;+ if(!impl_->revalidate(true)){+ const auto error=impl_->validation.message;impl_->chain=before;+ impl_->revalidate();emit notice(utf8Of(error),true);+ }+ emit settingsChanged();emit chainChanged();+}++// Stage-5 output stabiliser (anti-flicker). Global, not per-node: it runs once,+// after the whole NR stack and the residual composite. Strength 0 is the+// default and the graph then skips the dispatch entirely, so committing it+// never costs anything until the user turns it on.+double QmlPlayerBridge::nrHoldStrength() const { return double(settings().nrHoldStrength); }+void QmlPlayerBridge::setNrHoldStrength(double value) {auto s = settings();- const int32_t want = value ? 1 : 0;- if (s.model.uiCorrection == want) return;- s.model.uiCorrection = want;+ const float next = float(value);+ if (s.nrHoldStrength == next) return;+ s.nrHoldStrength = next;impl_->commit(std::move(s));emit settingsChanged();}-int QmlPlayerBridge::nrStyle() const { return int(settings().model.style); }-void QmlPlayerBridge::setNrStyle(int value) {+double QmlPlayerBridge::nrHoldTolerance() const { return double(settings().nrHoldTolerance); }+void QmlPlayerBridge::setNrHoldTolerance(double value) {auto s = settings();- if (s.model.style == value) return;- s.model.style = value;+ const float next = float(value);+ if (s.nrHoldTolerance == next) return;+ s.nrHoldTolerance = next;impl_->commit(std::move(s));emit settingsChanged();}@@ -849,19 +3160,29 @@ double QmlPlayerBridge::playbackSpeed() const { return impl_->snapshot.playbackS// The settings the UI is showing: the facade's pending copy, which the engine// has been asked to apply. One accessor so every property reads the same value.engine::EnhancementSettings QmlPlayerBridge::settings() const {- return impl_->facade.pendingSettings();+ auto result = impl_->facade.pendingSettings();+ if (impl_->chain.mode == engine::ChainMode::Node) impl_->draftGlobals.apply(result);+ return result;}QVariantList QmlPlayerBridge::chain() const {QVariantList out;+ int nrOrdinal=0;const auto& c = impl_->chain;for (uint32_t i = 0; i < c.nodeCount; ++i) {const auto& node = c.nodes[i];const auto& info = engine::effectInfo(node.type);QVariantMap item;item["index"] = int(i);+ item["id"] = c.mode == engine::ChainMode::Node ? impl_->layout.ids[i] : i + 2;item["type"] = utf8Of(info.id);item["label"] = utf8Of(info.label);+ if(node.type==engine::EffectType::FrameGeneration)+ for(const auto& choice:fgBackendChoices()){+ const auto option=choice.toMap();+ if(option.value("id").toString()==fgBackendName())item["label"]=option.value("label");+ }+ if(node.type==engine::EffectType::NrEnhance)item["label"]=tr("NR 画面增强 · 第 %1 层").arg(++nrOrdinal);item["enabled"] = node.enabled;item["x"] = double(node.viewX);item["y"] = double(node.viewY);@@ -874,9 +3195,77 @@ QVariantList QmlPlayerBridge::chain() const {return out;}+QVariantList QmlPlayerBridge::nrLayers() const {+ QVariantList out;+ for(uint32_t i=0;i<impl_->chain.nodeCount;++i){const auto& node=impl_->chain.nodes[i];+ if(node.type!=engine::EffectType::NrEnhance)continue;+ const auto& n=node.nr;+ out<<QVariantMap{{"index",int(i)},{"enabled",node.enabled},{"sizePolicy",int(n.sizePolicy)},{"runtime",int(engine::currentNrRuntime(n.runtime))},+ {"intensity",n.model.intensity},{"tone",n.model.tone},{"structure",n.model.structure},+ {"skin",n.model.skin},{"style",n.model.style},{"autoMask",bool(n.model.autoMask)},+ {"uiCorrection",bool(n.model.uiCorrection)},{"total",n.residual.total},+ {"darken",n.residual.darken},{"brighten",n.residual.brighten},+ {"color",n.residual.color},{"luminance",n.residual.luminance},{"temporal",n.temporal},+ {"antiFlicker",int(n.antiFlicker)}};+ }+ return out;+}++bool QmlPlayerBridge::setNrLayerParameter(int index,const QString& key,double value){+ if(index<0||uint32_t(index)>=impl_->chain.nodeCount||+ impl_->chain.nodes[index].type!=engine::EffectType::NrEnhance||!std::isfinite(value))return false;+ if(key=="runtime") {+ if(value!=0&&value!=2)return false;+ const auto before=impl_->chain;+ for(uint32_t i=0;i<impl_->chain.nodeCount;++i)+ if(impl_->chain.nodes[i].type==engine::EffectType::NrEnhance)+ impl_->chain.nodes[i].nr.runtime=static_cast<engine::NrRuntime>(int(value));+ const bool accepted=impl_->revalidate(true);+ if(!accepted){const auto error=impl_->validation.message;impl_->chain=before;impl_->revalidate();emit notice(utf8Of(error),true);}+ emit settingsChanged();emit chainChanged();return accepted;+ }+ auto& node=impl_->chain.nodes[index];const auto before=node;auto& n=node.nr;+ if(key=="intensity")n.model.intensity=float(value);+ else if(key=="tone")n.model.tone=float(value);+ else if(key=="structure")n.model.structure=float(value);+ else if(key=="skin")n.model.skin=float(value);+ else if(key=="total")n.residual.total=float(value);+ else if(key=="darken")n.residual.darken=float(value);+ else if(key=="brighten")n.residual.brighten=float(value);+ else if(key=="color")n.residual.color=float(value);+ else if(key=="luminance")n.residual.luminance=float(value);+ else {+ if(value!=std::floor(value)||value<0||value>5)return false;+ if(key=="sizePolicy")n.sizePolicy=static_cast<pipeline::NrSizePolicy>(int(value));+ else if(key=="style"&&value<=2)n.model.style=int(value);+ else if(key=="autoMask"&&value<=1)n.model.autoMask=int(value);+ else if(key=="uiCorrection"&&value<=1)n.model.uiCorrection=int(value);+ else if(key=="temporal"&&value<=1)n.temporal=value!=0;+ else if(key=="antiFlicker"&&validNrAntiFlicker(engine::NrAntiFlicker(int(value))))n.antiFlicker=static_cast<engine::NrAntiFlicker>(int(value));+ else return false;+ }+ if(node==before)return true;+ const bool accepted=impl_->revalidate(true);+ if(!accepted){const auto error=impl_->validation.message;node=before;impl_->revalidate();emit notice(utf8Of(error),true);}+ emit settingsChanged();emit chainChanged();return accepted;+}+QVariantList QmlPlayerBridge::effectCatalog() const {QVariantList out;for (const auto& info : engine::effectCatalog()) {+ if (impl_->chain.mode == engine::ChainMode::Node && info.type == engine::EffectType::Protection) continue;+ if (impl_->chain.mode == engine::ChainMode::Node && info.type == engine::EffectType::FrameGeneration) {+ for(const auto& choice : fgBackendChoices()) {+ const auto option=choice.toMap();const auto backend=option.value("id").toString();+ QVariantMap fg;+ fg["id"]=backend+QStringLiteral("-fg");+ fg["label"]=option.value("label");+ fg["maxInstances"]=1;fg["repeatable"]=false;fg["mustBeLast"]=true;+ fg["justBeforeLast"]=false;fg["experimental"]=backend!=QLatin1String("dlss");+ out<<fg;+ }+ continue;+ }QVariantMap item;item["id"] = utf8Of(info.id);item["label"] = utf8Of(info.label);@@ -894,10 +3283,44 @@ QString QmlPlayerBridge::chainError() const { return utf8Of(impl_->validation.mebool QmlPlayerBridge::chainValid() const { return impl_->validation.accepted; }int QmlPlayerBridge::nodeMode() const { return impl_->chain.mode == engine::ChainMode::Node ? 1 : 0; }void QmlPlayerBridge::setNodeMode(int mode) {+ if (mode < 0 || mode > 1) { emit notice(tr("无效编辑模式"), true); return; }const auto want = mode ? engine::ChainMode::Node : engine::ChainMode::List;if (impl_->chain.mode == want) return;- impl_->chain.mode = want;+ const auto previousSession = impl_->currentSession();+ auto candidate = previousSession;+ const bool freshNode = want == engine::ChainMode::Node && !candidate.initialized[size_t(want)];+ if (!candidate.select(want)) { emit notice(tr("模式配置无效,未切换"), true); return; }+ if (freshNode) {+ // The first visit to the node editor starts from an empty graph (input+ // straight to output), not a copy of the list's effects.+ auto& fresh = candidate.configurations[size_t(want)];+ auto empty = std::make_unique<engine::EffectChain>();+ empty->mode = engine::ChainMode::Node;+ empty->fgMultiplier = fresh.chain.fgMultiplier;+ fresh.chain = *empty;+ fresh.editor.reset();+ fresh.selectedNr = fresh.selectedColour = -1;+ }+ const auto previousSettings = impl_->facade.pendingSettings();+ auto next = previousSettings;+ const auto& configuration = candidate.configurations[size_t(want)];+ configuration.apply(next);+ if (!next.validate().empty()) { emit notice(tr("模式参数无效,未切换"), true); return; }+ // Save before changing the live mode; an unwritable/corrupt file cannot+ // silently discard the configuration the user is about to leave.+ if (!impl_->facade.saveChainSession(candidate)) { emit notice(utf8Of(impl_->facade.error()), true); return; }+ if (!impl_->facade.applySettings(next,engine::runtimeOrder(configuration.chain))) {+ impl_->facade.setPending(previousSettings);+ if (!impl_->facade.saveChainSession(previousSession))+ emit notice(tr("引擎拒绝切换,存档回退失败:") + utf8Of(impl_->facade.error()), true);+ emit notice(tr("引擎未接受模式设置,当前配置不变"), true); return;+ }+ impl_->session = impl_->savedSession = candidate;+ impl_->restoreConfiguration(configuration);+ impl_->revalidate();+ impl_->options = engine::PlayerOptions::from(next,engine::runtimeOrder(impl_->activeRuntime()));emit chainChanged();+ emit settingsChanged();}QVariantList QmlPlayerBridge::recentFiles() const {@@ -968,16 +3391,28 @@ QString QmlPlayerBridge::captureSessionSummary() const {// history that never happened.const auto& session = impl_->facade.lastCaptureSession();QStringList parts;- if (!session.devicePath.empty()) parts << QFileInfo(utf8Of(session.devicePath)).fileName();- if (!session.formatKey.empty()) parts << utf8Of(session.formatKey);- if (session.fps > 0.01) parts << QStringLiteral("%1 fps").arg(session.fps, 0, 'f', 2);+ // The device's friendly name (stored when the session started); the moniker+ // path itself is not something a person can read.+ const QString name = impl_->prefString("captureDeviceName");+ if (!name.isEmpty()) parts << name;+ else if (!session.devicePath.empty()) parts << QFileInfo(utf8Of(session.devicePath)).fileName();+ const QString formatLabel = impl_->prefString("captureFormatLabel");+ if (!formatLabel.isEmpty()) parts << formatLabel.section(QStringLiteral(" · "), 0, 1);+ else if (!session.formatKey.empty()) parts << utf8Of(session.formatKey);+ if (formatLabel.isEmpty() && session.fps > 0.01) parts << QStringLiteral("%1 fps").arg(session.fps, 0, 'f', 2);if (!session.presetName.empty()) parts << tr("预设「%1」").arg(utf8Of(session.presetName));return parts.join(QStringLiteral(" · "));}void QmlPlayerBridge::resumeCaptureSession() {- const auto& session = impl_->facade.lastCaptureSession();- if (!session.devicePath.empty()) emit notice(tr("采集会话恢复尚未接入"), true);+ // "Continue": the remembered device, format, audio and colour, re-checked+ // against what the machine reports now; nothing else is picked for the user.+ impl_->capturePrefs = ui::CapturePreferenceStore(impl_->dataDir).load();+ if (impl_->capturePrefs.videoPath.empty()) { emit notice(tr("还没有采集记录"), true); return; }+ impl_->captureDevice = impl_->capturePrefs.videoPath;+ impl_->captureColor = impl_->capturePrefs.colorForDevice(impl_->captureDevice);+ impl_->captureResumePending = true;+ queryCapture(2, impl_->captureDevice);}QString QmlPlayerBridge::colorStatus() const { return utf8Of(impl_->snapshot.colorStatus); }@@ -987,7 +3422,30 @@ QString QmlPlayerBridge::videoHdrStatus() const { return utf8Of(impl_->snapshot.// Poll the export job once per UI tick. Its snapshot is the source of the// numbers below; nothing here keeps a parallel counter that could drift.void QmlPlayerBridge::pollExport() {+ const auto failuresBefore = impl_->exportSnapshot.queueFailures;impl_->exportSnapshot = impl_->exportJob.poll();+ const auto& snap = impl_->exportSnapshot;+ if (snap.queueFailures > failuresBefore) {+ emit notice(tr("队列中有一项未能开始:%1").arg(utf8Of(snap.lastQueueFailure)), true);+ // The manager names no row; the oldest waiting row that is not the+ // job now running is the one it refused.+ for (auto& row : impl_->exportRows)+ if (row.state == QLatin1String("queued") && row.output != snap.output) {+ row.state = QStringLiteral("failed"); row.note = utf8Of(snap.lastQueueFailure); break;+ }+ }+ for (auto& row : impl_->exportRows) {+ if (row.output != snap.output || snap.output.empty()) continue;+ using S = engine::ExportState;+ if (snap.active()) { row.state = snap.state == S::Paused ? QStringLiteral("paused") : QStringLiteral("running"); row.progress = snap.progress; }+ else if (snap.state == S::Succeeded) { row.state = QStringLiteral("done"); row.progress = 1.0; }+ else if (snap.state == S::Failed) { row.state = QStringLiteral("failed"); row.note = utf8Of(snap.message); }+ else if (snap.state == S::Cancelled) row.state = QStringLiteral("cancelled");+ }+ // A running row that is no longer the job (the next one started) finished.+ if (!snap.output.empty())+ for (auto& row : impl_->exportRows)+ if (row.state == QLatin1String("running") && row.output != snap.output) { row.state = QStringLiteral("done"); row.progress = 1.0; }emit exportChanged();}@@ -1017,6 +3475,8 @@ int QmlPlayerBridge::exportEncoded() const { return int(impl_->exportSnapshot.enint QmlPlayerBridge::exportGenerated() const { return int(impl_->exportSnapshot.generated); }double QmlPlayerBridge::exportEtaSeconds() const { return impl_->exportSnapshot.etaSeconds; }int QmlPlayerBridge::exportQueueCount() const { return int(impl_->exportSnapshot.queued); }+int QmlPlayerBridge::exportQueueFailures() const { return int(impl_->exportSnapshot.queueFailures); }+QString QmlPlayerBridge::exportQueueFailure() const { return utf8Of(impl_->exportSnapshot.lastQueueFailure); }// HEVC or H.264: the engine's export entry takes this as a flag, so it is a real// choice with a real effect rather than a label.@@ -1054,7 +3514,7 @@ int QmlPlayerBridge::exportSrTargetIndex() const {return impl_->exportResolutionIndex;}void QmlPlayerBridge::setExportSrTargetIndex(int index) {- if (index < -1 || index > 3 || impl_->exportResolutionIndex == index) return;+ if (index < -1 || index > 6 || impl_->exportResolutionIndex == index) return;impl_->exportResolutionIndex = index;emit exportChanged();}@@ -1090,26 +3550,36 @@ QString QmlPlayerBridge::srTargetLabel() const {case 1: return QStringLiteral("2K");case 2: return QStringLiteral("4K");case 3: return QStringLiteral("8K");+ case 4: return QStringLiteral("5K");+ case 5: return QStringLiteral("6K");+ case 6: return QStringLiteral("7K");default: return tr("源尺寸");}}int QmlPlayerBridge::srTargetIndex() const {- // 0 keeps the source size; 1..3 are the engine's Qhd/Uhd4K/Uhd8K targets.+ // UI IDs 1/2/3 remain 2K/4K/8K; append 4/5/6 for 5K/6K/7K.switch (settings().srTarget) {case pipeline::SrTarget::Qhd: return 1;case pipeline::SrTarget::Uhd4K: return 2;case pipeline::SrTarget::Uhd8K: return 3;+ case pipeline::SrTarget::Uhd5K: return 4;+ case pipeline::SrTarget::Uhd6K: return 5;+ case pipeline::SrTarget::Uhd7K: return 6;}return 0;}void QmlPlayerBridge::setSrTargetIndex(int index) {+ if(index<1||index>6)return;auto s = settings();pipeline::SrTarget want = pipeline::SrTarget::Uhd4K;switch (index) {case 1: want = pipeline::SrTarget::Qhd; break;case 2: want = pipeline::SrTarget::Uhd4K; break;case 3: want = pipeline::SrTarget::Uhd8K; break;+ case 4: want = pipeline::SrTarget::Uhd5K; break;+ case 5: want = pipeline::SrTarget::Uhd6K; break;+ case 6: want = pipeline::SrTarget::Uhd7K; break;default: break;}if (s.srTarget == want) return;@@ -1180,6 +3650,7 @@ int QmlPlayerBridge::thumbnailGeneration() const { return impl_->thumbnailGeneravoid QmlPlayerBridge::openPath(const QString& path) {if (path.isEmpty()) return;+ ++impl_->liveOpenGen; impl_->pendingLiveText.clear(); // a waiting live open is droppedimpl_->exportTrimStartSeconds = 0.0;impl_->exportTrimEndSeconds = 0.0;emit exportChanged();@@ -1187,6 +3658,8 @@ void QmlPlayerBridge::openPath(const QString& path) {impl_->openingSessionId = 0;const std::wstring wide = wideOf(path);impl_->sourceLabel = wide;+ impl_->liveKind.clear();+ impl_->liveLabel.clear();++impl_->thumbnailGeneration;emit thumbnailSourceChanged(path);emit thumbnailGenerationChanged();@@ -1201,13 +3674,40 @@ void QmlPlayerBridge::openPath(const QString& path) {// design's source menu implies.if (impl_->currentPage.isEmpty() || impl_->currentPage == QLatin1String("home"))emit navigate(QStringLiteral("min"));+ rememberPosition(true); // the file being leftif (impl_->preOpen) impl_->preOpen();- impl_->engine.open(impl_->videoWindow, wide, impl_->options);+ auto options = impl_->options;+ options.softwareDecode = impl_->prefString("decode") == QLatin1String("software");+ options.hardwareDecodeOnly = impl_->prefString("decode") == QLatin1String("hardware");+ impl_->engine.open(impl_->videoWindow, wide, options);impl_->openingSessionId = impl_->engine.snapshot().sessionId;+ impl_->resumeSession = 0;+ if (impl_->prefBool("rememberPosition", true)) {+ const auto saved = impl_->prefs.value("positions").toMap().value(path).toMap();+ if (!saved.isEmpty()) { impl_->resumeSession = impl_->openingSessionId; impl_->resumeAt = saved.value("at").toDouble(); }+ }+ refreshSubtitles(wide);}-void QmlPlayerBridge::togglePlayPause() { impl_->engine.pause(impl_->snapshot.running); }+void QmlPlayerBridge::togglePlayPause() {+ // AppShell's Play button: a paused session is still "running" (the worker+ // stays alive), so the decision must come from the transport state.+ const auto& s = impl_->snapshot;+ using T = engine::TransportState;+ if (s.capture || s.image || s.transport == T::Opening || s.transport == T::Stopping) return;+ if (!s.running || s.transport == T::Ended) {+ // Only a real file is reopened; device/stream labels are not paths.+ const QString file = QString::fromStdWString(impl_->sourceLabel);+ if (!file.isEmpty() && QFileInfo(file).isFile()) openPath(file);+ return;+ }+ const bool pause = s.transport == T::Playing;+ impl_->engine.pause(pause);+ veyra::log::info("ui-transport", pause ? "pause" : "resume");+}void QmlPlayerBridge::stopPlayback() {+ rememberPosition(true);+ ++impl_->liveOpenGen; impl_->pendingLiveText.clear();impl_->openingSource = false;impl_->openingSessionId = 0;impl_->engine.stop();@@ -1235,7 +3735,9 @@ void QmlPlayerBridge::setWindowMask(QObject* window, const QRectF& rect) {w->setMask(QRegion(rect.toAlignedRect()));}void QmlPlayerBridge::holdOriginal(bool held) {- impl_->engine.comparison(held ? 1 : 0, false);+ // Releasing the key returns to whatever the 显示 page chose (off or split).+ if (held) impl_->engine.comparison(1, false);+ else impl_->engine.comparison(impl_->compareMode, impl_->compareBase, float(impl_->compareSplit));veyra::log::info("ui-compare", held ? "hold original on" : "hold original off");}void QmlPlayerBridge::stepFrame(int direction) {@@ -1246,14 +3748,252 @@ void QmlPlayerBridge::stepFrame(int direction) {}void QmlPlayerBridge::takeScreenshot() {+ if (!hasSource()) { emit notice(tr("没有正在播放的画面,无法截图"), true); return; }+ const QString folder = screenshotDirectory();+ if (!QDir().mkpath(folder)) { emit notice(tr("截图目录不可用:%1").arg(folder), true); return; }const QString name = QStringLiteral("veyra-%1.png")- .arg(QDateTime::currentDateTime().toString(QStringLiteral("yyyyMMdd-HHmmss")));- const std::wstring path = wideOf(QDir(QDir::homePath()).filePath(name));- impl_->engine.saveFrame(path);- emit notice(tr("已保存截图: %1").arg(utf8Of(path)), false);+ .arg(QDateTime::currentDateTime().toString(QStringLiteral("yyyyMMdd-HHmmss-zzz")));+ const QString path = QDir(folder).filePath(name);+ impl_->engine.saveFrame(wideOf(QDir::toNativeSeparators(path)));+ impl_->lastScreenshot = path;+ veyra::log::info("ui-screenshot", "requested path=" + path.toStdString());+ emit preferencesChanged();+ emit notice(tr("截图保存到:%1").arg(QDir::toNativeSeparators(path)), false);+}++// --- shell preferences (P4-f / P4-c / P4-d) --------------------------------+QVariantMap QmlPlayerBridge::preferences() const { return impl_->prefs; }+void QmlPlayerBridge::rememberWindowSize(int width, int height) {+ // Only kept when the user chose "记住上次"; the key is internal.+ if (width < 400 || height < 200 || width > 16384 || height > 16384) return;+ const QString v = QStringLiteral("%1x%2").arg(width).arg(height);+ if (impl_->prefs.value(QStringLiteral("lastWindow")).toString() == v) return;+ impl_->prefs[QStringLiteral("lastWindow")] = v;+ if (!impl_->savePrefs()) veyra::log::warn("ui-prefs", "last window size not saved");+}+bool QmlPlayerBridge::setPreference(const QString& key, const QVariant& value) {+ static const QHash<QString, std::pair<int, int>> ranges{+ {"subtitleSize", {16, 56}}, {"subtitleFont", {0, 5}}, {"subtitleOutline", {0, 3}},+ {"subtitleMargin", {0, 240}}, {"subtitleLines", {0, 8}}};+ static const QStringList flags{"subtitleEnabled", "subtitleBackground", "subtitleFit",+ "subtitleSecondLanguage", "audioForceStereo", "holdCompare"};+ QVariant stored;+ if (ranges.contains(key)) {+ bool ok = false; const int n = value.toInt(&ok);+ const auto [low, high] = ranges.value(key);+ if (!ok || n < low || n > high) return false;+ stored = n;+ } else if (flags.contains(key)) {+ stored = value.toBool();+ } else if (key == QLatin1String("screenshotDir")) {+ const QString dir = value.toString();+ if (!dir.isEmpty() && !QFileInfo(dir).isDir()) { emit notice(tr("截图目录不存在:%1").arg(dir), true); return false; }+ stored = dir;+ } else if (key == QLatin1String("audioDevice")) {+ stored = value.toString();+ } else if (key == QLatin1String("accent")) {+ const QString v = value.toString();+ if (v != QLatin1String("orange") && v != QLatin1String("white")) return false;+ stored = v;+ } else if (key == QLatin1String("backdrop")) {+ bool ok = false; const int n = value.toInt(&ok);+ if (!ok || n < 0 || n > 2) return false;+ stored = n;+ } else if (key == QLatin1String("uiScale")) {+ bool ok = false; const int n = value.toInt(&ok);+ if (!ok || (n != 0 && n != 100 && n != 125 && n != 150)) return false;+ stored = n;+ } else if (key == QLatin1String("decode")) {+ const QString v = value.toString();+ if (v != QLatin1String("auto") && v != QLatin1String("software") && v != QLatin1String("hardware")) return false;+ stored = v;+ } else if (key == QLatin1String("rememberPosition") || key == QLatin1String("dockPinned")) {+ stored = value.toBool();+ } else if (key == QLatin1String("windowSize")) {+ const QString v = value.toString();+ static const QStringList sizes{"1280x800", "1600x1000", "1920x1200", "last"};+ if (!sizes.contains(v)) return false;+ stored = v;+ } else {+ return false;+ }+ if (impl_->prefs.value(key) == stored) return true;+ const auto previous = impl_->prefs;+ impl_->prefs[key] = stored;+ if (!impl_->savePrefs()) {+ impl_->prefs = previous;+ emit notice(tr("偏好保存失败,已保留原设置"), true);+ return false;+ }+ veyra::log::info("ui-prefs", std::format("{}={}", key.toStdString(), stored.toString().toStdString()));+ applyPreference(key);+ emit preferencesChanged();+ return true;+}+void QmlPlayerBridge::applyPreference(const QString& key) {+ if (key == QLatin1String("audioDevice")) sink::setPreferredRenderEndpoint(impl_->prefString("audioDevice").toStdWString());+ else if (key == QLatin1String("audioForceStereo")) sink::setForceStereoDownmix(impl_->prefBool("audioForceStereo", false));+}+QVariantList QmlPlayerBridge::audioDevices() const {+ QVariantList out;+ out << QVariantMap{{"id", QString()}, {"label", tr("跟随系统默认")}, {"isDefault", false}};+ const QString chosen = impl_->prefString("audioDevice");+ bool listed = chosen.isEmpty();+ for (const auto& e : impl_->audioEndpoints) {+ const QString id = QString::fromStdWString(e.id);+ listed = listed || id == chosen;+ out << QVariantMap{{"id", id}, {"label", QString::fromStdWString(e.name) + (e.isDefault ? tr(" · 当前默认") : QString())},+ {"isDefault", e.isDefault}};+ }+ // A saved device that is unplugged stays visible, marked, instead of vanishing.+ if (!listed) out << QVariantMap{{"id", chosen}, {"label", tr("已保存的设备(未连接)")}, {"isDefault", false}, {"missing", true}};+ return out;+}+QString QmlPlayerBridge::audioOutputStatus() const {+ const auto& a = impl_->audioActive;+ if (!a.valid) return tr("尚未打开音频输出");+ QString text = QString::fromStdWString(a.name.empty() ? L"(未命名设备)" : a.name) + tr(" · %1 声道").arg(a.channels);+ if (a.downmix) text += tr(" · 下混");+ if (a.fallback) text = tr("所选设备不可用,已回落到系统默认:") + text;+ return text;+}+bool QmlPlayerBridge::audioOutputFallback() const { return impl_->audioActive.valid && impl_->audioActive.fallback; }+void QmlPlayerBridge::refreshAudioDevices() {+ impl_->audioEndpoints = sink::enumerateRenderEndpoints();+ impl_->audioActive = sink::activeRenderEndpoint();+ veyra::log::info("ui-audio", std::format("render endpoints={}", impl_->audioEndpoints.size()));+ emit audioDevicesChanged();+}+// --- shortcuts (P4-f) --------------------------------------------------------+namespace {+const QVariantMap& shortcutDefaults() {+ static const QVariantMap d{{"playPause", "Space"}, {"fullscreen", "F"}, {"lock", "Ctrl+L"},+ {"hold", "V"}, {"screenshot", "Ctrl+S"}, {"toggleMode", "Tab"}};+ return d;+}+}+QVariantMap QmlPlayerBridge::shortcuts() const {+ QVariantMap out = shortcutDefaults();+ const auto custom = impl_->prefs.value("shortcuts").toMap();+ for (auto it = custom.begin(); it != custom.end(); ++it)+ if (out.contains(it.key())) out[it.key()] = it.value();+ return out;+}+bool QmlPlayerBridge::setShortcut(const QString& action, const QString& sequence) {+ if (!shortcutDefaults().contains(action)) return false;+ const QKeySequence seq(sequence, QKeySequence::PortableText);+ if (seq.isEmpty() || seq.count() != 1) { emit notice(tr("无效的按键"), true); return false; }+ const QString text = seq.toString(QKeySequence::PortableText);+ // Keys the shell already owns cannot be taken over.+ static const QStringList reserved{"Esc", "F11", "Left", "Right", "Up", "Down", "Ctrl+O", "Ctrl+E",+ "B", "Z", "X", "T", "Y", "Shift+Z", "Shift+X", "Alt+Return"};+ if (reserved.contains(text)) { emit notice(tr("%1 已被固定功能占用").arg(text), true); return false; }+ const auto current = shortcuts();+ for (auto it = current.begin(); it != current.end(); ++it)+ if (it.key() != action && it.value().toString() == text) {+ emit notice(tr("%1 已用于其他操作").arg(text), true); return false;+ }+ auto custom = impl_->prefs.value("shortcuts").toMap();+ custom[action] = text;+ const auto previous = impl_->prefs;+ impl_->prefs["shortcuts"] = custom;+ if (!impl_->savePrefs()) { impl_->prefs = previous; emit notice(tr("快捷键保存失败"), true); return false; }+ veyra::log::info("ui-prefs", std::format("shortcut {}={}", action.toStdString(), text.toStdString()));+ emit preferencesChanged();+ return true;+}+void QmlPlayerBridge::resetShortcuts() {+ const auto previous = impl_->prefs;+ impl_->prefs.remove("shortcuts");+ if (!impl_->savePrefs()) { impl_->prefs = previous; return; }+ emit preferencesChanged();+}+int QmlPlayerBridge::uiScaleActive() const { return qApp ? qApp->property("veyraUiScale").toInt() : 0; }+void QmlPlayerBridge::openFeedbackPage() {+ copyDiagnostics();+ QDesktopServices::openUrl(QUrl(QStringLiteral("https://github.com/Likely7/Veyra-NRVideo/issues")));+ emit notice(tr("诊断信息已复制,可直接粘贴到反馈里"), false);+}+void QmlPlayerBridge::openReleasesPage() {+ QDesktopServices::openUrl(QUrl(QStringLiteral("https://github.com/Likely7/Veyra-NRVideo/releases")));+}+bool QmlPlayerBridge::eventFilter(QObject* watched, QEvent* event) {+ const auto type = event->type();+ if (type == QEvent::KeyPress || type == QEvent::KeyRelease) {+ auto* key = static_cast<QKeyEvent*>(event);+ if (!key->isAutoRepeat() && qobject_cast<QWindow*>(watched)) {+ const QKeySequence hold(shortcuts().value("hold").toString(), QKeySequence::PortableText);+ const int pressed = key->key() | int(key->modifiers() & ~Qt::KeypadModifier);+ // Typing into a text field never compares.+ const QObject* focus = QGuiApplication::focusObject();+ const bool typing = focus && (focus->inherits("QQuickTextInput") || focus->inherits("QQuickTextEdit"));+ if (!hold.isEmpty() && hold[0].toCombined() == pressed && !typing && impl_->prefBool("holdCompare", true)) {+ const bool down = type == QEvent::KeyPress;+ if (down != impl_->holdKeyDown) { impl_->holdKeyDown = down; holdOriginal(down); }+ return true;+ }+ if (type == QEvent::KeyRelease && impl_->holdKeyDown && key->key() == QKeySequence(hold)[0].key()) {+ impl_->holdKeyDown = false; holdOriginal(false);+ }+ }+ } else if (type == QEvent::ApplicationDeactivate && impl_->holdKeyDown) {+ impl_->holdKeyDown = false; holdOriginal(false);+ }+ return QObject::eventFilter(watched, event);+}+// Remembered playback positions: files only, the last 40, saved on switch/stop/exit.+void QmlPlayerBridge::rememberPosition(bool flush) {+ const auto& s = impl_->snapshot;+ const QString file = QString::fromStdWString(impl_->sourceLabel);+ if (s.running && !s.image && !s.capture && s.duration > 30 && !file.isEmpty() && QFileInfo(file).isFile()) {+ auto positions = impl_->prefs.value("positions").toMap();+ const double at = s.position;+ if (at > 5 && at < s.duration - 10) positions[file] = QVariantMap{{"at", at}, {"t", QDateTime::currentSecsSinceEpoch()}};+ else positions.remove(file); // finished or barely started: next time from the top+ while (positions.size() > 40) {+ auto oldest = positions.begin();+ for (auto it = positions.begin(); it != positions.end(); ++it)+ if (it.value().toMap().value("t").toLongLong() < oldest.value().toMap().value("t").toLongLong()) oldest = it;+ positions.erase(oldest);+ }+ impl_->prefs["positions"] = positions;+ }+ if (flush) impl_->savePrefs();+}++QString QmlPlayerBridge::screenshotDirectory() const {+ const QString chosen = impl_->prefString("screenshotDir");+ if (!chosen.isEmpty()) return chosen;+ const QString pictures = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);+ return QDir(pictures.isEmpty() ? QDir::homePath() : pictures).filePath(QStringLiteral("Veyra"));+}+QString QmlPlayerBridge::lastScreenshot() const { return impl_->lastScreenshot; }+QString QmlPlayerBridge::dataDirectory() const { return QString::fromStdWString(impl_->dataDir.wstring()); }+// main() records the file it actually opened (it falls back to a per-process name).+QString QmlPlayerBridge::logFile() const { return qApp ? qApp->property("veyraLogFile").toString() : QString(); }+void QmlPlayerBridge::chooseScreenshotDirectory() {+ const QString dir = QFileDialog::getExistingDirectory(nullptr, tr("选择截图目录"), screenshotDirectory());+ if (!dir.isEmpty()) setPreference(QStringLiteral("screenshotDir"), dir);+}+void QmlPlayerBridge::openScreenshotDirectory() {+ const QString dir = screenshotDirectory();+ QDir().mkpath(dir);+ if (!QDesktopServices::openUrl(QUrl::fromLocalFile(dir))) emit notice(tr("无法打开目录:%1").arg(dir), true);+}+void QmlPlayerBridge::openLogFolder() {+ const QString file = logFile();+ const QString dir = file.isEmpty() ? QString() : QFileInfo(file).absolutePath();+ if (dir.isEmpty() || !QDesktopServices::openUrl(QUrl::fromLocalFile(dir))) emit notice(tr("日志目录不可用"), true);+}+void QmlPlayerBridge::openDataFolder() {+ if (!QDesktopServices::openUrl(QUrl::fromLocalFile(dataDirectory()))) emit notice(tr("无法打开数据目录"), true);}void QmlPlayerBridge::chooseExportPath() {+ if (impl_->chain.mode == engine::ChainMode::Node) {+ emit notice(tr("节点链尚未接入导出执行器,请切换列表模式后导出"), true);+ return;+ }const QString path = QFileDialog::getSaveFileName(nullptr, tr("导出到"), QString(),tr("MP4 视频 (*.mp4);;所有文件 (*)"));setExportPath(path);@@ -1267,70 +4007,136 @@ void QmlPlayerBridge::setExportPath(const QString& path) {}void QmlPlayerBridge::startExport() {+ QString error;+ auto settings = impl_->exportSettings(error);+ if (!settings) { emit notice(error, true); return; }if (impl_->exportOutput.empty()) { emit notice(tr("先选择导出位置"), true); return; }- if (impl_->sourceLabel.empty()) { emit notice(tr("先打开要导出的文件"), true); return; }- // The settings are frozen at start, exactly as the engine's job expects: an- // export must not change under the user mid-run.- auto settings = impl_->facade.pendingSettings();- engine::fromChain(impl_->chain, settings);- if (!impl_->exportPresetName.empty()) {- const auto& entries = impl_->facade.presets().entries();- const auto preset = std::find_if(entries.begin(), entries.end(), [this](const auto& entry) {- return entry.name == impl_->exportPresetName;- });- if (preset == entries.end()) { emit notice(tr("导出预设已不存在,请重新选择"), true); return; }- if (preset->kind == engine::ChainMode::Node) {- emit notice(tr("节点预设尚未接入导出执行器"), true);- return;- }- engine::PresetLibrary::apply(*preset, settings);- }- settings.exportBitrateMbps = impl_->exportBitrateMbps;- if (impl_->exportResolutionIndex >= 0) {- settings.sr = impl_->exportResolutionIndex != 0;- if (settings.sr) {- switch (impl_->exportResolutionIndex) {- case 1: settings.srTarget = pipeline::SrTarget::Qhd; break;- case 2: settings.srTarget = pipeline::SrTarget::Uhd4K; break;- case 3: settings.srTarget = pipeline::SrTarget::Uhd8K; break;- default: break;- }- }+ if (!QFileInfo(utf8Of(impl_->sourceLabel)).isFile()) {+ emit notice(tr("先打开要导出的本地文件"), true); return;}- if (!settings.validate().empty()) { emit notice(tr("导出设置无效"), true); return; }veyra::log::info("qml-export", std::format("preset={} revision={} nr={} sr={} fg={} bitrate={} srTarget={}",impl_->exportPresetName.empty() ? "current" : utf8Of(impl_->exportPresetName).toStdString(),- settings.revision, settings.nr, settings.sr, settings.multiplier,- settings.exportBitrateMbps, settings.sr ? int(settings.srTarget) : -1));+ settings->revision, settings->nr, settings->sr, settings->multiplier,+ settings->exportBitrateMbps, settings->sr ? int(settings->srTarget) : -1));const bool started = impl_->exportJob.start(impl_->sourceLabel, impl_->exportOutput,- settings, impl_->exportHevc, 0,+ *settings, impl_->exportHevc, 0,impl_->snapshot.selectedAudioTrack,impl_->exportTrimStartSeconds,impl_->exportTrimEndSeconds,impl_->exportRateControl);if (!started) { emit notice(tr("导出启动失败;详见诊断"), true); return; }+ impl_->exportRows.push_back({impl_->sourceLabel, impl_->exportOutput, QStringLiteral("running"), 0.0, {}});pollExport();emit navigate(QStringLiteral("exp"));}void QmlPlayerBridge::cancelExport() {impl_->exportJob.cancel();+ for (auto& row : impl_->exportRows)+ if (row.state == QLatin1String("queued")) row.state = QStringLiteral("cancelled");pollExport();}void QmlPlayerBridge::quit() {+ rememberPosition(true);if (auto* app = qobject_cast<QGuiApplication*>(QCoreApplication::instance())) app->quit();}void QmlPlayerBridge::openCaptureDialog() { emit navigate(QStringLiteral("capture")); }void QmlPlayerBridge::openPs5Dialog() { emit navigate(QStringLiteral("ps5")); }void QmlPlayerBridge::openScreenCaptureDialog() { emit navigate(QStringLiteral("screen")); }+void QmlPlayerBridge::openAudioDialog() { emit navigate(QStringLiteral("audio")); }+void QmlPlayerBridge::openSubtitleDialog() { emit navigate(QStringLiteral("subtitle")); }// --- chain editing ----------------------------------------------------------// The validator is the authority: an edit that would put frame generation or// RTX Video HDR where the pipeline cannot honour them is refused with a reason,// not silently dropped.int QmlPlayerBridge::addEffect(const QString& type) {+ const bool fgType=type==QLatin1String("dlss-fg")||type==QLatin1String("xess-fg")||+ type==QLatin1String("fsr3-fg")||type==QLatin1String("fsr4-fg");+ const auto fgBackend=type==QLatin1String("fsr4-fg")?engine::FrameGenerationBackend::Fsr4:+ type==QLatin1String("fsr3-fg")?engine::FrameGenerationBackend::Fsr:+ type==QLatin1String("xess-fg")?engine::FrameGenerationBackend::XeSS:engine::FrameGenerationBackend::Dlss;+ const auto fgCeiling=engine::fsrFrameGeneration(fgBackend)?2u:+ fgBackend==engine::FrameGenerationBackend::XeSS?uint32_t(xessCeiling(impl_->snapshot)):6u;+ if (impl_->chain.mode == engine::ChainMode::Node) {+ const bool fg = fgType;+ const engine::EffectInfo* info = nullptr;+ for (const auto& item : engine::effectCatalog())+ if ((fg && item.type == engine::EffectType::FrameGeneration) || utf8Of(item.id) == type) info = &item;+ if (!info || info->type == engine::EffectType::Protection) {+ emit notice(tr("节点模式不支持该效果类型"), true); return -1;+ }+ auto& c = impl_->chain;+ auto before = std::make_unique<engine::EffectChain>(c);+ const auto oldLayout = impl_->layout; const auto previous = impl_->facade.pendingSettings();+ const auto oldGlobals = impl_->draftGlobals;+ auto pending = settings();+ if (fg){pending.frameGenerationBackend=fgBackend;c.fgMultiplier=std::clamp(c.fgMultiplier,2u,fgCeiling);}+ int index = -1;+ if (fg) for (uint32_t i = 0; i < c.nodeCount; ++i)+ if (c.nodes[i].type == engine::EffectType::FrameGeneration) index = int(i);+ if (index < 0) {+ if (c.nodeCount >= engine::kMaxChainNodes || c.countOf(info->type) >= info->maxInstances ||+ impl_->layout.nextId == std::numeric_limits<uint32_t>::max()) {+ emit notice(tr("该类型节点已达上限(含禁用和未连接节点)"), true); return -1;+ }+ index = int(c.nodeCount++);+ auto& node = c.nodes[index]; node = engine::ChainNode{}; node.type = info->type; node.enabled = true;+ node.viewX = float(index % 4) * 260; node.viewY = float(index / 4) * 300;+ if (info->type == engine::EffectType::NrEnhance) {+ node.nr.runtime = previous.nrRuntime; node.nr.lowLatencyPairing = previous.lowLatency;+ }+ const uint32_t id = impl_->layout.nextId++; impl_->layout.ids[index] = id; impl_->layout.next[index] = 0;+ auto projected = std::make_unique<engine::EffectChain>();+ if (oldLayout.project(*before, *projected).accepted) {+ uint32_t predecessor = 0, next = impl_->layout.inputNext;+ while (next > 1) {+ const int at = impl_->layout.indexOf(c, next);+ const auto t = c.nodes[at].type;+ if (t == engine::EffectType::FrameGeneration ||+ (info->type != engine::EffectType::FrameGeneration && t == engine::EffectType::VideoHdr)) break;+ predecessor = next; next = impl_->layout.next[at];+ }+ if (predecessor == 0) impl_->layout.inputNext = id;+ else impl_->layout.next[size_t(impl_->layout.indexOf(c, predecessor))] = id;+ impl_->layout.next[index] = next;+ }+ } else c.nodes[index].enabled = true;+ impl_->draftGlobals = engine::ChainGlobalSettings::capture(pending);+ if (!impl_->revalidate(true, &previous)) {+ const auto error = impl_->validation.message; c = *before; impl_->layout = oldLayout;+ impl_->draftGlobals = oldGlobals;+ impl_->facade.setPending(previous); impl_->revalidate(); emit notice(utf8Of(error), true); return -1;+ }+ if (info->type == engine::EffectType::NrEnhance) impl_->selectedNr = index;+ if (info->type == engine::EffectType::Color) impl_->selectedColour = index;+ emit chainChanged(); emit settingsChanged(); return index;+ }+ if(fgType) {+ const auto before=impl_->chain;const auto previous=settings();+ auto& c=impl_->chain;+ int slot=-1;+ for(uint32_t i=0;i<c.nodeCount;++i)if(c.nodes[i].type==engine::EffectType::FrameGeneration)slot=int(i);+ if(slot<0) {+ if(c.nodeCount>=engine::kMaxChainNodes){emit notice(tr("效果链已满"),true);return -1;}+ slot=int(c.nodeCount++);c.nodes[slot]={};c.nodes[slot].type=engine::EffectType::FrameGeneration;+ c.nodes[slot].viewX=float(slot%4)*260;c.nodes[slot].viewY=float(slot/4)*300;+ }+ c.nodes[slot].enabled=true;+ c.fgMultiplier=std::clamp(c.fgMultiplier,2u,fgCeiling);+ auto next=previous;engine::fromChain(c,next);+ next.frameGenerationBackend=fgBackend;+ impl_->validation=engine::validateChain(c);+ if(!impl_->validation.accepted||!next.validate().empty()||+ !impl_->facade.applySettings(next,engine::runtimeOrder(c))) {+ c=before;impl_->facade.setPending(previous);impl_->validation=engine::validateChain(c);+ emit notice(tr("补帧选择未被接受,保留原设置;请检查倍率和后端能力"),true);return -1;+ }+ impl_->options=engine::PlayerOptions::from(next,engine::runtimeOrder(c));+ emit settingsChanged();emit chainChanged();return slot;+ }engine::EffectType wanted = engine::EffectType::NrEnhance;bool found = false;for (const auto& info : engine::effectCatalog()) {@@ -1341,6 +4147,9 @@ int QmlPlayerBridge::addEffect(const QString& type) {}}if (!found) { emit notice(tr("未知的效果: %1").arg(type), true); return -1; }+ if (impl_->chain.mode == engine::ChainMode::Node && wanted == engine::EffectType::Protection) {+ emit notice(tr("节点模式已取消 NR 保护区域;请在列表模式使用全局保护"), true); return -1;+ }auto& c = impl_->chain;if (c.nodeCount >= engine::kMaxChainNodes) { emit notice(tr("效果链已满"), true); return -1; }@@ -1350,25 +4159,43 @@ int QmlPlayerBridge::addEffect(const QString& type) {return -1;}+ const auto before=c; const int selected=impl_->selectedNr,colourSelected=impl_->selectedColour;// Insert before a pinned tail so the validator never has to undo the edit:// frame generation stays last and RTX Video HDR stays in front of it.uint32_t insertAt = c.nodeCount;if (wanted != engine::EffectType::FrameGeneration) {for (uint32_t i = 0; i < c.nodeCount; ++i) {const auto& nodeInfo = engine::effectInfo(c.nodes[i].type);- if (nodeInfo.mustBeLast) { insertAt = i; break; }+ if (nodeInfo.mustBeLast||(wanted==engine::EffectType::Color&&c.nodes[i].type==engine::EffectType::VideoHdr)||+ (wanted==engine::EffectType::NrEnhance&&+ (c.nodes[i].type==engine::EffectType::Protection||c.nodes[i].type==engine::EffectType::VideoHdr))) { insertAt = i; break; }}}for (uint32_t i = c.nodeCount; i > insertAt; --i) c.nodes[i] = c.nodes[i - 1];+ if(impl_->selectedNr>=int(insertAt))++impl_->selectedNr;+ if(impl_->selectedColour>=int(insertAt))++impl_->selectedColour;c.nodes[insertAt] = engine::ChainNode{};c.nodes[insertAt].type = wanted;- c.nodes[insertAt].enabled = true;+ // A new list-mode NR layer arrives switched off: adding a layer must not+ // change the picture until the user turns it on.+ c.nodes[insertAt].enabled = !(wanted == engine::EffectType::NrEnhance && c.mode == engine::ChainMode::List);+ if(wanted==engine::EffectType::Color)impl_->selectedColour=int(insertAt);+ if(wanted==engine::EffectType::NrEnhance){+ c.nodes[insertAt].nr.runtime=settings().nrRuntime;+ c.nodes[insertAt].nr.lowLatencyPairing=settings().lowLatency;+ impl_->selectedNr=int(insertAt);+ }// A new node lands below the others in node mode, in a stable column.c.nodes[insertAt].viewX = 40.0f + float(insertAt % 4) * 260.0f;c.nodes[insertAt].viewY = 40.0f + float(insertAt / 4) * 200.0f;++c.nodeCount;- impl_->revalidate();+ const bool live=c.mode==engine::ChainMode::Node||wanted==engine::EffectType::NrEnhance||wanted==engine::EffectType::Color;+ if(!impl_->revalidate(live)){+ const auto error=impl_->validation.message;c=before;impl_->selectedNr=selected;+ impl_->selectedColour=colourSelected;+ impl_->revalidate();emit notice(utf8Of(error),true);return -1;+ }emit chainChanged();if (!impl_->validation.accepted) {emit notice(utf8Of(impl_->validation.message), true);@@ -1378,14 +4205,149 @@ int QmlPlayerBridge::addEffect(const QString& type) {return int(insertAt);}+QVariantList QmlPlayerBridge::nodeConnections() const {+ QVariantList out;+ if (impl_->chain.mode != engine::ChainMode::Node) return out;+ const auto add = [&](uint32_t from, uint32_t to) {+ if (to != engine::NodeGraphLayout::Input)+ out << QVariantMap{{"from", from}, {"to", to}};+ };+ add(0, impl_->layout.inputNext);+ for (uint32_t i = 0; i < impl_->chain.nodeCount; ++i)+ add(impl_->layout.ids[i], impl_->layout.next[i]);+ return out;+}++int QmlPlayerBridge::nodeIndexForId(uint id) const {+ return impl_->chain.mode == engine::ChainMode::Node ? impl_->layout.indexOf(impl_->chain, id) : -1;+}++int QmlPlayerBridge::duplicateNode(uint id) {+ if (impl_->chain.mode != engine::ChainMode::Node) return -1;+ auto before = std::make_unique<engine::EffectChain>(impl_->chain);+ const auto layout = impl_->layout;+ uint32_t created = 0;+ const auto result = impl_->layout.duplicate(impl_->chain, id, created);+ if (!result.accepted) { emit notice(utf8Of(result.message), true); return -1; }+ if (!impl_->revalidate(true)) {+ const auto error = impl_->validation.message;+ impl_->chain = *before; impl_->layout = layout; impl_->revalidate();+ emit notice(utf8Of(error), true); return -1;+ }+ const int index = nodeIndexForId(created);+ if (impl_->chain.nodes[index].type == engine::EffectType::NrEnhance) impl_->selectedNr = index;+ if (impl_->chain.nodes[index].type == engine::EffectType::Color) impl_->selectedColour = index;+ emit chainChanged(); emit settingsChanged(); return index;+}++bool QmlPlayerBridge::resetNode(uint id) {+ const int index = nodeIndexForId(id);+ if (index < 0) return false;+ auto& node = impl_->chain.nodes[index];+ const auto before = node; const auto multiplier = impl_->chain.fgMultiplier;+ const auto strict = impl_->chain.fgStrictAdmission;+ const auto previous = impl_->facade.pendingSettings();+ const auto oldGlobals = impl_->draftGlobals;+ node = engine::ChainNode{};+ node.type = before.type; node.enabled = before.enabled;+ node.viewX = before.viewX; node.viewY = before.viewY;+ if (node.type == engine::EffectType::FrameGeneration) {+ impl_->chain.fgMultiplier = 2; impl_->chain.fgStrictAdmission = false;+ }+ if (node.type == engine::EffectType::SuperResolution) {+ const engine::EnhancementSettings defaults;+ impl_->draftGlobals.srTarget = defaults.srTarget;+ impl_->draftGlobals.videoSrQuality = defaults.videoSrQuality;+ }+ if (!impl_->revalidate(true, &previous)) {+ const auto error = impl_->validation.message; node = before;+ impl_->draftGlobals = oldGlobals;+ impl_->facade.setPending(previous);+ impl_->chain.fgMultiplier = multiplier; impl_->chain.fgStrictAdmission = strict; impl_->revalidate();+ emit notice(utf8Of(error), true); return false;+ }+ emit chainChanged(); emit settingsChanged(); return true;+}++bool QmlPlayerBridge::connectNodes(uint from, uint to) {+ if (impl_->chain.mode != engine::ChainMode::Node) return false;+ const auto before = impl_->layout;+ const auto result = impl_->layout.connect(impl_->chain, from, to);+ if (!result.accepted) { emit notice(utf8Of(result.message), true); return false; }+ if (!impl_->revalidate(true)) {+ const auto error = impl_->validation.message; impl_->layout = before; impl_->revalidate();+ emit notice(utf8Of(error), true); return false;+ }+ emit chainChanged(); emit settingsChanged(); return true;+}++bool QmlPlayerBridge::disconnectNode(uint from) {+ if (impl_->chain.mode != engine::ChainMode::Node) return false;+ const auto before = impl_->layout;+ const auto result = impl_->layout.disconnect(impl_->chain, from);+ if (!result.accepted) { emit notice(utf8Of(result.message), true); return false; }+ if (!impl_->revalidate(true)) {+ const auto error = impl_->validation.message; impl_->layout = before; impl_->revalidate();+ emit notice(utf8Of(error), true); return false;+ }+ emit chainChanged(); emit settingsChanged(); return true;+}++bool QmlPlayerBridge::insertNodeAfter(uint id, uint after) {+ if (impl_->chain.mode != engine::ChainMode::Node) return false;+ const auto before = impl_->layout;+ const auto result = impl_->layout.insertAfter(impl_->chain, id, after);+ if (!result.accepted) { emit notice(utf8Of(result.message), true); return false; }+ if (!impl_->revalidate(true)) {+ const auto error = impl_->validation.message; impl_->layout = before; impl_->revalidate();+ emit notice(utf8Of(error), true); return false;+ }+ emit chainChanged(); emit settingsChanged(); return true;+}++int QmlPlayerBridge::duplicateNrLayer(int index){+ if (impl_->chain.mode == engine::ChainMode::Node)+ return index >= 0 && uint32_t(index) < impl_->chain.nodeCount ? duplicateNode(impl_->layout.ids[index]) : -1;+ auto& c=impl_->chain;+ if(index<0||uint32_t(index)>=c.nodeCount||c.nodes[index].type!=engine::EffectType::NrEnhance||+ c.countOf(engine::EffectType::NrEnhance)>=engine::kMaxNrInstances||c.nodeCount>=engine::kMaxChainNodes)return -1;+ const auto before=c; const int selected=impl_->selectedNr,colourSelected=impl_->selectedColour;+ const auto original=c.nodes[index];+ for(uint32_t i=c.nodeCount;i>uint32_t(index+1);--i)c.nodes[i]=c.nodes[i-1];+ c.nodes[index+1]=original;++c.nodeCount;impl_->selectedNr=index+1;+ if(impl_->selectedColour>index)++impl_->selectedColour;+ if(!impl_->revalidate(true)){+ const auto error=impl_->validation.message;c=before;impl_->selectedNr=selected;+ impl_->selectedColour=colourSelected;+ impl_->revalidate();emit notice(utf8Of(error),true);return -1;+ }+ emit chainChanged();emit settingsChanged();return index+1;+}+bool QmlPlayerBridge::removeEffect(int index) {auto& c = impl_->chain;if (index < 0 || uint32_t(index) >= c.nodeCount) return false;const auto& info = engine::effectInfo(c.nodes[index].type);if (info.mustBeLast) { emit notice(tr("补帧固定为最后一步,不能删除"), true); return false; }- for (uint32_t i = uint32_t(index); i + 1 < c.nodeCount; ++i) c.nodes[i] = c.nodes[i + 1];- --c.nodeCount;- impl_->revalidate();+ const bool live=c.mode==engine::ChainMode::Node||c.nodes[index].type==engine::EffectType::NrEnhance||c.nodes[index].type==engine::EffectType::Color;+ const auto before=c; const int selected=impl_->selectedNr,colourSelected=impl_->selectedColour;+ const auto previousLayout = impl_->layout;+ if (c.mode == engine::ChainMode::Node) {+ const auto result = impl_->layout.remove(c, impl_->layout.ids[index]);+ if (!result.accepted) { emit notice(utf8Of(result.message), true); return false; }+ } else {+ for (uint32_t i = uint32_t(index); i + 1 < c.nodeCount; ++i) c.nodes[i] = c.nodes[i + 1];+ --c.nodeCount;+ }+ if(impl_->selectedNr==index)impl_->selectedNr=-1;+ else if(impl_->selectedNr>index)--impl_->selectedNr;+ if(impl_->selectedColour==index)impl_->selectedColour=-1;+ else if(impl_->selectedColour>index)--impl_->selectedColour;+ if(!impl_->revalidate(live)){+ const auto error=impl_->validation.message;c=before;impl_->layout=previousLayout;impl_->selectedNr=selected;+ impl_->selectedColour=colourSelected;+ impl_->revalidate();emit notice(utf8Of(error),true);return false;+ }emit chainChanged();emit settingsChanged();return true;@@ -1394,6 +4356,10 @@ bool QmlPlayerBridge::removeEffect(int index) {bool QmlPlayerBridge::moveEffect(int from, int to) {auto& c = impl_->chain;if (from < 0 || to < 0 || uint32_t(from) >= c.nodeCount || uint32_t(to) >= c.nodeCount) return false;+ if (c.mode == engine::ChainMode::Node) {+ if (from == to) return true;+ return insertNodeAfter(impl_->layout.ids[from], impl_->layout.ids[to]);+ }// The two pinned stages cannot be dragged; the UI greys them, and the// engine refuses them too so a script cannot route around the UI.if (engine::effectInfo(c.nodes[from].type).mustBeLast ||@@ -1401,19 +4367,28 @@ bool QmlPlayerBridge::moveEffect(int from, int to) {emit notice(tr("补帧固定为最后一步,不能拖动"), true);return false;}+ const auto before = c;const auto moving = c.nodes[from];if (from < to) for (int i = from; i < to; ++i) c.nodes[i] = c.nodes[i + 1];else for (int i = from; i > to; --i) c.nodes[i] = c.nodes[i - 1];c.nodes[to] = moving;- const auto before = impl_->chain;- impl_->revalidate();+ impl_->revalidate(true);if (!impl_->validation.accepted) {+ const auto error=impl_->validation.message;impl_->chain = before;impl_->revalidate();- emit notice(utf8Of(impl_->validation.message), true);+ emit notice(utf8Of(error), true);return false;}+ const auto remap=[&](int i){+ if(i==from)return to;+ if(from<to&&i>from&&i<=to)return i-1;+ if(from>to&&i>=to&&i<from)return i+1;+ return i;+ };+ impl_->selectedNr=remap(impl_->selectedNr);+ impl_->selectedColour=remap(impl_->selectedColour);emit chainChanged();emit settingsChanged();return true;@@ -1424,15 +4399,33 @@ bool QmlPlayerBridge::setEffectEnabled(int index, bool enabled) {if (index < 0 || uint32_t(index) >= c.nodeCount) return false;if (c.nodes[index].enabled == enabled) return true;c.nodes[index].enabled = enabled;- impl_->revalidate();+ if(!impl_->revalidate(true)){+ const auto error=impl_->validation.message;c.nodes[index].enabled=!enabled;+ impl_->revalidate();emit notice(utf8Of(error),true);return false;+ }emit chainChanged();emit settingsChanged();return true;}+QVariantMap QmlPlayerBridge::nodeAnchors() const { return impl_->anchors; }+bool QmlPlayerBridge::setNodeAnchor(const QString& key, double x, double y) {+ if ((key != QLatin1String("input") && key != QLatin1String("flow") && key != QLatin1String("output")) ||+ !std::isfinite(x) || !std::isfinite(y) || std::abs(x) > 1000000 || std::abs(y) > 1000000) return false;+ impl_->anchors[key] = QVariantMap{{"x", x}, {"y", y}};+ if (!impl_->anchorsFile.empty()) {+ QFile file(QString::fromStdWString(impl_->anchorsFile.wstring()));+ if (file.open(QIODevice::WriteOnly | QIODevice::Truncate))+ file.write(QJsonDocument(QJsonObject::fromVariantMap(impl_->anchors)).toJson(QJsonDocument::Compact));+ else veyra::log::warn("ui-node", "node anchor positions not saved");+ }+ emit nodeAnchorsChanged();+ return true;+}bool QmlPlayerBridge::setEffectPosition(int index, double x, double y) {auto& c = impl_->chain;- if (index < 0 || uint32_t(index) >= c.nodeCount) return false;+ if (index < 0 || uint32_t(index) >= c.nodeCount || !std::isfinite(x) || !std::isfinite(y) ||+ std::abs(x) > 1000000 || std::abs(y) > 1000000) return false;c.nodes[index].viewX = float(x);c.nodes[index].viewY = float(y);// Positions never affect the picture, so this deliberately does not@@ -1461,26 +4454,93 @@ QVariantMap QmlPlayerBridge::effectDescriptor(const QString& type) const {// --- presets ----------------------------------------------------------------bool QmlPlayerBridge::applyPresetIndex(int index) {if (index < 0 || size_t(index) >= impl_->facade.presets().entries().size()) return false;- if (!impl_->facade.applyPreset(size_t(index))) return false;- impl_->chain = engine::toChain(impl_->facade.pendingSettings());- impl_->revalidate();+ const auto mode = impl_->chain.mode;+ const auto& entry = impl_->facade.presets().entries()[size_t(index)];+ if (entry.kind != mode) { emit notice(tr("请先切换到预设对应的编辑模式"), true); return false; }+ const auto previous = impl_->facade.pendingSettings();+ const auto oldGlobals = impl_->draftGlobals;+ auto nextGlobals = oldGlobals;+ auto settings = previous;+ auto candidate = impl_->chain;+ const auto oldLayout = impl_->layout;+ auto nextLayout = oldLayout;+ engine::ChainValidation validation;+ if (mode == engine::ChainMode::Node) {+ auto document = std::make_unique<engine::NodeEditorDocument>();+ document->nodes = candidate; document->layout = nextLayout; document->globals = oldGlobals;+ validation = engine::PresetLibrary::applyToEditor(entry, *document, settings);+ candidate = document->nodes; nextLayout = document->layout;+ nextGlobals = document->globals.value_or(engine::ChainGlobalSettings::capture(settings));+ // Keep the facade on accepted values until revalidate projects the new+ // document. Audio/non-chain preset fields are retained in this copy.+ engine::fromChain(impl_->activeRuntime(), settings);+ engine::ChainGlobalSettings::capture(previous).apply(settings);+ } else validation = engine::PresetLibrary::applyToChain(entry, candidate, settings);+ if (!validation.accepted) { emit notice(utf8Of(validation.message), true); return false; }+ if (const auto error = settings.validate(); !error.empty()) {+ veyra::log::error("qml-preset", error);+ emit notice(tr("预设参数无效,已保留原状态"), true); return false;+ }+ // Partial presets do not change the current editing target. Colour-only+ // insertion/removal can shift NR indices, so retain the instance ordinal.+ const auto remapSelection = [&](int selected, engine::EffectType type) {+ if (entry.contents & engine::presetContentMask(engine::PresetContent::Chain)) return -1;+ if (selected < 0) return -1;+ uint32_t ordinal = 0;+ for (int i = 0; i < selected; ++i) if (impl_->chain.nodes[i].type == type) ++ordinal;+ for (uint32_t i = 0; i < candidate.nodeCount; ++i) {+ if (candidate.nodes[i].type != type) continue;+ if (ordinal == 0) return int(i);+ --ordinal;+ }+ return -1;+ };+ const int selectedNr = remapSelection(impl_->nrIndex(), engine::EffectType::NrEnhance);+ const int selectedColour = remapSelection(impl_->colourIndex(), engine::EffectType::Color);+ auto oldChain = std::make_unique<engine::EffectChain>(impl_->chain);+ impl_->chain = candidate;+ impl_->layout = nextLayout;+ if (mode == engine::ChainMode::Node) {+ impl_->draftGlobals = nextGlobals;+ engine::ChainGlobalSettings::capture(previous).apply(settings);+ }+ impl_->facade.setPending(settings);+ if (!impl_->revalidate(true, &previous)) {+ const auto error = impl_->validation.message; impl_->chain = *oldChain; impl_->layout = oldLayout;+ impl_->draftGlobals = oldGlobals;+ impl_->facade.setPending(previous); impl_->revalidate();+ emit notice(utf8Of(error), true); return false;+ }+ impl_->selectedNr = selectedNr;+ impl_->selectedColour = selectedColour;emit settingsChanged();emit chainChanged();return true;}void QmlPlayerBridge::enqueueExportFile(const QString& input, const QString& output) {+ QString error;+ auto settings = impl_->exportSettings(error);+ if (!settings) { emit notice(error, true); return; }if (input.isEmpty() || output.isEmpty()) { emit notice(tr("队列项目缺少输入或输出"), true); return; }- auto settings = impl_->facade.pendingSettings();- engine::fromChain(impl_->chain, settings);- settings.exportBitrateMbps = impl_->exportBitrateMbps;- const bool queued = impl_->exportJob.enqueue(wideOf(input), wideOf(output), settings, impl_->exportHevc, 0,- -1, 0.0, 0.0, impl_->exportRateControl);+ if (!QFileInfo(input).isFile()) { emit notice(tr("队列输入文件不存在"), true); return; }+ const bool currentFile = wideOf(input) == impl_->sourceLabel;+ const bool busy = impl_->exportJob.poll().active() || impl_->exportJob.queuedCount() > 0;+ const bool queued = impl_->exportJob.enqueue(wideOf(input), wideOf(output), *settings, impl_->exportHevc, 0,+ currentFile ? impl_->snapshot.selectedAudioTrack : -1,+ currentFile ? impl_->exportTrimStartSeconds : 0.0,+ currentFile ? impl_->exportTrimEndSeconds : 0.0,+ impl_->exportRateControl);if (!queued) { emit notice(tr("加入导出队列失败;详见诊断"), true); return; }+ impl_->exportRows.push_back({wideOf(input), wideOf(output), busy ? QStringLiteral("queued") : QStringLiteral("running"), 0.0, {}});pollExport();}void QmlPlayerBridge::addExportFilesDialog() {+ if (impl_->chain.mode == engine::ChainMode::Node) {+ emit notice(tr("节点链尚未接入导出执行器,请切换列表模式后导出"), true);+ return;+ }const auto files = QFileDialog::getOpenFileNames(nullptr, tr("加入导出队列"), QString(),tr("媒体文件 (*.mp4 *.mkv *.mov *.avi *.webm *.ts *.m2ts);;所有文件 (*)"));if (files.isEmpty()) return;@@ -1506,14 +4566,30 @@ bool QmlPlayerBridge::selectExportPreset(int index) {bool QmlPlayerBridge::savePresetAs(const QString& name, int contentsMask, bool nodeMode) {if (name.isEmpty()) { emit notice(tr("预设需要一个名字"), true); return false; }+ if (nodeMode != (impl_->chain.mode == engine::ChainMode::Node)) {+ emit notice(tr("请先切换到要保存的编辑模式"), true); return false;+ }engine::PresetEntry entry;entry.name = wideOf(name);entry.kind = nodeMode ? engine::ChainMode::Node : engine::ChainMode::List;entry.contents = uint32_t(contentsMask);entry.chain = impl_->chain;+ entry.globals=engine::ChainGlobalSettings::capture(impl_->facade.pendingSettings());entry.color = impl_->facade.pendingSettings().color;entry.fg.multiplier = impl_->facade.pendingSettings().multiplier;+ entry.fg.backend = impl_->facade.pendingSettings().frameGenerationBackend;+ entry.audioSync = impl_->facade.pendingSettings().audioSync;entry.audioOffsetMs = impl_->facade.pendingSettings().audioOffsetMs;+ if (nodeMode) {+ entry.nodeConfiguration = impl_->currentSession().configurations[1];+ entry.chain = entry.nodeConfiguration->chain;+ if (const auto* color = impl_->chain.firstOf(engine::EffectType::Color)) {+ entry.color = color->color; entry.color.enabled = color->enabled;+ }+ entry.fg.multiplier = uint32_t(fgMultiplier());+ entry.fg.backend = impl_->draftGlobals.fgBackend;+ entry.globals=impl_->draftGlobals;+ }const bool ok = impl_->facade.savePreset(entry, false);if (ok) emit presetsChanged();else emit notice(tr("保存预设失败: %1").arg(utf8Of(impl_->facade.error())), true);@@ -1580,9 +4656,11 @@ int QmlPlayerBridge::defaultPresetIndex() const {}bool QmlPlayerBridge::setDefaultPreset(int index) {- if (index < 0 || size_t(index) >= impl_->facade.presets().entries().size()) return false;- const bool ok = impl_->facade.presets().setDefault(size_t(index));+ if (index < -1 || (index >= 0 && size_t(index) >= impl_->facade.presets().entries().size())) return false;+ const bool ok = index == -1 ? impl_->facade.presets().clearDefault()+ : impl_->facade.presets().setDefault(size_t(index));if (ok) emit presetsChanged();+ else emit notice(tr("默认预设保存失败:") + utf8Of(impl_->facade.presets().error()), true);return ok;}@@ -1604,4 +4682,748 @@ void QmlPlayerBridge::clearRecentFiles() {emit recentFilesChanged();}++// --- audio sync (1.4.4 声音补偿, #12) ------------------------------------------+int QmlPlayerBridge::audioSyncMode() const { return int(settings().audioSync); }+void QmlPlayerBridge::setAudioSyncMode(int value) {+ if (value < 0 || value > 2) return;+ auto s = settings();+ if (int(s.audioSync) == value) return;+ s.audioSync = static_cast<engine::AudioSyncMode>(value);+ if (!impl_->commit(std::move(s))) return;+ impl_->prefs[QStringLiteral("audioSync")] = value;+ if (!impl_->savePrefs()) veyra::log::warn("ui-prefs", "sound sync mode not saved");+ emit settingsChanged();+}+bool QmlPlayerBridge::audioSyncLive() const {+ const auto& s = impl_->snapshot;+ return s.running && (s.capture || s.remotePlay);+}+double QmlPlayerBridge::audioCompensationMs() const {+ return audioSyncLive() ? impl_->snapshot.captureAudio.compensationMs : 0.0;+}++// --- performance orbs and status light (#13) --------------------------------+double QmlPlayerBridge::gpuUtilization() const { return std::max(0.0, impl_->gpuUtil.load()); }+bool QmlPlayerBridge::gpuUtilizationKnown() const { return impl_->gpuUtil.load() >= 0.0; }+QString QmlPlayerBridge::runStatus() const { return impl_->runStatus; }+QString QmlPlayerBridge::runStatusLevel() const { return impl_->runLevel; }+QString QmlPlayerBridge::runStatusDetail() const { return impl_->runDetail; }+double QmlPlayerBridge::outputRateRatio() const { return impl_->rateRatio; }++void QmlPlayerBridge::startGpuSampler() {+ // Task Manager's source: the "GPU Engine" utilization counters, summed per+ // engine type across processes, busiest type wins. Sampled once a second on+ // its own thread; -1 means the counters are unavailable.+ auto* impl = impl_.get();+ impl->gpuSampler = std::jthread([impl](std::stop_token stop) {+ PDH_HQUERY query = nullptr; PDH_HCOUNTER counter = nullptr;+ if (PdhOpenQueryW(nullptr, 0, &query) != ERROR_SUCCESS) return;+ if (PdhAddEnglishCounterW(query, L"\\GPU Engine(*)\\Utilization Percentage", 0, &counter) != ERROR_SUCCESS) {+ PdhCloseQuery(query); veyra::log::warn("perf", "GPU engine counters unavailable"); return;+ }+ PdhCollectQueryData(query);+ std::vector<unsigned char> buffer;+ while (!stop.stop_requested()) {+ for (int i = 0; i < 10 && !stop.stop_requested(); ++i) std::this_thread::sleep_for(std::chrono::milliseconds(100));+ if (stop.stop_requested()) break;+ if (PdhCollectQueryData(query) != ERROR_SUCCESS) continue;+ DWORD bytes = 0, count = 0;+ if (PdhGetFormattedCounterArrayW(counter, PDH_FMT_DOUBLE, &bytes, &count, nullptr) != PDH_MORE_DATA) continue;+ buffer.resize(bytes);+ auto* items = reinterpret_cast<PDH_FMT_COUNTERVALUE_ITEM_W*>(buffer.data());+ if (PdhGetFormattedCounterArrayW(counter, PDH_FMT_DOUBLE, &bytes, &count, items) != ERROR_SUCCESS) continue;+ std::map<std::wstring, double> byType;+ for (DWORD i = 0; i < count; ++i) {+ if (items[i].FmtValue.CStatus != PDH_CSTATUS_VALID_DATA && items[i].FmtValue.CStatus != PDH_CSTATUS_NEW_DATA) continue;+ const std::wstring name = items[i].szName ? items[i].szName : L"";+ const auto at = name.find(L"engtype_");+ byType[at == std::wstring::npos ? std::wstring{} : name.substr(at + 8)] += items[i].FmtValue.doubleValue;+ }+ double busiest = 0;+ for (const auto& [type, value] : byType) busiest = std::max(busiest, value);+ impl->gpuUtil = std::clamp(busiest, 0.0, 100.0);+ }+ PdhCloseQuery(query);+ });+}++void QmlPlayerBridge::updateRunStatus() {+ auto& i = *impl_;+ const auto& s = i.snapshot;+ i.history.sample(s);+ const auto& f = s.metrics.flow;+ const bool active = s.running && !s.image && s.transport == engine::TransportState::Playing;+ QString status = tr("待机"), level = QStringLiteral("idle");+ if (s.failed) { status = tr("错误"); level = QStringLiteral("err"); }+ else if (s.remoteRecovering) { status = tr("恢复中"); level = QStringLiteral("warn"); }+ else if (active && !s.applying && f.rateWindowReady) {+ status = QString::fromWCharArray(i.history.rateStatus(s));+ level = status == tr("正常") ? QStringLiteral("ok") : QStringLiteral("warn");+ }+ else if (s.applying && s.running) { status = tr("调整中"); level = QStringLiteral("warn"); }+ else if (active) status = tr("采样中");+ else if (s.transport == engine::TransportState::Paused) status = tr("已暂停");+ QStringList detail;+ if (s.running && !s.image) {+ if (s.applied.multiplier > 1) {+ QString backend;+ switch (s.applied.frameGenerationBackend) {+ case engine::FrameGenerationBackend::Dlss: backend = tr("DLSS"); break;+ case engine::FrameGenerationBackend::XeSS: backend = tr("XeSS"); break;+ case engine::FrameGenerationBackend::Fsr: backend = tr("FSR 3.1"); break;+ case engine::FrameGenerationBackend::Fsr4: backend = tr("FSR 4 ML"); break;+ }+ detail << tr("补帧 %1X · %2").arg(s.applied.multiplier)+ .arg(backend);+ }+ else detail << tr("未补帧");+ if (s.applied.multiplier > 1 && (s.fgBudgetLimited || s.xessGenerationSuppressed)) detail << tr("调度降档");+ if (s.nominalSourceFps > 0.01) detail << tr("源 %1 fps").arg(s.nominalSourceFps, 0, 'f', 2);+ }+ // 1.4.4 DashboardHistory: target = source x multiplier (half-rate capture+ // halves it); actual = what reached present (XeSS: its SDK submit rate).+ double ratio = -1.0;+ if (active && f.rateWindowReady) {+ const bool measuredInput = s.capture && s.captureReceived > 30 && s.captureFps > 0;+ const double source = measuredInput ? std::min(s.nominalSourceFps, s.captureFps) : s.nominalSourceFps;+ const bool xessSink = s.applied.multiplier > 1 && engine::presentSinkFrameGeneration(s.applied.frameGenerationBackend);+ const double actual = xessSink ? f.xessSdkSubmitFps : f.presentSubmitFps;+ const double target = source * (s.captureHalfRate ? 0.5 : 1.0) * s.applied.multiplier;+ if (target > 0) ratio = actual / target;+ }+ const bool ratioChanged = std::abs(ratio - i.rateRatio) > 0.005;+ i.rateRatio = ratio;+ // Frame-time line: the submit interval while playing (a real display rate is+ // not available here), 48 samples = 12 s at the 250 ms cadence.+ if (active && submitFpsKnown() && submitFps() > 0.5) {+ i.frameTimes.push_back(1000.0 / submitFps());+ while (i.frameTimes.size() > 48) i.frameTimes.pop_front();+ } else if (!s.running && !i.frameTimes.empty()) i.frameTimes.clear();+ const QString text = detail.join(QStringLiteral(" · "));+ const double gpu = i.gpuUtil.load();+ const bool changed = ratioChanged || active || status != i.runStatus || level != i.runLevel || text != i.runDetail || std::abs(gpu - i.gpuPublished) > 0.05;+ i.runStatus = status; i.runLevel = level; i.runDetail = text; i.gpuPublished = gpu;+ if (changed) emit perfChanged();+}++// --- NR protection regions drawn on the picture (#8) ------------------------+namespace {+// Outline of the region being drawn, on a layered child of the video window+// (the swapchain is never read or touched), as 1.4.4's ProtectionOverlay.+void drawProtectionOutline(HWND overlay, HWND video, RECT box, bool ellipse) {+ RECT r{}; GetClientRect(video, &r);+ if (r.right < 1 || r.bottom < 1) return;+ SetWindowPos(overlay, HWND_TOP, 0, 0, r.right, r.bottom, SWP_NOACTIVATE);+ BITMAPINFO info{}; info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); info.bmiHeader.biWidth = r.right;+ info.bmiHeader.biHeight = -r.bottom; info.bmiHeader.biPlanes = 1; info.bmiHeader.biBitCount = 32;+ HDC screen = GetDC(nullptr), memory = CreateCompatibleDC(screen); void* bits = nullptr;+ HBITMAP bitmap = CreateDIBSection(screen, &info, DIB_RGB_COLORS, &bits, nullptr, 0);+ if (!bitmap || !bits) { if (bitmap) DeleteObject(bitmap); DeleteDC(memory); ReleaseDC(nullptr, screen); return; }+ auto previous = SelectObject(memory, bitmap);+ memset(bits, 0, size_t(r.right) * size_t(r.bottom) * 4);+ {+ Gdiplus::Bitmap canvas(r.right, r.bottom, r.right * 4, PixelFormat32bppPARGB, static_cast<BYTE*>(bits));+ Gdiplus::Graphics g(&canvas); g.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);+ Gdiplus::Pen pen(Gdiplus::Color(255, 255, 138, 61), 2.0f);+ Gdiplus::SolidBrush fill(Gdiplus::Color(40, 255, 138, 61));+ const Gdiplus::Rect rect(box.left, box.top, std::max(1L, box.right - box.left), std::max(1L, box.bottom - box.top));+ if (ellipse) { g.FillEllipse(&fill, rect); g.DrawEllipse(&pen, rect); }+ else { g.FillRectangle(&fill, rect); g.DrawRectangle(&pen, rect); }+ }+ SIZE size{r.right, r.bottom}; POINT origin{}; BLENDFUNCTION blend{AC_SRC_OVER, 0, 255, AC_SRC_ALPHA};+ if (UpdateLayeredWindow(overlay, screen, nullptr, &size, memory, &origin, 0, &blend, ULW_ALPHA))+ ShowWindow(overlay, SW_SHOWNOACTIVATE);+ SelectObject(memory, previous); DeleteObject(bitmap); DeleteDC(memory); ReleaseDC(nullptr, screen);+}+}++QVariantList QmlPlayerBridge::protectionRegions() const {+ QVariantList out;+ const auto& p = settings().protection;+ for (int i = 0; i < int(p.regions.size()); ++i) {+ const auto& q = p.regions[size_t(i)];+ if (q.empty()) continue;+ out << QVariantMap{{"index", i}, {"left", double(q.left)}, {"top", double(q.top)}, {"right", double(q.right)},+ {"bottom", double(q.bottom)}, {"ellipse", q.ellipse}};+ }+ return out;+}+QString QmlPlayerBridge::protectionDrawShape() const { return impl_->protDraw; }++bool QmlPlayerBridge::editProtection(const std::function<bool(engine::ChainNode&)>& edit) {+ if (impl_->chain.mode != engine::ChainMode::List) { emit notice(tr("NR 保护区域仅在列表模式可用"), true); return false; }+ for (uint32_t i = 0; i < impl_->chain.nodeCount; ++i) {+ auto& node = impl_->chain.nodes[i];+ if (node.type != engine::EffectType::Protection) continue;+ const auto before = node;+ if (!edit(node)) return false;+ if (node == before) return true;+ const bool accepted = impl_->revalidate(true);+ if (!accepted) { const auto error = impl_->validation.message; node = before; impl_->revalidate(); emit notice(utf8Of(error), true); }+ emit settingsChanged(); emit chainChanged();+ return accepted;+ }+ emit notice(tr("处理链中没有 NR 保护节点,未更改设置"), true);+ return false;+}++bool QmlPlayerBridge::beginProtectionDraw(const QString& shape) {+ auto& i = *impl_;+ if (shape.isEmpty()) {+ if (i.protOverlay) ShowWindow(i.protOverlay, SW_HIDE);+ if (!i.protDraw.isEmpty()) { i.protDraw.clear(); emit protectionDrawChanged(); }+ return true;+ }+ if (shape != QLatin1String("rect") && shape != QLatin1String("ellipse")) return false;+ if (i.chain.mode != engine::ChainMode::List) { emit notice(tr("NR 保护区域仅在列表模式可用"), true); return false; }+ if (!i.snapshot.running || !i.videoWindow) { emit notice(tr("请先打开视频,再在画面上绘制保护区域"), true); return false; }+ bool space = false;+ for (const auto& q : settings().protection.regions) space |= q.empty();+ if (!space) { emit notice(tr("最多 4 个保护区域,请先删除一个"), true); return false; }+ i.protDraw = shape;+ emit protectionDrawChanged();+ return true;+}++void QmlPlayerBridge::updateProtectionDraw(double x0, double y0, double x1, double y1) {+ auto& i = *impl_;+ if (i.protDraw.isEmpty() || !i.videoWindow) return;+ if (!i.protOverlay) { ensureGdiplus(); i.protOverlay = createSubtitleOverlay(i.videoWindow); }+ if (!i.protOverlay) return;+ RECT client{}; GetClientRect(i.videoWindow, &client);+ const auto px = [&](double f, LONG extent) { return LONG(std::lround(std::clamp(f, 0.0, 1.0) * extent)); };+ const RECT box{px(std::min(x0, x1), client.right), px(std::min(y0, y1), client.bottom),+ px(std::max(x0, x1), client.right), px(std::max(y0, y1), client.bottom)};+ drawProtectionOutline(i.protOverlay, i.videoWindow, box, i.protDraw == QLatin1String("ellipse"));+}++bool QmlPlayerBridge::commitProtectionDraw(double x0, double y0, double x1, double y1) {+ auto& i = *impl_;+ const bool ellipse = i.protDraw == QLatin1String("ellipse");+ const bool armed = !i.protDraw.isEmpty();+ beginProtectionDraw(QString());+ if (!armed || !i.videoWindow) return false;+ RECT client{}; GetClientRect(i.videoWindow, &client);+ if (client.right < 1 || client.bottom < 1) return false;+ const double w = client.right, h = client.bottom;+ // Too small to be intended (1.4.4: at least 3 px each way).+ if (std::abs(x1 - x0) * w < 3 || std::abs(y1 - y0) * h < 3) return false;+ // Host pixels -> source-normalized, through the current zoom/pan (1.4.4).+ const auto e = i.snapshot.metrics.resolution.output;+ const auto view = i.engine.previewView();+ const auto a = view.sourcePoint(float(x0 * w), float(y0 * h), float(w), float(h), float(e.width), float(e.height));+ const auto b = view.sourcePoint(float(x1 * w), float(y1 * h), float(w), float(h), float(e.width), float(e.height));+ engine::ProtectionRect q{std::clamp(std::min(a.first, b.first), 0.0f, 1.0f), std::clamp(std::min(a.second, b.second), 0.0f, 1.0f),+ std::clamp(std::max(a.first, b.first), 0.0f, 1.0f), std::clamp(std::max(a.second, b.second), 0.0f, 1.0f), ellipse};+ if (q.empty()) return false;+ const bool ok = editProtection([&](engine::ChainNode& node) {+ for (auto& slot : node.protection.regions)+ if (slot.empty()) { slot = q; node.enabled = true; node.protection.enabled = true; return true; }+ emit notice(tr("最多 4 个保护区域,请先删除一个"), true);+ return false;+ });+ veyra::log::info("ui-protection", std::format("{} accepted={} bounds={:.3f},{:.3f},{:.3f},{:.3f} source-normalized NR-only",+ ellipse ? "ellipse" : "rectangle", ok, q.left, q.top, q.right, q.bottom));+ return ok;+}++bool QmlPlayerBridge::removeProtectionRegion(int index) {+ if (index < 0 || index >= int(engine::ProtectionSettings{}.regions.size())) return false;+ return editProtection([&](engine::ChainNode& node) {+ // Keep the remaining regions packed in order.+ auto& regions = node.protection.regions;+ for (int k = index; k + 1 < int(regions.size()); ++k) regions[size_t(k)] = regions[size_t(k + 1)];+ regions.back() = {};+ return true;+ });+}+bool QmlPlayerBridge::clearProtectionRegions() {+ return editProtection([](engine::ChainNode& node) { node.protection.regions = {}; return true; });+}+bool QmlPlayerBridge::setProtectionFeather(double pixels) {+ if (!std::isfinite(pixels) || pixels < 0 || pixels > 64) return false;+ return editProtection([&](engine::ChainNode& node) { node.protection.featherPixels = float(pixels); return true; });+}+++// --- design gap A1-A5: flow, cadence, presentation ----------------------------+int QmlPlayerBridge::hdrOutputMode()const{return int(settings().hdrOutputMode);}+void QmlPlayerBridge::setHdrOutputMode(int value){if(value<0||value>1)return;auto s=settings();if(int(s.hdrOutputMode)==value)return;s.hdrOutputMode=engine::HdrOutputMode(value);if(impl_->commit(std::move(s)))emit settingsChanged();}+int QmlPlayerBridge::fgMotionSource()const{return engine::motionUsesFlow(settings().fgMotion,settings().frameGenerationBackend)?1:0;}+void QmlPlayerBridge::setFgMotionSource(int value){if(value<0||value>1)return;auto s=settings();s.fgMotion=engine::MotionSource(value);if(impl_->commit(std::move(s)))emit settingsChanged();}+int QmlPlayerBridge::srMotionSource()const{return engine::motionUsesFlow(settings().srMotion)?1:0;}+void QmlPlayerBridge::setSrMotionSource(int value){if(value<0||value>1)return;auto s=settings();s.srMotion=engine::MotionSource(value);if(impl_->commit(std::move(s)))emit settingsChanged();}+int QmlPlayerBridge::nrMotionSource()const{return engine::motionUsesFlow(settings().nrMotion)?1:0;}+void QmlPlayerBridge::setNrMotionSource(int value){if(value<0||value>1)return;auto s=settings();s.nrMotion=engine::MotionSource(value);if(impl_->commit(std::move(s)))emit settingsChanged();}+int QmlPlayerBridge::flowQuality() const { return int(settings().flow); }+void QmlPlayerBridge::setFlowQuality(int value) {+ if (value < 0 || value > 2) return;+ auto s = settings();+ if (int(s.flow) == value) return;+ s.flow = static_cast<engine::FlowQuality>(value);+ if (!impl_->commit(std::move(s))) { emit notice(tr("引擎未接受运动估算质量,原设置保留"), true); return; }+ emit settingsChanged();+}+bool QmlPlayerBridge::amdFlowHalf() const { return settings().amdFlowHalfResolution; }+void QmlPlayerBridge::setAmdFlowHalf(bool value) {+ auto s = settings();+ if (s.amdFlowHalfResolution == value) return;+ s.amdFlowHalfResolution = value;+ if (!impl_->commit(std::move(s))) { emit notice(tr("引擎未接受 AMD 性能档,原设置保留"), true); return; }+ emit settingsChanged();+}+int QmlPlayerBridge::contentRate() const { return int(settings().content); }+void QmlPlayerBridge::setContentRate(int value) {+ if (value < 0 || value > int(engine::ContentRate::Capture60To30)) return;+ auto s = settings();+ if (int(s.content) == value) return;+ s.content = static_cast<engine::ContentRate>(value);+ if (!impl_->commit(std::move(s))) { emit notice(tr("引擎未接受内容节奏,原设置保留"), true); return; }+ // A player setting, not part of either chain: kept in the shell preferences.+ impl_->prefs[QStringLiteral("contentRate")] = value;+ if (!impl_->savePrefs()) veyra::log::warn("ui-prefs", "content cadence not saved");+ emit settingsChanged();+}++int QmlPlayerBridge::displaySync() const { return int(impl_->presentation.display); }+void QmlPlayerBridge::setPresentationFullscreen(bool value) {+ if(impl_->presentation.fullscreen==value)return;+ impl_->presentation.fullscreen=value;+ impl_->engine.requestPresentation(impl_->presentation);+ emit presentationChanged();+}+double QmlPlayerBridge::previewAspect() const {+ const int mode=impl_->screenFillActive?2:impl_->aspectMode;+ if(mode==4)return 16.0/9;if(mode==5)return 4.0/3;if(mode==6)return 21.0/9;+ const auto e=impl_->snapshot.metrics.resolution.output;+ if(mode==1&&e.height)return double(e.width)/e.height;+ return sourceAspect();+}+void QmlPlayerBridge::setDisplaySync(int value) {+ if (value < 0 || value > 2 || int(impl_->presentation.display) == value) return;+ impl_->presentation.display = static_cast<engine::DisplaySync>(value);+ applyPresentation();+}+int QmlPlayerBridge::outputRateMode() const { return int(impl_->presentation.outputRate); }+void QmlPlayerBridge::setOutputRateMode(int value) {+ if (value < 0 || value > 2 || int(impl_->presentation.outputRate) == value) return;+ impl_->presentation.outputRate = static_cast<engine::OutputRateMode>(value);+ applyPresentation();+}+double QmlPlayerBridge::outputCustomFps() const { return impl_->presentation.customFps; }+void QmlPlayerBridge::setOutputCustomFps(double value) {+ if (!std::isfinite(value) || value < 1.0 || value > 1000.0) { emit notice(tr("输出上限需在 1–1000 fps 之间"), true); return; }+ if (std::abs(impl_->presentation.customFps - value) < 1e-6) return;+ impl_->presentation.customFps = value;+ applyPresentation();+}+bool QmlPlayerBridge::presentationOwned() const { return impl_->snapshot.presentationProviderOwned; }+QString QmlPlayerBridge::presentationStatus() const { return utf8Of(impl_->snapshot.presentationStatus); }+void QmlPlayerBridge::applyPresentation() {+ auto& p = impl_->presentation;+ if (!p.valid()) return;+ impl_->engine.requestPresentation(p);+ impl_->prefs[QStringLiteral("presentation")] = QVariantMap{+ {"lowQueue", p.enabled}, {"display", int(p.display)}, {"outputRate", int(p.outputRate)}, {"customFps", p.customFps}};+ if (!impl_->savePrefs()) veyra::log::warn("ui-prefs", "presentation settings not saved");+ veyra::log::info("ui-presentation", std::format("lowQueue={} display={} outputRate={} customFps={:.3f}",+ p.enabled, int(p.display), int(p.outputRate), p.customFps));+ emit presentationChanged();+ emit settingsChanged();+}++// --- design gap B8-B11: compare and aspect ------------------------------------+int QmlPlayerBridge::compareMode() const { return impl_->compareMode; }+void QmlPlayerBridge::setCompareMode(int value) {+ if (value < 0 || value > 2 || impl_->compareMode == value) return;+ impl_->compareMode = value;+ if (!impl_->holdKeyDown) impl_->engine.comparison(value, impl_->compareBase, float(impl_->compareSplit));+ veyra::log::info("ui-compare", std::format("mode={} base={} split={:.3f}", value, impl_->compareBase, impl_->compareSplit));+ emit compareChanged();+}+bool QmlPlayerBridge::compareBase() const { return impl_->compareBase; }+void QmlPlayerBridge::setCompareBase(bool value) {+ if (impl_->compareBase == value) return;+ impl_->compareBase = value;+ if (!impl_->holdKeyDown) impl_->engine.comparison(impl_->compareMode, value, float(impl_->compareSplit));+ emit compareChanged();+}+double QmlPlayerBridge::compareSplit() const { return impl_->compareSplit; }+void QmlPlayerBridge::setCompareSplitAt(double fx) {+ // 1.4.4 AppShell: the split is a fraction of the displayed picture, which is+ // letterboxed and may be zoomed/panned inside the host.+ auto& i = *impl_;+ if (!i.videoWindow || !std::isfinite(fx)) return;+ RECT r{}; GetClientRect(i.videoWindow, &r);+ if (r.right < 1 || r.bottom < 1) return;+ const auto e = i.snapshot.metrics.resolution.output;+ const auto view = i.engine.previewView();+ float contentWidth = float(r.right);+ if (e.width && e.height) contentWidth = view.renderedSize(float(r.right),float(r.bottom),float(e.width),float(e.height)).first;+ const float left = r.right * .5f - contentWidth * view.centerX;+ i.compareSplit = std::clamp((float(fx) * r.right - left) / std::max(1.0f, contentWidth), 0.0f, 1.0f);+ if (!i.holdKeyDown) i.engine.comparison(i.compareMode, i.compareBase, float(i.compareSplit));+ emit compareChanged();+}+int QmlPlayerBridge::aspectMode() const { return impl_->aspectMode; }+void QmlPlayerBridge::setAspectMode(int value) {+ if (value < 0 || value > 6 || impl_->aspectMode == value) return;+ impl_->aspectMode = value;+ impl_->prefs[QStringLiteral("aspect")] = value;+ if (!impl_->savePrefs()) veyra::log::warn("ui-prefs", "aspect mode not saved");+ applyAspect(true);+ emit compareChanged();+}+void QmlPlayerBridge::applyAspect(bool force) {+ auto& i = *impl_;+ const int mode = i.screenFillActive ? 2 : i.aspectMode;+ if (!i.videoWindow) return;+ RECT r{}; GetClientRect(i.videoWindow, &r);+ const auto e = i.snapshot.metrics.resolution.output;+ const QSize client(r.right, r.bottom), image(int(e.width), int(e.height));+ if (!force && mode == i.aspectApplied && client == i.screenFitClient && image == i.screenFitImage) return;+ i.screenFitClient = client; i.screenFitImage = image; i.aspectApplied = mode;+ auto view=force?engine::PreviewView{}:i.engine.previewView();+ view.mode=mode;+ const double dar=sourceAspect();+ view.displayAspect=dar>0&&image.height()>0&&std::abs(dar-double(image.width())/image.height())>.001?dar:0;+ i.engine.previewView(view);+ veyra::log::info("ui-aspect", std::format("mode={} zoom={:.3f} dar={:.4f} client={}x{} image={}x{}",mode,view.zoom,dar,+ client.width(),client.height(),image.width(),image.height()));+}++// --- design gap D18 / C15 / E20 / F21 / F24 ------------------------------------+double QmlPlayerBridge::audioSkewMs() const {+ const auto& skew = impl_->snapshot.captureAudio.skewMs;+ return audioSkewKnown() ? *skew : 0.0;+}+bool QmlPlayerBridge::audioSkewKnown() const {+ const auto& skew = impl_->snapshot.captureAudio.skewMs;+ return audioSyncLive() && skew.has_value() && std::isfinite(*skew) && std::abs(*skew) < 5000.0;+}++QString QmlPlayerBridge::exportSizeEstimate() const {+ const auto gb = [](double bytes) {+ return bytes >= 1024.0 * 1024 * 1024 ? QStringLiteral("%1 GB").arg(bytes / (1024.0 * 1024 * 1024), 0, 'f', 2)+ : QStringLiteral("%1 MB").arg(bytes / (1024.0 * 1024), 0, 'f', 0);+ };+ if (exportRunning()) {+ const double progress = exportProgress();+ const QFileInfo partial(exportTarget() + QStringLiteral(".partial"));+ if (progress > 0.02 && partial.exists() && partial.size() > 0)+ return tr("预计约 %1(按已写入 %2 推算)").arg(gb(partial.size() / progress)).arg(gb(double(partial.size())));+ return tr("开始写入后按已写入量推算");+ }+ const double end = impl_->exportTrimEndSeconds > 0 ? impl_->exportTrimEndSeconds : impl_->snapshot.duration;+ const double seconds = std::max(0.0, end - impl_->exportTrimStartSeconds);+ if (seconds <= 0) return QString();+ if (impl_->exportBitrateMbps > 0)+ return tr("约 %1(视频 %2 Mbps × %3,音轨另计)").arg(gb(impl_->exportBitrateMbps * 1e6 / 8.0 * seconds))+ .arg(impl_->exportBitrateMbps).arg(formatTime(seconds));+ return tr("恒定质量:大小取决于画面,开始后按已写入量推算");+}++QVariantMap QmlPlayerBridge::lastSource() const {+ auto saved = impl_->prefs.value(QStringLiteral("lastSource")).toMap();+ const QString kind = saved.value(QStringLiteral("kind")).toString();+ if (kind == QLatin1String("capture")) {+ if (!hasCaptureSession()) return {};+ saved[QStringLiteral("summary")] = captureSessionSummary();+ } else if (kind == QLatin1String("ps5")) {+ saved[QStringLiteral("summary")] = tr("PS5 串流 · %1").arg(saved.value(QStringLiteral("label")).toString());+ } else if (kind == QLatin1String("screen")) {+ saved[QStringLiteral("summary")] = tr("屏幕捕获 · %1").arg(saved.value(QStringLiteral("label")).toString());+ } else if (hasCaptureSession()) {+ // Before this was recorded, only capture sessions were remembered.+ return QVariantMap{{"kind", "capture"}, {"summary", captureSessionSummary()}};+ } else return {};+ return saved;+}+void QmlPlayerBridge::rememberSource(const QString& kind, const QString& label) {+ impl_->liveKind = kind;+ impl_->liveLabel = label;+ QVariantMap value{{"kind", kind}, {"label", label}};+ if (kind == QLatin1String("screen")) value[QStringLiteral("screenKind")] = screenOptions().value(QStringLiteral("kind")).toInt();+ if (impl_->prefs.value(QStringLiteral("lastSource")).toMap() == value) return;+ impl_->prefs[QStringLiteral("lastSource")] = value;+ if (!impl_->savePrefs()) veyra::log::warn("ui-prefs", "last source not saved");+ emit preferencesChanged();+}+void QmlPlayerBridge::resumeLastSource() {+ const auto last = lastSource();+ const QString kind = last.value(QStringLiteral("kind")).toString();+ veyra::log::info("ui-resume-source", "kind=" + kind.toStdString());+ if (kind == QLatin1String("capture")) { resumeCaptureSession(); return; }+ if (kind == QLatin1String("ps5")) {+#ifdef VEYRA_ENABLE_REMOTEPLAY+ ps5Load();+ if (!ps5Connect()) emit notice(tr("没能继续上次的 PS5 串流:%1").arg(impl_->ps5Status), true);+#else+ emit notice(tr("此版本不含 PS5 串流"), true);+#endif+ return;+ }+ if (kind == QLatin1String("screen")) {+ const int screenKind = last.value(QStringLiteral("screenKind")).toInt();+ if (screenOptions().value(QStringLiteral("kind")).toInt() != screenKind) setScreenOption(QStringLiteral("kind"), screenKind);+ refreshCaptureTargets();+ const QString label = last.value(QStringLiteral("label")).toString();+ for (const auto& item : screenTargets()) {+ const auto map = item.toMap();+ if (map.value(QStringLiteral("label")).toString() == label) {+ setScreenTargetId(map.value(QStringLiteral("id")).toString());+ startScreenCapture();+ return;+ }+ }+ emit notice(tr("上次的捕获目标「%1」已不在,请重新选择").arg(label), true);+ emit navigate(QStringLiteral("screen"));+ return;+ }+ emit notice(tr("还没有可以继续的片源"), true);+}++bool QmlPlayerBridge::resetNrLayer(int index) {+ auto& c = impl_->chain;+ if (c.mode != engine::ChainMode::List || index < 0 || index >= int(c.nodeCount) ||+ c.nodes[size_t(index)].type != engine::EffectType::NrEnhance) return false;+ auto& node = c.nodes[size_t(index)];+ const auto before = node;+ const engine::NrLayerSettings defaults;+ // The model and residual parameters, the size and the temporal option go+ // back to their defaults; the shared runtime and the on/off state stay.+ node.nr.model = defaults.model; node.nr.residual = defaults.residual;+ node.nr.temporal = defaults.temporal; node.nr.sizePolicy = defaults.sizePolicy;+ if (node == before) return true;+ if (!impl_->revalidate(true)) {+ const auto error = impl_->validation.message; node = before; impl_->revalidate();+ emit notice(utf8Of(error), true); return false;+ }+ emit settingsChanged(); emit chainChanged();+ return true;+}++QVariantList QmlPlayerBridge::frameTimes() const {+ QVariantList out;+ for (const double v : impl_->frameTimes) out << v;+ return out;+}++// --- P5 (2026-09-29): headers, colour history, export rows, presets -------+QString QmlPlayerBridge::sourceKind() const {+ const auto& s = impl_->snapshot;+ if (!hasSource()) return {};+ if (s.image) return QStringLiteral("image");+ if (s.remotePlay) return QStringLiteral("ps5");+ if (!impl_->liveKind.isEmpty()) return impl_->liveKind;+ if (s.capture) return QStringLiteral("capture");+ return QStringLiteral("file");+}+QString QmlPlayerBridge::sourceTitle() const {+ const QString kind = sourceKind();+ if (kind.isEmpty()) return {};+ if (kind == QLatin1String("file") || kind == QLatin1String("image")) return sourceName();+ if (kind == QLatin1String("capture")) {+ const QString name = impl_->prefString("captureDeviceName");+ return tr("采集卡 · %1").arg(name.isEmpty() ? impl_->liveLabel : name);+ }+ if (kind == QLatin1String("ps5")) return tr("PS5 串流 · %1").arg(impl_->liveLabel);+ return tr("屏幕捕获 · %1").arg(impl_->liveLabel);+}+// "1080p60" / "1080p59.94": the reported height and nominal rate only.+QString QmlPlayerBridge::sourceRateText() const {+ const auto& s = impl_->snapshot;+ if (!s.sourceHeight) return {};+ if (s.image) return QStringLiteral("%1×%2").arg(s.sourceWidth).arg(s.sourceHeight);+ const double fps = s.nominalSourceFps;+ if (fps <= 0.0) return QStringLiteral("%1p").arg(s.sourceHeight);+ const bool whole = std::abs(fps - std::round(fps)) < 0.01;+ return QStringLiteral("%1p%2").arg(s.sourceHeight)+ .arg(whole ? QString::number(int(std::round(fps))) : QString::number(fps, 'f', 2));+}+QString QmlPlayerBridge::sourceFormatText() const {+ QStringList parts;+ const QString rate = sourceRateText();+ if (rate.isEmpty()) return {};+ parts << rate;+ if (sourceKind() == QLatin1String("capture")) {+ for (const auto& f : impl_->captureFormatList)+ if (f.key == impl_->captureFormatKey) {+ const QString label = utf8Of(f.label);+ const int dot = label.lastIndexOf(QString::fromUtf8("·"));+ if (dot >= 0) parts << label.mid(dot + 1).trimmed();+ break;+ }+ }+ const QString colour = utf8Of(impl_->snapshot.colorStatus);+ if (!colour.isEmpty()) parts << colour.section(QString::fromUtf8(" → "), 0, 0).trimmed();+ return parts.join(QString::fromUtf8(" · "));+}++bool QmlPlayerBridge::colourCanUndo() const { return !impl_->colourUndo.empty(); }+bool QmlPlayerBridge::colourCanRedo() const { return !impl_->colourRedo.empty(); }+bool QmlPlayerBridge::colourCanPaste() const { return impl_->colourClip.has_value(); }+namespace {+bool isColourNode(const engine::EffectChain& chain, int index) {+ return index >= 0 && uint32_t(index) < chain.nodeCount && chain.nodes[index].type == engine::EffectType::Color;+}+}+// Undo and redo re-commit a stored state through the normal path (validation,+// chain rebuild), marked as a replay so it does not push history of its own.+bool QmlPlayerBridge::colourUndo() {+ while (!impl_->colourUndo.empty()) {+ const auto step = impl_->colourUndo.back();+ impl_->colourUndo.pop_back();+ if (!isColourNode(impl_->chain, step.index)) continue;+ impl_->selectedColour = step.index;+ const auto current = selectedColourSettings();+ impl_->colourReplaying = true;+ const bool ok = commitColour(step.colour);+ impl_->colourReplaying = false;+ if (ok) impl_->colourRedo.push_back({step.index, current});+ impl_->colourLastIndex = -1;+ veyra::log::info("ui-colour", std::format("undo layer={} ok={} left={}", step.index, ok, impl_->colourUndo.size()));+ emit settingsChanged();+ return ok;+ }+ emit settingsChanged();+ return false;+}+bool QmlPlayerBridge::colourRedo() {+ while (!impl_->colourRedo.empty()) {+ const auto step = impl_->colourRedo.back();+ impl_->colourRedo.pop_back();+ if (!isColourNode(impl_->chain, step.index)) continue;+ impl_->selectedColour = step.index;+ const auto current = selectedColourSettings();+ impl_->colourReplaying = true;+ const bool ok = commitColour(step.colour);+ impl_->colourReplaying = false;+ if (ok) impl_->colourUndo.push_back({step.index, current});+ impl_->colourLastIndex = -1;+ veyra::log::info("ui-colour", std::format("redo layer={} ok={}", step.index, ok));+ emit settingsChanged();+ return ok;+ }+ emit settingsChanged();+ return false;+}+void QmlPlayerBridge::colourCopy() {+ if (impl_->colourIndex() < 0) { emit notice(tr("处理链中没有调色节点"), true); return; }+ impl_->colourClip = selectedColourSettings();+ veyra::log::info("ui-colour", "copy");+ emit settingsChanged();+ emit notice(tr("已复制调色参数"), false);+}+bool QmlPlayerBridge::colourPaste() {+ if (!impl_->colourClip) return false;+ auto next = *impl_->colourClip;+ next.enabled = selectedColourSettings().enabled; // paste the grade, not the switch+ impl_->colourLastIndex = -1; // a paste is its own step+ const bool ok = commitColour(next);+ veyra::log::info("ui-colour", std::format("paste ok={}", ok));+ return ok;+}++QVariantList QmlPlayerBridge::exportItems() const {+ QVariantList out;+ for (const auto& row : impl_->exportRows) {+ const QString input = utf8Of(row.input);+ out << QVariantMap{{"name", QFileInfo(input).fileName()}, {"input", input}, {"output", utf8Of(row.output)},+ {"state", row.state}, {"progress", row.progress}, {"note", row.note},+ {"current", row.input == impl_->sourceLabel}};+ }+ return out;+}+void QmlPlayerBridge::clearFinishedExportItems() {+ std::erase_if(impl_->exportRows, [](const auto& row) {+ return row.state != QLatin1String("running") && row.state != QLatin1String("queued") &&+ row.state != QLatin1String("paused");+ });+ emit exportChanged();+}+// A thumbnail of any file (export queue rows), through the same provider.+QString QmlPlayerBridge::fileThumbnailId(const QString& path, double seconds) const {+ if (path.isEmpty()) return {};+ return QStringLiteral("image://veyra-thumb/file/%1/%2/%3")+ .arg(impl_->thumbnailGeneration)+ .arg(QString::fromLatin1(path.toUtf8().toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals)))+ .arg(qint64(std::max(0.0, seconds) * 1000.0));+}++QString QmlPlayerBridge::capturePreviewUrl() const {+ const auto& s = impl_->snapshot;+ if (!s.running || s.posterRgba.empty() || !s.posterWidth || !s.posterHeight) return {};+ if (impl_->posterSession != s.sessionId || impl_->posterUrl.isEmpty()) {+ const QImage image(s.posterRgba.data(), int(s.posterWidth), int(s.posterHeight), int(s.posterWidth * 4),+ QImage::Format_RGBA8888);+ QByteArray png;+ QBuffer buffer(&png);+ buffer.open(QIODevice::WriteOnly);+ image.save(&buffer, "PNG");+ impl_->posterSession = s.sessionId;+ impl_->posterUrl = png.isEmpty() ? QString()+ : QStringLiteral("data:image/png;base64,") + QString::fromLatin1(png.toBase64());+ }+ return impl_->posterUrl;+}+QString QmlPlayerBridge::captureSignalLevel() const {+ const auto& s = impl_->snapshot;+ if (!s.running || !s.capture) return QStringLiteral("idle");+ if (s.captureRecovering) return QStringLiteral("warn");+ return s.captureFps > 0.5 ? QStringLiteral("ok") : QStringLiteral("warn");+}+QString QmlPlayerBridge::captureSignalText() const {+ const auto& s = impl_->snapshot;+ if (captureSignalLevel() == QLatin1String("idle")) return tr("未连接");+ if (s.captureRecovering) return tr("正在恢复");+ return s.captureFps > 0.5 ? tr("信号正常") : tr("等待信号");+}++void QmlPlayerBridge::importPresetDialog() {+ const QString path = QFileDialog::getOpenFileName(nullptr, tr("导入预设"), QString(),+ tr("Veyra 预设 (*.vpreset);;所有文件 (*)"));+ if (!path.isEmpty()) importPreset(path);+}+bool QmlPlayerBridge::importPreset(const QString& path) {+ std::wstring name;+ auto& library = impl_->facade.presets();+ const bool ok = library.importFile(std::filesystem::path(wideOf(path)), name);+ veyra::log::info("ui-preset", std::format("import ok={} name={}", ok, utf8Of(name).toStdString()));+ if (!ok) { emit notice(tr("导入失败:%1").arg(utf8Of(library.error())), true); return false; }+ emit presetsChanged();+ emit notice(tr("已导入预设:%1").arg(utf8Of(name)), false);+ return true;+}+void QmlPlayerBridge::exportPresetDialog(int index) {+ const auto& entries = impl_->facade.presets().entries();+ if (index < 0 || size_t(index) >= entries.size()) return;+ const QString path = QFileDialog::getSaveFileName(nullptr, tr("导出预设"),+ utf8Of(entries[size_t(index)].name) + QStringLiteral(".vpreset"),+ tr("Veyra 预设 (*.vpreset)"));+ if (!path.isEmpty()) exportPreset(index, path);+}+bool QmlPlayerBridge::exportPreset(int index, const QString& path) {+ auto& library = impl_->facade.presets();+ if (index < 0 || size_t(index) >= library.entries().size()) return false;+ const bool ok = library.exportEntry(size_t(index), std::filesystem::path(wideOf(path)));+ veyra::log::info("ui-preset", std::format("export index={} ok={}", index, ok));+ if (!ok) { emit notice(tr("导出失败:%1").arg(utf8Of(library.error())), true); return false; }+ emit notice(tr("预设已导出到:%1").arg(QDir::toNativeSeparators(path)), false);+ return true;+}++QString QmlPlayerBridge::liveOpeningText() const {+ if (!impl_->pendingLiveText.isEmpty()) return impl_->pendingLiveText;+ const auto& s = impl_->snapshot;+ if (s.running || s.failed || s.transport != engine::TransportState::Opening) return {};+ const QString status = QString::fromStdWString(s.status);+ if (s.remotePlay)+ return status.contains(QStringLiteral("PIN")) ? status : tr("正在连接 PS5 · %1").arg(impl_->liveLabel);+ if (impl_->liveKind == QLatin1String("screen")) return tr("正在开始屏幕捕获…");+ if (s.capture) return tr("正在打开采集设备…");+ return {};+}+} // namespace veyra::uidiff --git a/src/ui/ThumbnailProvider.cpp b/src/ui/ThumbnailProvider.cppindex b579109c..f97aabbb 100644--- a/src/ui/ThumbnailProvider.cpp+++ b/src/ui/ThumbnailProvider.cpp@@ -3,6 +3,9 @@#include <QImage>#include "veyra/engine/PosterFrame.h"+#include "veyra/Log.h"++#include <format>extern "C" {#include <libavcodec/avcodec.h>@@ -33,6 +36,9 @@ void ThumbnailProvider::setSource(const QString& path) {source_ = path;}+// Ids: "<gen>/<ms>" a frame of the playing source+// "cover/<gen>" the playing source's embedded cover art+// "file/<gen>/<base64url>/<ms>" a frame of any file (export queue rows)QImage ThumbnailProvider::requestImage(const QString& id, QSize* size, const QSize&) {if (size) *size = {};QString path;@@ -40,10 +46,78 @@ QImage ThumbnailProvider::requestImage(const QString& id, QSize* size, const QSistd::lock_guard lock(mutex_);path = source_;}- bool validTime = false;- const int64_t milliseconds = id.section(QLatin1Char('/'), 1, 1).toLongLong(&validTime);- if (path.isEmpty() || !validTime || milliseconds < 0) return {};+ QImage result;+ if (id.startsWith(QLatin1String("cover/"))) {+ result = coverArt(path);+ // No cover: a transparent pixel, so the plate stays black without the+ // image element reporting a provider failure for every file.+ if (result.isNull()) { result = QImage(1, 1, QImage::Format_ARGB32); result.fill(Qt::transparent); }+ } else if (id.startsWith(QLatin1String("file/"))) {+ bool ok = false;+ const int64_t ms = id.section(QLatin1Char('/'), 3, 3).toLongLong(&ok);+ const QString file = QString::fromUtf8(QByteArray::fromBase64(id.section(QLatin1Char('/'), 2, 2).toLatin1(),+ QByteArray::Base64UrlEncoding));+ if (ok && ms >= 0 && !file.isEmpty()) result = frameAt(file, ms);+ } else {+ bool validTime = false;+ const int64_t milliseconds = id.section(QLatin1Char('/'), 1, 1).toLongLong(&validTime);+ if (!path.isEmpty() && validTime && milliseconds >= 0) result = frameAt(path, milliseconds);+ }+ if (size) *size = result.size();+ return result;+}+// The attached picture a container carries (MP4 covr / ID3 APIC, and MKV+// image attachments, which FFmpeg exposes the same way). Decoded with FFmpeg so+// no Qt image plugin is involved. Empty when the file has none: the bar then+// stays black rather than showing a stand-in.+QImage ThumbnailProvider::coverArt(const QString& path) {+ QImage result;+ if (path.isEmpty()) return result;+ AVFormatContext* format = nullptr;+ AVCodecContext* decoder = nullptr;+ AVFrame* frame = nullptr;+ const QByteArray encodedPath = path.toUtf8();+ if (avformat_open_input(&format, encodedPath.constData(), nullptr, nullptr) < 0) return result;+ for (unsigned i = 0; i < format->nb_streams && result.isNull(); ++i) {+ AVStream* stream = format->streams[i];+ if (!(stream->disposition & AV_DISPOSITION_ATTACHED_PIC) || stream->attached_pic.size <= 0) continue;+ const AVCodec* codec = avcodec_find_decoder(stream->codecpar->codec_id);+ // The bundled FFmpeg carries no PNG decoder: Qt reads the attached bytes+ // itself (PNG is built into QtGui; JPEG when the image plugin is present).+ const auto fromBytes = [&]() {+ QImage image = QImage::fromData(stream->attached_pic.data, stream->attached_pic.size);+ if (!image.isNull()) result = image.scaled(160, 160, Qt::KeepAspectRatio, Qt::SmoothTransformation);+ veyra::log::info("thumb-cover", std::format("stream={} qt-decoded={}", i, !result.isNull()));+ };+ if (!codec) { fromBytes(); continue; }+ decoder = avcodec_alloc_context3(codec);+ frame = av_frame_alloc();+ if (decoder) decoder->thread_count = 1; // one picture: no frame threading to wait on+ int received = -1;+ if (decoder && frame && avcodec_parameters_to_context(decoder, stream->codecpar) >= 0 &&+ avcodec_open2(decoder, codec, nullptr) >= 0 &&+ avcodec_send_packet(decoder, &stream->attached_pic) >= 0) {+ // Drain: a single-picture decoder may hold its frame until the end of stream.+ received = avcodec_receive_frame(decoder, frame);+ if (received == AVERROR(EAGAIN)) { avcodec_send_packet(decoder, nullptr); received = avcodec_receive_frame(decoder, frame); }+ }+ veyra::log::info("thumb-cover", std::format("stream={} codec={} decoded={}", i, codec->name, received >= 0));+ if (received < 0) fromBytes();+ else {+ std::vector<uint8_t> rgba;+ uint32_t width = 0, height = 0;+ if (engine::makePosterFrame(frame, 160, 160, rgba, width, height))+ result = QImage(rgba.data(), int(width), int(height), int(width * 4), QImage::Format_RGBA8888).copy();+ }+ av_frame_free(&frame);+ avcodec_free_context(&decoder);+ }+ avformat_close_input(&format);+ return result;+}++QImage ThumbnailProvider::frameAt(const QString& path, int64_t milliseconds) {AVFormatContext* format = nullptr;AVCodecContext* decoder = nullptr;AVPacket* packet = nullptr;@@ -101,7 +175,6 @@ done:av_packet_free(&packet);avcodec_free_context(&decoder);avformat_close_input(&format);- if (size) *size = result.size();return result;}diff --git a/tests/integration/CaptureAudioTests.cpp b/tests/integration/CaptureAudioTests.cppindex 9a9f2a0f..b91732cd 100644--- a/tests/integration/CaptureAudioTests.cpp+++ b/tests/integration/CaptureAudioTests.cpp@@ -30,6 +30,9 @@ int main(int argc,char** argv){const bool compensatedTransientTest=argc>=2&&std::string_view(argv[1])=="--transient-comp";const bool fastDrift=argc>=2&&std::string_view(argv[1])=="--drift-fast";const bool driftTest=fastDrift||(argc>=2&&std::string_view(argv[1])=="--drift-slow");+ // Test-only stopped-device gap: no source callbacks should be replayed+ // to catch up with a deadline from the previous ingress epoch.+ const bool restartGap=argc>=2&&std::string_view(argv[1])=="--restart-gap";if(endpointTest)SetEnvironmentVariableW(L"VEYRA_TEST_CAPTURE_AUDIO_ENDPOINT_LOSS",L"1");if(slowStart)SetEnvironmentVariableW(L"VEYRA_TEST_CAPTURE_AUDIO_SLOW_START",L"1");const bool multichannel=argc>=3&&std::string_view(argv[2])=="--5.1";@@ -38,7 +41,7 @@ int main(int argc,char** argv){if(!(multichannel?audio.configure(extended.Format,sizeof(extended)):audio.configure(f))||!audio.start())return 2;audio.setGain(0);const unsigned channels=multichannel?6:2;std::vector<int16_t> pcm(480*channels);for(size_t i=0;i<pcm.size()/channels;++i)for(unsigned c=0;c<channels;++c)pcm[i*channels+c]=int16_t(2000*std::sin((i*channels+c)*0.031));- const auto start=Clock::now();+ auto start=Clock::now();const bool legacyClock=argc>=2&&std::string_view(argv[1])=="--legacy-clock";auto present=[&](double pts,int64_t host,double localDelay){audio.videoPresented(pts,host,legacyClock?std::nullopt:std::optional<int64_t>(host-int64_t(localDelay*10000)));@@ -177,9 +180,13 @@ int main(int argc,char** argv){unsigned sequence=160;auto phase=[&](unsigned mode,int offset,double delay,double expectedComp,double expectedSkew,double commonInputMs=0,double maxSkewError=28){audio.setSync(mode,offset);double error=0;unsigned samples=0;bool boundedPhase=true;+ double maxIngressLateMs=0;unsigned catchUpCallbacks=0;const unsigned steps=delay>500?300:150;for(unsigned j=0;j<steps;++j,++sequence){- pacer.until(start+std::chrono::milliseconds(sequence*10));+ const auto due=start+std::chrono::milliseconds(sequence*10);pacer.until(due);+ const double late=std::chrono::duration<double,std::milli>(Clock::now()-due).count();+ maxIngressLateMs=std::max(maxIngressLateMs,late);+ if(late>=10)++catchUpCallbacks;const auto host=std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;if(!audio.push(pcm.data(),pcm.size()*2,sequence*10.0-commonInputMs,j==0&&commonInputMs!=0))return false;present(sequence*10.0-commonInputMs-delay,host,delay);const auto s=audio.snapshot();@@ -187,14 +194,20 @@ int main(int argc,char** argv){if(j>steps-80&&s.running&&s.skewMs){error+=std::abs(*s.skewMs-expectedSkew);++samples;}}const auto s=audio.snapshot();const bool pass=samples>=60&&error/samples<maxSkewError&&std::abs(s.compensationMs-expectedComp)<15&&boundedPhase&&s.overflows==0;- std::cout<<(pass?"PASS ":"FAIL ")<<"capture phase mode="<<mode<<" delay="<<delay<<" commonInputMs="<<commonInputMs<<" compensation="<<s.compensationMs<<" meanSkewError="<<(samples?error/samples:-1)<<" resets="<<s.resets<<" queueMs="<<s.bufferedMs<<" endpointMs="<<s.endpointBufferedMs<<" underruns="<<s.underruns<<" correctionPpm="<<s.driftCorrectionPpm<<'\n';return pass;+ std::cout<<(pass?"PASS ":"FAIL ")<<"capture phase mode="<<mode<<" delay="<<delay<<" commonInputMs="<<commonInputMs<<" compensation="<<s.compensationMs<<" meanSkewError="<<(samples?error/samples:-1)<<" resets="<<s.resets<<" queueMs="<<s.bufferedMs<<" endpointMs="<<s.endpointBufferedMs<<" underruns="<<s.underruns<<" correctionPpm="<<s.driftCorrectionPpm<<" maxIngressLateMs="<<maxIngressLateMs<<" catchUpCallbacks="<<catchUpCallbacks<<'\n';return pass;};ok=phase(0,0,160,160,0)&&ok;ok=phase(0,0,400,400,0)&&ok;ok=phase(0,0,400,400,0,900)&&ok;ok=phase(0,0,900,900,0,900)&&ok;// Start a fresh ingress epoch after the shared-input offset fixture.- audio.stop();if(!audio.start())return 7;+ audio.stop();+ if(restartGap)std::this_thread::sleep_for(std::chrono::milliseconds(400));+ if(!audio.start())return 7;+ // start() creates a fresh ingress clock. Restart the synthetic callback+ // schedule too: stopped time is not captured PCM waiting to be replayed.+ // Do not rebase between live phases or across the intentional input stall.+ start=Clock::now()-std::chrono::milliseconds(sequence*10);ok=phase(0,0,80,80,0)&&ok;const auto beforeGraphReset=audio.snapshot();audio.videoReset(false);@@ -229,7 +242,9 @@ int main(int argc,char** argv){audio.stop();const auto stopped=audio.snapshot();const bool stoppedClean=!stopped.available&&!stopped.running&&!stopped.skewMs&&stopped.bufferedMs==0;std::cout<<(stoppedClean?"PASS ":"FAIL ")<<"stopped audio has no stale clock or queued state\n";ok=stoppedClean&&ok;+ if(restartGap)std::this_thread::sleep_for(std::chrono::milliseconds(400));if(!audio.start())return 4;+ start=Clock::now()-std::chrono::milliseconds(sequence*10);ok=phase(0,0,80,80,0)&&ok;audio.stop();if(!audio.start())return 5;diff --git a/tests/integration/ColorGradeGpuTests.cpp b/tests/integration/ColorGradeGpuTests.cppindex d1a6bfff..a3a5dd0e 100644--- a/tests/integration/ColorGradeGpuTests.cpp+++ b/tests/integration/ColorGradeGpuTests.cpp@@ -11,15 +11,21 @@#include "veyra/gfx/CommandSlotRing.h"#include "veyra/sink/ImageExportSink.h"#include "veyra/engine/EnhancementSettings.h"+#include "veyra/engine/GraphDescription.h"#include "veyra/engine/ColorSettings.h"#include "veyra/RuntimePaths.h"#include "veyra/engine/ColorLut.h"#include <filesystem>#include <fstream>+#include <array>+#include <memory>#include <cmath>#include <cstdio>#include <string>+#include <string_view>#include <vector>+#include <cstdlib>+#include <d3d12sdklayers.h>extern "C" {#include <libavutil/frame.h>#include <libavutil/pixfmt.h>@@ -38,6 +44,18 @@ constexpr int kSize=64;struct Frame {AVFrame* frame=nullptr;~Frame(){if(frame)av_frame_free(&frame);}+ bool makeHdr(bool hlg){+ frame=av_frame_alloc();if(!frame)return false;+ frame->format=AV_PIX_FMT_P010;frame->width=frame->height=kSize;+ frame->color_range=AVCOL_RANGE_MPEG;frame->colorspace=AVCOL_SPC_BT2020_NCL;+ frame->color_primaries=AVCOL_PRI_BT2020;frame->color_trc=hlg?AVCOL_TRC_ARIB_STD_B67:AVCOL_TRC_SMPTE2084;+ if(av_frame_get_buffer(frame,32)<0)return false;+ for(int y=0;y<kSize;++y)for(int x=0;x<kSize;++x)+ reinterpret_cast<uint16_t*>(frame->data[0]+y*frame->linesize[0])[x]=uint16_t((100+650*x/(kSize-1))<<6);+ for(int y=0;y<kSize/2;++y)for(int x=0;x<kSize;++x)+ reinterpret_cast<uint16_t*>(frame->data[1]+y*frame->linesize[1])[x]=32768;+ return true;+ }bool make(uint8_t r,uint8_t g,uint8_t b){frame=av_frame_alloc();frame->format=AV_PIX_FMT_BGR0;frame->width=frame->height=kSize;@@ -51,13 +69,13 @@ struct Frame {}// Horizontal ramp used by the banding check: the grade compresses it so the// ideal 8-bit output advances by a fraction of a code per pixel.- bool makeRamp(uint8_t from,uint8_t to){+ bool makeRamp(uint8_t from,uint8_t to,int size=kSize){frame=av_frame_alloc();- frame->format=AV_PIX_FMT_BGR0;frame->width=frame->height=kSize;+ frame->format=AV_PIX_FMT_BGR0;frame->width=frame->height=size;frame->color_range=AVCOL_RANGE_UNSPECIFIED;frame->color_trc=AVCOL_TRC_IEC61966_2_1;frame->colorspace=AVCOL_SPC_RGB;if(av_frame_get_buffer(frame,32)<0)return false;- for(int y=0;y<kSize;++y)for(int x=0;x<kSize;++x){- const int value=from+int(std::lround(double(to-from)*double(x)/double(kSize-1)));+ for(int y=0;y<size;++y)for(int x=0;x<size;++x){+ const int value=from+int(std::lround(double(to-from)*double(x)/double(size-1)));auto* p=frame->data[0]+std::size_t(y)*frame->linesize[0]+std::size_t(x)*4;p[0]=uint8_t(value);p[1]=uint8_t(value);p[2]=uint8_t(value);p[3]=255;}@@ -66,8 +84,27 @@ struct Frame {};struct Graph {gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;- pipeline::EnhanceGraph g{ctx,ring};+ // A graph owns six large baked-table instances. Several local Graphs in+ // one test function must not exhaust the default Windows 1 MiB stack.+ std::unique_ptr<pipeline::EnhanceGraph> graph=std::make_unique<pipeline::EnhanceGraph>(ctx,ring);+ pipeline::EnhanceGraph& g=*graph;bool up=false;+ bool startColors(const engine::EnhancementSettings& settings,bool hdrInput=false,bool hdrOutput=false,int size=kSize){+ if(!up){+ gfx::DeviceContextDesc device;Status st;+ device.enableDebugLayer=std::getenv("VEYRA_COLOR_GPU_DEBUG")!=nullptr;+ if(!ctx.initialize(device,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,st))return false;+ up=true;+ }else {ring.drainQueue();g.shutdown();}+ pipeline::EnhanceGraphDesc gd;+ gd.sourceWidth=gd.sourceHeight=gd.workWidth=gd.workHeight=size;+ gd.rgbInput=!hdrInput;gd.hdrInput=hdrInput;gd.hdrOutput=hdrOutput;+ gd.stillImage=true;gd.noFeatures=true;gd.noNgx=true;+ gd.enableNr=false;gd.enableSr=false;gd.enableFg=false;gd.outputDitherStep=0;+ engine::StageRequest request;request.width=request.height=size;request.stillImage=true;+ engine::describeStages(request,settings,gd);+ return g.initialize(gd)&&g.createViews();+ }bool start(bool colorEnabled,bool rgb=true){gfx::DeviceContextDesc device;Status st;if(!ctx.initialize(device,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,st))return false;@@ -109,11 +146,29 @@ struct Graph {return g.process(frame.frame,0,true,outputs,1)&&sink::readRgba8(ctx,ring,g.videoFrameResource(outputs.videoSlot),out);}- ~Graph(){if(up){ring.drainQueue();g.shutdown();ring.shutdown();ctx.shutdown();}}+ ~Graph(){if(up){+ ring.drainQueue();g.shutdown();ring.shutdown();+ if(std::getenv("VEYRA_COLOR_GPU_DEBUG")){+ Microsoft::WRL::ComPtr<ID3D12InfoQueue> info;+ const bool available=SUCCEEDED(ctx.device()->QueryInterface(IID_PPV_ARGS(&info)));+ check(available,"D3D12 debug info queue is actually available");+ unsigned errors=0;+ if(available)for(UINT64 i=0;i<info->GetNumStoredMessagesAllowedByRetrievalFilter();++i){+ SIZE_T size=0;info->GetMessage(i,nullptr,&size);std::vector<uint8_t> storage(size);+ auto* message=reinterpret_cast<D3D12_MESSAGE*>(storage.data());+ if(SUCCEEDED(info->GetMessage(i,message,&size))&&message->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){+ std::printf("D3D12_ERROR id=%u %s\n",unsigned(message->ID),message->pDescription);++errors;+ }+ }+ check(available&&errors==0,"D3D12 resource lifetime and dispatch errors=0");+ }+ ctx.shutdown();+ }}};struct Pixel { int r=0,g=0,b=0; };// Test-only raw FP16 readback preserves exact comparison-reference values.-bool readReference(Graph& graph,ID3D12Resource* texture,std::vector<uint8_t>& pixels){+bool readReference(Graph& graph,ID3D12Resource* texture,std::vector<uint8_t>& pixels,+ D3D12_RESOURCE_STATES initialState=D3D12_RESOURCE_STATE_COMMON){if(!texture)return false;const auto desc=texture->GetDesc();D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};UINT64 bytes=0;@@ -125,7 +180,7 @@ bool readReference(Graph& graph,ID3D12Resource* texture,std::vector<uint8_t>& piif(FAILED(graph.ctx.device()->CreateCommittedResource(&heap,D3D12_HEAP_FLAG_NONE,&buffer,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&readback))))return false;Status status;uint32_t slot;auto* list=graph.ring.acquireNext(slot,status);if(!list)return false;D3D12_RESOURCE_BARRIER barrier{};barrier.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;- barrier.Transition={texture,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_SOURCE};+ barrier.Transition={texture,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,initialState,D3D12_RESOURCE_STATE_COPY_SOURCE};list->ResourceBarrier(1,&barrier);D3D12_TEXTURE_COPY_LOCATION src{},dst{};src.pResource=texture;src.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;dst.pResource=readback.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;dst.PlacedFootprint=fp;@@ -137,12 +192,327 @@ bool readReference(Graph& graph,ID3D12Resource* texture,std::vector<uint8_t>& pifor(unsigned y=0;y<desc.Height;++y)memcpy(pixels.data()+size_t(y)*desc.Width*8,static_cast<uint8_t*>(data)+fp.Offset+size_t(y)*fp.Footprint.RowPitch,size_t(desc.Width)*8);D3D12_RANGE empty{};readback->Unmap(0,&empty);return true;}+// Keep this separate from the legacy large wmain stack frame.+__declspec(noinline) void exactExposureTests(){+ // Multiplication by two and its inverse are exact on this normal FP16+ // range. Neutral log/HSV round trips must not lose a half-float ULP.+ auto plainStorage=std::make_unique<engine::EnhancementSettings>();+ auto settingsStorage=std::make_unique<engine::EnhancementSettings>();+ auto& plain=*plainStorage;auto& settings=*settingsStorage;settings.additionalColorCount=2;+ settings.additionalColors[0].enabled=settings.additionalColors[1].enabled=true;+ settings.additionalColors[0].exposure=1;settings.additionalColors[1].exposure=-1;+ auto baseline=std::make_unique<Graph>();auto graded=std::make_unique<Graph>();Frame frame;+ pipeline::EnhanceGraph::FrameOutputs output;std::vector<uint8_t> reference,roundTrip;+ const auto linear=[&](Graph& graph,std::vector<uint8_t>& data){+ return graph.g.process(frame.frame,0,true,output,1)&&+ readReference(graph,graph.g.diagnosticLinearInput(),data,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);};+ const bool ok=frame.makeRamp(0,255)&&baseline->startColors(plain)&&graded->startColors(settings)&&+ linear(*baseline,reference)&&linear(*graded,roundTrip);+ check(ok&&!reference.empty()&&reference==roundTrip,"standalone +1/-1 EV round trip preserves every FP16 bit");+ settings.additionalColors[0].temperature=30;+ std::vector<uint8_t> warm;+ check(ok&&graded->apply(settings)&&linear(*graded,warm)&&warm!=reference,"non-neutral live edits leave the exact-exposure path");+ settings.additionalColors[0].groupBypassMask=1u<<1; // bypass white balance+ std::vector<uint8_t> bypassed;+ check(ok&&graded->apply(settings)&&linear(*graded,bypassed)&&bypassed==reference,"bypassed white balance restores exact exposure without rebuilding graph");+}Pixel center(const sink::RgbaImage& image){const auto index=(std::size_t(kSize/2)*std::size_t(image.width)+std::size_t(kSize/2))*4;return {image.pixels[index],image.pixels[index+1],image.pixels[index+2]};}+// Generate the reference in an isolated stage with the original v1.4.4 RGB+// ingress shader, then compare these deterministic intermediate/output bytes.+// This tests the shader contract, not the complete v1.4.4 executable.+bool fusedLegacyReference(const std::filesystem::path& path,bool write){+ std::vector<uint8_t> actual;+ constexpr std::array<const char*,7> names={+ "off","disabled-exposure","neutral","plus-one","minus-one","quarter","mixed"};+ for(size_t i=0;i<names.size();++i){+ auto settings=std::make_unique<engine::EnhancementSettings>();+ settings->color.enabled=i>=2;+ if(i==1||i==3)settings->color.exposure=1;+ if(i==4)settings->color.exposure=-1;+ if(i==5)settings->color.exposure=0.25f;+ if(i==6){settings->color.exposure=0.25f;settings->color.temperature=20;settings->color.saturation=-15;}+ Graph graph;Frame frame;sink::RgbaImage image;std::vector<uint8_t> linear;+ if(!frame.makeRamp(0,255))return false;+ for(int y=0;y<kSize;++y)for(int x=0;x<kSize;++x){+ auto* p=frame.frame->data[0]+size_t(y)*frame.frame->linesize[0]+size_t(x)*4;+ p[0]=uint8_t(x*255/(kSize-1));p[1]=uint8_t(y*255/(kSize-1));+ p[2]=uint8_t((x+y)*255/(2*(kSize-1)));+ }+ if(!graph.startColors(*settings)||!graph.render(frame,image)||+ !readReference(graph,graph.g.diagnosticLinearInput(),linear,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)||+ linear.size()!=size_t(kSize)*kSize*8||image.pixels.size()!=size_t(kSize)*kSize*4)return false;+ actual.insert(actual.end(),linear.begin(),linear.end());+ actual.insert(actual.end(),image.pixels.begin(),image.pixels.end());+ std::printf("FUSED-LEGACY case=%s linearBytes=%zu outputBytes=%zu%c",names[i],linear.size(),image.pixels.size(),10);+ }+ if(write){+ if(std::filesystem::exists(path)||!std::filesystem::is_directory(path.parent_path()))return false;+ std::ofstream file(path,std::ios::binary);+ file.write(reinterpret_cast<const char*>(actual.data()),std::streamsize(actual.size()));+ return bool(file);+ }+ std::ifstream file(path,std::ios::binary|std::ios::ate);+ if(!file||file.tellg()!=std::streamoff(actual.size()))return false;+ std::vector<uint8_t> expected(actual.size());file.seekg(0);+ if(!file.read(reinterpret_cast<char*>(expected.data()),std::streamsize(expected.size())))return false;+ size_t differences=0;for(size_t i=0;i<actual.size();++i)differences+=actual[i]!=expected[i];+ std::printf("FUSED-LEGACY comparedBytes=%zu differingBytes=%zu%c",actual.size(),differences,10);+ return differences==0;+}}-int wmain(){+void colorLifecycleTests(){+ auto settings=std::make_unique<engine::EnhancementSettings>();+ settings->color.enabled=true;settings->color.exposure=0.25f;settings->additionalColorCount=5;+ for(unsigned i=0;i<5;++i){settings->additionalColors[i].enabled=true;settings->additionalColors[i].saturation=float(i)*4-8;}+ Graph graph;Frame frame;sink::RgbaImage first;+ const bool started=frame.makeRamp(0,255)&&graph.startColors(*settings)&&graph.render(frame,first);+ check(started,"lifecycle: open six-instance graph and produce a complete frame");+ if(!started)return;+ const std::array<double,4> pts{16.0,0.0,10000.0,10016.0};+ for(size_t i=0;i<pts.size();++i){+ pipeline::EnhanceGraph::FrameOutputs output;sink::RgbaImage image;+ const bool ok=graph.g.process(frame.frame,pts[i],i==1||i==2,output,i+2)&&+ sink::readRgba8(graph.ctx,graph.ring,graph.g.videoFrameResource(output.videoSlot),image);+ check(ok&&image.pixels==first.pixels,"lifecycle: frame/reset/backward-seek/discontinuity preserves stateless color");+ }+ {+ Frame larger;Graph reference;sink::RgbaImage resized,expected;+ const bool ok=larger.makeRamp(0,255,96)&&graph.startColors(*settings,false,false,96)&&graph.render(larger,resized)&&+ reference.startColors(*settings,false,false,96)&&reference.render(larger,expected);+ check(ok&&resized.width==96&&resized.height==96&&resized.pixels==expected.pixels,+ "lifecycle: resize/recreate six instances matches a fresh graph");+ }+ {+ Frame other;Graph reference;sink::RgbaImage changed,expected;+ const bool ok=other.make(10,80,200)&&graph.startColors(*settings)&&graph.render(other,changed)&&+ reference.startColors(*settings)&&reference.render(other,expected);+ check(ok&&changed.pixels==expected.pixels&&changed.pixels!=first.pixels,+ "lifecycle: source switch does not retain preceding source pixels");+ }+ for(unsigned count:std::array<unsigned,2>{1,0}){+ settings->additionalColorCount=count;settings->color.enabled=count!=0;+ const bool requiresRebuild=!graph.apply(*settings);+ Graph reference;sink::RgbaImage changed,expected;+ const bool ok=graph.startColors(*settings)&&graph.render(frame,changed)&&+ reference.startColors(*settings)&&reference.render(frame,expected);+ check(requiresRebuild&&ok&&changed.pixels==expected.pixels,+ "lifecycle: six-to-two-to-zero topology rebuild matches a fresh graph");+ }+ graph.g.shutdown();graph.g.shutdown();+ check(!graph.g.initialized()&&!graph.g.colorGradeActive(),"lifecycle: repeated close releases all color state");+}+void colorDeviceRemovalTest(){+ auto settings=std::make_unique<engine::EnhancementSettings>();+ settings->color.enabled=true;settings->color.exposure=0.25f;settings->additionalColorCount=5;+ for(auto& c:settings->additionalColors){c.enabled=true;c.saturation=-4;}+ Frame frame;sink::RgbaImage before,after;+ if(!frame.makeRamp(0,255)){check(false,"device-removal fixture");return;}+ {+ Graph graph;Microsoft::WRL::ComPtr<ID3D12Device5> device;+ const bool ready=graph.startColors(*settings)&&graph.render(frame,before)&&graph.ring.drainQueue()&&+ SUCCEEDED(graph.ctx.device()->QueryInterface(IID_PPV_ARGS(&device)));+ check(ready,"device-removal: isolated graph ready and submitted work drained");+ if(!ready)return;+ // Explicitly remove this test process's device, not a system TDR.+ // Expected removal diagnostics are separate from unexpected debug errors.+ device->RemoveDevice();+ const HRESULT reason=graph.ctx.device()->GetDeviceRemovedReason();+ std::printf("EXPECTED_DEVICE_REMOVAL reason=0x%08X%c",unsigned(reason),10);+ check(FAILED(reason),"device-removal: failure was actually injected");+ pipeline::EnhanceGraph::FrameOutputs output;+ // process() records/submits asynchronous GPU work; true is not proof of+ // execution or presentation. VideoPresenter::present rejects a removed+ // device separately. This test only certifies color-resource recovery.+ const bool submissionAccepted=graph.g.process(frame.frame,16,true,output,2);+ uint32_t reportedReason=0;+ std::printf("EXPECTED_DEVICE_REMOVAL submissionAccepted=%d%c",int(submissionAccepted),10);+ check(!graph.ctx.checkDeviceAlive(reportedReason)&&reportedReason==uint32_t(reason),+ "device-removal: device health remains failed regardless of submission result");+ graph.g.shutdown();graph.g.shutdown();+ check(!graph.g.initialized()&&!graph.g.colorGradeActive(),"device-removal: graph teardown is idempotent");+ graph.ring.shutdown();graph.ctx.shutdown();graph.up=false;device.Reset();+ }+ Graph recovered;+ check(recovered.startColors(*settings)&&recovered.render(frame,after)&&before.pixels==after.pixels,+ "device-removal: a fresh device and graph reproduce the complete prior image");+}+int wmain(int argc,wchar_t** argv){+ if(argc>1){+ if(argc==2&&std::wstring_view(argv[1])==L"--lifecycle"){colorLifecycleTests();return failures?1:0;}+ if(argc==2&&std::wstring_view(argv[1])==L"--device-removal"){colorDeviceRemovalTest();return failures?1:0;}+ if(argc!=3)return 2;+ const std::wstring_view mode=argv[1];+ if(mode!=L"--write-fused-reference"&&mode!=L"--compare-fused-reference")return 2;+ check(fusedLegacyReference(argv[2],mode==L"--write-fused-reference"),+ "legacy fused full-image intermediate/output byte contract");+ return failures?1:0;+ }+ exactExposureTests();+ // R5.3: compare complete images, not just hashes or a centre pixel. The+ // independent path rounds ingress to FP16 before grading (fused does not).+ const auto maxDifference=[](const sink::RgbaImage& a,const sink::RgbaImage& b){+ if(a.pixels.empty()||a.pixels.size()!=b.pixels.size())return 999;+ int maxDiff=0;for(size_t i=0;i<a.pixels.size();++i)if(i%4!=3)maxDiff=std::max(maxDiff,std::abs(int(a.pixels[i])-int(b.pixels[i])));+ return maxDiff;+ };+ {+ engine::EnhancementSettings settings,plain;settings.color.enabled=true;settings.additionalColorCount=5;+ for(auto& color:settings.additionalColors)color.enabled=true;+ Graph a,b;Frame frame;sink::RgbaImage first,second;+ const bool ok=frame.makeRamp(0,255)&&a.startColors(settings)&&b.startColors(plain)&&a.render(frame,first)&&b.render(frame,second);+ check(ok&&first.pixels==second.pixels,"six enabled-neutral grades are byte-identical to no grading");+ }+ {+ engine::EnhancementSettings missing,reference;missing.color.enabled=true;missing.additionalColorCount=1;missing.additionalColors[0].enabled=true;+ missing.color.setLutName(L"r53-unavailable-primary.cube");missing.additionalColors[0].setLutName(L"r53-unavailable-secondary.cube");+ reference=missing;reference.color.lutName={};reference.additionalColors[0].lutName={};+ Graph a,b;Frame frame;sink::RgbaImage first,second;+ bool ok=frame.makeRamp(30,190)&&a.startColors(missing)&&b.startColors(reference);+ missing.color.exposure=reference.color.exposure=.25f;missing.additionalColors[0].contrast=reference.additionalColors[0].contrast=10;+ ok=ok&&a.apply(missing)&&b.apply(reference)&&a.render(frame,first)&&b.render(frame,second);+ check(ok&&first.pixels==second.pixels,"missing primary and secondary LUTs stay disabled after live edits");+ }+ // Additional grades run after ingress tone mapping. Their LUT contract is+ // the working texture's domain, not the source video's original transfer.+ {+ const engine::ColorLutStore store(runtime::localDataDirectory());+ std::filesystem::create_directories(store.folder());+ const std::wstring name=L"gpu-post-tonemap-halve.cube";+ {+ std::ofstream file(store.folder()/name);file<<"LUT_3D_SIZE 2\n";+ for(int b=0;b<2;++b)for(int g=0;g<2;++g)for(int r=0;r<2;++r)+ file<<r*.5f<<' '<<g*.5f<<' '<<b*.5f<<'\n';+ }+ for(bool hlg:{false,true}){+ engine::EnhancementSettings plain,srgb,pq;+ srgb.additionalColorCount=1;auto& grade=srgb.additionalColors[0];+ grade.enabled=true;grade.setLutName(name);grade.lutInputSpace=engine::ColorSettings::kLutInputSrgb;+ pq=srgb;pq.additionalColors[0].lutInputSpace=engine::ColorSettings::kLutInputPq;+ auto baseline=std::make_unique<Graph>(),accepted=std::make_unique<Graph>(),rejected=std::make_unique<Graph>();+ Frame frame;sink::RgbaImage reference,withSrgb,withPq;+ bool ok=frame.makeHdr(hlg)&&baseline->startColors(plain,true,false)&&accepted->startColors(srgb,true,false)&&+ rejected->startColors(pq,true,false)&&baseline->render(frame,reference)&&accepted->render(frame,withSrgb)&&rejected->render(frame,withPq);+ int maxError=999;+ if(ok&&!reference.pixels.empty()&&reference.pixels.size()==withSrgb.pixels.size()){+ maxError=0;+ for(size_t i=0;i<reference.pixels.size();++i)if(i%4!=3)+ maxError=std::max(maxError,std::abs(int(withSrgb.pixels[i])-int(std::lround(reference.pixels[i]*.5f))));+ }+ check(ok&&accepted->g.colorLutNotice().empty()&&maxError<=2&&maxDifference(reference,withSrgb)>20,+ std::format("{} to SDR standalone sRGB LUT halves coded ramp (maxError={})",hlg?"HLG":"PQ",maxError));+ check(ok&&!rejected->g.colorLutNotice().empty()&&reference.pixels==withPq.pixels,+ std::format("{} to SDR rejects standalone PQ LUT without changing pixels",hlg?"HLG":"PQ"));+ engine::EnhancementSettings noLut=pq;noLut.additionalColors[0].lutName={};+ noLut.additionalColors[0].exposure=pq.additionalColors[0].exposure=.25f;+ auto editedReference=std::make_unique<Graph>();sink::RgbaImage edited,expected;+ ok=ok&&rejected->apply(pq)&&editedReference->startColors(noLut,true,false)&&+ rejected->render(frame,edited)&&editedReference->render(frame,expected);+ check(ok&&edited.pixels==expected.pixels,+ std::format("{} to SDR rejected PQ LUT stays disabled after live edits",hlg?"HLG":"PQ"));+ }+ std::error_code ec;std::filesystem::remove(store.folder()/name,ec);+ }+ for(bool hlg:{false,true}){+ engine::EnhancementSettings fused,standalone;+ fused.color.enabled=true;fused.color.exposure=.75f;+ standalone.additionalColorCount=1;standalone.additionalColors[0]=fused.color;+ Graph a,b;Frame frame;pipeline::EnhanceGraph::FrameOutputs oa,ob;+ std::vector<uint8_t> first,second;+ const bool ok=frame.makeHdr(hlg)&&a.startColors(fused,true,true)&&b.startColors(standalone,true,true)&&+ a.g.process(frame.frame,0,true,oa,1)&&b.g.process(frame.frame,0,true,ob,1)&&+ readReference(a,a.g.videoFrameResource(oa.videoSlot),first)&&readReference(b,b.g.videoFrameResource(ob.videoSlot),second);+ const auto half=[](uint16_t h){+ const unsigned exponent=(h>>10)&31,mantissa=h&1023;+ const float value=exponent?std::ldexp(1.f+float(mantissa)/1024,int(exponent)-15):std::ldexp(float(mantissa),-24);+ return h&0x8000?-value:value;+ };+ float maxError=0,maxValue=0;+ if(ok&&first.size()==second.size())for(size_t i=0;i<first.size();i+=2){+ const float x=half(uint16_t(first[i])|(uint16_t(first[i+1])<<8));+ const float y=half(uint16_t(second[i])|(uint16_t(second[i+1])<<8));+ maxError=std::max(maxError,std::abs(x-y));maxValue=std::max(maxValue,y);+ }+ check(ok&&!first.empty()&&first.size()==second.size()&&maxError<=.04f&&maxValue>1,+ std::format("native {} fused/standalone FP16 full-ramp maxError={} maxValue={}",hlg?"HLG":"PQ",maxError,maxValue));+ }+ {+ engine::EnhancementSettings settings;settings.color.enabled=true;settings.additionalColorCount=5;+ for(auto& color:settings.additionalColors)color.enabled=true;+ Graph streamed,reference;Frame frame;pipeline::EnhanceGraph::FrameOutputs outputs;+ bool ok=frame.makeRamp(30,160)&&streamed.startColors(settings);+ for(unsigned i=0;ok&&i<24;++i){+ settings.color.exposure=float(i%4)*.1f;+ settings.color.curves[0].points[1].y=.85f+float(i%4)*.04f;+ for(unsigned c=0;c<5;++c)settings.additionalColors[c].saturation=float((i+c)%6)*2;+ ok=streamed.apply(settings)&&streamed.g.process(frame.frame,i*16.667,i==0,outputs,i+1);+ }+ sink::RgbaImage first,second;+ ok=ok&&sink::readRgba8(streamed.ctx,streamed.ring,streamed.g.videoFrameResource(outputs.videoSlot),first)&&+ reference.startColors(settings)&&reference.render(frame,second);+ check(ok&&maxDifference(first,second)<=1,"24 six-grade live updates without per-frame readback match a fresh graph");+ }+ {+ engine::EnhancementSettings fused,standalone;+ fused.color.enabled=true;fused.color.exposure=0.55f;fused.color.contrast=12;fused.color.temperature=8;+ standalone.additionalColorCount=1;standalone.additionalColors[0]=fused.color;+ Graph a,b;Frame ramp;sink::RgbaImage first,second;+ const bool ok=ramp.makeRamp(28,210)&&a.startColors(fused)&&b.startColors(standalone)&&a.render(ramp,first)&&b.render(ramp,second);+ check(ok&&maxDifference(first,second)<=2,"standalone and fused SDR grades agree within 2 codes over a full ramp");+ standalone.additionalColors[0].exposure=-0.5f;+ sink::RgbaImage edited;+ check(ok&&b.apply(standalone)&&b.render(ramp,edited)&&maxDifference(second,edited)>20,"independent color live parameters update the actual GPU output");+ }+ {+ engine::EnhancementSettings ab,ba;ab.color.enabled=true;ab.color.exposure=1;+ ab.additionalColorCount=1;ab.additionalColors[0].enabled=true;ab.additionalColors[0].contrast=65;+ ba=ab;std::swap(ba.color,ba.additionalColors[0]);+ Graph a,b;Frame ramp;sink::RgbaImage first,second;+ const bool ok=ramp.makeRamp(35,180)&&a.startColors(ab)&&b.startColors(ba)&&a.render(ramp,first)&&b.render(ramp,second);+ check(ok&&maxDifference(first,second)>8,"two GPU color instances preserve noncommutative execution order");+ }+ {+ const engine::ColorLutStore store(runtime::localDataDirectory());+ std::filesystem::create_directories(store.folder());+ const unsigned sizes[]={2,3,5,17,33,4}; // exercise 256-byte padded rows+ engine::EnhancementSettings settings;settings.additionalColorCount=5;+ for(unsigned i=0;i<6;++i){+ auto& color=i?settings.additionalColors[i-1]:settings.color;+ color.enabled=true;color.lutInputSpace=engine::ColorSettings::kLutInputSrgb;+ color.setLutName(L"gpu-multi-"+std::to_wstring(i)+L".cube");+ std::ofstream file(store.folder()/color.lutNameString());+ file<<"LUT_3D_SIZE "<<sizes[i]<<'\n';+ for(unsigned z=0;z<sizes[i];++z)for(unsigned y=0;y<sizes[i];++y)for(unsigned x=0;x<sizes[i];++x){+ const float d=float(sizes[i]-1);+ file<<(float(x)/d*(.90f+.01f*i)+.008f*(i+1))<<' '+ <<(float(y)/d*(.93f-.01f*i)+.005f*(6-i))<<' '+ <<(float(z)/d*(.88f+.015f*i)+.01f*(i%3))<<'\n';+ }+ }+ Graph graph;Frame ramp;bool ok=ramp.makeRamp(32,196);+ for(unsigned cycle=0;cycle<3;++cycle){+ sink::RgbaImage result;ok=ok&&graph.startColors(settings)&&graph.render(ramp,result);+ int maxError=0,minValue=255,maxValue=0;+ if(ok){+ for(int y=0;y<kSize;++y)for(int x=0;x<kSize;++x){+ float r=ramp.frame->data[0][y*ramp.frame->linesize[0]+x*4]/255.0f,g=r,b=r;+ for(unsigned i=0;i<6;++i){r=r*(.90f+.01f*i)+.008f*(i+1);g=g*(.93f-.01f*i)+.005f*(6-i);b=b*(.88f+.015f*i)+.01f*(i%3);}+ const float expected[]={r,g,b};+ for(unsigned c=0;c<3;++c){const int value=result.pixels[(size_t(y)*kSize+x)*4+c];+ maxError=std::max(maxError,std::abs(value-int(std::lround(expected[c]*255))));minValue=std::min(minValue,value);maxValue=std::max(maxValue,value);}+ }+ }+ check(ok&&maxError<=3&&minValue>0&&maxValue-minValue>30,std::format("six independent LUTs cycle={} maxError={} min={} max={} (nonblack/nonconstant)",cycle,maxError,minValue,maxValue));+ if(ok){+ check(!graph.g.setColorLut(nullptr,2,1)&&!graph.g.setColorLut(nullptr,2,6),"invalid LUT payload/index rejected without replacing resources");+ graph.g.shutdown();graph.g.shutdown();+ check(!graph.g.colorGradeActive(),"shutdown releases and resets all color instances (idempotent)");+ }+ }+ for(unsigned i=0;i<6;++i){std::error_code ec;std::filesystem::remove(store.folder()/(L"gpu-multi-"+std::to_wstring(i)+L".cube"),ec);}+ }{Graph graph;Frame red;bool ready=graph.start(true)&&red.make(200,0,0);diff --git a/tests/integration/ExportColorChainTest.h b/tests/integration/ExportColorChainTest.hnew file mode 100644index 00000000..57e4516b--- /dev/null+++ b/tests/integration/ExportColorChainTest.h@@ -0,0 +1,180 @@+#pragma once+// Test-only end-to-end coverage: the production D3D12/NVENC exporter writes+// files, then the existing software decoder compares their active pixels.+// No GPU video readback is added to the player or exporter.+#include "veyra/engine/ColorLut.h"+#include "veyra/engine/VideoExportJob.h"+#include "veyra/source/MediaFileSource.h"+#include "veyra/RuntimePaths.h"+#include <algorithm>+#include <array>+#include <chrono>+#include <filesystem>+#include <fstream>+#include <iostream>+#include <thread>+#include <vector>+extern "C" {+#include <libavutil/frame.h>+#include <libavutil/imgutils.h>+}++namespace {+constexpr unsigned kExportColorFrames=12;+std::string exportColorPathText(const std::filesystem::path& path){+ const auto text=path.u8string();return {text.begin(),text.end()};+}+struct ExportColorFrame {+ int width=0,height=0,format=0;+ veyra::pipeline::Rational pts;+ std::vector<uint8_t> pixels;+};+using ExportColorFrames=std::vector<ExportColorFrame>;++bool decodeExportColorFrames(const std::filesystem::path& path,ExportColorFrames& frames){+ using namespace veyra;+ source::SourceOpenDesc desc;desc.path=path.wstring();desc.preferHardwareDecode=false;+ source::MediaFileSource source;if(!source.open(desc))return false;+ const auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(20);+ while(std::chrono::steady_clock::now()<deadline){+ pipeline::FramePacket packet;const AVFrame* frame=nullptr;+ const auto status=source.read(packet,&frame);+ if(status==source::SourceReadStatus::Eos)return frames.size()==kExportColorFrames;+ if(status==source::SourceReadStatus::Waiting){std::this_thread::sleep_for(std::chrono::milliseconds(1));continue;}+ if(status!=source::SourceReadStatus::Frame||!frame||frames.size()>=kExportColorFrames)return false;+ // This fixture is SDR H.264; comparing bytes of a 10-bit frame would+ // make the predeclared code-value difference threshold meaningless.+ if(frame->format!=AV_PIX_FMT_YUV420P||frame->width<=0||frame->height<=0||+ frame->width>3840||frame->height>2160||packet.pts.isUnknown())return false;+ ExportColorFrame result{frame->width,frame->height,frame->format,packet.pts,{}};+ const auto format=static_cast<AVPixelFormat>(frame->format);+ const int size=av_image_get_buffer_size(format,frame->width,frame->height,1);+ if(size<=0)return false;+ result.pixels.resize(size);+ if(av_image_copy_to_buffer(result.pixels.data(),size,frame->data,frame->linesize,+ format,frame->width,frame->height,1)!=size)return false;+ frames.push_back(std::move(result));+ }+ return false;+}++struct ExportColorDifference {+ bool comparable=true;+ unsigned maximum=0;+ uint64_t changed=0,total=0;+};+ExportColorDifference exportColorDifference(const ExportColorFrames& a,const ExportColorFrames& b){+ ExportColorDifference result;+ if(a.size()!=kExportColorFrames||b.size()!=a.size()){result.comparable=false;return result;}+ for(size_t f=0;f<a.size();++f){+ if(a[f].width!=b[f].width||a[f].height!=b[f].height||a[f].format!=b[f].format||+ !a[f].pts.equals(b[f].pts)||a[f].pixels.size()!=b[f].pixels.size()){result.comparable=false;return result;}+ result.total+=a[f].pixels.size();+ for(size_t p=0;p<a[f].pixels.size();++p){+ const unsigned delta=unsigned(std::abs(int(a[f].pixels[p])-int(b[f].pixels[p])));+ result.maximum=std::max(result.maximum,delta);result.changed+=delta!=0;+ }+ }+ return result;+}+bool exportColorChanged(const ExportColorDifference& difference){+ // Registered before running: >=2 code values and >=1% changed samples.+ return difference.comparable&&difference.maximum>=2&&difference.changed*100>=difference.total;+}++bool runExportColorChainTest(const std::filesystem::path& input,const std::filesystem::path& output){+ using namespace veyra;using namespace veyra::engine;+ // Explicitly acknowledge the staging data root, so accidental execution+ // beside the user's normal application cannot create test LUTs there.+ wchar_t expectedRoot[32768]{};+ const DWORD length=GetEnvironmentVariableW(L"VEYRA_TEST_COLOR_CHAIN_DATA_ROOT",expectedRoot,32768);+ if(!length||length>=32768||!std::filesystem::equivalent(expectedRoot,runtime::localDataDirectory())||+ !std::filesystem::is_regular_file(input)||std::filesystem::exists(output))return false;+ if(!std::filesystem::create_directories(output))return false;+ const ColorLutStore store(runtime::localDataDirectory());std::filesystem::create_directories(store.folder());+ std::cout<<"COLOR-WORKER dataRoot="<<exportColorPathText(runtime::localDataDirectory())<<" output="<<exportColorPathText(output)<<'\n';+ EnhancementSettings plain;plain.nr=plain.sr=false;plain.multiplier=1;plain.nrPolicy=pipeline::NrSizePolicy::Native;+ auto six=plain;six.additionalColorCount=5;+ const unsigned sizes[]={2,3,5,17,33,4};+ for(unsigned i=0;i<kMaxColorInstances;++i){+ auto& color=i?six.additionalColors[i-1]:six.color;+ color.enabled=true;color.lutInputSpace=ColorSettings::kLutInputSrgb;+ color.setLutName(L"worker-color-"+std::to_wstring(GetCurrentProcessId())+L"-"+std::to_wstring(i)+L".cube");+ const auto path=store.folder()/color.lutNameString();+ if(std::filesystem::exists(path))return false;+ std::ofstream file(path);file.precision(9);file<<"LUT_3D_SIZE "<<sizes[i]<<'\n';+ for(unsigned z=0;z<sizes[i];++z)for(unsigned y=0;y<sizes[i];++y)for(unsigned x=0;x<sizes[i];++x){+ const float d=float(sizes[i]-1);+ file<<(float(x)/d*(.90f+.01f*i)+.008f*(i+1))<<' '+ <<(float(y)/d*(.93f-.01f*i)+.005f*(6-i))<<' '+ <<(float(z)/d*(.88f+.015f*i)+.01f*(i%3))<<'\n';+ }+ file.close();if(!file)return false;+ ColorLutData lut;if(!store.resolve(color.lutNameString(),lut)||lut.size!=int(sizes[i]))return false;+ std::filesystem::copy_file(path,output/path.filename());+ }+ struct Case {std::wstring name;EnhancementSettings settings;};+ auto one=plain;one.color=six.color;+ auto disabled=six;disabled.color.enabled=false;disabled.additionalColors[2].enabled=false;+ auto reversed=six;std::array<ColorSettings,kMaxColorInstances> colors;+ colors[0]=six.color;for(unsigned i=1;i<kMaxColorInstances;++i)colors[i]=six.additionalColors[i-1];+ reversed.color=colors.back();for(unsigned i=1;i<kMaxColorInstances;++i)reversed.additionalColors[i-1]=colors[kMaxColorInstances-1-i];+ std::vector<Case> cases{{L"plain",plain},{L"one",one},{L"six",six},{L"disabled-first-middle",disabled},{L"reverse",reversed}};+ for(unsigned i=0;i<kMaxColorInstances;++i){+ auto without=six;(i?without.additionalColors[i-1]:without.color).enabled=false;+ cases.push_back({L"without-"+std::to_wstring(i),without});+ }+ ExportColorFrames plainFrames,oneFrames,sixFrames;bool all=true;unsigned passed=0;+ for(size_t index=0;index<cases.size();++index){+ auto& test=cases[index];test.settings.revision=5300+index;+ const auto directPath=output/(test.name+L"-direct.mp4");+ const auto workerPath=output/(test.name+L"-worker.mp4");+ std::atomic<bool> cancel=false;ExportCounts counts;bool directNvenc=false;+ const bool direct=exportVideo(input.wstring(),directPath.wstring(),PlayerOptions::from(test.settings),false,cancel,+ [&](double progress,const std::wstring& message){if(progress>=1)directNvenc=message.find(L"NVENC")!=std::wstring::npos;},+ kExportColorFrames,{},[&](const ExportCounts& value){counts=value;});+ ExportJobSnapshot snapshot;bool launched=false;+ {+ ExportJobManager manager;launched=manager.start(input.wstring(),workerPath.wstring(),test.settings,false,kExportColorFrames);+ const auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(30);+ do{snapshot=manager.poll();if(!snapshot.active())break;std::this_thread::sleep_for(std::chrono::milliseconds(10));}+ while(std::chrono::steady_clock::now()<deadline);+ if(snapshot.active())manager.cancel();+ }+ if(!snapshot.workerLog.empty()&&std::filesystem::is_regular_file(snapshot.workerLog))+ std::filesystem::copy_file(snapshot.workerLog,output/(test.name+L"-worker.log"));+ bool workerNvenc=false,workerD3D12=false;+ std::ifstream workerLog(output/(test.name+L"-worker.log"));+ for(std::string line;std::getline(workerLog,line);){+ workerNvenc=workerNvenc||line.find("encoder selected=NVIDIA-NVENC")!=std::string::npos;+ workerD3D12=workerD3D12||line.find("OpenD3D12Session status=0")!=std::string::npos;+ }+ ExportColorFrames directFrames,workerFrames;+ const bool decoded=direct&&snapshot.state==ExportState::Succeeded&&+ decodeExportColorFrames(directPath,directFrames)&&decodeExportColorFrames(workerPath,workerFrames);+ const auto difference=exportColorDifference(directFrames,workerFrames);+ bool ok=launched&&direct&&decoded&&directNvenc&&workerNvenc&&workerD3D12&&counts.source==kExportColorFrames&&counts.encoded==kExportColorFrames&&+ counts.generated==0&&counts.holds==0&&snapshot.sourceFrames==kExportColorFrames&&snapshot.encoded==kExportColorFrames&&+ snapshot.generated==0&&snapshot.holds==0&&snapshot.frozen==test.settings&&snapshot.frozenRevision==test.settings.revision&&+ snapshot.workerPid!=0&&snapshot.workerPid!=GetCurrentProcessId()&&+ std::filesystem::is_regular_file(output/(test.name+L"-worker.log"))&&difference.comparable&&difference.maximum==0;+ const auto changed=exportColorDifference(workerFrames,index>2?sixFrames:plainFrames);+ if(index>0)ok=ok&&exportColorChanged(changed);+ if(index==2)ok=ok&&exportColorChanged(exportColorDifference(workerFrames,oneFrames));+ std::cout<<"COLOR-WORKER case="<<exportColorPathText(test.name)<<" direct="<<direct<<" state="<<int(snapshot.state)+ <<" directNvenc="<<directNvenc<<" workerNvenc="<<workerNvenc<<" workerD3D12="<<workerD3D12+ <<" directSource="<<counts.source<<" directEncoded="<<counts.encoded<<" workerSource="<<snapshot.sourceFrames+ <<" workerEncoded="<<snapshot.encoded<<" workerGenerated="<<snapshot.generated<<" workerHolds="<<snapshot.holds+ <<" frozenEqual="<<(snapshot.frozen==test.settings)<<" workerPid="<<snapshot.workerPid<<" decodedFrames="<<workerFrames.size()+ <<" equalPixels="<<(difference.comparable&&difference.maximum==0)<<" maxError8="<<difference.maximum+ <<" changedCodes="<<difference.changed<<" effectMaxError8="<<changed.maximum+ <<" effectChangedCodes="<<changed.changed<<" effectTotalCodes="<<changed.total<<" passed="<<ok<<'\n';+ if(index==0)plainFrames=std::move(workerFrames);+ if(index==1)oneFrames=std::move(workerFrames);+ if(index==2)sixFrames=std::move(workerFrames);+ all=all&&ok;passed+=ok;+ }+ std::cout<<"COLOR-WORKER SUMMARY passed="<<passed<<" cases="<<cases.size()<<" gpuReadback=false\n";+ return all;+}+} // namespacediff --git a/tests/integration/ExportWorkerFailureTests.cpp b/tests/integration/ExportWorkerFailureTests.cppindex c2bdb994..88e72858 100644--- a/tests/integration/ExportWorkerFailureTests.cpp+++ b/tests/integration/ExportWorkerFailureTests.cpp@@ -1,5 +1,6 @@#include "veyra/engine/ExportJobManager.h"#include "veyra/engine/FgCompatibilityProbe.h"+#include "ExportColorChainTest.h"#include <chrono>#include <filesystem>#include <iostream>@@ -20,6 +21,14 @@ int wmain(int argc,wchar_t** argv){return runFgCompatibilityProbe(reinterpret_cast<HANDLE>(_wcstoui64(argv[2],nullptr,10)));if(argc!=4)return 2;const std::wstring mode=argv[1];+ if(mode==L"color-chain"){+ const HRESULT com=CoInitializeEx(nullptr,COINIT_MULTITHREADED);+ if(FAILED(com))return 1;+ bool ok=false;+ try{ok=runExportColorChainTest(argv[2],argv[3]);}+ catch(const std::exception& e){std::cerr<<"COLOR-WORKER exception="<<e.what()<<'\n';}+ CoUninitialize();return ok?0:1;+ }const bool encoder=mode==L"encoder",cancel=mode==L"cancel";if(encoder)SetEnvironmentVariableW(L"VEYRA_TEST_NVENC_FIRST_OPEN_FAILS",L"1");else{diff --git a/tests/integration/FsrFgDispatchTests.cpp b/tests/integration/FsrFgDispatchTests.cppnew file mode 100644index 00000000..2cd644b8--- /dev/null+++ b/tests/integration/FsrFgDispatchTests.cpp@@ -0,0 +1,107 @@+#include "veyra/gfx/FsrFgPresenter.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include "veyra/gfx/CommandSlotRing.h"+#include "veyra/pipeline/GpuPassUtils.h"+#include <d3d12sdklayers.h>+#include <cmath>+#include <cstring>+#include <iostream>+#include <vector>++// Real GPU interpolation contract, with no window or swapchain. Test-only+// pixel readback proves a moving square reaches its temporal midpoint.+int wmain(int argc, wchar_t** argv) {+ using namespace veyra;+ constexpr unsigned W = 640, H = 360, pitch = W * 4;+ const bool amd = argc > 1 && std::wstring_view(argv[1]) == L"amd";+ gfx::D3D12DeviceContext ctx; gfx::CommandSlotRing ring; Status st = Status::Ok;+ gfx::DeviceContextDesc desc; desc.enableDebugLayer = true; desc.requiredVendorId = amd ? 0x1002 : 0;+ bool ok = ctx.initialize(desc, st) && ring.initialize(ctx.device(), ctx.directQueue(), ctx.fence(), ctx.fenceEvent(), 4, st);+ if (!ok) return 2;+ Microsoft::WRL::ComPtr<ID3D12InfoQueue> info;+ ctx.device()->QueryInterface(IID_PPV_ARGS(&info));+ auto color = pipeline::makeTexture(ctx.device(), W, H, DXGI_FORMAT_R8G8B8A8_UNORM, false);+ auto motion = pipeline::makeTexture(ctx.device(), W, H, DXGI_FORMAT_R16G16_FLOAT, false);+ auto depth = pipeline::makeTexture(ctx.device(), W, H, DXGI_FORMAT_R32_FLOAT, false);+ auto output = pipeline::makeTexture(ctx.device(), W, H, DXGI_FORMAT_R8G8B8A8_UNORM, true);+ auto upload = pipeline::makeUploadBuffer(ctx.device(), uint64_t(pitch) * H * 3);+ Microsoft::WRL::ComPtr<ID3D12Resource> readback;+ D3D12_RESOURCE_DESC buffer{}; buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;+ buffer.Width = uint64_t(pitch) * H; buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = 1;+ buffer.SampleDesc.Count = 1; buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;+ D3D12_HEAP_PROPERTIES heap{}; heap.Type = D3D12_HEAP_TYPE_READBACK;+ ok = color && motion && depth && output && upload &&+ SUCCEEDED(ctx.device()->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer,+ D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback)));+ uint8_t* pixels = nullptr;+ ok = ok && SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast<void**>(&pixels)));+ unsigned samples = 0, intermediate = 0;+ double errorSum = 0;+ for (unsigned cycle = 0; ok && cycle < 3; ++cycle) {+ gfx::FsrFgPresenter fg;+ ok = fg.initializeIndependent(ctx.device(), W, H, DXGI_FORMAT_R8G8B8A8_UNORM, false);+ for (unsigned frame = 0; ok && frame < 16; ++frame) {+ const unsigned left = 80 + frame * 16;+ for (unsigned y = 0; y < H; ++y) for (unsigned x = 0; x < W; ++x) {+ const size_t at = size_t(y) * pitch + x * 4;+ const uint8_t value = y >= 140 && y < 220 && x >= left && x < left + 80 ? 240 : 32;+ pixels[at] = pixels[at + 1] = pixels[at + 2] = value; pixels[at + 3] = 255;+ const uint16_t mv[2] = {0xcc00, 0}; // current->previous, -16 pixels+ std::memcpy(pixels + size_t(pitch) * H + at, mv, 4);+ const float z = 0.5f;+ std::memcpy(pixels + size_t(pitch) * H * 2 + at, &z, 4);+ }+ unsigned slot = 0; auto* list = ring.acquireNext(slot, st); if (!list) { ok = false; break; }+ pipeline::StateTracker states;+ ID3D12Resource* inputs[] = {color.Get(), motion.Get(), depth.Get()};+ const DXGI_FORMAT formats[] = {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R16G16_FLOAT, DXGI_FORMAT_R32_FLOAT};+ for (unsigned i = 0; i < 3; ++i) {+ states.transition(list, inputs[i], D3D12_RESOURCE_STATE_COPY_DEST);+ D3D12_TEXTURE_COPY_LOCATION dst{}; dst.pResource = inputs[i]; dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;+ D3D12_TEXTURE_COPY_LOCATION src{}; src.pResource = upload.Get(); src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;+ src.PlacedFootprint.Offset = uint64_t(pitch) * H * i;+ src.PlacedFootprint.Footprint = {formats[i], W, H, 1, pitch};+ list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);+ states.transition(list, inputs[i], D3D12_RESOURCE_STATE_COMMON);+ }+ ok = fg.generate(list, color.Get(), motion.Get(), depth.Get(), output.Get(), frame == 0, 1000.0f / 30);+ if (!ok) { ring.discardRecording(); break; }+ states.transition(list, output.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE);+ D3D12_TEXTURE_COPY_LOCATION src{}; src.pResource = output.Get(); src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;+ D3D12_TEXTURE_COPY_LOCATION dst{}; dst.pResource = readback.Get(); dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;+ dst.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, W, H, 1, pitch};+ list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);+ states.transition(list, output.Get(), D3D12_RESOURCE_STATE_COMMON);+ ok = ring.submitAndSignal(slot) && ctx.waitForFenceValue(ring.lastSignaledValue());+ const uint8_t* captured = nullptr; D3D12_RANGE read{0, size_t(pitch) * H};+ ok = ok && SUCCEEDED(readback->Map(0, &read, reinterpret_cast<void**>(const_cast<uint8_t**>(&captured))));+ if (ok && frame >= 3) {+ uint64_t sum = 0, count = 0;+ for (unsigned y = 156; y < 204; ++y) for (unsigned x = 0; x < W; ++x)+ if (captured[size_t(y) * pitch + x * 4] > 200) { sum += x; ++count; }+ const double center = count ? double(sum) / count : -10000;+ const double expected = left + 39.5 - 8;+ const double error = std::abs(center - expected);+ ++samples; errorSum += error;+ if (error < 4) ++intermediate;+ std::cout << "MIDPOINT cycle=" << cycle << " frame=" << frame << " center=" << center+ << " expected=" << expected << " error=" << error << " pixels=" << count << std::endl;+ }+ if (captured) { D3D12_RANGE written{0, 0}; readback->Unmap(0, &written); }+ }+ ok = ring.drainQueue() && ok; fg.shutdown();+ }+ if (pixels) upload->Unmap(0, nullptr);+ unsigned errors = 0;+ if (info) for (UINT64 i = 0; i < info->GetNumStoredMessagesAllowedByRetrievalFilter(); ++i) {+ SIZE_T size = 0; info->GetMessage(i, nullptr, &size); std::vector<uint8_t> data(size);+ auto* message = reinterpret_cast<D3D12_MESSAGE*>(data.data());+ if (SUCCEEDED(info->GetMessage(i, message, &size)) && message->Severity <= D3D12_MESSAGE_SEVERITY_ERROR) {+ ++errors; std::cout << "GPU_ERROR " << message->pDescription << std::endl;+ }+ }+ ok = ok && samples >= 30 && intermediate == samples && errorSum / std::max(1u, samples) < 3 && errors == 0;+ std::cout << "FSR_INDEPENDENT pass=" << ok << " samples=" << samples << " intermediate=" << intermediate+ << " meanError=" << errorSum / std::max(1u, samples) << " debugErrors=" << errors << std::endl;+ return ok ? 0 : 1;+}diff --git a/tests/integration/FsrFgSwitchTests.cpp b/tests/integration/FsrFgSwitchTests.cppnew file mode 100644index 00000000..0ae6d061--- /dev/null+++ b/tests/integration/FsrFgSwitchTests.cpp@@ -0,0 +1,151 @@+#include "veyra/engine/VideoPresenter.h"+#include "veyra/pipeline/EnhanceGraph.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include "veyra/sink/ImageExportSink.h"+#include <d3d12sdklayers.h>+#include <filesystem>+#include <iostream>+#include <vector>+extern "C" {+#include <libavutil/frame.h>+#include <libavutil/pixfmt.h>+}++// One real HWND, one process. Test reads back only to establish that actual+// generated/real presentations contain pixels; production never calls it.+int wmain(int argc, wchar_t** argv) {+ using namespace veyra;+ if(argc<2||FAILED(CoInitializeEx(nullptr,COINIT_MULTITHREADED)))return 2;+ const bool amd=argc>2&&std::wstring_view(argv[2])==L"amd";+ std::filesystem::create_directories(argv[1]);+ HWND window=CreateWindowExW(0,L"STATIC",L"Veyra FG switch acceptance",WS_POPUP,+ 40,40,640,360,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status st=Status::Ok;+ gfx::DeviceContextDesc device;device.enableDebugLayer=true;device.requiredVendorId=amd?0x1002:0;+ bool ok=window&&ctx.initialize(device,st)&&ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,st);+ if(!ok){if(window)DestroyWindow(window);return 2;}+ Microsoft::WRL::ComPtr<ID3D12InfoQueue> info;ctx.device()->QueryInterface(IID_PPV_ARGS(&info));+ ctx.directQueue()->SetName(L"Veyra FG acceptance producer queue");+ UINT64 diagnosed=0;+ const auto diagnose=[&](unsigned cycle,unsigned input,const char* stage){+ if(!info)return;+ const auto count=info->GetNumStoredMessagesAllowedByRetrievalFilter();+ for(;diagnosed<count;++diagnosed){+ SIZE_T size=0;info->GetMessage(diagnosed,nullptr,&size);std::vector<uint8_t> data(size);+ auto* message=reinterpret_cast<D3D12_MESSAGE*>(data.data());+ if(SUCCEEDED(info->GetMessage(diagnosed,message,&size))&&message->Severity<=D3D12_MESSAGE_SEVERITY_ERROR)+ std::cout<<"GPU_DIAG cycle="<<cycle<<" input="<<input<<" stage="<<stage<<" "<<message->pDescription<<std::endl;+ }+ };+ pipeline::EnhanceGraph graph(ctx,ring);engine::VideoPresenter presenter;+ AVFrame* frame=av_frame_alloc();+ if(!frame){ring.shutdown();ctx.shutdown();DestroyWindow(window);CoUninitialize();return 2;}+ frame->format=AV_PIX_FMT_RGBA;frame->width=640;frame->height=360;+ frame->color_range=AVCOL_RANGE_JPEG;frame->color_trc=AVCOL_TRC_IEC61966_2_1;+ ok=av_frame_get_buffer(frame,32)>=0;+ struct Case{engine::FrameGenerationBackend backend;unsigned multiplier;};+ std::vector<Case> cases;+ for(unsigned repeat=0;repeat<3;++repeat){+ cases.push_back({engine::FrameGenerationBackend::Fsr,2});+ cases.push_back({engine::FrameGenerationBackend::XeSS,4});+ cases.push_back({engine::FrameGenerationBackend::Fsr,2});+ cases.push_back({engine::FrameGenerationBackend::XeSS,2});+ cases.push_back({engine::FrameGenerationBackend::Dlss,1});+ if(!amd)cases.push_back({engine::FrameGenerationBackend::Dlss,2});+ }+ uint64_t source=0;unsigned cycles=0,totalGenerated=0;+ for(const auto& c:cases){+ if(!ok)break;++cycles;+ pipeline::EnhanceGraphDesc desc;desc.sourceWidth=desc.workWidth=640;desc.sourceHeight=desc.workHeight=360;+ desc.rgbInput=true;desc.enableNr=desc.enableSr=false;desc.enableFg=c.multiplier>1;+ desc.fgMultiplier=std::max(2u,c.multiplier);desc.frameGenerationBackend=c.backend;+ desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();desc.settingsRevision=cycles;+ desc.opticalFlowBackend=amd?engine::OpticalFlowBackend::AmdFidelityFx:engine::OpticalFlowBackend::Nvidia;+ ok=graph.initialize(desc)&&presenter.open(ctx,window,graph)&&graph.createViews();+ if(!ok){std::cout<<"SWITCH_OPEN_FAIL backend="<<engine::frameGenerationBackendName(c.backend)<<" multiplier="<<c.multiplier<<std::endl;break;}+ for(unsigned slot=0;slot<2;++slot){+ graph.videoFrameResource(slot)->SetName(L"Veyra acceptance graph video");+ graph.generatedFrameResource(slot)->SetName(L"Veyra acceptance graph generated");+ }+ if(graph.presentDepth())graph.presentDepth()->SetName(L"Veyra acceptance graph depth");+ diagnose(cycles,0,"open");+ unsigned generated=0,nonblack=0;+ for(unsigned i=0;ok&&i<40;++i){+ if(i==20)SetWindowPos(window,nullptr,40,40,800,450,SWP_NOZORDER|SWP_NOACTIVATE);+ if(i==30)SetWindowPos(window,nullptr,40,40,640,360,SWP_NOZORDER|SWP_NOACTIVATE);+ const unsigned left=60+i*4;+ for(unsigned y=0;y<360;++y)for(unsigned x=0;x<640;++x){+ auto* p=frame->data[0]+size_t(y)*frame->linesize[0]+x*4;+ p[0]=uint8_t(y>130&&y<230&&x>=left&&x<left+80?230:32);+ p[1]=p[0];p[2]=p[0];p[3]=255;+ }+ ok=presenter.beginSourceInput()&&presenter.beginSourceProcessing();+ pipeline::EnhanceGraph::FrameOutputs out;+ ++source;+ ok=ok&&graph.process(frame,double(source-1)*1000/30,i==0||i==24,out,source);+ diagnose(cycles,i,"process");+ if(!ok)break;+ presenter.sourceProcessed(out.batch.identity);+ ok=ctx.waitForFenceValue(std::max(out.videoFenceValue,out.genFenceValue))&&graph.resolveGeneration(out);+ for(unsigned k=0;ok&&k<out.batch.count;++k){+ const auto& item=out.batch.frames[k];const bool gen=item.kind==pipeline::FrameKind::Generated;+ if(gen&&item.validity!=pipeline::GenerationValidity::Valid)continue;+ ok=presenter.present(ctx,ring,graph,item.lease->slot,gen,false,0,false,.5f,item.identity,{},item.pts100ns);+ diagnose(cycles,i,"present");+ if(gen)++generated;+ if(i==10||i==35){+ sink::RgbaImage image;+ // XeSS's proxy exposes buffers still used by its private+ // presentation queue. An application-queue fence cannot+ // authorize a test readback from that buffer. Validate its+ // real input here and use the SDK status for generated counts;+ // FSR/DLSS outputs are read from our owned presentation queue.+ ok=ok&&(c.backend==engine::FrameGenerationBackend::XeSS+ ?sink::readRgba8(ctx,ring,graph.videoFrameResource(item.lease->slot),image)+ :presenter.readPresentedFrameForTest(ctx,ring,image));+ diagnose(cycles,i,"readback");+ if(ok){+ uint64_t light=0;for(size_t p=0;p<image.pixels.size();p+=4)light+=image.pixels[p];+ ok=light>uint64_t(image.width)*image.height*10;+ if(ok)++nonblack;+ if(gen&&i==10)ok=sink::saveImage((std::filesystem::path(argv[1])/(std::to_wstring(cycles)+L"-generated.png")).wstring(),image)&&ok;+ }+ }+ }+ if(c.backend==engine::FrameGenerationBackend::XeSS)generated=unsigned(presenter.xessGeneratedCount());+ Sleep(12);+ }+ const unsigned minGenerated=c.multiplier>1?c.backend==engine::FrameGenerationBackend::XeSS?(c.multiplier-1)*25:25:0;+ ok=ok&&generated>=minGenerated&&nonblack>=2;+ totalGenerated+=generated;+ std::cout<<"SWITCH_CASE cycle="<<cycles<<" pid="<<GetCurrentProcessId()<<" hwnd="<<window+ <<" backend="<<engine::frameGenerationBackendName(c.backend)<<" multiplier="<<c.multiplier+ <<" generated="<<generated<<" nonblack="<<nonblack<<" pass="<<ok<<std::endl;+ ok=ring.drainQueue()&&ok;presenter.close();graph.shutdown();+ }+ if(ok){+ // Unsupported FSR 4 must fail before a swapchain is touched. The same+ // HWND must subsequently reopen, with no FSR 3.1 mislabeled as ML.+ pipeline::EnhanceGraphDesc ml;ml.sourceWidth=ml.workWidth=640;ml.sourceHeight=ml.workHeight=360;+ ml.rgbInput=ml.enableFg=true;ml.enableNr=ml.enableSr=false;ml.fgMultiplier=2;+ ml.frameGenerationBackend=engine::FrameGenerationBackend::Fsr4;ml.opticalFlowBackend=engine::OpticalFlowBackend::AmdFidelityFx;+ const bool accepted=graph.initialize(ml);+ if(accepted){std::cout<<"FSR4_AVAILABLE provider="<<graph.fsrProviderVersion()<<std::endl;graph.shutdown();}+ else{ok=graph.failedBackend()==engine::FailedBackend::Fg;graph.shutdown();+ ml.frameGenerationBackend=engine::FrameGenerationBackend::Fsr;+ ok=ok&&graph.initialize(ml)&&presenter.open(ctx,window,graph)&&graph.createViews();+ std::cout<<"FSR4_UNSUPPORTED_ROLLBACK pass="<<ok<<std::endl;+ presenter.close();graph.shutdown();}+ }+ unsigned errors=0;+ if(info)for(UINT64 i=0;i<info->GetNumStoredMessagesAllowedByRetrievalFilter();++i){+ SIZE_T size=0;info->GetMessage(i,nullptr,&size);std::vector<uint8_t> data(size);+ auto* message=reinterpret_cast<D3D12_MESSAGE*>(data.data());+ if(SUCCEEDED(info->GetMessage(i,message,&size))&&message->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){+ ++errors;std::cout<<"GPU_ERROR "<<message->pDescription<<std::endl;}+ }+ ok=ok&&errors==0&&cycles==cases.size();+ av_frame_free(&frame);ring.shutdown();ctx.shutdown();DestroyWindow(window);CoUninitialize();+ std::cout<<"FSR_SWITCH pass="<<ok<<" cycles="<<cycles<<" generated="<<totalGenerated<<" debugErrors="<<errors<<std::endl;+ return ok?0:1;+}diff --git a/tests/integration/ImageDimensionTests.cpp b/tests/integration/ImageDimensionTests.cppindex 839bea9a..a79042e8 100644--- a/tests/integration/ImageDimensionTests.cpp+++ b/tests/integration/ImageDimensionTests.cpp@@ -4,6 +4,7 @@#include "veyra/sink/ImageExportSink.h"#include "veyra/engine/EnhancementSettings.h"#include "veyra/engine/TiledImageProcessor.h"+#include "veyra/engine/GraphDescription.h"#include "veyra/pipeline/ColorMetadata.h"#include "veyra/ngx/NgxParameters.h"#include <filesystem>@@ -372,9 +373,60 @@ bool nrOptionalResourcePixels(const std::filesystem::path& directory,bool rgba=fstd::cout<<"NR_OPTIONAL_MATRIX executionPass="<<ok<<" expectedContractMatch="<<matrixMatch<<std::endl;return ok&&changed>100&&matrixMatch;}+bool tiledColors(unsigned width,unsigned height,unsigned count,bool sparse,const std::filesystem::path& directory){+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status;gfx::DeviceContextDesc device;device.enableDebugLayer=true;+ if(!ctx.initialize(device,status)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,status))return false;+ engine::EnhancementSettings settings;settings.additionalColorCount=count?count-1:0;+ for(unsigned i=0;i<count;++i){auto& c=i?settings.additionalColors[i-1]:settings.color;+ c.enabled=!sparse||(i!=0&&i!=2);c.exposure=.1f*float(i+1);c.contrast=float(i)*3;}+ pipeline::EnhanceGraphDesc desc;desc.rgbInput=true;desc.stillImage=true;desc.noFeatures=true;desc.noNgx=true;desc.outputDitherStep=0;+ engine::StageRequest request;request.width=width;request.height=height;request.stillImage=true;+ engine::describeStages(request,settings,desc);+ sink::RgbaImage source;source.width=width;source.height=height;source.pixels.resize(size_t(width)*height*4);+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x){auto* p=source.pixels.data()+(size_t(y)*width+x)*4;+ p[0]=uint8_t(24+(x*7+y*11)%144);p[1]=uint8_t(32+(x*3+y*5)%128);p[2]=uint8_t(40+(x*13+y*7)%120);p[3]=255;}+ const auto freeFrame=[](AVFrame* p){av_frame_free(&p);};+ std::unique_ptr<AVFrame,decltype(freeFrame)> frame(av_frame_alloc(),freeFrame);if(!frame)return false;+ frame->width=width;frame->height=height;frame->format=AV_PIX_FMT_RGBA;+ frame->color_range=AVCOL_RANGE_JPEG;frame->color_trc=AVCOL_TRC_IEC61966_2_1;frame->colorspace=AVCOL_SPC_RGB;+ if(av_frame_get_buffer(frame.get(),32)<0)return false;+ for(unsigned y=0;y<height;++y)memcpy(frame->data[0]+size_t(y)*frame->linesize[0],source.pixels.data()+size_t(y)*width*4,size_t(width)*4);+ sink::RgbaImage reference,result;pipeline::EnhanceGraph::FrameOutputs out;+ auto graph=std::make_unique<pipeline::EnhanceGraph>(ctx,ring);+ bool direct=graph->initialize(desc)&&graph->createViews()&&graph->process(frame.get(),0,true,out,1)&&+ sink::readRgba8(ctx,ring,graph->videoFrameResource(out.videoSlot),reference);+ out={};ring.drainQueue();graph->shutdown();graph.reset();+ std::atomic<bool> cancel=false;engine::TiledImageProcessor::Stats stats;+ const bool processed=engine::TiledImageProcessor::process(ctx,ring,source,result,desc,cancel,stats);+ bool ok=direct&&processed&&result.width==width&&result.height==height&&result.pixels.size()==source.pixels.size()&&reference.pixels.size()==source.pixels.size()&&stats.tiles==2&&stats.nrEvaluations==0;+ int maxError=0;size_t changed=0;+ if(direct&&reference.pixels.size()==source.pixels.size())for(size_t i=0;i<source.pixels.size();++i)+ if(i%4!=3&&std::abs(int(reference.pixels[i])-int(source.pixels[i]))>2)++changed;+ if(ok){for(size_t i=0;i<result.pixels.size();++i)maxError=std::max(maxError,std::abs(int(result.pixels[i])-int(reference.pixels[i])));+ ok=maxError<=1&&(count?changed>100:changed==0);+ const auto prefix="tiled-color-"+std::to_string(width)+"x"+std::to_string(height)+"-"+std::to_string(count)+(sparse?"-sparse":"");+ ok=sink::saveImage((directory/(prefix+"-full.png")).wstring(),reference)&&sink::saveImage((directory/(prefix+"-tiles.png")).wstring(),result)&&ok;}+ ring.drainQueue();pipeline::ComPtr<ID3D12InfoQueue> info;uint64_t errors=0;+ if(FAILED(ctx.device()->QueryInterface(IID_PPV_ARGS(&info))))ok=false;+ else for(UINT64 i=0;i<info->GetNumStoredMessages();++i){SIZE_T bytes=0;+ if(FAILED(info->GetMessage(i,nullptr,&bytes))){ok=false;break;}+ std::vector<uint8_t> storage(bytes);auto* message=reinterpret_cast<D3D12_MESSAGE*>(storage.data());+ if(FAILED(info->GetMessage(i,message,&bytes))){ok=false;break;}+ if(message->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;std::cerr<<message->pDescription<<'\n';}}+ ok=ok&&errors==0;+ std::cout<<"TILED_COLOR width="<<width<<" height="<<height<<" instances="<<count<<" sparse="<<sparse+ <<" direct="<<direct<<" tiled="<<processed<<" tiles="<<stats.tiles<<" maxError8="<<maxError<<" changed="<<changed<<" debugErrors="<<errors<<" pass="<<ok<<std::endl;+ info.Reset();ring.shutdown();ctx.shutdown();return ok;+}+bool tiledColorMatrix(const std::filesystem::path& directory){+ bool ok=true;for(unsigned count:{0u,1u,2u,6u})ok=tiledColors(1301,17,count,false,directory)&&ok;+ ok=tiledColors(17,1301,6,false,directory)&&ok;+ return tiledColors(1301,17,6,true,directory)&&ok;+}int wmain(int argc,wchar_t** argv){- if(argc!=2&&!(argc==3&&(std::wstring(argv[1])==L"--nr-optional"||std::wstring(argv[1])==L"--nr-optional-rgba")))return 2;CoInitializeEx(nullptr,COINIT_MULTITHREADED);std::filesystem::path directory(argv[argc-1]);std::filesystem::create_directories(directory);- if(argc==3){bool result=nrOptionalResourcePixels(directory,std::wstring(argv[1])==L"--nr-optional-rgba");CoUninitialize();return result?0:1;}+ if(argc!=2&&!(argc==3&&(std::wstring(argv[1])==L"--nr-optional"||std::wstring(argv[1])==L"--nr-optional-rgba"||std::wstring(argv[1])==L"--tiled-color")))return 2;CoInitializeEx(nullptr,COINIT_MULTITHREADED);std::filesystem::path directory(argv[argc-1]);std::filesystem::create_directories(directory);+ if(argc==3){bool result=std::wstring(argv[1])==L"--tiled-color"?tiledColorMatrix(directory):nrOptionalResourcePixels(directory,std::wstring(argv[1])==L"--nr-optional-rgba");CoUninitialize();return result?0:1;}+ if(!tiledColorMatrix(directory)){CoUninitialize();return 1;}bool ok=true;for(auto e:{pipeline::Extent{1,1},{257,513},{97,9001},{4097,257},{257,4097}}){if(!run(e.width,e.height,false,directory)){ok=false;break;}}if(ok)ok=run(257,513,true,directory);if(ok)ok=run(97,9001,true,directory);diff --git a/tests/integration/NrAntiFlickerTests.cpp b/tests/integration/NrAntiFlickerTests.cppnew file mode 100644index 00000000..d9fc6a14--- /dev/null+++ b/tests/integration/NrAntiFlickerTests.cpp@@ -0,0 +1,134 @@+// Stage-6 anti-flicker tier acceptance+// (docs/NR_FG_OPTIMIZATION_PLAN_2026-09-29.md §5A).+//+// Ported from SAOG0721/Magpie, GPL-3.0, commit+// 3841698348bfb246623d4acf791984c8b68a577b, tests/DLSSNRTemporalTests.cpp.+// The upstream tests are value-level checks on the tier arithmetic and the+// state machine; they are re-expressed here against Veyra's own types, and the+// GPU behaviour is covered by veyra_nr_temporal_gpu_tests.+//+// What each tier must guarantee:+// * Static never accumulates across a moving patch (this is the tier's+// whole point), so a moving block cannot smear.+// * Flow is the pre-tier behaviour and must stay bit-identical for a+// session that only ever knew `temporal=true`.+// * FlowPlus keeps its support channel in history alpha and refuses a+// correction whose direction reverses.+// * LowFrequency must still publish history when the half-resolution support+// is missing, rather than fabricating a zero observation.++#include "veyra/engine/EnhancementSettings.h"+#include "veyra/engine/EffectChain.h"++#include <cmath>+#include <iostream>+#include <string>++namespace {++int failures = 0;++void check(const char* name, bool ok)+{+ std::cout << name << '=' << (ok ? 1 : 0) << std::endl;+ if (!ok) ++failures;+}++// The tier is an enum the wire, presets and the bridge all narrow to an int.+// An out-of-range value must be rejected rather than silently truncated into a+// different tier, which would change behaviour on load.+void checkTierNarrowing()+{+ using namespace veyra::engine;+ check("off is valid", validNrAntiFlicker(NrAntiFlicker::Off));+ check("static is valid", validNrAntiFlicker(NrAntiFlicker::Static));+ check("flow is valid", validNrAntiFlicker(NrAntiFlicker::Flow));+ check("flow plus is valid", validNrAntiFlicker(NrAntiFlicker::FlowPlus));+ check("low frequency is valid", validNrAntiFlicker(NrAntiFlicker::LowFrequency));+ check("above range rejected", !validNrAntiFlicker(NrAntiFlicker(5)));+ check("far above range rejected", !validNrAntiFlicker(NrAntiFlicker(200)));+ // The default has to be the pre-tier behaviour: a chain that was created+ // before the tiers existed carries no tier field, and must keep meaning+ // what it meant.+ check("default tier preserves pre-tier behaviour", NrLayerSettings{}.antiFlicker == NrAntiFlicker::Flow);+ check("flat default tier preserves pre-tier behaviour", EnhancementSettings{}.nrAntiFlicker == NrAntiFlicker::Flow);+}++// The flat mirror and the list entry must agree, because the graph builds from+// whichever the path uses (describeNrLayers reads the list, the flat fields+// drive the single-layer API).+void checkFlatAndListAgree()+{+ using namespace veyra::engine;+ EnhancementSettings s;+ s.nr = true;+ s.nrLayerCount = 1;+ s.nrLayers[0].enabled = true;+ s.nrLayers[0].temporal = true;+ s.nrLayers[0].antiFlicker = NrAntiFlicker::LowFrequency;+ s.nrAntiFlicker = NrAntiFlicker::LowFrequency;+ check("flat and list agree on the tier", s.nrLayer(0).antiFlicker == s.nrAntiFlicker);+ // A layer's tier is only consulted when its temporal accumulation is on.+ // Presets store the tier unconditionally so toggling temporal back on+ // restores the user's chosen tier rather than resetting to the default.+ s.nrLayers[0].temporal = false;+ check("tier survives a temporal toggle", s.nrLayers[0].antiFlicker == NrAntiFlicker::LowFrequency);+}++// Validation must accept every tier and reject only genuinely invalid settings.+void checkValidation()+{+ using namespace veyra::engine;+ EnhancementSettings s;+ for (auto tier : {NrAntiFlicker::Off, NrAntiFlicker::Static, NrAntiFlicker::Flow,+ NrAntiFlicker::FlowPlus, NrAntiFlicker::LowFrequency}) {+ s.nrAntiFlicker = tier;+ s.nrLayers[0].antiFlicker = tier;+ check("every tier validates", s.validate().empty());+ }+ s = EnhancementSettings{};+ s.nrHoldStrength = 1.5f;+ check("stabiliser strength above 1 rejected", !s.validate().empty());+ s = EnhancementSettings{};+ s.nrHoldStrength = -0.1f;+ check("stabiliser strength below 0 rejected", !s.validate().empty());+ s = EnhancementSettings{};+ s.nrHoldTolerance = 2.0f;+ check("stabiliser tolerance above 1 rejected", !s.validate().empty());+ s = EnhancementSettings{};+ s.nrHoldStrength = 0.8f;+ s.nrHoldTolerance = 0.02f;+ check("stabiliser defaults are valid", s.validate().empty());+}++// The chain node carries the tier so the node editor and the list page edit the+// same value, per the 2026-09-28 user decision.+void checkChainCarriesTier()+{+ using namespace veyra::engine;+ ChainNode node;+ node.type = EffectType::NrEnhance;+ node.enabled = true;+ node.nr.temporal = true;+ node.nr.antiFlicker = NrAntiFlicker::Static;+ check("chain node defaults to flow", ChainNrParams{}.antiFlicker == NrAntiFlicker::Flow);+ check("chain node stores the tier", node.nr.antiFlicker == NrAntiFlicker::Static);+ ChainNode other = node;+ other.nr.antiFlicker = NrAntiFlicker::Static;+ check("equal tiers compare equal", node == other);+ other.nr.antiFlicker = NrAntiFlicker::FlowPlus;+ check("different tiers compare unequal", !(node == other));+}++} // namespace++int main()+{+ std::cout << "=== NR anti-flicker tier assertions ===" << std::endl;+ checkTierNarrowing();+ checkFlatAndListAgree();+ checkValidation();+ checkChainCarriesTier();+ std::cout << "failures=" << failures << std::endl;+ return failures == 0 ? 0 : 1;+}diff --git a/tests/integration/NrHoldGpuTests.cpp b/tests/integration/NrHoldGpuTests.cppnew file mode 100644index 00000000..7a38bb58--- /dev/null+++ b/tests/integration/NrHoldGpuTests.cpp@@ -0,0 +1,233 @@+// Stage-5 output stabiliser acceptance (docs/NR_FG_OPTIMIZATION_PLAN_2026-09-29.md §5).+//+// The plan's criteria, checked here on real D3D12 dispatches:+// * a static image with tiny per-frame perturbation must show a clear drop in+// the frame-to-frame output difference,+// * a moving block must not ghost (edge error no worse than the pass off),+// * strength 0 must be a no-op the caller never even dispatches, and+// * the debug layer must stay clean.+//+// It does not measure the GPU cost: that needs a real frame budget, and is+// measured in the product smoke run instead (reported in the WORKLOG).++#include "veyra/pipeline/NrHoldPass.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include "veyra/gfx/CommandSlotRing.h"+#include <DirectXPackedVector.h>+#include <cmath>+#include <d3d12sdklayers.h>+#include <iostream>+#include <limits>+#include <vector>++int main() {+ using namespace veyra;+ using namespace pipeline;+ gfx::D3D12DeviceContext ctx;+ gfx::CommandSlotRing ring;+ Status status = Status::Ok;+ gfx::DeviceContextDesc desc;+ desc.enableDebugLayer = true;+ if (!ctx.initialize(desc, status) ||+ !ring.initialize(ctx.device(), ctx.directQueue(), ctx.fence(), ctx.fenceEvent(), 4, status)) return 2;++ constexpr unsigned width = 64, height = 48;+ constexpr unsigned pitch = width * 8; // RGBA16F+ auto current = makeTexture(ctx.device(), width, height, DXGI_FORMAT_R16G16B16A16_FLOAT, true);+ auto base = makeTexture(ctx.device(), width, height, DXGI_FORMAT_R16G16B16A16_FLOAT, true);+ if (!current || !base) return 2;+ auto upload = makeUploadBuffer(ctx.device(), pitch * height);+ if (!upload) return 2;++ D3D12_HEAP_PROPERTIES hp{}; hp.Type = D3D12_HEAP_TYPE_READBACK;+ D3D12_RESOURCE_DESC bd{};+ bd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; bd.Width = pitch * height;+ bd.Height = 1; bd.DepthOrArraySize = 1; bd.MipLevels = 1; bd.SampleDesc.Count = 1;+ bd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;+ ComPtr<ID3D12Resource> readback;+ if (FAILED(ctx.device()->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &bd,+ D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback)))) return 2;++ StateTracker states;+ // `pixels` is RGBA8 for readability; expanded to FP16 on upload.+ auto fill = [&](ID3D12Resource* texture, const std::vector<uint8_t>& pixels) {+ void* data = nullptr;+ if (FAILED(upload->Map(0, nullptr, &data))) return false;+ auto* half = static_cast<DirectX::PackedVector::HALF*>(data);+ for (unsigned y = 0; y < height; ++y)+ for (unsigned x = 0; x < width; ++x) {+ const size_t src = (size_t(y) * width + x) * 4;+ const size_t dst = size_t(y) * pitch / 2 + x * 4;+ for (unsigned c = 0; c < 4; ++c)+ half[dst + c] = DirectX::PackedVector::XMConvertFloatToHalf(pixels[src + c] / 255.0f);+ }+ upload->Unmap(0, nullptr);+ unsigned slot;+ auto* list = ring.acquireNext(slot, status);+ if (!list) return false;+ states.transition(list, texture, D3D12_RESOURCE_STATE_COPY_DEST);+ D3D12_TEXTURE_COPY_LOCATION dst{}, src{};+ dst.pResource = texture; dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;+ src.pResource = upload.Get(); src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;+ src.PlacedFootprint.Footprint = {DXGI_FORMAT_R16G16B16A16_FLOAT, width, height, 1, pitch};+ list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);+ return ring.submitAndSignal(slot) && ring.waitIdle();+ };++ NrHoldPass pass;+ if (!pass.initialize(ctx.device(), width, height, current.Get(), base.Get())) return 2;++ // Read the stabilised result the way the graph does.+ auto readResult = [&](std::vector<uint8_t>& out) {+ auto* stabilised = pass.result();+ if (!stabilised) return false;+ unsigned slot;+ auto* list = ring.acquireNext(slot, status);+ if (!list) return false;+ states.transition(list, stabilised, D3D12_RESOURCE_STATE_COPY_SOURCE);+ D3D12_TEXTURE_COPY_LOCATION dst{}, src{};+ src.pResource = stabilised; src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;+ dst.pResource = readback.Get(); dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;+ dst.PlacedFootprint.Footprint = {DXGI_FORMAT_R16G16B16A16_FLOAT, width, height, 1, pitch};+ list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);+ if (!ring.submitAndSignal(slot) || !ring.waitIdle()) return false;+ void* data = nullptr;+ D3D12_RANGE range{0, pitch * height};+ if (FAILED(readback->Map(0, &range, &data))) return false;+ out.resize(pitch * height);+ const auto* half = static_cast<const DirectX::PackedVector::HALF*>(data);+ for (size_t i = 0; i < pitch * height / 2; ++i) {+ const float v = DirectX::PackedVector::XMConvertHalfToFloat(half[i]);+ out[i] = uint8_t(std::clamp(v * 255.0f, 0.0f, 255.0f));+ }+ D3D12_RANGE empty{0, 0};+ readback->Unmap(0, &empty);+ return true;+ };++ bool ok = true;+ auto check = [&](const char* name, bool success) {+ std::cout << name << '=' << (success ? 1 : 0) << std::endl;+ ok &= success;+ };++ // --- static scene, tiny perturbation -------------------------------------+ // The source varies by +-1/255 per frame but stays within tolerance: the+ // hold must damp the output difference substantially versus the raw input.+ auto staticScene = [&](unsigned frame, std::vector<uint8_t>& out) {+ out.resize(size_t(width) * height * 4);+ for (unsigned y = 0; y < height; ++y)+ for (unsigned x = 0; x < width; ++x) {+ const int base = 120 + int((x * 7 + y * 3) % 24);+ const int jitter = ((x + y + frame) % 3) - 1; // -1, 0, +1+ const uint8_t v = uint8_t(std::clamp(base + jitter, 0, 255));+ const size_t i = (size_t(y) * width + x) * 4;+ out[i] = out[i + 1] = out[i + 2] = v; out[i + 3] = 255;+ }+ };+ // The criterion is a *drop* in the frame-to-frame difference, so the held+ // output has to be compared against the unheld input over the same frames.+ // An absolute threshold would only encode this clip's contrast.+ std::vector<uint8_t> input, output, previousOutput, previousInput;+ double rawDelta = 0, heldDelta = 0;+ int samples = 0;+ for (unsigned frame = 0; frame < 8; ++frame) {+ staticScene(frame, input);+ if (!fill(base.Get(), input) || !fill(current.Get(), input)) { ok = false; break; }+ // A reset on the first frame seeds history without holding.+ unsigned slot;+ auto* list = ring.acquireNext(slot, status);+ if (!list) { ok = false; break; }+ pass.run(list, states, frame == 0, 0.8f, 0.02f);+ if (!ring.submitAndSignal(slot) || !ring.waitIdle()) { ok = false; break; }+ if (!readResult(output)) { ok = false; break; }+ if (frame >= 2 && previousOutput.size() == output.size()) {+ // `rawDelta`: how much the source itself moved between these frames.+ // `heldDelta`: how much the stabilised output moved. The hold is+ // only useful if the second is clearly smaller than the first.+ for (size_t i = 0; i < output.size(); ++i) {+ rawDelta += std::abs(int(input[i]) - int(previousInput[i]));+ heldDelta += std::abs(int(output[i]) - int(previousOutput[i]));+ }+ ++samples;+ }+ previousOutput = output;+ previousInput = input;+ }+ const double rawMean = samples ? rawDelta / samples : 0.0;+ const double heldMean = samples ? heldDelta / samples : 0.0;+ const double reduction = rawMean > 0 ? 1.0 - heldMean / rawMean : 0.0;+ std::cout << "static samples=" << samples+ << " rawMean=" << rawMean << " heldMean=" << heldMean+ << " reduction=" << reduction << std::endl;+ check("static scene holds (frame-to-frame difference clearly reduced)",+ samples > 0 && reduction >= 0.5);++ // --- strength 0 is never dispatched --------------------------------------+ // The caller skips run() at 0; verify the pass reports inactive history and+ // that calling it anyway is a no-op (no dispatch, no state change).+ pass.reset();+ check("strength zero leaves history unseeded", !pass.active());+ {+ unsigned slot;+ auto* list = ring.acquireNext(slot, status);+ pass.run(list, states, false, 0.0f, 0.02f);+ check("strength zero dispatches nothing", ring.submitAndSignal(slot) && ring.waitIdle() && !pass.active());+ }++ // --- moving block must not ghost -----------------------------------------+ auto movingScene = [&](unsigned frame, std::vector<uint8_t>& out) {+ out.assign(size_t(width) * height * 4, 30);+ const unsigned left = 4 + frame * 6;+ for (unsigned y = 8; y < 32; ++y)+ for (unsigned x = left; x < left + 12 && x < width; ++x) {+ const size_t i = (size_t(y) * width + x) * 4;+ out[i] = 240; out[i + 1] = 40; out[i + 2] = 40; out[i + 3] = 255;+ }+ for (size_t i = 3; i < out.size(); i += 4) out[i] = 255;+ };+ std::vector<uint8_t> moveInput, moveOutput;+ for (unsigned frame = 0; frame < 6; ++frame) {+ movingScene(frame, moveInput);+ if (!fill(base.Get(), moveInput) || !fill(current.Get(), moveInput)) { ok = false; break; }+ unsigned slot;+ auto* list = ring.acquireNext(slot, status);+ pass.run(list, states, frame == 0, 0.8f, 0.02f);+ if (!ring.submitAndSignal(slot) || !ring.waitIdle()) { ok = false; break; }+ if (!readResult(moveOutput)) { ok = false; break; }+ }+ // The block's leading edge must have advanced with the input, not stayed+ // behind. Find the rightmost "red" column and compare with the input's.+ auto rightmostRed = [&](const std::vector<uint8_t>& px) {+ int found = -1;+ for (unsigned y = 20; y < 21; ++y)+ for (unsigned x = 0; x < width; ++x) {+ const size_t i = (size_t(y) * width + x) * 4;+ if (px[i] > 150 && px[i + 1] < 120) found = std::max(found, int(x));+ }+ return found;+ };+ const int expected = rightmostRed(moveInput);+ const int observed = rightmostRed(moveOutput);+ std::cout << "moving edge expected=" << expected << " observed=" << observed << std::endl;+ check("moving block does not ghost behind its input", observed >= 0 && expected - observed <= 2);++ ring.drainQueue();+ ComPtr<ID3D12InfoQueue> info;+ if (FAILED(ctx.device()->QueryInterface(IID_PPV_ARGS(&info)))) return 2;+ unsigned errors = 0;+ for (UINT64 i = 0; i < info->GetNumStoredMessages(); ++i) {+ SIZE_T size = 0;+ if (FAILED(info->GetMessage(i, nullptr, &size))) return 2;+ std::vector<uint8_t> bytes(size);+ auto* message = reinterpret_cast<D3D12_MESSAGE*>(bytes.data());+ if (FAILED(info->GetMessage(i, message, &size))) return 2;+ if (message->Severity <= D3D12_MESSAGE_SEVERITY_ERROR) {+ ++errors;+ std::cerr << message->pDescription << std::endl;+ }+ }+ check("debug layer clean", errors == 0);+ pass.close();+ return ok ? 0 : 1;+}diff --git a/tests/integration/NrRuntimeAssertionTests.cpp b/tests/integration/NrRuntimeAssertionTests.cppnew file mode 100644index 00000000..2a586bb2--- /dev/null+++ b/tests/integration/NrRuntimeAssertionTests.cpp@@ -0,0 +1,138 @@+// Stage-4 defect audit assertions (docs/NR_FG_OPTIMIZATION_PLAN_2026-09-29.md).+//+// These are the cheap, GPU-free checks for defects other projects hit:+// * architecture substitution scope (sdli 0.3.4 / video2dlssnr 1.4.1: a+// spoof meant for NR leaked into SR and crashed RTX 30),+// * NR-layer release accounting (NeuralScreen 25180371 leaked 3.6GB),+// * the version policy that decides whether Ampere is re-labelled Blackwell.+//+// They assert on the real decision functions, not on restated constants, so a+// future edit that widens the spoof scope or flips a version threshold fails+// here instead of on a user's 30-series card.++#include "veyra/ngx/NrArchitecturePolicy.h"+#include "veyra/ngx/AmpereMfgUnlock.h"++#include <cstdint>+#include <iostream>+#include <string>++namespace {++int failures = 0;++void check(const char* name, bool ok)+{+ std::cout << name << '=' << (ok ? 1 : 0) << std::endl;+ if (!ok) ++failures;+}++// The NR architecture rewrite is the whole compatibility contract for RTX 30.+// It must fire only for a successful query about the selected adapter whose+// real architecture is Ampere -- never for another GPU, never on failure.+void auditNrArchitectureRewriteScope()+{+ using namespace veyra::ngx;++ // A successful Ampere query on the selected adapter is rewritten.+ {+ uint32_t arch = 0x170u;+ check("ampere rewrite applies to selected ampere",+ rewriteNrAmpereArchitecture(arch, true, 0) && arch == 0x1B0u);+ }+ // Failure result: the driver's answer is preserved whatever it says.+ for (int result : {1, -1, -8, 0x7FFFFFFF}) {+ uint32_t arch = 0x170u;+ check("ampere rewrite preserves on failure",+ !rewriteNrAmpereArchitecture(arch, true, result) && arch == 0x170u);+ }+ // Not the selected adapter: an unknown handle is never treated as ours.+ {+ uint32_t arch = 0x170u;+ check("ampere rewrite skips unselected adapter",+ !rewriteNrAmpereArchitecture(arch, false, 0) && arch == 0x170u);+ }+ // Every other architecture is left alone, including the ones a real+ // product session runs on.+ for (uint32_t arch : {0x190u, 0x1B0u, 0x160u, 0x150u, 0x130u, 0x0u, 0x1A0u}) {+ const uint32_t original = arch;+ check("ampere rewrite skips non-ampere architecture",+ !rewriteNrAmpereArchitecture(arch, true, 0) && arch == original);+ }+}++// Version policy: builds that lift the gate themselves must keep the real+// architecture, because reporting Blackwell makes them choose kernels Ampere+// cannot run. 310.8.0 / 310.8.1 (the NeuralScreen line) still need the rewrite;+// 310.8.2+ and anything unknown do not.+void auditAmpereRewriteVersionPolicy()+{+ using namespace veyra::ngx;++ auto version = [](uint32_t major, uint32_t minor, uint32_t build) {+ return std::pair<uint32_t, uint32_t>{major << 16 | minor, build << 16};+ };++ const auto [ms080, ls080] = version(310, 8, 0);+ const auto [ms081, ls081] = version(310, 8, 1);+ const auto [ms082, ls082] = version(310, 8, 2);+ const auto [ms083, ls083] = version(310, 8, 3);+ const auto [ms090, ls090] = version(310, 9, 0);+ const auto [ms070, ls070] = version(310, 7, 0);+ const auto [ms100, ls100] = version(311, 0, 0);+ const auto [msZero, lsZero] = version(0, 0, 0);++ // Only the known self-lifting family is exempt: exactly 310.8.2 and later+ // builds of the 310.8 line (SF-v2, Lecram). These are the versions whose+ // own gate handling makes the rewrite actively harmful.+ check("310.8.0 needs ampere rewrite", nrRuntimeNeedsAmpereRewrite(ms080, ls080));+ check("310.8.1 needs ampere rewrite", nrRuntimeNeedsAmpereRewrite(ms081, ls081));+ check("310.8.2 keeps real architecture", !nrRuntimeNeedsAmpereRewrite(ms082, ls082));+ check("310.8.3 (Lecram) keeps real architecture", !nrRuntimeNeedsAmpereRewrite(ms083, ls083));+ // Everything else is deliberately conservative, including versions newer+ // than the ones we have tested: an unrecognised build gets the rewrite+ // rather than the benefit of the doubt. This is the documented policy in+ // NrArchitecturePolicy.h ("unknown new versions default to rewrite"); the+ // trade-off is recorded in the WORKLOG as a known limitation, because a+ // future self-lifting build outside the 310.8 line would be mis-handled.+ check("310.7 unverified build still rewrites", nrRuntimeNeedsAmpereRewrite(ms070, ls070));+ check("310.9 unknown build still rewrites", nrRuntimeNeedsAmpereRewrite(ms090, ls090));+ check("311.0 unknown build still rewrites", nrRuntimeNeedsAmpereRewrite(ms100, ls100));+ // An unreadable version (no VS_FIXEDFILEINFO) must fall back to the same+ // conservative behaviour rather than silently trusting a new build.+ check("unreadable version falls back to rewrite", nrRuntimeNeedsAmpereRewrite(msZero, lsZero));+ // The exemption is a floor, not an equality: later builds of the same minor+ // line stay exempt too, otherwise 310.8.9 would regress to the rewrite.+ const auto [ms089, ls089] = version(310, 8, 9);+ check("310.8.9 stays exempt", !nrRuntimeNeedsAmpereRewrite(ms089, ls089));+}++// The Ada and Ampere provider unlocks must never both believe they own the+// same provider: the 310.9.1 module is patched by DlssgTransfusion, and the+// 310.7 unlocks apply only to the audited 310.7 bytes.+void auditUnlockOwnership()+{+ using namespace veyra::ngx;++ check("ampere unlock starts unapplied", !AmpereMfgUnlock::applied());+ // apply() returns a State report, not a bool: a null module must produce a+ // report that did not apply and found no module.+ const auto refused = AmpereMfgUnlock::apply(nullptr, true, 0);+ check("ampere unlock rejects a null module",+ !refused.applied && !refused.moduleFound && !refused.identityVerified);+ check("ampere unlock still unapplied after refusal", !AmpereMfgUnlock::applied());+ check("ampere unlock snapshot agrees with applied",+ AmpereMfgUnlock::snapshot().applied == AmpereMfgUnlock::applied());+}++} // namespace++int main()+{+ std::cout << "=== NR runtime audit assertions ===" << std::endl;+ auditNrArchitectureRewriteScope();+ auditAmpereRewriteVersionPolicy();+ auditUnlockOwnership();+ std::cout << "failures=" << failures << std::endl;+ return failures == 0 ? 0 : 1;+}diff --git a/tests/integration/NrTemporalGpuTests.cpp b/tests/integration/NrTemporalGpuTests.cppindex cd27fcbb..3e01c658 100644--- a/tests/integration/NrTemporalGpuTests.cpp+++ b/tests/integration/NrTemporalGpuTests.cpp@@ -1,10 +1,13 @@#include "veyra/pipeline/NrTemporalPass.h"+#include "veyra/pipeline/NrInstance.h"#include "veyra/gfx/D3D12DeviceContext.h"#include "veyra/gfx/CommandSlotRing.h"#include <DirectXPackedVector.h>#include <cmath>#include <iostream>#include <limits>+#include <memory>+#include <set>#include <d3d12sdklayers.h>int main() {@@ -44,6 +47,7 @@ int main() {return ring.submitAndSignal(slot)&&ring.waitIdle();};engine::ProtectionSettings protection;+ float outputMinimum=0.f;auto run=[&](float raw,bool reset,double ms=16.6667,bool haveMotion=true,float total=1.f){if(!fill(pass.raw(),raw))return std::numeric_limits<float>::quiet_NaN();unsigned slot;auto* list=ring.acquireNext(slot,status);@@ -55,14 +59,91 @@ int main() {void* data=nullptr;D3D12_RANGE range{0,pitch*height};readback->Map(0,&range,&data);float result=XMConvertHalfToFloat(static_cast<HALF*>(data)[6*pitch/2+8*4]);uint64_t fingerprint=14695981039346656037ull;+ outputMinimum=std::numeric_limits<float>::infinity();for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width*4;++x){fingerprint^=static_cast<HALF*>(data)[y*pitch/2+x];fingerprint*=1099511628211ull;+ if(x%4!=3)outputMinimum=std::min(outputMinimum,XMConvertHalfToFloat(static_cast<HALF*>(data)[y*pitch/2+x]));}std::cout<<"frame fingerprint="<<fingerprint<<std::endl;D3D12_RANGE empty{0,0};readback->Unmap(0,&empty);return result;};bool ok=fill(base.Get(),.5f)&&fill(motion.Get(),0,true);auto check=[&](const char* name,bool success){std::cout<<name<<"="<<success<<std::endl;ok&=success;};+ // A borrowed texture is still held by a ComPtr: close must release only+ // this instance's reference and leave the graph's owner usable.+ auto depth=makeTexture(ctx.device(),width,height,DXGI_FORMAT_R32_FLOAT,true);+ NrInstance borrowed;+ check("borrowed input create",borrowed.create(ctx.device(),width,height,width,height,motion.Get(),depth.Get(),base.Get()));+ check("borrowed input alias",borrowed.input()==base.Get()&&borrowed.inputIsBorrowed());+ borrowed.historyValid=true;+ borrowed.close();+ check("borrowed input close releases reference",borrowed.input()==nullptr&&!borrowed.inputIsBorrowed()&&!borrowed.historyValid);+ check("graph owner survives borrowed close",fill(base.Get(),.5f));+ borrowed.close();+ check("repeated close stays empty",borrowed.input()==nullptr);+ // Memory regression (NeuralScreen 25180371 / OptiScaler v0.8.5 leaked 3.6GB+ // by keeping dropped NR layers alive). Four layers are allocated, three are+ // dropped, then the survivor is resized repeatedly; the process-local VRAM+ // usage must come back to the pre-allocation baseline. The tolerance is+ // generous because the driver caches committed allocations, but a retained+ // layer costs tens of MB, so a real leak cannot hide under it.+ auto localUsage=[&](){uint64_t budget=0,usage=0;return ctx.videoMemoryInfo(budget,usage)?usage:UINT64_MAX;};+ auto settle=[](){return true;};+ const uint64_t baselineUsage=localUsage();+ std::cout<<"vram baseline MiB="<<(baselineUsage==UINT64_MAX?-1:long long(baselineUsage/1048576))<<std::endl;+ std::vector<std::unique_ptr<NrInstance>> layers;+ std::set<ID3D12Resource*> resources;+ for(unsigned n=0;n<4;++n){+ auto layer=std::make_unique<NrInstance>();+ check("layer allocation",layer->create(ctx.device(),width,height,width*2,height*2,motion.Get(),depth.Get()));+ for(auto* resource:{layer->input(),layer->proxy(),layer->neural(),layer->finalRgba(),layer->residual(),layer->outputFull()})+ check("layer texture distinct",resource&&resources.insert(resource).second);+ layers.push_back(std::move(layer));+ std::cout<<"allocated layers="<<layers.size()<<" distinct textures="<<resources.size()<<std::endl;+ }+ const uint64_t peakUsage=localUsage();+ std::cout<<"vram with 4 layers MiB="<<(peakUsage==UINT64_MAX?-1:long long(peakUsage/1048576))<<std::endl;+ // 4 -> 1 layer: drop three, keeping layer 0 alive across the whole cycle.+ // The dropped slots must be empty and the survivor must still be usable.+ for(unsigned n=1;n<4;++n)layers[n].reset();+ check("dropped layers release their textures",+ layers.size()==4&&!layers[1]&&!layers[2]&&!layers[3]&&layers[0]!=nullptr);+ check("surviving layer still usable after drops",+ layers[0]->input()!=nullptr&&layers[0]->outputFull()!=nullptr&&layers[0]->width()==width);+ for(auto& layer:layers){+ if(!layer)continue;+ layer->close();+ check("owned input close",!layer->input()&&!layer->outputFull()&&layer->width()==0);+ check("layer resize recreate",layer->create(ctx.device(),width+2,height+2,width+2,height+2,motion.Get(),depth.Get())&&layer->width()==width+2);+ layer->close();+ }+ // Resize churn: recreate the same layer at a different extent twelve times.+ // Each cycle must close cleanly and end at zero, so the last one is the+ // measurement point.+ for(unsigned cycle=0;cycle<12;++cycle){+ const unsigned w=width+(cycle%3),h=height+(cycle%2);+ check("resize churn create",layers[0]->create(ctx.device(),w,h,w*2,h*2,motion.Get(),depth.Get()));+ check("resize churn extent",layers[0]->width()==w&&layers[0]->height()==h);+ layers[0]->close();+ check("resize churn close",!layers[0]->input()&&layers[0]->width()==0);+ }+ layers.clear();+ const uint64_t finalUsage=localUsage();+ std::cout<<"vram after all layers released MiB="<<(finalUsage==UINT64_MAX?-1:long long(finalUsage/1048576))+ <<" baseline="<<(baselineUsage==UINT64_MAX?-1:long long(baselineUsage/1048576))<<std::endl;+ if(baselineUsage==UINT64_MAX||finalUsage==UINT64_MAX){+ std::cerr<<"video memory query unavailable; memory regression not measured"<<std::endl;+ check("vram regression measurable",false);+ }else{+ const double growthMiB=double(finalUsage-baselineUsage)/1048576.0;+ std::cout<<"vram growth MiB="<<growthMiB<<std::endl;+ // The dropped layers held 4 x (input+proxy+neural+final+residual+output)+ // textures; at this test's tiny extents that is well under 1 MiB, so the+ // ±100MB contract from the plan is unreachable at this size. What this+ // test can prove is that the leak is not proportional: the growth must+ // stay under a few MiB rather than the tens of MB a retained layer costs.+ check("vram returns to baseline after 4->1 and 12 resizes",growthMiB<8.0);+ }check("reset identity",run(.75f,true)==.75f);check("constant residual",run(.75f,false)==.75f);const float decay=run(.5f,false);@@ -87,6 +168,42 @@ int main() {fill(motion.Get(),0,true);fill(base.Get(),-.5f);check("signed HDR identity",run(-1.f,true)==-1.f);fill(base.Get(),2.f);check("HDR highlight identity",run(3.f,true)==3.f);+ // Guide differences below .008 accept the old correction even when the+ // new positive base is too small for it. This formerly generated negative+ // SDR channels, which became colored contours after later composition.+ fill(base.Get(),1.f/128);run(1.f/1024,true);+ fill(base.Get(),1.f/1024);+ const float darkened=run(1.f/2048,false);+ check("temporal positive shadow stays positive",darkened>0&&darkened<=1.f/2048&&outputMinimum>=0);+ // Keep a second pair below the perceptual guide threshold so this tests+ // rebasing, not rejection. All constants are exactly representable in FP16.+ fill(base.Get(),1.f/1024);run(1.f/8192,true);+ fill(base.Get(),1.f/2048);+ const float deepShadow=run(1.f/16384,false);+ const float weight=float(std::exp(-16.6667/80.));+ const float current=1.f/16384-1.f/2048,old=1.f/8192-1.f/1024;+ const float requested=current+weight*(old-current);+ const float expected=(1.f/16384)/(1.f+(current-requested)/(1.f/16384));+ check("temporal shadow soft limit oracle",deepShadow>0&&std::abs(deepShadow-expected)<1.e-7f&&outputMinimum>=0);+ fill(base.Get(),1.f/128);run(1.f/1024,true);+ fill(base.Get(),1.f/1024);+ check("temporal zero anchor stays zero",run(0.f,false)==0.f&&outputMinimum>=0);+ // Nonnegative-source protection must not erase valid signed gamut data.+ fill(base.Get(),.5f);run(-.25f,true);+ check("temporal signed raw preserved",run(-.25f,false)==-.25f);+ fill(base.Get(),-.5f);run(-1.f,true);+ check("temporal signed base preserved",run(-1.f,false)==-1.f);+ fill(base.Get(),2.f);run(3.f,true);+ const float highlight=run(2.f,false);+ check("HDR highlight history still smooths",highlight>2.f&&highlight<3.f);+ // A fourfold source change in shadows is not the same surface observation.+ // Linear .008 guide tolerance previously trusted it at full weight.+ fill(base.Get(),1.f/128);run(1.f/16,true);+ fill(base.Get(),1.f/512);+ check("visible dark guide change rejects history",run(1.f/512,false)==1.f/512);+ fill(base.Get(),1.f/512);run(1.f/256,true);+ const float stableDark=run(1.f/512,false);+ check("stable dark guide still smooths",stableDark>1.f/512&&stableDark<1.f/256);// Full-frame fingerprints include odd-size tile boundaries, fractional flow,// changing signed corrections and a mid-sequence reset for shader A/B runs.patterned=true;fill(base.Get(),.25f);fill(motion.Get(),.125f,true);diff --git a/tests/integration/NrVideoQualityProbe.cpp b/tests/integration/NrVideoQualityProbe.cppindex 8fa9f30b..301d493c 100644--- a/tests/integration/NrVideoQualityProbe.cpp+++ b/tests/integration/NrVideoQualityProbe.cpp@@ -1,4 +1,6 @@#include "veyra/pipeline/EnhanceGraph.h"+#include "veyra/engine/EffectChain.h"+#include "veyra/engine/GraphDescription.h"#include "veyra/source/MediaFileSource.h"#include "veyra/gfx/D3D12DeviceContext.h"#include "veyra/gfx/CommandSlotRing.h"@@ -8,17 +10,23 @@#include <fstream>#include <iostream>#include <array>+#include <algorithm>#include <string_view>#include <d3d12sdklayers.h>#include <vector>+#include <sstream>+#include <set>+#include <bit>+#include <dxgi1_4.h>-// Offline, matched natural-frame observations. Readbacks and CPU waits are+// Offline, matched source-frame observations (synthetic or natural). Readbacks and CPU waits are// confined to this executable; these timings are NOT playback performance.namespace {using namespace veyra;constexpr unsigned cropWidth=640,cropHeight=360;bool dumpCrop(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,- ID3D12Resource* texture,std::ofstream& output){+ ID3D12Resource* texture,std::ostream& output,+ D3D12_RESOURCE_STATES before=D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE){if(!texture)return false;const auto desc=texture->GetDesc();const unsigned channels=desc.Format==DXGI_FORMAT_R16G16_FLOAT?2:4;@@ -37,7 +45,7 @@ bool dumpCrop(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,Status status;unsigned slot;auto* list=ring.acquireNext(slot,status);if(!list)return false;D3D12_RESOURCE_BARRIER barrier{};barrier.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;barrier.Transition={texture,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,- D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,D3D12_RESOURCE_STATE_COPY_SOURCE};+ before,D3D12_RESOURCE_STATE_COPY_SOURCE};list->ResourceBarrier(1,&barrier);D3D12_TEXTURE_COPY_LOCATION src{},dst{};src.pResource=texture;src.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;dst.pResource=readback.Get();@@ -56,9 +64,40 @@ bool dumpCrop(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,}}int wmain(int argc,wchar_t** argv){- if(argc!=5&&argc!=6)return 2; // source, output directory, start seconds, frame count, optional video-sr4k+ if(argc!=5&&argc!=6)return 2; // source, output, start, count, optional video-sr4k / stack2..4[-raw]const bool videoSr4k=argc==6&&std::wstring_view(argv[5])==L"video-sr4k";- if(argc==6&&!videoSr4k)return 2;+ unsigned stackLayers=1;+ bool temporal=true;+ bool liveEdit=false;+ bool protectedStack=false;+ bool cycle=false;+ bool featherStack=false,colorProtected=false,hdrProtected=false,srFirst=false,nrFirst=false;+ bool referenceOnly=false,referenceOff=false;+ bool mixedSizes=false,exportFull=false,stillFull=false;+ if(argc==6&&!videoSr4k){+ const std::wstring_view option(argv[5]);+ if(option.size()<6||option.substr(0,5)!=L"stack"||option[5]<L'1'||option[5]>L'4')return 2;+ stackLayers=unsigned(option[5]-L'0');+ if(option.substr(6)==L"-sizes"){mixedSizes=true;temporal=false;}+ else if(option.substr(6)==L"-sizes-nr-first"){mixedSizes=true;temporal=false;nrFirst=true;}+ else if(option.substr(6)==L"-sizes-sr-first"){mixedSizes=true;temporal=false;srFirst=true;}+ else if(option.substr(6)==L"-sizes-export"){mixedSizes=true;temporal=false;exportFull=true;}+ else if(option.substr(6)==L"-sizes-still"){mixedSizes=true;temporal=false;stillFull=true;}+ else if(option.size()==10&&option.substr(6)==L"-raw")temporal=false;+ else if(option.size()==11&&option.substr(6)==L"-edit")liveEdit=true;+ else if(option.substr(6)==L"-protected")protectedStack=true;+ else if(option.substr(6)==L"-protected-raw"){protectedStack=true;temporal=false;}+ else if(option.substr(6)==L"-cycle")cycle=true;+ else if(option.substr(6)==L"-feather")featherStack=true;+ else if(option.substr(6)==L"-color-protected"){protectedStack=true;colorProtected=true;}+ else if(option.substr(6)==L"-hdr-protected"){protectedStack=true;hdrProtected=true;}+ else if(option.substr(6)==L"-sr-first")srFirst=true;+ else if(option.substr(6)==L"-nr-first")nrFirst=true;+ else if(option.substr(6)==L"-reference")referenceOnly=true;+ else if(option.substr(6)==L"-reference-off"){referenceOnly=true;referenceOff=true;}+ else if(option.size()!=6)return 2;+ if(liveEdit&&stackLayers<2)return 2;+ }const double start=_wtof(argv[3]);const unsigned count=unsigned(_wtoi(argv[4]));if(start<0||count<2||count>240)return 2;const std::filesystem::path directory=argv[2];std::filesystem::create_directories(directory);@@ -77,16 +116,135 @@ int wmain(int argc,wchar_t** argv){pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc settings;settings.sourceWidth=settings.workWidth=settings.nrWidth=settings.flowWidth=info.width;settings.sourceHeight=settings.workHeight=settings.nrHeight=settings.flowHeight=info.height;- settings.enableNr=true;settings.nrTemporal=true;settings.enableFg=false;settings.enableSr=false;- settings.enableNvofStandalone=true;settings.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();+ settings.enableNr=true;settings.nrTemporal=temporal;settings.enableFg=false;settings.enableSr=false;+ // Product path, not a hand-filled descriptor that bypasses the UI boundary.+ engine::EffectChain chain;chain.nodeCount=stackLayers;+ for(unsigned layer=0;layer<stackLayers;++layer){+ auto& node=chain.nodes[layer];node.type=engine::EffectType::NrEnhance;node.enabled=!referenceOff;+ node.nr.model.intensity=1.f-.2f*float(layer);node.nr.temporal=temporal;+ node.nr.lowLatencyPairing=nrFirst;+ if(mixedSizes){const pipeline::NrSizePolicy sizes[]={pipeline::NrSizePolicy::P480,pipeline::NrSizePolicy::P720,+ pipeline::NrSizePolicy::P1440,pipeline::NrSizePolicy::Native};node.nr.sizePolicy=sizes[layer];}+ }+ engine::EnhancementSettings pending;engine::fromChain(chain,pending);+ if(protectedStack){pending.protection.enabled=true;pending.protection.featherPixels=12;pending.protection.regions[0]={.25f,.25f,.75f,.75f};}+ if(featherStack){pending.protection.enabled=true;pending.protection.featherPixels=32;pending.protection.regions[0]={.45f,.3f,.8f,.7f};}+ if(colorProtected){pending.color.enabled=true;pending.color.exposure=.3f;pending.color.contrast=20;}+ if(referenceOnly&&!referenceOff){pending.color.enabled=true;pending.color.exposure=.3f;}+ if(srFirst||nrFirst){pending.sr=true;pending.videoSrQuality=3;pending.srTarget=pipeline::SrTarget::Uhd4K;}+ if(!engine::validateChain(chain).accepted||!pending.validate().empty())return 2;+ engine::StageRequest request;request.nr=true;request.width=info.width;request.height=info.height;+ request.sr=srFirst||nrFirst;+ request.exportJob=exportFull;request.stillImage=stillFull;+ engine::describeStages(request,pending,settings);+ if(exportFull||stillFull){+ for(const auto extent:settings.nrLayersExtent)+ if(extent!=pipeline::Extent{settings.workWidth,settings.workHeight})return 2;+ std::cout<<"fullProcessing=1 exportJob="<<exportFull<<" stillImage="<<stillFull<<std::endl;+ }+ // The HDR mode requires the caller to supply a genuinely PQ/HLG-tagged fixture.+ if(hdrProtected){settings.hdrInput=true;settings.hdrOutput=true;}+ if(request.sr&&(!settings.enableSr||settings.nrBeforeSr!=nrFirst))return 2;+ std::cout<<"mappedSr="<<settings.enableSr<<" nrBeforeSr="<<settings.nrBeforeSr<<" work="<<settings.workWidth<<'x'<<settings.workHeight<<" nr="<<settings.nrWidth<<'x'<<settings.nrHeight<<std::endl;+ settings.enableNvofStandalone=settings.enableNr;settings.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();+ std::set<NVSDK_NGX_Parameter*> parameterBlocks;+ std::set<ID3D12Resource*> proxies,neuralOutputs;+ bool resourceSizes=true;+ auto expectedExtents=settings.nrLayersExtent;+ size_t sizeProbeCalls=0;+ settings.nrParameterProbe=[&](NVSDK_NGX_Parameter* parameters,ID3D12Resource* proxy,ID3D12Resource* neural,uint32_t width,uint32_t height){+ parameterBlocks.insert(parameters);proxies.insert(proxy);neuralOutputs.insert(neural);+ const auto a=proxy->GetDesc(),b=neural->GetDesc();+ if(expectedExtents.empty()){resourceSizes=false;return;}+ const auto extent=expectedExtents[sizeProbeCalls++%expectedExtents.size()];+ resourceSizes=resourceSizes&&a.Width==width&&a.Height==height&&b.Width==width&&b.Height==height;+ // Evaluate order must match each active layer, not merely any requested size.+ resourceSizes=resourceSizes&&extent.width==width&&extent.height==height;+ };if(videoSr4k){settings.workWidth=3840;settings.workHeight=2160;settings.enableSr=true;settings.videoSrQuality=3;}+ if(cycle){+ Microsoft::WRL::ComPtr<IDXGIFactory4> factory;+ Microsoft::WRL::ComPtr<IDXGIAdapter3> adapter;+ if(FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))||+ FAILED(factory->EnumAdapterByLuid(ctx.device()->GetAdapterLuid(),IID_PPV_ARGS(&adapter))))return 2;+ auto usage=[&](){DXGI_QUERY_VIDEO_MEMORY_INFO m{};return SUCCEEDED(adapter->QueryVideoMemoryInfo(0,DXGI_MEMORY_SEGMENT_GROUP_LOCAL,&m))?m.CurrentUsage:UINT64_MAX;};+ std::ofstream memory(directory/L"memory.csv");memory<<"cycle,layers,nrWidth,nrHeight,before,live,after\n";+ const unsigned layers[]={1,2,3,4,4,4,4,4,4};+ const unsigned widths[]={1920,1920,1920,1920,1280,960,1920,1920,1920};+ std::vector<uint64_t> released;bool pass=true;+ for(unsigned i=0;i<std::size(layers);++i){+ auto d=settings;d.nrWidth=widths[i];d.nrHeight=widths[i]*9/16;+ d.nrLayersExtent.assign(layers[i],pipeline::Extent{d.nrWidth,d.nrHeight});+ d.nrLayersModel.resize(layers[i]);d.nrLayersResidual.resize(layers[i]);+ d.nrLayersTemporal.resize(layers[i]);d.nrLayersProtection.resize(layers[i]);+ parameterBlocks.clear();proxies.clear();neuralOutputs.clear();+ expectedExtents=d.nrLayersExtent;sizeProbeCalls=0;+ const auto before=usage();+ if(!graph.initialize(d)||!graph.createViews()||!source.seek({0,1000}))return 2;+ pass=pass&&graph.nrLayerCount()==layers[i]&&graph.nrWidth()==d.nrWidth&&graph.nrHeight()==d.nrHeight;+ const auto evaluatedBefore=graph.metrics().nrEvaluateCount;+ for(unsigned j=0;j<3;++j){+ pipeline::FramePacket packet;const AVFrame* frame=nullptr;pipeline::EnhanceGraph::FrameOutputs result;+ if(source.read(packet,&frame)!=source::SourceReadStatus::Frame||+ !graph.process(frame,packet.pts.toDouble()*1000,j==0||j==2,result,packet.sequence,&packet.colorInfo)||!ring.waitIdle())return 2;+ }+ pass=pass&¶meterBlocks.size()==layers[i]&&proxies.size()==layers[i]&&neuralOutputs.size()==layers[i]+ &&graph.metrics().nrEvaluateCount-evaluatedBefore==3*layers[i];+ std::cout<<"parameters="<<parameterBlocks.size()<<" proxies="<<proxies.size()<<" outputs="<<neuralOutputs.size()<<" evaluateDelta="<<graph.metrics().nrEvaluateCount-evaluatedBefore<<std::endl;+ const auto live=usage();ring.drainQueue();graph.shutdown();const auto after=usage();+ pass=pass&&graph.nrLayerCount()==0&&before!=UINT64_MAX&&live!=UINT64_MAX&&after!=UINT64_MAX;+ released.push_back(after);memory<<i<<','<<layers[i]<<','<<d.nrWidth<<','<<d.nrHeight<<','<<before<<','<<live<<','<<after<<'\n';+ std::cout<<"cycle="<<i<<" layers="<<layers[i]<<" nrExtent="<<d.nrWidth<<'x'<<d.nrHeight<<" before="<<before<<" live="<<live<<" released="<<after<<" structuralPass="<<pass<<std::endl;+ if(!pass)break;+ }+ source.close();+ Microsoft::WRL::ComPtr<ID3D12InfoQueue> debug;unsigned errors=0;+ if(FAILED(ctx.device()->QueryInterface(IID_PPV_ARGS(&debug))))return 2;+ for(UINT64 i=0;i<debug->GetNumStoredMessages();++i){SIZE_T size=0;debug->GetMessage(i,nullptr,&size);std::vector<unsigned char>b(size);auto* m=reinterpret_cast<D3D12_MESSAGE*>(b.data());if(FAILED(debug->GetMessage(i,m,&size)))return 2;if(m->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;std::cerr<<m->pDescription<<'\n';}}+ const auto tail=std::minmax_element(released.end()-std::min<size_t>(3,released.size()),released.end());+ const auto spread=released.empty()?UINT64_MAX:*tail.second-*tail.first;+ // Short-run process-local residency, not a long-run leak or hardware certification.+ const bool bounded=spread<=64ull*1024*1024;+ std::cout<<"releaseTailSpreadBytes="<<spread<<" bounded64MiB="<<bounded<<" debugErrors="<<errors<<std::endl;+ return pass&&memory&&released.size()==std::size(layers)&&bounded&&errors==0?0:1;+ }if(!graph.initialize(settings)||!graph.createViews())return 2;+ // Re-run the product's exact area shader on the completed upstream output.+ // Even equal extents use floating coordinates in that shader, so comparing+ // its output directly to the source texture is not a bit-exact oracle.+ std::array<pipeline::ComputePass,3> expectedPasses;+ std::array<Microsoft::WRL::ComPtr<ID3D12Resource>,3> expectedInputs;+ pipeline::StateTracker expectedStates;+ for(unsigned layer=1;!referenceOnly&&layer<stackLayers;++layer){+ auto& pass=expectedPasses[layer-1];+ std::vector<uint8_t> shader;+ const auto extent=graph.diagnosticNrLayerInput(layer)->GetDesc();+ expectedInputs[layer-1]=pipeline::makeTexture(ctx.device(),uint32_t(extent.Width),extent.Height,DXGI_FORMAT_R16G16B16A16_FLOAT,true);+ if(!expectedInputs[layer-1]||!pass.loadShader("NrDownsample.dxil",shader)||!pass.create(ctx.device(),shader,2,1,1))return 2;+ pipeline::DescriptorStager staging;if(!staging.initialize(ctx.device(),1))return 2;+ staging.stageSrv(graph.diagnosticNrLayerOutput(layer-1),nullptr,pass.heap.Get(),0);+ pipeline::makeUav(ctx.device(),expectedInputs[layer-1].Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,pipeline::cpuHandleOf(pass,1));+ }+ pipeline::ComputePass protectionOracle;+ Microsoft::WRL::ComPtr<ID3D12Resource> protectionExpected;+ if(featherStack){+ std::vector<uint8_t> shader;+ protectionExpected=pipeline::makeTexture(ctx.device(),info.width,info.height,DXGI_FORMAT_R16G16B16A16_FLOAT,true);+ if(!protectionExpected||!protectionOracle.loadShader("NrResidualComposite.dxil",shader)||!protectionOracle.create(ctx.device(),shader,4,3,1,24))return 2;+ pipeline::DescriptorStager staging;if(!staging.initialize(ctx.device(),3))return 2;+ staging.stageSrv(graph.diagnosticNrBase(),nullptr,protectionOracle.heap.Get(),0);+ staging.stageSrv(graph.diagnosticNrBase(),nullptr,protectionOracle.heap.Get(),1);+ staging.stageSrv(graph.diagnosticNrLayerOutput(stackLayers-1),nullptr,protectionOracle.heap.Get(),2);+ pipeline::makeUav(ctx.device(),protectionExpected.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,pipeline::cpuHandleOf(protectionOracle,3));+ }std::array<std::ofstream,4> streams;const char* names[]={"base.rgba16f","raw.rgba16f","filtered.rgba16f","motion.rg16f"};for(unsigned i=0;i<4;++i)streams[i].open(directory/names[i],std::ios::binary);+ std::ofstream stackOutput;+ if(featherStack)stackOutput.open(directory/L"stack.rgba16f",std::ios::binary);std::ofstream metadata(directory/L"frames.csv");metadata<<"index,source,ptsMs,epoch\n";bool ok=true;unsigned captured=0;while(captured<count){@@ -94,13 +252,93 @@ int wmain(int argc,wchar_t** argv){if(source.read(packet,&frame)!=source::SourceReadStatus::Frame){ok=false;break;}if(packet.pts.toDouble()<start)continue;pipeline::EnhanceGraph::FrameOutputs output;- if(!graph.process(frame,packet.pts.toDouble()*1000,captured==0||(videoSr4k&&captured==count/2),output,packet.sequence,&packet.colorInfo)||!ring.waitIdle()){ok=false;break;}+ if(liveEdit&&captured==count/2){+ chain.nodes[1].nr.model.tone=0.25f;chain.nodes[1].nr.residual.total=0.7f;+ engine::fromChain(chain,pending);++pending.revision;+ const auto firstInput=graph.diagnosticNrLayerInput(0);+ if(!graph.applySettings(pending)||graph.diagnosticNrLayerInput(0)!=firstInput){ok=false;break;}+ for(unsigned layer=0;layer<stackLayers;++layer){+ const auto actual=graph.diagnosticNrLayerSettings(layer);+ const auto& want=chain.nodes[layer].nr;+ ok=ok&&actual.model==want.model&&actual.residual==want.residual&&+ actual.temporal==want.temporal&&graph.diagnosticNrInputRevision(layer)>1;+ }+ std::cout<<"liveSettingsApplied="<<ok<<" allLayerHistoriesInvalidated="<<ok<<std::endl;+ if(!ok)break;+ }+ if(!graph.process(frame,packet.pts.toDouble()*1000,captured==0||(!liveEdit&&(videoSr4k||stackLayers>1)&&captured==count/2),output,packet.sequence,&packet.colorInfo,nullptr,referenceOnly)||!ring.waitIdle()){ok=false;break;}+ if(referenceOnly){+ const auto& lease=output.batch.frames[output.batch.count-1].lease;+ ok=lease&&lease->referencesValid&&dumpCrop(ctx,ring,lease->sourceReference.Get(),streams[0],D3D12_RESOURCE_STATE_COMMON);+ auto* processed=referenceOff?graph.diagnosticLinearInput():graph.diagnosticNrFiltered();+ ok=dumpCrop(ctx,ring,processed,streams[2],graph.diagnosticResourceState(processed))&&ok;+ if(!ok)break;+ metadata<<captured<<','<<packet.sequence<<','<<packet.pts.toDouble()*1000<<','<<output.batch.identity.epoch<<'\n';++captured;continue;+ }ID3D12Resource* textures[]={graph.diagnosticNrBase(),graph.diagnosticNrRaw(),graph.diagnosticNrFiltered(),graph.flowResource()};- for(unsigned i=0;i<4;++i)ok=dumpCrop(ctx,ring,textures[i],streams[i])&&ok;+ for(unsigned i=0;i<4;++i)ok=dumpCrop(ctx,ring,textures[i],streams[i],graph.diagnosticResourceState(textures[i]))&&ok;+ if(featherStack){auto* texture=graph.diagnosticNrLayerOutput(stackLayers-1);ok=dumpCrop(ctx,ring,texture,stackOutput,graph.diagnosticResourceState(texture))&&ok;}+ if(featherStack){+ unsigned slot=0;auto* list=ring.acquireNext(slot,status);if(!list)return 2;+ expectedStates.transition(list,protectionExpected.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ // Protect the complete stack, preserving signed residuals outside it.+ float constants[24]={1,1,1,1,1,1,32,1};+ constants[8]=.45f;constants[9]=.3f;constants[10]=.8f;constants[11]=.7f;+ protectionOracle.bind(list,constants,pipeline::gpuHandleOf(protectionOracle,0).ptr,pipeline::gpuHandleOf(protectionOracle,3).ptr);+ list->Dispatch((info.width+15)/16,(info.height+15)/16,1);+ expectedStates.uavBarrier(list,protectionExpected.Get());expectedStates.transition(list,protectionExpected.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ if(!ring.submitAndSignal(slot)||!ring.waitIdle())return 2;+ std::ostringstream expected,actual;+ const bool matched=dumpCrop(ctx,ring,protectionExpected.Get(),expected)&&dumpCrop(ctx,ring,textures[2],actual,graph.diagnosticResourceState(textures[2]))&&expected.str()==actual.str();+ std::cout<<"featherExact="<<matched<<" frame="<<captured<<std::endl;ok=ok&&matched;+ }+ if(protectedStack){+ std::ostringstream base,final;+ const bool read=dumpCrop(ctx,ring,textures[0],base,graph.diagnosticResourceState(textures[0]))+ &&dumpCrop(ctx,ring,textures[2],final,graph.diagnosticResourceState(textures[2]));+ const bool identical=read&&!base.str().empty()&&base.str()==final.str();+ std::cout<<"protectedOriginal="<<identical<<" frame="<<captured<<" bytes="<<base.str().size()<<std::endl;+ ok=ok&&identical;+ }+ // Every downstream layer must have consumed the CURRENT composed output,+ // including temporal filtering, not uninitialized/previous-frame data.+ for(unsigned layer=1;layer<stackLayers;++layer){+ unsigned slot=0;auto* list=ring.acquireNext(slot,status);if(!list){ok=false;break;}+ auto& pass=expectedPasses[layer-1];auto* expected=expectedInputs[layer-1].Get();+ expectedStates.transition(list,expected,D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ const auto upstreamDesc=graph.diagnosticNrLayerOutput(layer-1)->GetDesc();+ const auto extent=expected->GetDesc();+ const float dims[8]={std::bit_cast<float>(uint32_t(upstreamDesc.Width)),std::bit_cast<float>(upstreamDesc.Height),std::bit_cast<float>(uint32_t(extent.Width)),std::bit_cast<float>(extent.Height),0,0,0,0};+ pass.bind(list,dims,pipeline::gpuHandleOf(pass,0).ptr,pipeline::gpuHandleOf(pass,1).ptr);+ list->Dispatch((UINT(extent.Width)+15)/16,(extent.Height+15)/16,1);+ expectedStates.uavBarrier(list,expected);expectedStates.transition(list,expected,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ if(!ring.submitAndSignal(slot)||!ring.waitIdle()){ok=false;break;}+ std::ostringstream upstream,downstream;+ const bool copied=dumpCrop(ctx,ring,expected,upstream)+ &&dumpCrop(ctx,ring,graph.diagnosticNrLayerInput(layer),downstream);+ const auto a=upstream.str(),b=downstream.str();+ size_t different=0;+ if(a.size()==b.size())for(size_t i=0;i<a.size();++i)different+=a[i]!=b[i];+ const bool matched=copied&&!a.empty()&&a.size()==b.size()&&different==0;+ std::cout<<"same-frame layer="<<layer+1<<" frame="<<captured<<" matched="<<matched+ <<" bytes="<<a.size()<<" different="<<different<<std::endl;+ ok=ok&&matched;+ }if(!ok)break;metadata<<captured<<','<<packet.sequence<<','<<packet.pts.toDouble()*1000<<','<<output.batch.identity.epoch<<'\n';++captured;}+ const auto metrics=graph.metrics();+ const unsigned activeLayers=referenceOff?0:stackLayers;+ const bool isolated=parameterBlocks.size()==activeLayers&&proxies.size()==activeLayers&&neuralOutputs.size()==activeLayers;+ const bool sharedFlow=metrics.nvofExecuteCount<=captured&&metrics.nvofFrameFailures==0;+ const bool allLayersRan=metrics.nrEvaluateCount==uint64_t(captured)*activeLayers;+ std::cout<<"isolated="<<isolated<<" parameters="<<parameterBlocks.size()<<" proxies="<<proxies.size()<<" neuralOutputs="<<neuralOutputs.size()+ <<" nrEvaluations="<<metrics.nrEvaluateCount<<" flowExecutions="<<metrics.nvofExecuteCount+ <<" flowFailures="<<metrics.nvofFrameFailures<<" sharedFlow="<<sharedFlow<<" allLayersRan="<<allLayersRan<<std::endl;+ std::cout<<"perLayerTextureSizes="<<resourceSizes<<std::endl;+ ok=ok&&isolated&&sharedFlow&&allLayersRan&&resourceSizes;+ if(request.sr){const bool srRan=metrics.srEvaluateCount==captured;std::cout<<"srEvaluations="<<metrics.srEvaluateCount<<" srRan="<<srRan<<std::endl;ok=ok&&srRan;}ring.drainQueue();graph.shutdown();source.close();Microsoft::WRL::ComPtr<ID3D12InfoQueue> debug;unsigned errors=0;diff --git a/tests/integration/PreviewGeometryTests.cpp b/tests/integration/PreviewGeometryTests.cppindex 6e9808b9..00ff3992 100644--- a/tests/integration/PreviewGeometryTests.cpp+++ b/tests/integration/PreviewGeometryTests.cpp@@ -38,6 +38,10 @@ int wmain(int argc,wchar_t** argv){if(ok)ok=test("pan",{2,.25f,.5f},0,{{280,60,255,0,0},{280,200,255,0,255}});if(ok)ok=test("reference",{2,.5f,.5f},1,{{40,10,255,0,0},{280,10,0,255,0}});if(ok)ok=test("reset",{},0,{{160,10,0,0,0},{280,80,0,255,0}});+ if(ok)ok=test("dar-4-3",{1,.5f,.5f,0,4.0/3},0,{{40,10,255,0,0},{280,10,0,255,0},{40,230,255,0,255}});+ if(ok)ok=test("stretch",{1,.5f,.5f,3},0,{{40,10,255,0,0},{280,10,0,255,0},{280,230,255,255,255}});+ if(ok)ok=test("forced-16-9",{1,.5f,.5f,4},0,{{160,10,0,0,0},{40,40,255,0,0},{280,200,255,255,255}});+ if(ok)ok=test("native",{1,.5f,.5f,1},0,{{40,80,0,0,0},{145,111,255,0,0},{175,129,255,255,255}});if(ok){SetPropW(window,L"Veyra.ResizeDeferUntil",reinterpret_cast<HANDLE>(uintptr_t(GetTickCount64()+60000)));SetWindowPos(window,nullptr,0,0,400,400,SWP_NOMOVE|SWP_NOZORDER);diff --git a/tests/integration/UiMigrationPerfGateTests.ps1 b/tests/integration/UiMigrationPerfGateTests.ps1new file mode 100644index 00000000..f0ad5846--- /dev/null+++ b/tests/integration/UiMigrationPerfGateTests.ps1@@ -0,0 +1,102 @@+# Tests the gate, not GPU performance. Preserve each run's fixtures and output.+# UTF-8 BOM preserves the artifact-root literal in Windows PowerShell 5.1.+param([Parameter(Mandatory=$true)][string]$OutputDirectory)+$ErrorActionPreference = 'Stop'+$out = [IO.Path]::GetFullPath($OutputDirectory)+$artifactRoot = [IO.Path]::GetFullPath('E:/项目/Veyra/')+if (-not $out.StartsWith($artifactRoot,[StringComparison]::OrdinalIgnoreCase)) {+ throw 'OutputDirectory must be inside E:/项目/Veyra/'+}+if (Test-Path -LiteralPath $out) { throw 'OutputDirectory already exists; preserve previous evidence' }+New-Item -ItemType Directory -Path $out | Out-Null+$gate = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../../scripts/compare-ui-migration-perf.ps1'))+$cases = 'nr-1080','nr-fg-1080','nr-fg-4k','plain-1080'+function New-Result {+ $result = [ordered]@{}+ foreach ($case in $cases) {+ $result[$case] = [pscustomobject]@{ exit=0; samples=6; realPresented=300; graphSubmitP95Ms=1.0; gpuReadyP95Ms=8.0 }+ }+ return [pscustomobject]$result+}+$specs = @(+ @{name='equal'; expected=0},+ @{name='exact-boundaries'; expected=0},+ @{name='submit-over-limit'; expected=1},+ @{name='ready-over-limit'; expected=1},+ @{name='missing-case'; expected=1},+ @{name='missing-metric'; expected=1},+ @{name='no-samples'; expected=1},+ @{name='no-frames'; expected=1},+ @{name='failed-process'; expected=1},+ @{name='timeout'; expected=1},+ @{name='null-metric'; expected=1},+ @{name='string-metric'; expected=1},+ @{name='boolean-metric'; expected=1},+ @{name='zero-metric'; expected=1},+ @{name='negative-metric'; expected=1},+ @{name='invalid-baseline'; expected=1},+ @{name='malformed-results'; expected=2},+ @{name='malformed-baseline'; expected=2},+ @{name='protect-baseline'; expected=2},+ @{name='protect-results'; expected=2}+)+$summary = @()+foreach ($spec in $specs) {+ $dir = Join-Path $out $spec.name+ New-Item -ItemType Directory -Path $dir | Out-Null+ $current = New-Result; $baseline = New-Result+ $row = $current.'nr-1080'+ switch ($spec.name) {+ 'exact-boundaries' { foreach ($case in $cases) { $current.$case.graphSubmitP95Ms=1.1; $current.$case.gpuReadyP95Ms=8.4 } }+ 'submit-over-limit' { $row.graphSubmitP95Ms=1.10001 }+ 'ready-over-limit' { $row.gpuReadyP95Ms=8.40001 }+ 'missing-case' { $current.PSObject.Properties.Remove('nr-1080') }+ 'missing-metric' { $row.PSObject.Properties.Remove('graphSubmitP95Ms') }+ 'no-samples' { $row.samples=0 }+ 'no-frames' { $row.realPresented=0 }+ 'failed-process' { $row.exit=1 }+ 'timeout' { $current.'nr-1080'='timeout' }+ 'null-metric' { $row.graphSubmitP95Ms=$null }+ 'string-metric' { $row.graphSubmitP95Ms='1.0' }+ 'boolean-metric' { $row.graphSubmitP95Ms=$true }+ 'zero-metric' { $row.graphSubmitP95Ms=0 }+ 'negative-metric' { $row.graphSubmitP95Ms=-1 }+ 'invalid-baseline' { $baseline.'nr-1080'.realPresented=0 }+ }+ $resultsPath=Join-Path $dir 'results.json'; $baselinePath=Join-Path $dir 'baseline.json'+ $reportPath=Join-Path $dir 'gate.json'+ $current | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $resultsPath -Encoding utf8+ $baseline | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $baselinePath -Encoding utf8+ switch ($spec.name) {+ 'malformed-results' { '{' | Set-Content -LiteralPath $resultsPath -Encoding utf8 }+ 'malformed-baseline' { '{' | Set-Content -LiteralPath $baselinePath -Encoding utf8 }+ 'protect-baseline' { $reportPath=$baselinePath }+ 'protect-results' { $reportPath=$resultsPath }+ }+ $beforeResults=(Get-FileHash -LiteralPath $resultsPath -Algorithm SHA256).Hash+ $beforeBaseline=(Get-FileHash -LiteralPath $baselinePath -Algorithm SHA256).Hash+ # Separate host: the gate's exit must not terminate this test driver.+ $arguments=@('-NoProfile','-ExecutionPolicy','Bypass','-File',('"'+$gate+'"'),+ '-Results',('"'+$resultsPath+'"'),'-Baseline',('"'+$baselinePath+'"'),'-Report',('"'+$reportPath+'"'))+ $launch=@{ FilePath='powershell.exe'; ArgumentList=$arguments; PassThru=$true; WindowStyle='Hidden';+ RedirectStandardOutput=(Join-Path $dir 'stdout.log'); RedirectStandardError=(Join-Path $dir 'stderr.log') }+ $p=Start-Process @launch; $null=$p.Handle+ if (-not $p.WaitForExit(15000)) { $p.Kill(); $p.WaitForExit(); $exitCode=-1 }+ else { $p.WaitForExit(); $exitCode=$p.ExitCode }+ $unchanged=$beforeResults -eq (Get-FileHash -LiteralPath $resultsPath -Algorithm SHA256).Hash -and+ $beforeBaseline -eq (Get-FileHash -LiteralPath $baselinePath -Algorithm SHA256).Hash+ $reportOk=$true+ if ($spec.expected -ne 2) {+ $reportOk=Test-Path -LiteralPath $reportPath+ if ($reportOk) {+ $report=Get-Content -LiteralPath $reportPath -Raw | ConvertFrom-Json+ $reportOk=$report.passed -eq ($spec.expected -eq 0) -and @($report.cases).Count -eq 4+ }+ } elseif ($spec.name -notlike 'protect-*') { $reportOk=-not (Test-Path -LiteralPath $reportPath) }+ $passed=$exitCode -eq $spec.expected -and $unchanged -and $reportOk+ $summary += [pscustomobject]@{ name=$spec.name; passed=$passed; expected=$spec.expected; actual=$exitCode; inputHashesUnchanged=$unchanged; reportValid=$reportOk }+ Write-Output (('{0} {1} exit={2}' -f $(if($passed){'PASS'}else{'FAIL'}),$spec.name,$exitCode))+}+$summary | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $out 'summary.json') -Encoding utf8+if (@($summary | Where-Object { -not $_.passed }).Count) { exit 1 }+exit 0diff --git a/tests/integration/VideoHdrTests.cpp b/tests/integration/VideoHdrTests.cppindex 76fb54e9..e0d1487c 100644--- a/tests/integration/VideoHdrTests.cpp+++ b/tests/integration/VideoHdrTests.cpp@@ -4,9 +4,15 @@#include "veyra/gfx/CommandSlotRing.h"#include "veyra/source/MediaFileSource.h"#include "veyra/sink/ImageExportSink.h"+#include "veyra/engine/GraphDescription.h"#include <DirectXPackedVector.h>+#include <d3d12sdklayers.h>#include <algorithm>+#include <chrono>#include <cmath>+#include <filesystem>+#include <fstream>+#include <iomanip>#include <iostream>extern "C" {#include <libavutil/frame.h>@@ -15,17 +21,19 @@ using namespace veyra;using namespace veyra::pipeline;// Diagnostic readback only. The product conversion stays on the GPU.-static bool pixels(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,ID3D12Resource* texture,std::vector<float>& result){+static bool pixels(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,ID3D12Resource* texture,std::vector<float>& result,+ D3D12_RESOURCE_STATES initialState=D3D12_RESOURCE_STATE_COMMON){+ if(!texture)return false;const auto d=texture->GetDesc();D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};UINT64 bytes=0;ctx.device()->GetCopyableFootprints(&d,0,1,0,&fp,nullptr,nullptr,&bytes);D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=bytes;bd.Height=1;bd.DepthOrArraySize=bd.MipLevels=1;bd.SampleDesc.Count=1;bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;ComPtr<ID3D12Resource> buffer;if(FAILED(ctx.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&buffer))))return false;unsigned slot=0;Status status;auto* list=ring.acquireNext(slot,status);if(!list)return false;- StateTracker states;states.transition(list,texture,D3D12_RESOURCE_STATE_COPY_SOURCE);+ StateTracker states;states.set(texture,initialState);states.transition(list,texture,D3D12_RESOURCE_STATE_COPY_SOURCE);D3D12_TEXTURE_COPY_LOCATION src{},dst{};src.pResource=texture;src.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;dst.pResource=buffer.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;dst.PlacedFootprint=fp;- list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);states.transition(list,texture,D3D12_RESOURCE_STATE_COMMON);+ list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);states.transition(list,texture,initialState);if(!ring.submitAndSignal(slot)||!ring.waitIdle())return false;void* p=nullptr;D3D12_RANGE range{0,size_t(bytes)};if(FAILED(buffer->Map(0,&range,&p)))return false;result.resize(size_t(d.Width)*d.Height*3);@@ -39,8 +47,159 @@ static bool pixels(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,ID3D1}D3D12_RANGE none{};buffer->Unmap(0,&none);return true;}+static bool colorChain(const std::filesystem::path& directory){+ std::filesystem::create_directories(directory);+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status;gfx::DeviceContextDesc dd;dd.enableDebugLayer=true;+ if(!ctx.initialize(dd,status)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,status))return false;+ const auto freeFrame=[](AVFrame* p){av_frame_free(&p);};+ std::unique_ptr<AVFrame,decltype(freeFrame)> frame(av_frame_alloc(),freeFrame);if(!frame)return false;+ frame->format=AV_PIX_FMT_BGRA;frame->width=1280;frame->height=720;+ frame->color_range=AVCOL_RANGE_JPEG;frame->color_primaries=AVCOL_PRI_BT709;frame->color_trc=AVCOL_TRC_IEC61966_2_1;+ if(av_frame_get_buffer(frame.get(),32)<0)return false;+ for(int y=0;y<720;++y)for(int x=0;x<1280;++x){auto* p=frame->data[0]+size_t(y)*frame->linesize[0]+x*4;+ p[0]=p[1]=p[2]=uint8_t(x*255/1279);p[3]=255;}+ // The HDR chain must exercise the same six independent LUT files that the+ // export worker uses. Keep these files in the isolated executable staging+ // directory; the normal user's runtime_local is never touched.+ const auto lutFolder=runtime::localDataDirectory()/L"luts";+ std::error_code lutEc;std::filesystem::create_directories(lutFolder,lutEc);if(lutEc)return false;+ const auto stamp=std::to_string(std::chrono::steady_clock::now().time_since_epoch().count());+ const unsigned lutSizes[]={2,3,5,17,33,4};+ auto writeLut=[&](unsigned index)->std::wstring{+ const auto name=L"hdr-color-"+std::wstring(stamp.begin(),stamp.end())+L"-"+std::to_wstring(index)+L".cube";+ std::ofstream file(lutFolder/name);if(!file)return {};+ const unsigned size=lutSizes[index];file.precision(9);file<<"LUT_3D_SIZE "<<size<<'\n';+ for(unsigned z=0;z<size;++z)for(unsigned y=0;y<size;++y)for(unsigned x=0;x<size;++x){+ const float d=float(size-1);+ // Stay close to identity so the HDR peak remains representative;+ // the per-instance offsets still make every LUT observable.+ file<<(float(x)/d*(.98f+.002f*index)+.004f*(index+1))<<' '+ <<(float(y)/d*(.98f-.001f*index)+.002f*(6-index))<<' '+ <<(float(z)/d*(.98f+.001f*index)+.003f*(index%3))<<'\n';+ }+ file.close();return file?name:L"";+ };+ std::array<std::wstring,engine::kMaxColorInstances> lutNames{};+ for(unsigned i=0;i<engine::kMaxColorInstances;++i){+ lutNames[i]=writeLut(i);if(lutNames[i].empty())return false;+ }+ auto render=[&](const char* name,const engine::EnhancementSettings& settings,std::vector<float>& result,std::vector<float>* linear=nullptr){+ EnhanceGraphDesc desc;desc.rgbInput=true;desc.hdrOutput=true;desc.outputDitherStep=0;+ desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();+ engine::StageRequest request;request.width=1280;request.height=720;request.stillImage=true;+ engine::describeStages(request,settings,desc);+ auto graph=std::make_unique<EnhanceGraph>(ctx,ring);+ bool ok=graph->initialize(desc)&&graph->createViews()&&graph->videoHdrActive();+ EnhanceGraph::FrameOutputs out;+ for(unsigned n=0;n<3&&ok;++n){out={};ok=graph->process(frame.get(),n*1000.0/30,n==0,out,n+1);}+ if(ok)ok=pixels(ctx,ring,graph->videoFrameResource(out.videoSlot),result);+ if(ok&&linear)ok=pixels(ctx,ring,graph->diagnosticLinearInput(),*linear,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ double peak=0;+ if(ok){ok=result.size()==size_t(1280)*720*3&&std::all_of(result.begin(),result.end(),[](float v){return std::isfinite(v)&&v>=-.5f&&v<100;});+ if(!result.empty())peak=*std::max_element(result.begin(),result.end())*80;+ ok=ok&&peak>100&&peak<2100;+ ok=ok&&sink::saveHdrScreenshot((directory/(std::string(name)+".jxr")).wstring(),ctx,ring,graph->videoFrameResource(out.videoSlot));}+ out={};ring.drainQueue();graph->shutdown();graph.reset();+ std::cout<<"VIDEO_HDR_COLOR case="<<name<<" peakNits="<<peak<<" values="<<result.size()<<" pass="<<ok<<std::endl;+ return ok;+ };+ engine::EnhancementSettings plain;plain.videoHdr.enabled=true;plain.hdrOutputMode=engine::HdrOutputMode::ScRgb;+ auto fused=plain;fused.color.enabled=true;fused.color.exposure=1;+ auto standalone=plain;standalone.additionalColorCount=1;standalone.additionalColors[0]=fused.color;+ auto six=plain;six.color.enabled=true;six.color.exposure=.1f;six.additionalColorCount=5;+ for(auto& color:six.additionalColors){color.enabled=true;color.exposure=.1f;}+ auto sixLut=six;+ sixLut.color.setLutName(lutNames[0]);sixLut.color.lutInputSpace=engine::ColorSettings::kLutInputCineon;+ for(unsigned i=1;i<engine::kMaxColorInstances;++i){+ sixLut.additionalColors[i-1].setLutName(lutNames[i]);+ sixLut.additionalColors[i-1].lutInputSpace=engine::ColorSettings::kLutInputCineon;+ }+ std::vector<float> reference,a,b,c,d,repeated,linearPlain,linearFused,linearStandalone;+ bool ok=render("plain",plain,reference,&linearPlain);ok=render("fused",fused,a,&linearFused)&&ok;+ ok=render("standalone",standalone,b,&linearStandalone)&&ok;ok=render("six",six,c)&&ok;ok=render("six-lut",sixLut,d)&&ok;+ ok=render("fused-repeat",fused,repeated)&&ok;+ double maxFusedError=0,meanSingleChange=0,meanSixChange=0,meanSixLutChange=0,maxRepeatError=0,meanFusedError=0;+ size_t worstIndex=0,differentValues=0;+ if(ok){ok=a.size()==reference.size()&&b.size()==reference.size()&&c.size()==reference.size();+ ok=ok&&repeated.size()==reference.size();+ ok=ok&&d.size()==reference.size();+ if(ok){for(size_t i=0;i<reference.size();++i){const double error=std::abs(a[i]-b[i]);+ if(error>maxFusedError){maxFusedError=error;worstIndex=i;}+ meanFusedError+=error;differentValues+=error!=0;+ maxRepeatError=std::max(maxRepeatError,double(std::abs(a[i]-repeated[i])));+ meanSingleChange+=std::abs(a[i]-reference[i]);meanSixChange+=std::abs(c[i]-reference[i]);meanSixLutChange+=std::abs(d[i]-reference[i]);}+ meanSingleChange/=reference.size();meanSixChange/=reference.size();meanSixLutChange/=reference.size();meanFusedError/=reference.size();+ std::cout<<"VIDEO_HDR_COLOR_DIAGNOSTIC maxRepeatError="<<maxRepeatError<<" meanFusedError="<<meanFusedError+ <<" differentValues="<<differentValues<<" worstX="<<(worstIndex/3)%1280<<" worstY="<<worstIndex/(3*1280)+ <<" channel="<<worstIndex%3<<" fused="<<a[worstIndex]<<" standalone="<<b[worstIndex]<<std::endl;+ // Compare final TrueHDR output for the same one-stop grade. 1/64 scRGB is+ // a bounded FP16 tolerance (1.25 nits), not a visual-quality claim.+ ok=maxFusedError<=1.0/64&&meanSingleChange>.001&&meanSixChange>.001&&meanSixLutChange>.001;}}+ // Separate diagnostic renders expose the exact SDR codes passed to TrueHDR:+ // the same blit encode is used when TrueHDR is disabled. Do not use this+ // diagnostic to relax the HDR tolerance or change product precision.+ auto renderSdr=[&](engine::EnhancementSettings settings,sink::RgbaImage& image){+ settings.videoHdr.enabled=false;+ EnhanceGraphDesc desc;desc.rgbInput=true;desc.outputDitherStep=0;+ engine::StageRequest request;request.width=1280;request.height=720;request.stillImage=true;+ engine::describeStages(request,settings,desc);+ auto graph=std::make_unique<EnhanceGraph>(ctx,ring);EnhanceGraph::FrameOutputs out;+ bool rendered=graph->initialize(desc)&&graph->createViews()&&graph->process(frame.get(),0,true,out,1);+ if(rendered)rendered=sink::readRgba8(ctx,ring,graph->videoFrameResource(out.videoSlot),image);+ out={};ring.drainQueue();graph->shutdown();return rendered;+ };+ sink::RgbaImage sdrFused,sdrStandalone;+ const bool sdrOk=renderSdr(fused,sdrFused)&&renderSdr(standalone,sdrStandalone)&&+ sdrFused.pixels.size()==sdrStandalone.pixels.size()&&!sdrFused.pixels.empty();+ int maxCodeError=0;size_t differentCodes=0;+ if(sdrOk)for(size_t i=0;i<sdrFused.pixels.size();++i){const int error=std::abs(int(sdrFused.pixels[i])-int(sdrStandalone.pixels[i]));+ maxCodeError=std::max(maxCodeError,error);differentCodes+=error!=0;}+ std::cout<<"VIDEO_HDR_COLOR_SDR_DIAGNOSTIC rendered="<<sdrOk<<" maxCodeError="<<maxCodeError+ <<" differentCodes="<<differentCodes<<std::endl;+ ok=ok&&sdrOk;+ // Diagnostic only: identify the earliest divergence without changing the+ // legacy fused shader, the standalone RGBA16F contract, or the HDR gate.+ const bool linearOk=linearPlain.size()==size_t(1280)*720*3&&linearFused.size()==linearPlain.size()&&+ linearStandalone.size()==linearPlain.size()&&a.size()==linearPlain.size()&&b.size()==linearPlain.size();+ double maxLinearError=0,meanLinearError=0;size_t linearDifferent=0,linearWorst=0;+ if(linearOk){+ for(size_t i=0;i<linearFused.size();++i){const double error=std::abs(linearFused[i]-linearStandalone[i]);+ if(error>maxLinearError){maxLinearError=error;linearWorst=i;}+ meanLinearError+=error;linearDifferent+=error!=0;}+ meanLinearError/=linearFused.size();+ std::cout<<"VIDEO_HDR_COLOR_LINEAR_DIAGNOSTIC maxError="<<maxLinearError<<" meanError="<<meanLinearError+ <<" differentValues="<<linearDifferent<<" worstX="<<(linearWorst/3)%1280<<" channel="<<linearWorst%3+ <<" fused="<<linearFused[linearWorst]<<" standalone="<<linearStandalone[linearWorst]<<std::endl;+ std::ofstream csv(directory/"linear-sdr-hdr-row.csv");+ csv<<"x,inputCode,channel,plainLinear,fusedLinear,standaloneLinear,fusedSdr,standaloneSdr,fusedHdr,standaloneHdr\n"<<std::setprecision(10);+ if(sdrOk)for(size_t x=0;x<1280;++x)for(size_t ch=0;ch<3;++ch){const size_t i=x*3+ch;+ csv<<x<<','<<x*255/1279<<','<<ch<<','<<linearPlain[i]<<','<<linearFused[i]<<','<<linearStandalone[i]+ <<','<<unsigned(sdrFused.pixels[x*4+ch])<<','<<unsigned(sdrStandalone.pixels[x*4+ch])+ <<','<<a[i]<<','<<b[i]<<'\n';}+ csv.flush();ok=bool(csv)&&ok;+ }+ ok=linearOk&&ok;+ ComPtr<ID3D12InfoQueue> info;uint64_t errors=0;+ if(FAILED(ctx.device()->QueryInterface(IID_PPV_ARGS(&info))))ok=false;+ else for(UINT64 i=0;i<info->GetNumStoredMessages();++i){SIZE_T size=0;+ if(FAILED(info->GetMessage(i,nullptr,&size))){ok=false;break;}+ std::vector<uint8_t> bytes(size);auto* message=reinterpret_cast<D3D12_MESSAGE*>(bytes.data());+ if(FAILED(info->GetMessage(i,message,&size))){ok=false;break;}+ if(message->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;std::cerr<<message->pDescription<<std::endl;}}+ ok=ok&&errors==0;+ std::cout<<"VIDEO_HDR_COLOR_MATRIX maxFusedErrorScRgb="<<maxFusedError<<" meanSingleChange="<<meanSingleChange+ <<" meanSixChange="<<meanSixChange<<" meanSixLutChange="<<meanSixLutChange+ <<" debugErrors="<<errors<<" pass="<<ok<<std::endl;+ info.Reset();ring.shutdown();ctx.shutdown();return ok;+}int wmain(int argc,wchar_t** argv){CoInitializeEx(nullptr,COINIT_MULTITHREADED);+ if(argc>1&&std::wstring_view(argv[1])==L"--color-chain"){+ const bool ok=argc==3&&colorChain(argv[2]);CoUninitialize();return ok?0:1;}+ // Leave legacy numeric arguments unchanged; the harness supplies an isolated+ // evidence path rather than deleting or overwriting a previous screenshot.+ std::wstring screenshotPath=L"video-hdr.jxr";+ if(argc>=3&&std::wstring_view(argv[argc-2])==L"--output"){screenshotPath=argv[argc-1];argc-=2;}gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status;gfx::DeviceContextDesc dd;if(!ctx.initialize(dd,status)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,status))return 2;EnhanceGraph graph(ctx,ring);EnhanceGraphDesc gd;@@ -75,7 +234,7 @@ int wmain(int argc,wchar_t** argv){ok=ok&&peak>100&&peak<2100;if(n==5)baseline=data;if(n==11){for(size_t i=0;i<data.size();++i)changed+=std::abs(data[i]-baseline[i]);changed/=data.size();- ok=ok&&changed>.001&&sink::saveHdrScreenshot(L"video-hdr.jxr",ctx,ring,graph.videoFrameResource(out.videoSlot));}+ ok=ok&&changed>.001&&sink::saveHdrScreenshot(screenshotPath,ctx,ring,graph.videoFrameResource(out.videoSlot));}if(gd.enableFg){ok=ok&&graph.resolveGeneration(out);if(out.hasGenerated)++generated;}}ok=ok&&(!gd.enableFg||generated>0);diff --git a/tests/qml/QmlEasingTests.cpp b/tests/qml/QmlEasingTests.cppindex 5997e75e..fc95a38f 100644--- a/tests/qml/QmlEasingTests.cpp+++ b/tests/qml/QmlEasingTests.cpp@@ -7,7 +7,9 @@// Reading the curve through QML matters: easing.bezierCurve silently falls back to// linear when its length is not a multiple of 6, which is exactly the bug this catches.#include <QCoreApplication>+#include <QDir>#include <QEasingCurve>+#include <QFileInfo>#include <QGuiApplication>#include <QQmlComponent>#include <QQmlEngine>@@ -93,7 +95,12 @@ int main(int argc, char** argv) {qputenv("QT_QPA_PLATFORM", "offscreen");QGuiApplication app(argc, argv);QQmlEngine engine;- engine.addImportPath(QStringLiteral(VEYRA_QML_DIR));+ const QString qmlDir = QDir(app.applicationDirPath()).filePath(QStringLiteral("qml"));+ if (!QFileInfo::exists(QDir(qmlDir).filePath(QStringLiteral("Veyra/qmldir")))) {+ std::printf("FAIL missing staged QML module: %s\n", qPrintable(qmlDir));+ return 2;+ }+ engine.addImportPath(qmlDir);const Stops spring = css_linear({{0, -1}, {.009, -1}, {.035, 2.1}, {.141, 4.4}, {.723, 12.9}, {.938, 16.7},{1.017, 20.2}, {1.043, 24}, {1.035, 28.4}, {.998, 38.5}, {.99, 44.1},diff --git a/tests/qml/QuickSmokeTests.cpp b/tests/qml/QuickSmokeTests.cppindex db05f9ef..e5c478a8 100644--- a/tests/qml/QuickSmokeTests.cpp+++ b/tests/qml/QuickSmokeTests.cpp@@ -1,14 +1,35 @@// G1.6: component smoke tests through Qt Quick Test (tests/qml/quick/tst_*.qml).-// The Veyra module loads from the source tree's qml/ as plain files, like the app.+// The test source and Veyra module are resolved from the executable's staging+// directory. This prevents a staging run from silently reading the source tree.+#include <QCoreApplication>+#include <QDir>+#include <QFileInfo>#include <QQmlEngine>+#include <QtQml/qqml.h>#include <QtQuickTest/quicktest.h>class Setup : public QObject {Q_OBJECTpublic slots:- void qmlEngineAvailable(QQmlEngine* engine) { engine->addImportPath(QStringLiteral(VEYRA_QML_DIR)); }+ void qmlEngineAvailable(QQmlEngine* engine) {+ engine->addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath(QStringLiteral("qml")));+ // ProPage is private to the production shell's directory, not exported+ // by Veyra/qmldir. Register it only here to test its real inline controls.+ qmlRegisterType(QUrl::fromLocalFile(QDir(QCoreApplication::applicationDirPath()).filePath(+ QStringLiteral("qml/Veyra/ProPage.qml"))), "VeyraTest", 1, 0, "ProPage");+ }};-QUICK_TEST_MAIN_WITH_SETUP(veyra_qml_quick_tests, Setup)+int main(int argc, char** argv) {+ const QString applicationDirectory = QFileInfo(QString::fromLocal8Bit(argv[0])).absolutePath();+ const QString sourceDirectory = QDir(applicationDirectory).filePath(QStringLiteral("qml-tests"));+ if (!QFileInfo::exists(QDir(sourceDirectory).filePath(QStringLiteral("tst_components.qml")))) {+ fprintf(stderr, "missing staged Qt Quick Test source directory: %s\n", qPrintable(sourceDirectory));+ return 2;+ }+ const QByteArray sourceDirectoryBytes = sourceDirectory.toLocal8Bit();+ Setup setup;+ return quick_test_main_with_setup(argc, argv, "veyra_qml_quick_tests", sourceDirectoryBytes.constData(), &setup);+}#include "QuickSmokeTests.moc"diff --git a/tests/qml/quick/tst_components.qml b/tests/qml/quick/tst_components.qmlindex 307732ee..cf2f1912 100644--- a/tests/qml/quick/tst_components.qml+++ b/tests/qml/quick/tst_components.qml@@ -3,11 +3,12 @@import QtQuickimport QtTestimport Veyra+import VeyraTest 1.0Item {id: root- width: 800- height: 600+ width: 1480+ height: 900VSwitch { id: sw; x: 10; y: 10 }SignalSpy { id: swSpy; target: sw; signalName: "toggled" }@@ -22,6 +23,20 @@ Item {VSlider { id: slider; x: 10; y: 100; width: 200; from: 0; to: 100; value: 50 }SignalSpy { id: sliderSpy; target: slider; signalName: "moved" }+ VButton { id: underSlider; x: 680; y: 100; width: 200; height: 20; text: "underlying inspector" }+ SignalSpy { id: underSliderSpy; target: underSlider; signalName: "clicked" }+ VSlider { id: overSlider; x: 680; y: 100; width: 200; from: 0; to: 100; value: 50 }+ VSlider { id: resetSlider; x: 10; y: 135; width: 200; from: 0; to: 100; value: 25; resettable: true; defaultValue: 50 }+ SignalSpy { id: resetSpy; target: resetSlider; signalName: "moved" }++ QtObject { id: boundState; property real amount: 25; property bool acceptEdits: true }+ VSlider {+ id: boundSlider; x: 240; y: 135; width: 200+ from: 0; to: 100; value: boundState.amount+ valueFromModel: true+ resettable: true; defaultValue: 50+ onMoved: value => { if (boundState.acceptEdits) boundState.amount = value }+ }VAccordion {id: acc@@ -47,13 +62,150 @@ Item {}SignalSpy { id: menuSpy; target: menu; signalName: "picked" }+ // Real controls with an explicit snapshot fixture; this is not an engine test.+ Component {+ id: nrFixture+ Item {+ id: fixture+ width: 1480; height: 900; z: 20+ property int lastIndex: -1+ property string lastKey: ""+ property var rows: [0,1,2,3].map(i => ({+ index: 2*i+1, enabled: true, sizePolicy: 0, intensity: 1,+ tone: 1, structure: 1, skin: -1, style: 0, autoMask: false,+ uiCorrection: false, total: 1, darken: 1, brighten: 1,+ color: 1, luminance: 1, temporal: false+ }))+ function edit(nodeIndex,key,amount) {+ lastIndex=nodeIndex; lastKey=key+ const next=rows.map(r => Object.assign({},r))+ next.find(r => r.index===nodeIndex)[key]=amount+ rows=next+ }+ Repeater {+ model: 4+ delegate: ProPage.NrLayerCard {+ required property int index+ x: index*370; width: 360+ layerData: fixture.rows[index]+ layerNumber: index+1; layerCount: 4+ onEdited: (nodeIndex,key,amount) => fixture.edit(nodeIndex,key,amount)+ onEnabledEdited: (nodeIndex,enabled) => fixture.edit(nodeIndex,"enabled",enabled)+ }+ }+ }+ }++ Component {+ id: colourFixture+ Item {+ id: fixture+ width:1100;height:800;z:40+ property int edits:0+ property string lastKey:""+ ColourCurve {+ id: curve;objectName:"test-curve";x:10;y:10;width:300+ onEdited:(channel,points)=>{+ const copy=curves.slice();copy[channel]=points;curves=copy;++fixture.edits+ }+ }+ ColourMixer {+ id:mixer;objectName:"test-mixer";x:330;y:10;width:320+ onModeEdited:blackWhite=>state=Object.assign({},state,{blackWhite:blackWhite})+ onEdited:(name,value)=>{+ const parts=name.split("."),next=Object.assign({},state),arr=state[parts[0]].slice()+ arr[Number(parts[1])]=value;next[parts[0]]=arr;state=next;fixture.lastKey=name;++fixture.edits+ }+ }+ Row {+ x:10;y:400;spacing:20+ Repeater {+ model:4+ ColourWheel {+ property bool sliderResetEnabled: true+ property bool sliderValueFromModel: true+ required property int index+ objectName:"test-wheel-"+index;width:150+ title:["阴影","中间调","高光","全局"][index]+ onEdited:(h,s,l)=>{hue=h;saturation=s;luminance=l;++fixture.edits}+ }+ }+ }+ }+ }+TestCase {name: "Components"when: windowShownfunction initTestCase() { Theme.reduced = true } // no waiting on transitions+ function test_colour_mixer_design_motion() {+ const f=createTemporaryObject(colourFixture,root)+ verify(f!==null);verify(waitForPolish(root.Window.window))+ const mixer=findChild(f,"test-mixer")+ const band=i=>findChild(mixer,"colour-mixer-band-"+i)+ compare(band(5).height,22);compare(band(5).radius,7)+ compare(band(0).scale,1.08);compare(band(5).scale,1)+ try {+ Theme.reduced=false+ const start=Date.now(),samples=[]+ mouseClick(band(5),band(5).width/2,band(5).height/2)+ for(let i=0;i<32;++i){+ samples.push({ms:Date.now()-start,scale:band(5).scale})+ wait(16)+ }+ console.log("P3_MIXER_MOTION "+JSON.stringify(samples))+ verify(samples.some(s=>s.scale>1&&s.scale<1.08),"real intermediate frames")+ verify(samples.some(s=>s.scale>1.08),"design spring overshoot")+ fuzzyCompare(band(5).scale,1.08,0.0001)+ for(const i of [2,4,7]){mouseClick(band(i),band(i).width/2,band(i).height/2);wait(48)}+ wait(420);compare(mixer.band,7)+ for(let i=0;i<8;++i)fuzzyCompare(band(i).scale,i===7?1.08:1,0.0001)+ Theme.reduced=true+ mouseClick(band(3),band(3).width/2,band(3).height/2)+ compare(mixer.band,3);fuzzyCompare(band(3).scale,1.08,0.0001)+ fuzzyCompare(band(7).scale,1,0.0001)+ } finally { Theme.reduced=true }+ }++ function test_accordion_header_action_keeps_open_state() {+ const f=createTemporaryQmlObject(`import QtQuick; import Veyra; VAccordion {+ id:fixture;x:700;y:10;width:330;open:true;enabledSwitch:false;title:"颜色";+ property int resets:0;+ headerActions: [VButton {objectName:"test-header-reset";text:"还原";implicitWidth:40;implicitHeight:24;onClicked:fixture.resets++}]+ Rectangle {implicitHeight:80;implicitWidth:100}+ }`,root)+ verify(f!==null);verify(waitForPolish(root.Window.window))+ const button=findChild(f,"test-header-reset")+ mouseClick(button,button.width/2,button.height/2)+ compare(f.resets,1);verify(f.open,"header action must not collapse section")+ mouseClick(f,80,24);verify(!f.open,"ordinary header still toggles")+ }++ function test_colour_header_leading_action() {+ const f=createTemporaryQmlObject(`import QtQuick; import Veyra; VAccordion {+ id:fixture;x:700;y:10;width:330;open:true;enabledSwitch:false;title:"颜色";+ compactHeader:true;property int resets:0;+ headerLeadingActions: [VButton {objectName:"test-header-eye";icon:true;iconName:fixture.bypassed?"eyeoff":"eye";ghost:true;implicitWidth:24;implicitHeight:24;onClicked:fixture.bypassed=!fixture.bypassed}]+ headerActions: [VButton {objectName:"test-header-reset";icon:true;iconName:"reset";ghost:true;implicitWidth:26;implicitHeight:26;onClicked:fixture.resets++}]+ Rectangle {objectName:"test-header-body";implicitHeight:80;implicitWidth:100}+ }`,root)+ verify(f!==null);verify(waitForPolish(root.Window.window))+ compare(f.headerHeight,42);compare(acc.headerHeight,48)+ const eye=findChild(f,"test-header-eye"),reset=findChild(f,"test-header-reset")+ const body=findChild(f,"test-header-body").parent+ verify(eye.mapToItem(f,0,0).x<reset.mapToItem(f,0,0).x)+ mouseClick(eye,12,12);verify(f.bypassed);verify(f.open);compare(eye.iconName,"eyeoff")+ tryCompare(body,"opacity",0.45)+ mouseClick(reset,13,13);compare(f.resets,1);verify(f.open);verify(f.bypassed)+ mouseClick(eye,12,12);verify(!f.bypassed);verify(f.open);tryCompare(body,"opacity",1)+ mouseClick(f,80,21);verify(!f.open);tryCompare(body,"opacity",0)+ }+function test_switch() {+ sw.checked=false+ swSpy.clear()compare(sw.checked, false)mouseClick(sw)compare(sw.checked, true)@@ -80,6 +232,80 @@ Item {compare(sliderSpy.count, 1)}+ function test_slider_does_not_click_through() {+ underSliderSpy.clear()+ overSlider.value = 50+ mouseClick(overSlider, 150, overSlider.height / 2)+ fuzzyCompare(overSlider.value, 75, 1)+ compare(underSliderSpy.count, 0, "Foreground slider must not open an underlying node inspector")+ }++ function test_slider_reset_nonzero_and_hit_area() {+ resetSlider.enabledControl = true+ resetSlider.value = 25+ resetSpy.clear()+ const button = findChild(resetSlider, "vslider-reset")+ verify(button !== null && button.visible)+ mouseClick(button, button.width / 2, button.height / 2)+ compare(resetSlider.value, 50)+ compare(resetSpy.count, 1)+ compare(resetSpy.signalArguments[0][0], 50)+ // The reset click must not also jump to the track's right edge.+ mouseClick(button, button.width / 2, button.height / 2)+ compare(resetSpy.count, 1)+ mouseClick(resetSlider, 43, resetSlider.height / 2)+ fuzzyCompare(resetSlider.value, 25, 1)+ compare(resetSpy.count, 2)+ resetSlider.enabledControl = false+ mouseClick(button, button.width / 2, button.height / 2)+ mouseClick(resetSlider, 120, resetSlider.height / 2)+ fuzzyCompare(resetSlider.value, 25, 1)+ compare(resetSpy.count, 2)+ resetSlider.enabledControl = true+ }++ function test_slider_reset_exact_endpoint_and_sentinel() {+ const button = findChild(resetSlider, "vslider-reset")+ for (const amount of [0, 100, -1]) {+ resetSlider.value = 25+ resetSlider.defaultValue = amount+ resetSpy.clear()+ mouseClick(button, button.width / 2, button.height / 2)+ compare(resetSlider.value, amount)+ compare(resetSpy.count, 1)+ }+ resetSlider.defaultValue = 50+ compare(findChild(slider, "vslider-reset").visible, false)+ }++ function test_slider_keeps_external_parameter_binding() {+ boundState.acceptEdits = true+ boundState.amount = 25+ mouseClick(boundSlider, boundSlider.trackWidth * 0.75, boundSlider.height / 2)+ fuzzyCompare(boundState.amount, 75, 1)+ boundState.amount = 35+ compare(boundSlider.value, 35, "External group/node reset must update an edited slider")+ const button = findChild(boundSlider, "vslider-reset")+ mouseClick(button, button.width / 2, button.height / 2)+ compare(boundState.amount, 50)+ boundState.amount = 15+ compare(boundSlider.value, 15, "Single-parameter reset must preserve model binding")+ boundState.amount = 50+ const x = boundSlider.trackWidth / 2, y = boundSlider.height / 2+ mousePress(boundSlider, x, y)+ for (let i = 1; i <= 8; ++i) mouseMove(boundSlider, x + i * 5, y)+ mouseRelease(boundSlider, x + 40, y)+ fuzzyCompare(boundState.amount, 50 + 4000 / boundSlider.trackWidth, 2)+ boundState.amount = 20+ compare(boundSlider.value, 20, "Dragging must preserve model binding")+ boundState.acceptEdits = false+ mouseClick(boundSlider, boundSlider.trackWidth * 0.75, y)+ compare(boundSlider.value, 20, "Rejected backend edit must not appear accepted")+ mouseClick(button, button.width / 2, button.height / 2)+ compare(boundSlider.value, 20, "Rejected reset must not override the model")+ boundState.acceptEdits = true+ }+function test_slider_drag() {// Drag from the knob 40 px right: the value moves by 40/200 of the range,// not by a running total (the G1.5 drag fix).@@ -139,6 +365,207 @@ Item {dynamicMenu.close()}+ function popupFor(select) {+ for (const c of select.data)+ if (c && typeof c.openAt === "function") return c+ fail("select popup not found")+ }++ function pickOption(select,index) {+ verify(select.width>20 && select.height>10)+ mouseClick(select)+ const popup=popupFor(select)+ tryCompare(popup,"opened",true)+ verify(waitForPolish(root.Window.window))+ const rows=findRows(popup.contentItem)+ compare(rows.length,select.options.length)+ mouseClick(rows[index])+ tryCompare(popup,"visible",false)+ verify(waitForPolish(root.Window.window))+ }++ function test_nr_four_independent_cards() {+ const fixture=createTemporaryObject(nrFixture,root)+ verify(fixture)+ verify(waitForPolish(root.Window.window))+ const policies=[2,3,5,1]+ const optionIndices=[0,1,4,5]+ for(let i=0;i<4;++i) {+ const card=findChild(fixture,"nr-card-"+(i+1))+ // 2026-09-29 P5: the layer cards sit inside the NR stage card, titled "NR 层 N".+ verify(card.title.includes("NR 层 "+(i+1)))+ compare(card.layerData.sizePolicy,0)+ mouseClick(card,40,24)+ tryCompare(card,"open",true)+ const resolution=findChild(card,"nr-resolution")+ compare(resolution.options.map(o=>o.label).join(","),"480p,720p,900p,1080p · 默认,1440p,原生")+ pickOption(resolution,optionIndices[i])+ compare(fixture.rows[i].sizePolicy,policies[i])+ const intensity=findChild(card,"nr-intensity")+ mouseClick(intensity,intensity.trackWidth*(0.2+0.15*i),intensity.height/2)+ fuzzyCompare(fixture.rows[i].intensity,0.2+0.15*i,0.015)+ compare(fixture.lastIndex,2*i+1)+ compare(fixture.lastKey,"intensity")+ verify(!findChild(card,"nr-copy").enabled)+ // Snapshot updates preserve delegate and expansion state.+ compare(findChild(fixture,"nr-card-"+(i+1)),card)+ compare(card.open,true)+ }+ for(let i=0;i<4;++i) {+ compare(fixture.rows[i].sizePolicy,policies[i])+ fuzzyCompare(fixture.rows[i].intensity,0.2+0.15*i,0.015)+ }+ }++ function test_nr_complete_parameters_and_skin_range() {+ const fixture=createTemporaryObject(nrFixture,root)+ verify(waitForPolish(root.Window.window))+ const card=findChild(fixture,"nr-card-2")+ mouseClick(card,40,24)+ tryCompare(card,"open",true)+ const model=findChild(card,"nr-model-group")+ tryVerify(()=>model.width>300)+ mouseClick(model,40,15)+ tryCompare(model,"expanded",true)+ verify(waitForPolish(root.Window.window))+ for(const key of ["tone","structure"]) {+ const control=findChild(card,"nr-"+key)+ verify(control.width>50)+ mouseClick(control,control.trackWidth/4,control.height/2)+ fuzzyCompare(fixture.rows[1][key],0.25,0.015)+ const reset=findChild(control,"vslider-reset")+ mouseClick(reset,reset.width/2,reset.height/2)+ compare(fixture.rows[1][key],1)+ compare(fixture.rows[0][key],1)+ fixture.rows[1][key] = 0.6+ fixture.rows = fixture.rows.slice()+ compare(control.value, 0.6, "NR control must follow external instance updates")+ }+ compare(fixture.rows[1].skin,-1)+ pickOption(findChild(card,"nr-skin-mode"),1)+ compare(fixture.rows[1].skin,0)+ const skin=findChild(card,"nr-skin")+ compare(skin.from,0); compare(skin.to,2)+ mouseClick(skin,skin.trackWidth/4,skin.height/2)+ fuzzyCompare(fixture.rows[1].skin,0.5,0.02)+ const skinReset=findChild(skin,"vslider-reset")+ mouseClick(skinReset,skinReset.width/2,skinReset.height/2)+ compare(fixture.rows[1].skin,-1)+ for(const key of ["autoMask","uiCorrection"]) {+ mouseClick(findChild(card,"nr-"+key))+ compare(fixture.rows[1][key],1)+ }+ const style=findChild(card,"nr-style")+ mouseClick(style.currentItem.parent.children[2])+ compare(fixture.rows[1].style,2)+ mouseClick(model,40,15)+ verify(waitForPolish(root.Window.window))+ const residual=findChild(card,"nr-residual-group")+ verify(residual.width>300)+ mouseClick(residual,40,15)+ tryCompare(residual,"expanded",true)+ verify(waitForPolish(root.Window.window))+ for(const key of ["total","darken","brighten","color","luminance"]) {+ const control=findChild(card,"nr-"+key)+ verify(control.width>50)+ mouseClick(control,control.trackWidth/4,control.height/2)+ fuzzyCompare(fixture.rows[1][key],0.5,0.02)+ const reset=findChild(control,"vslider-reset")+ mouseClick(reset,reset.width/2,reset.height/2)+ compare(fixture.rows[1][key],1)+ compare(fixture.rows[0][key],1)+ compare(fixture.lastIndex,3)+ }+ mouseClick(residual,40,15)+ verify(waitForPolish(root.Window.window))+ const experimental=findChild(card,"nr-experimental-group")+ mouseClick(experimental,40,15)+ tryCompare(experimental,"expanded",true)+ verify(waitForPolish(root.Window.window))+ verify(findChild(card,"nr-temporal").visible)+ compare(fixture.rows[0].skin,-1)+ compare(fixture.rows[0].style,0)+ }++ function test_colour_curve_mouse_edit() {+ const f=createTemporaryObject(colourFixture,root)+ verify(f!==null);verify(waitForPolish(root.Window.window))+ const curve=findChild(f,"test-curve"),canvas=findChild(curve,"colour-curve-canvas")+ verify(canvas.width>200);compare(curve.points.length,2)+ mouseDoubleClickSequence(canvas,canvas.width*0.5,canvas.height*0.3)+ tryCompare(curve.points,"length",3)+ verify(Math.abs(curve.points[1].y-0.7)<0.03)+ mouseDrag(canvas,canvas.width*0.5,canvas.height*0.3,canvas.width*0.18,canvas.height*0.1)+ verify(curve.points[1].x>0.6&&curve.points[1].x<1)+ mouseClick(canvas,curve.points[1].x*canvas.width,(1-curve.points[1].y)*canvas.height,Qt.RightButton)+ compare(curve.points.length,2)+ mouseDrag(canvas,1,canvas.height-1,canvas.width*0.3,-canvas.height*0.2)+ compare(curve.points[0].x,0)+ verify(curve.points[0].y>0.1)+ curve.channel=1;compare(curve.points[0].y,0)+ verify(f.edits>2)+ }+ function test_colour_mixer_band_isolation() {+ const f=createTemporaryObject(colourFixture,root)+ verify(f!==null);verify(waitForPolish(root.Window.window))+ const mixer=findChild(f,"test-mixer")+ compare(findChild(mixer,"colour-mixer-mode-row").label,"模式")+ const hueRow=findChild(mixer,"colour-mixer-row-mixerHue")+ const satRow=findChild(mixer,"colour-mixer-row-mixerSaturation")+ compare(satRow.y-hueRow.y,38)+ const band=findChild(mixer,"colour-mixer-band-5")+ mouseClick(band,band.width/2,band.height/2);compare(mixer.band,5)+ const sat=findChild(mixer,"colour-mixer-mixerSaturation")+ compare(sat.width,150)+ const hue=findChild(mixer,"colour-mixer-mixerHue")+ const luminance=findChild(mixer,"colour-mixer-mixerLuminance")+ compare(hue.mapToItem(mixer,0,0).x,sat.mapToItem(mixer,0,0).x)+ compare(luminance.mapToItem(mixer,0,0).x,sat.mapToItem(mixer,0,0).x)+ mouseClick(sat,sat.trackWidth*0.85,sat.height/2)+ compare(f.lastKey,"mixerSaturation.5")+ verify(mixer.state.mixerSaturation[5]>50);compare(mixer.state.mixerSaturation[0],0)+ const fill=findChild(sat,"vslider-fill")+ verify(fill.visible);compare(fill.x,sat.trackWidth/2);verify(fill.width>0)+ verify(findChild(mixer,"colour-mixer-value-mixerSaturation").text.startsWith("+"))+ mouseClick(sat,sat.trackWidth*0.2,sat.height/2)+ verify(fill.x<sat.trackWidth/2);verify(Math.abs(fill.x+fill.width-sat.trackWidth/2)<0.01)+ verify(mixer.state.mixerSaturation[5]<0);compare(mixer.state.mixerSaturation[0],0)+ const mode=findChild(mixer,"colour-mixer-mode")+ mouseClick(mode,mode.width-20,mode.height/2)+ verify(mixer.state.blackWhite);verify(waitForPolish(root.Window.window))+ const bw=findChild(mixer,"colour-mixer-blackWhiteMix")+ compare(bw.width,150)+ mouseClick(bw,bw.trackWidth*0.2,bw.height/2)+ compare(f.lastKey,"blackWhiteMix.5")+ verify(mixer.state.blackWhiteMix[5]<-40);compare(mixer.state.blackWhiteMix[4],0)+ const previousSaturation=mixer.state.mixerSaturation[5]+ const reset=findChild(bw,"vslider-reset")+ mouseClick(reset,reset.width/2,reset.height/2)+ compare(mixer.state.blackWhiteMix[5],0)+ compare(mixer.state.mixerSaturation[5],previousSaturation)+ }+ function test_colour_wheels_mouse_and_reset() {+ const f=createTemporaryObject(colourFixture,root)+ verify(f!==null);verify(waitForPolish(root.Window.window))+ for(let i=0;i<4;++i){+ const wheel=findChild(f,"test-wheel-"+i),disc=findChild(wheel,"colour-wheel-disc")+ mouseClick(disc,disc.width*0.5,disc.height*0.9)+ verify(Math.abs(wheel.hue-90)<2);verify(wheel.saturation>75)+ const l=findChild(wheel,"colour-wheel-luminance")+ mouseClick(l,l.trackWidth*0.75,l.height/2);verify(wheel.luminance>40)+ const previousHue=wheel.hue,previousSaturation=wheel.saturation+ const button=findChild(l,"vslider-reset")+ verify(button.visible)+ mouseClick(button,button.width/2,button.height/2)+ compare(wheel.luminance,0)+ compare(wheel.hue,previousHue);compare(wheel.saturation,previousSaturation)+ wheel.luminance = 20+ compare(l.value,20,"Wheel luminance must follow group updates after reset")+ mouseDoubleClickSequence(disc,disc.width/2,disc.height/2)+ compare(wheel.hue,0);compare(wheel.saturation,0);compare(wheel.luminance,0)+ }+ }+// The option rows: Rectangles with radius 9 inside the menu's list.function findRows(item) {let out = []diff --git a/tests/unit/EffectChainTests.cpp b/tests/unit/EffectChainTests.cppindex 09972e4b..78ba3684 100644--- a/tests/unit/EffectChainTests.cpp+++ b/tests/unit/EffectChainTests.cpp@@ -1,6 +1,12 @@// EffectChain: conversion fidelity and the ordering rules that both editing// modes must obey. These are the guards for the multi-NR and node-mode work.#include "veyra/engine/EffectChain.h"+#include "veyra/engine/GraphDescription.h"+#include <type_traits>+#include <algorithm>+#include <random>+#include <memory>+#include <limits>#include <cstdio>#include <string>@@ -20,7 +26,7 @@ EnhancementSettings populated() {s.nr = true; s.sr = true; s.lowLatency = true;s.model = NrSettings{0.8f, 0.7f, 0.6f, 0.2f, 1, 1, 0};s.residual = ResidualSettings{1.4f, 0.8f, 1.1f, 0.9f, 1.2f};- s.nrRuntime = NrRuntime::Community;+ s.nrRuntime = NrRuntime::Ampere;s.nrTemporal = true;s.protection.enabled = true;s.protection.featherPixels = 12;@@ -44,7 +50,89 @@ EnhancementSettings populated() {}} // namespace-int main() {+__declspec(noinline) void testNodeEditorGraph() {+ auto document = std::make_unique<EffectChain>();+ document->mode = ChainMode::Node; document->nodeCount = 4;+ document->nodes[0].type = EffectType::NrEnhance; document->nodes[0].enabled = true;+ document->nodes[0].nr.model.intensity = 0.73f;+ document->nodes[0].nr.sizePolicy = veyra::pipeline::NrSizePolicy::Native;+ document->nodes[1].type = EffectType::Color; document->nodes[1].enabled = true;+ document->nodes[1].color.exposure = 0.63f;+ document->nodes[1].color.curves[0].points[1].y = 0.8f;+ document->nodes[1].color.setLutName(L"unchanged-reference.cube");+ document->nodes[2].type = EffectType::SuperResolution;+ document->nodes[3].type = EffectType::FrameGeneration;+ NodeGraphLayout graph;+ check(graph.initialize(*document).accepted, "editor: migrate clean legacy linear chain");+ auto output = std::make_unique<EffectChain>();+ check(graph.project(*document, *output).accepted && *output == *document,+ "editor: migration retains exact runtime payload and order");+ const uint32_t nr = graph.ids[0], color = graph.ids[1], sr = graph.ids[2], fg = graph.ids[3];+ auto previous = std::make_unique<EffectChain>(*output);+ uint32_t copy = 999;+ check(graph.duplicate(*document, nr, copy).accepted && copy != nr && copy != 999,+ "editor: duplicate uses new independent ID");+ const int ci = graph.indexOf(*document, copy);+ check(ci >= 0 && document->nodes[ci].enabled &&+ document->nodes[ci].nr == document->nodes[0].nr && graph.next[ci] == 0,+ "editor: NR duplicate keeps all parameters, size and enabled state while detached");+ check(graph.project(*document, *output).accepted && *output == *previous,+ "editor: enabled detached duplicate cannot enter runtime chain");+ document->nodes[ci].nr.model.intensity = 0.17f;+ check(document->nodes[0].nr.model.intensity == 0.73f, "editor: cloned NR parameters are independent");+ check(graph.insertAfter(*document, copy, nr).accepted && graph.project(*document, *output).accepted &&+ output->nodeCount == 5 && output->nodes[1].nr.model.intensity == 0.17f,+ "editor: explicit insertion alone routes detached node into execution");+ check(graph.remove(*document, copy).accepted && graph.project(*document, *output).accepted &&+ *output == *previous && graph.ids[0] == nr && graph.ids[1] == color,+ "editor: deleting active copy bypasses it and preserves original IDs and payload");+ uint32_t nextCopy = 0;+ check(graph.duplicate(*document, color, nextCopy).accepted && nextCopy > copy,+ "editor: removed IDs are never recycled");+ const int cc = graph.indexOf(*document, nextCopy);+ check(document->nodes[cc].color == document->nodes[1].color,+ "editor: Color clone copies complete curve HSL wheel and LUT payload");+ document->nodes[cc].color.exposure = -0.5f;+ check(document->nodes[1].color.exposure == 0.63f, "editor: cloned color is independent");+ const auto beforeGraph = graph;+ auto beforeDocument = std::make_unique<EffectChain>(*document);+ uint32_t untouched = 123;+ check(!graph.duplicate(*document, sr, untouched).accepted && untouched == 123 && graph == beforeGraph &&+ *document == *beforeDocument, "editor: disabled singleton duplication rejected atomically");+ check(!graph.duplicate(*document, fg, untouched).accepted &&+ !graph.duplicate(*document, NodeGraphLayout::Input, untouched).accepted &&+ !graph.remove(*document, NodeGraphLayout::Output).accepted, "editor: singleton and fixed endpoints cannot clone");+ check(!graph.connect(*document, nextCopy, nr).accepted && graph == beforeGraph,+ "editor: competing incoming edge rejected without mutations");+ check(!graph.connect(*document, nextCopy, nextCopy).accepted && graph == beforeGraph,+ "editor: detached self cycle rejected without mutations");+ check(!graph.connect(*document, nextCopy, 123456).accepted && graph == beforeGraph &&+ !graph.connect(*document, NodeGraphLayout::Output, nr).accepted &&+ !graph.connect(*document, nr, NodeGraphLayout::Input).accepted, "editor: invalid endpoint directions rejected");+ check(!graph.insertAfter(*document, nextCopy, fg).accepted && graph == beforeGraph,+ "editor: cannot insert behind even disabled FG");+ check(graph.disconnect(*document, nr).accepted && graph.validate(*document).accepted,+ "editor: partial wire edit remains a valid document");+ check(!graph.project(*document, *output).accepted && *output == *previous,+ "editor: incomplete path retains last runtime output unchanged");+ check(graph.connect(*document, nr, color).accepted && graph.project(*document, *output).accepted,+ "editor: reconnect restores valid runtime chain");+ auto corrupt = graph; corrupt.ids[1] = corrupt.ids[0];+ check(!corrupt.validate(*document).accepted, "editor: persisted duplicate IDs rejected");+ corrupt = graph; corrupt.next[cc] = 99999;+ check(!corrupt.validate(*document).accepted, "editor: persisted dangling edges rejected");+ corrupt = graph; corrupt.nextId = 2;+ check(!corrupt.validate(*document).accepted, "editor: persisted regressed ID allocator rejected");+ check(graph.remove(*document, nextCopy).accepted && graph.project(*document, *output).accepted &&+ *output == *previous, "editor: deleting detached node leaves runtime unchanged");+ for (int i = 0; i < 3; ++i) check(graph.duplicate(*document, nr, copy).accepted, "editor: NR detached copies within limit");+ check(!graph.duplicate(*document, nr, copy).accepted && document->countOf(EffectType::NrEnhance) == 4,+ "editor: all detached and disabled nodes count towards capacity");+ check(graph.project(*document, *output).accepted && *output == *previous,+ "editor: maximum detached copies still consume no runtime slots");+}++void testExistingChainContracts() {// 1. Round trip through the chain preserves every stage field.{const auto before = populated();@@ -204,6 +292,643 @@ int main() {check(requiresGraphRebuild(base, next), "changing the NR size policy rebuilds"); }}+ {+ static_assert(std::is_trivially_copyable_v<EnhancementSettings>);+ auto settings=populated();settings.additionalColorCount=kMaxColorInstances-1;+ for(unsigned i=0;i<settings.additionalColorCount;++i){+ auto& c=settings.additionalColors[i];c.enabled=i!=2;c.exposure=float(i)*0.2f;+ c.setLutName(L"grade-"+std::to_wstring(i)+L".cube");+ }+ auto chain=toChain(settings);auto roundTrip=settings;fromChain(chain,roundTrip);+ check(validateChain(chain).accepted&&roundTrip==settings,"six color settings round-trip independently including disabled nodes");+ auto edited=settings;edited.additionalColors[3].exposure+=0.2f;+ check(!requiresGraphRebuild(settings,edited)&&settings.sameVideoConfiguration(edited),"extra color uniforms remain live");+ edited.additionalColors[3].setLutName(L"replacement.cube");+ check(requiresGraphRebuild(settings,edited)&&!settings.sameVideoConfiguration(edited),"extra LUT changes require a rebuild");+ edited=settings;edited.additionalColors[2].enabled=true;+ check(requiresGraphRebuild(settings,edited)&&!settings.sameVideoConfiguration(edited),"extra color bypass changes require a rebuild");+ edited=settings;edited.additionalColorCount=6;+ check(!edited.validate().empty(),"a seventh color instance is rejected");+ }+ // P2 regression: the QML list uses this exact chain -> settings -> chain+ // boundary. A disabled first layer must not erase it or its successors.+ {+ EffectChain chain; chain.nodeCount=4;+ for(uint32_t i=0;i<chain.nodeCount;++i){+ auto& n=chain.nodes[i]; n.type=EffectType::NrEnhance; n.enabled=i!=0;+ n.nr.model.intensity=0.2f+0.2f*i; n.nr.residual.total=0.5f+0.2f*i;+ n.nr.temporal=(i%2)!=0;+ }+ EnhancementSettings settings; fromChain(chain,settings);+ settings.protection.enabled=true;settings.protection.regions[0]={0,0,0.3f,0.3f};+ veyra::pipeline::EnhanceGraphDesc desc;+ StageRequest request;request.nr=true;request.width=1920;request.height=1080;+ describeStages(request,settings,desc);+ check(desc.enableNr&&desc.nrLayersModel.size()==3&&desc.nrLayersModel[0]==chain.nodes[1].nr.model&&+ desc.nrLayersModel[2]==chain.nodes[3].nr.model,"only enabled NR layers reach graph creation in list order");+ check(desc.nrLayersTemporal==std::vector<bool>({true,false,true}),"each NR temporal flag reaches the graph");+ check(!desc.nrLayersProtection[0].enabled&&!desc.nrLayersProtection[1].enabled&&+ desc.nrLayersProtection[2]==settings.protection,"list protection belongs to the final NR output");+ auto restored=toChain(settings);+ check(restored.countOf(EffectType::NrEnhance)==4,"four NR list layers survive the settings boundary");+ uint32_t index=0;+ for(uint32_t i=0;i<restored.nodeCount;++i)if(restored.nodes[i].type==EffectType::NrEnhance){+ check(index<4&&restored.nodes[i].nr==chain.nodes[index].nr&&+ restored.nodes[i].enabled==chain.nodes[index].enabled,"NR payload and bypass survive independently");+ ++index;+ }+ auto editedChain=chain; editedChain.nodes[2].nr.model.tone=0.25f;+ auto edited=settings; fromChain(editedChain,edited);+ check(edited!=settings,"editing a downstream NR layer reaches settings");+ check(!requiresGraphRebuild(settings,edited),"downstream NR uniforms stay live");+ editedChain=chain; editedChain.nodes[2].enabled=false; fromChain(editedChain,edited);+ check(requiresGraphRebuild(settings,edited),"bypassing an NR layer changes the graph shape");+ editedChain=chain; editedChain.nodes[2].nr.temporal=true; fromChain(editedChain,edited);+ check(requiresGraphRebuild(settings,edited),"a downstream temporal toggle rebuilds its resources");+ editedChain=chain; editedChain.nodes[2].nr.runtime=NrRuntime::Community;+ check(!validateChain(editedChain).accepted,"mixed active runtimes cannot silently share one adapter");+ editedChain=chain; editedChain.nodes[2].nr.lowLatencyPairing=true;+ check(!validateChain(editedChain).accepted,"mixed active NR/SR orders cannot be silently flattened");+ for(uint32_t i=0;i<chain.nodeCount;++i)chain.nodes[i].enabled=false;+ fromChain(chain,settings); restored=toChain(settings);+ check(!settings.nr&&restored.countOf(EffectType::NrEnhance)==4,"all-bypassed list retains four editable layers");+ describeStages(request,settings,desc);+ check(!desc.enableNr&&desc.nrLayersModel.empty(),"all-bypassed list clears the reused descriptor");+ settings.nrLayerCount=kMaxNrInstances+1;+ check(!settings.validate().empty(),"oversized settings are rejected before allocation");+ }+ {+ using namespace veyra::pipeline;+ check(ChainNrParams{}.sizePolicy==NrSizePolicy::Realtime,"new NR instances default to 1080p");+ const NrSizePolicy policies[]={NrSizePolicy::Realtime,NrSizePolicy::Native,NrSizePolicy::P480,+ NrSizePolicy::P720,NrSizePolicy::P900,NrSizePolicy::P1440};+ const unsigned heights[]={1080,2160,480,720,900,1440};+ for(unsigned i=0;i<6;++i){+ EnhancementSettings s;s.nr=true;s.nrPolicy=policies[i];+ auto c=toChain(s);EnhancementSettings restored;fromChain(c,restored);+ check(restored.nrPolicy==policies[i],"legacy flat policy survives chain conversion");+ StageRequest request;request.nr=true;request.width=3840;request.height=2160;+ EnhanceGraphDesc d;describeStages(request,restored,d);+ check(d.nrLayersExtent.size()==1&&d.nrLayersExtent[0].height==heights[i]&&+ d.workWidth==3840&&d.workHeight==2160,"six NR policies preserve full output extent");+ }+ EffectChain c;c.nodeCount=4;+ for(unsigned i=0;i<4;++i){c.nodes[i].type=EffectType::NrEnhance;c.nodes[i].enabled=true;+ c.nodes[i].nr.sizePolicy=policies[i+2];}+ EnhancementSettings s;fromChain(c,s);+ StageRequest request;request.nr=true;request.sr=true;request.width=1920;request.height=1080;+ EnhanceGraphDesc d;describeStages(request,s,d);+ check(d.nrLayersExtent==std::vector<Extent>({{852,480},{1280,720},{1600,900},{2560,1440}}),+ "four post-SR instances have distinct internal sizes");+ auto changed=s;changed.nrLayers[3].sizePolicy=NrSizePolicy::Native;+ check(requiresGraphRebuild(s,changed),"downstream resolution change rebuilds resources");+ for(auto& node:c.nodes)node.nr.lowLatencyPairing=true;fromChain(c,s);describeStages(request,s,d);+ check(d.nrLayersExtent.back()==Extent{1920,1080},"NR-first policy never enlarges source input");+ request.exportJob=true;describeStages(request,s,d);+ check(std::all_of(d.nrLayersExtent.begin(),d.nrLayersExtent.end(),[](auto e){return e==Extent{3840,2160};})+ &&!d.nrBeforeSr,"export preserves full-size processing in every instance");+ request.exportJob=false;request.stillImage=true;describeStages(request,s,d);+ check(d.nrLayersExtent.front()==Extent{3840,2160},"still images preserve full processing extent");+ c.nodes[1].nr.sizePolicy=static_cast<NrSizePolicy>(99);c.nodes[1].enabled=false;+ check(!validateChain(c).accepted,"even bypassed layers reject invalid resolution policies");+ }+ {+ auto s = populated();+ auto session = ChainSession::initial(s);+ check(session.valid(), "initial editor session is valid");+ const auto list = session.configurations[0];+ check(session.select(ChainMode::Node), "first node activation clones the list");+ auto& node = session.configurations[1];+ node.videoSrQuality = 3;+ node.chain.firstOf(EffectType::NrEnhance)->nr.model.tone = .123f;+ node.chain.firstOf(EffectType::Color)->color.exposure = 1.25f;+ node.chain.nodes[0].viewX = 321;+ const auto edited = node;+ bool restored = true;+ for (int i = 0; i < 50; ++i) {+ restored = restored && session.select(ChainMode::List) && session.configurations[0] == list;+ restored = restored && session.select(ChainMode::Node) && session.configurations[1] == edited;+ }+ check(restored, "50 mode switches preserve independent chain parameters and layout");+ EnhancementSettings live;+ live.captureCompatible = true; live.captureFlipVertical = true;+ live.audioOffsetMs = 73; live.exportBitrateMbps = 81; live.forceSdrPreview = true;+ edited.apply(live);+ check(live.videoSrQuality == 3 && live.model.tone == .123f && live.color.exposure == 1.25f,+ "configuration restores chain and non-payload SR parameters");+ check(live.captureCompatible && live.captureFlipVertical && live.audioOffsetMs == 73 &&+ live.exportBitrateMbps == 81 && live.forceSdrPreview, "mode change preserves global settings");+ const auto before = session;+ check(!session.select(ChainMode(2)) && session == before, "invalid mode leaves session untouched");+ node.selectedNr = 999;+ check(!session.valid(), "invalid instance selection is rejected");+ }+}++void testExecutionPlans() {+ // Ordered execution planning is a preflight contract, not a GPU test.+ {+ const ChainExecutionRequest request{{1280, 720}, veyra::pipeline::SrTarget::Uhd4K};+ auto s = populated(); s.lowLatency = false;+ const auto fixed = toChain(s);+ ChainExecutionPlan plan;+ check(compileChainExecutionPlan(fixed, request, plan).accepted, "compile default fixed list plan");+ check(plan.stepCount == 6 && plan.steps[0].type == EffectType::Color &&+ plan.steps[1].type == EffectType::SuperResolution &&+ plan.steps[2].type == EffectType::NrEnhance &&+ plan.steps[3].type == EffectType::Protection &&+ plan.steps[4].type == EffectType::VideoHdr &&+ plan.steps[5].type == EffectType::FrameGeneration, "default list order stays Color SR NR Protection HDR FG");+ auto first = fixed; first.firstOf(EffectType::NrEnhance)->nr.lowLatencyPairing = true;+ check(compileChainExecutionPlan(first, request, plan).accepted &&+ plan.steps[1].type == EffectType::NrEnhance && plan.steps[2].type == EffectType::Protection &&+ plan.steps[3].type == EffectType::SuperResolution &&+ plan.steps[1].input == request.source, "preview NR-first list puts NR and protection before SR");+ auto offline = request; offline.exportJob = true;+ check(compileChainExecutionPlan(first, offline, plan).accepted &&+ plan.steps[1].type == EffectType::SuperResolution &&+ plan.steps[2].processing == plan.steps[2].input, "offline list stays SR-first with native NR");+ auto still = request; still.stillImage = true;+ check(compileChainExecutionPlan(first, still, plan).accepted &&+ plan.steps[1].type == EffectType::SuperResolution &&+ plan.steps[2].processing == plan.steps[2].input, "still image list preserves existing native SR-first contract");++ auto node = fixed; node.mode = ChainMode::Node;+ removeLegacyNodeProtection(node);+ std::swap(node.nodes[0], node.nodes[2]); // NR -> SR -> Color+ node.nodes[0].nr.sizePolicy = veyra::pipeline::NrSizePolicy::Native;+ check(compileChainExecutionPlan(node, request, plan).accepted &&+ plan.steps[0].type == EffectType::NrEnhance && plan.steps[0].processing == request.source &&+ plan.steps[2].type == EffectType::Color && plan.steps[2].input.width == 3840,+ "node plan preserves NR before SR and Color after SR");+ auto bypass = request; bypass.source = {3840, 2160};+ check(compileChainExecutionPlan(node, bypass, plan).accepted &&+ plan.resourceCounts[size_t(EffectType::SuperResolution)] == 0 && plan.stepCount == 4,+ "identity SR requests no execution step or resource slot");+ auto layout = node; layout.nodes[0].viewX = 731; layout.nodes[2].viewY = -300;+ ChainExecutionPlan moved;+ compileChainExecutionPlan(node, request, plan);+ check(compileChainExecutionPlan(layout, request, moved).accepted && moved == plan,+ "layout-only edits produce an identical execution plan");+ const auto before = plan;+ auto illegal = node; std::swap(illegal.nodes[0], illegal.nodes[illegal.nodeCount - 1]);+ check(!compileChainExecutionPlan(illegal, request, plan).accepted && plan == before,+ "illegal FG placement rejects without changing the accepted plan");+ auto badSize = request; badSize.source.width = 0;+ check(!compileChainExecutionPlan(node, badSize, plan).accepted && plan == before,+ "invalid source extent rejects atomically");+ node.mode = ChainMode(2);+ check(!compileChainExecutionPlan(node, request, plan).accepted && plan == before,+ "invalid chain mode rejects atomically");+ }+}++void testGeneratedExecutionPlans() {+ {+ // Deterministic varied legal chains: disabled instances, six NR sizes,+ // SR on either side of NR/Color, and optional HDR/FG tails. Verify each+ // step independently rather than merely asking validateChain() twice.+ std::mt19937 rng(0x5032026u);+ bool all = true;+ uint32_t beforeSr = 0, afterSr = 0, disabled = 0, mixedNr = 0;+ for (uint32_t sample = 0; sample < 200; ++sample) {+ EffectChain chain; chain.mode = ChainMode::Node;+ const auto add = [&](EffectType type, bool enabled) -> ChainNode& {+ auto& n = chain.nodes[chain.nodeCount++]; n.type = type; n.enabled = enabled; return n;+ };+ const auto colors = 1u + rng() % kMaxColorInstances;+ const auto nrs = 1u + rng() % kMaxNrInstances;+ for (uint32_t i = 0; i < colors; ++i) add(EffectType::Color, rng() % 4 != 0);+ for (uint32_t i = 0; i < nrs; ++i)+ add(EffectType::NrEnhance, rng() % 4 != 0).nr.sizePolicy = veyra::pipeline::NrSizePolicy(rng() % 6);+ add(EffectType::SuperResolution, sample % 3 != 0);+ std::shuffle(chain.nodes.begin(), chain.nodes.begin() + chain.nodeCount, rng);+ if (sample % 3) add(EffectType::VideoHdr, true);+ if (sample % 4) add(EffectType::FrameGeneration, true);+ const ChainExecutionRequest request{{1280, 720}, veyra::pipeline::SrTarget::Uhd4K};+ ChainExecutionPlan plan;+ bool ok = compileChainExecutionPlan(chain, request, plan).accepted;+ auto extent = request.source;+ std::array<uint32_t, effectTypeCount> parameter{}, resource{};+ uint32_t step = 0, nrBefore = 0, nrAfter = 0; bool scaled = false;+ for (uint32_t i = 0; i < chain.nodeCount; ++i) {+ const auto& n = chain.nodes[i]; const auto type = size_t(n.type);+ const auto ordinal = parameter[type]++;+ if (!n.enabled) { ++disabled; continue; }+ if (step >= plan.stepCount) { ok = false; break; }+ const auto& p = plan.steps[step++];+ ok = ok && p.nodeIndex == i && p.type == n.type && p.parameterIndex == ordinal &&+ p.resourceIndex == resource[type]++ && p.input == extent;+ if (n.type == EffectType::SuperResolution) { extent = {3840, 2160}; scaled = true; }+ if (n.type == EffectType::NrEnhance) {+ if (scaled) { ++afterSr; ++nrAfter; } else { ++beforeSr; ++nrBefore; }+ const auto limit = veyra::pipeline::nrHeightLimit(n.nr.sizePolicy);+ const auto expectedH = limit ? std::min(limit, extent.height) : extent.height;+ ok = ok && p.processing.height == expectedH && p.processing.width == ((expectedH * 16 / 9) & ~1u);+ } else ok = ok && p.processing == extent;+ ok = ok && p.output == extent;+ }+ if (nrBefore && nrAfter) ++mixedNr;+ ok = ok && step == plan.stepCount && resource == plan.resourceCounts && plan.output == extent;+ all = all && ok;+ if (!ok) std::printf("FAIL generated chain seed=0x5032026 sample=%u\n", sample);+ }+ std::printf("plan properties: 200 chains; NR before SR=%u after SR=%u mixed=%u disabled=%u\n",+ beforeSr, afterSr, mixedNr, disabled);+ check(all && beforeSr && afterSr && mixedNr && disabled,+ "200 fixed-seed plans preserve order, instance identity and per-stage extents (CPU only)");+ }+}++void testLegacyPlanDimensions() {+ bool all = true; uint32_t cases = 0;+ const std::array<veyra::pipeline::Extent, 4> sources{{{1280, 720}, {3440, 1440}, {1080, 1920}, {3840, 2160}}};+ for (const auto source : sources)+ for (uint32_t sr = 0; sr < 2; ++sr)+ for (uint32_t first = 0; first < 2; ++first)+ for (uint32_t context = 0; context < 3; ++context)+ for (uint32_t policy = 0; policy < 6; ++policy)+ for (uint32_t target = 0; target < 3; ++target) {+ auto s = populated();+ s.sr = sr != 0; s.lowLatency = first != 0;+ s.nrPolicy = veyra::pipeline::NrSizePolicy(policy);+ s.srTarget = veyra::pipeline::SrTarget(target);+ const auto chain = toChain(s);+ ChainExecutionPlan plan;+ const ChainExecutionRequest request{source, s.srTarget, context == 1, context == 2};+ bool ok = compileChainExecutionPlan(chain, request, plan).accepted;+ StageRequest legacyRequest;+ legacyRequest.width = source.width; legacyRequest.height = source.height;+ legacyRequest.nr = s.nr; legacyRequest.sr = s.sr; legacyRequest.fg = true;+ legacyRequest.stillImage = request.stillImage; legacyRequest.exportJob = request.exportJob;+ veyra::pipeline::EnhanceGraphDesc legacy;+ describeStages(legacyRequest, s, legacy);+ // Independent pre-integration formula: describeStages now consumes the+ // compiler, so comparing only those two would be a circular test.+ const auto oldPlan=veyra::pipeline::ResolutionPlan::make(source,s.sr,+ request.exportJob?veyra::pipeline::NrSizePolicy::Native:s.nrPolicy,+ request.stillImage||request.exportJob,s.revision,s.srTarget,+ !request.exportJob&&s.lowLatency&&s.nr);+ const bool oldNrFirst=!request.stillImage&&!request.exportJob&&s.lowLatency&&s.nr&&oldPlan.srApplied;+ ok = ok && legacy.fixedExecutionPlan.has_value() && legacy.validateFixedExecutionPlan().empty() &&+ plan.output == oldPlan.base && plan.output == veyra::pipeline::Extent{legacy.workWidth, legacy.workHeight} &&+ legacy.nrBeforeSr==oldNrFirst && legacy.nrWidth==oldPlan.nr.width && legacy.nrHeight==oldPlan.nr.height &&+ plan.resourceCounts[size_t(EffectType::SuperResolution)] == uint32_t(oldPlan.srApplied);+ bool checkedNr = false;+ for (uint32_t i = 0; i < plan.stepCount; ++i) {+ const auto& step = plan.steps[i];+ if (step.type != EffectType::NrEnhance) continue;+ const auto expectedInput = oldNrFirst ? source : oldPlan.base;+ ok = ok && step.input == expectedInput && step.output == expectedInput &&+ step.processing==oldPlan.nr && !legacy.nrLayersExtent.empty() && step.processing == legacy.nrLayersExtent.front();+ checkedNr = true;+ }+ all = all && ok && checkedNr; ++cases;+ if (!ok || !checkedNr) std::printf("FAIL legacy plan dimensions case=%u source=%ux%u sr=%u nrFirst=%u context=%u policy=%u target=%u\n",+ cases, source.width, source.height, sr, first, context, policy, target);+ }+ std::printf("legacy dimension parity: %u cases (CPU descriptions only)\n", cases);+ check(all && cases == 864, "production fixed plans match independent legacy formulas across 864 dimension/context combinations");+}++void testProductionFixedPlanDescription() {+ using namespace veyra::pipeline;+ EnhancementSettings s;s.nr=true;s.sr=true;s.nrLayerCount=3;+ s.nrLayers[0].enabled=false;+ s.nrLayers[1].enabled=true;s.nrLayers[1].sizePolicy=NrSizePolicy::Native;+ s.nrLayers[2].enabled=true;s.nrLayers[2].sizePolicy=NrSizePolicy::Realtime;+ StageRequest request;request.width=1280;request.height=720;request.nr=true;request.sr=true;+ EnhanceGraphDesc desc;describeStages(request,s,desc);+ check(desc.fixedExecutionPlan.has_value()&&desc.validateFixedExecutionPlan().empty(),+ "production builder supplies a validated fixed execution plan");+ std::vector<ChainExecutionStep> nr;+ if(desc.fixedExecutionPlan)for(uint32_t i=0;i<desc.fixedExecutionPlan->stepCount;++i)+ if(desc.fixedExecutionPlan->steps[i].type==EffectType::NrEnhance)nr.push_back(desc.fixedExecutionPlan->steps[i]);+ check(nr.size()==2&&nr[0].parameterIndex==1&&nr[0].resourceIndex==0&&+ nr[1].parameterIndex==2&&nr[1].resourceIndex==1,+ "production plan keeps disabled parameter slots distinct from active resources");+ check(desc.nrLayersExtent==std::vector<Extent>{{3840,2160},{1920,1080}},+ "production NR allocation extents come from each compiled active layer");+ desc.nrLayersExtent[0]={640,360};+ check(!desc.validateFixedExecutionPlan().empty(),+ "resource dimensions tampering is rejected before GPU allocation");+ s.lowLatency=true;for(auto& n:s.nrLayers)n.lowLatencyPairing=true;+ describeStages(request,s,desc);+ check(desc.validateFixedExecutionPlan().empty()&&desc.nrBeforeSr&&+ desc.nrLayersExtent==std::vector<Extent>{{1280,720},{1280,720}},+ "NR-first fixed plan uses source-space input for all active layers");+ request.exportJob=true;describeStages(request,s,desc);+ check(desc.validateFixedExecutionPlan().empty()&&!desc.nrBeforeSr&&+ desc.nrLayersExtent==std::vector<Extent>{{3840,2160},{3840,2160}},+ "offline description retains native NR and default order");+ request.exportJob=false;request.nvidiaAdapter=false;describeStages(request,s,desc);+ check(desc.validateFixedExecutionPlan().empty()&&!desc.enableNr&&!desc.enableSr&&+ desc.fixedExecutionPlan&&desc.fixedExecutionPlan->resourceCounts[size_t(EffectType::NrEnhance)]==0&&+ desc.fixedExecutionPlan->output==Extent{3840,2160},+ "non-NVIDIA fallback retains ordinary resize extent without NR resources");+ request.nvidiaAdapter=true;request.nr=false;describeStages(request,s,desc);+ check(desc.validateFixedExecutionPlan().empty()&&!desc.enableNr&&desc.fixedExecutionPlan&&+ desc.fixedExecutionPlan->resourceCounts[size_t(EffectType::NrEnhance)]==0,+ "request bypass clears active plan resources on a reused descriptor");+ s.nrLayerCount=0;s.nr=false;request.nr=true;request.sr=false;describeStages(request,s,desc);+ check(desc.validateFixedExecutionPlan().empty()&&desc.enableNr&&desc.fixedExecutionPlan&&+ desc.fixedExecutionPlan->resourceCounts[size_t(EffectType::NrEnhance)]==1,+ "flat caller request override is preserved rather than silently dropping NR");+ s.nrLayerCount=kMaxNrInstances+1;describeStages(request,s,desc);+ check(!desc.fixedExecutionPlan&&!desc.validateFixedExecutionPlan().empty(),+ "oversized runtime input fails instead of truncating into an apparently valid plan");+ s.nrLayerCount=0;request.width=0;describeStages(request,s,desc);+ check(!desc.fixedExecutionPlan&&!desc.validateFixedExecutionPlan().empty(),+ "invalid source dimensions leave an explicit construction error");+ request.width=1280;describeStages(request,s,desc);+ check(desc.fixedExecutionPlan&&desc.validateFixedExecutionPlan().empty(),+ "valid rebuild clears the preceding plan error");+ s.nr=true;s.color.enabled=true;s.sr=false;s.lowLatency=false;+ describeStages(request,s,desc);+ auto chain=toChain(s);chain.mode=ChainMode::Node;+ removeLegacyNodeProtection(chain);+ std::swap(chain.nodes[0],chain.nodes[2]);+ ChainExecutionPlan ordered;+ check(compileChainExecutionPlan(chain,{{1280,720},s.srTarget,false,false},ordered).accepted,+ "NR-before-color is a legal requested node plan");+ desc.fixedExecutionPlan=ordered;+ check(!desc.validateFixedExecutionPlan().empty(),+ "fixed dispatcher refuses legal but unsupported node order instead of pretending to execute it");+}++void testRuntimeOrderTransport() {+ namespace pipeline = veyra::pipeline;+ EnhancementSettings settings;+ settings.nr=true;settings.sr=true;settings.srTarget=pipeline::SrTarget::Qhd;+ settings.color.enabled=true;settings.nrLayerCount=2;+ settings.nrLayers[0].enabled=false;settings.nrLayers[0].model.intensity=.17f;+ settings.nrLayers[1].enabled=true;settings.nrLayers[1].model.intensity=.73f;+ settings.nrLayers[1].sizePolicy=pipeline::NrSizePolicy::P480;+ auto chain=toChain(settings);+ check(!runtimeOrder(chain),"legacy list keeps the original runtime request contract");+ chain.mode=ChainMode::Node;+ removeLegacyNodeProtection(chain);+ std::rotate(chain.nodes.begin()+1,chain.nodes.begin()+2,chain.nodes.begin()+4);+ fromChain(chain,settings);+ const auto order=runtimeOrder(chain);+ chain.nodes[0].viewX=519;chain.nodes[2].viewY=87;+ check(order==runtimeOrder(chain),"layout is excluded from runtime topology and cannot trigger a rebuild");+ EffectChain restored;+ check(order&&restoreRuntimeOrder(settings,*order,restored).accepted&&+ restored.mode==ChainMode::Node&&restored.nodes[1].type==EffectType::NrEnhance&&+ !restored.nodes[1].enabled&&restored.nodes[1].nr.model.intensity==.17f&&+ restored.nodes[2].enabled&&restored.nodes[2].nr.model.intensity==.73f&&+ restored.nodes[3].type==EffectType::SuperResolution,+ "runtime envelope restores actual order and disabled per-instance parameter slots");+ StageRequest request;request.width=640;request.height=360;request.nr=true;request.sr=true;+ request.nodeOrder=&*order;+ pipeline::EnhanceGraphDesc desc;describeStages(request,settings,desc);+ check(desc.runtimeNodeOrder&&desc.fixedExecutionPlan&&desc.validateFixedExecutionPlan().empty()&&+ desc.nrBeforeSr&&desc.fixedExecutionPlan->steps[1].type==EffectType::NrEnhance&&+ desc.fixedExecutionPlan->steps[1].parameterIndex==1&&+ desc.fixedExecutionPlan->steps[1].resourceIndex==0&&+ desc.fixedExecutionPlan->steps[1].input==pipeline::Extent{640,360},+ "production builder consumes requested node order instead of flattening to SR-first");+ const auto preserved=restored;+ auto broken=*order;broken.types[0]=EffectType::Count;+ check(!restoreRuntimeOrder(settings,broken,restored).accepted&&restored==preserved,+ "invalid runtime order leaves previously accepted chain untouched");+ broken=*order;broken.nodeCount=kMaxChainNodes+1;+ check(!restoreRuntimeOrder(settings,broken,restored).accepted&&restored==preserved,+ "oversized runtime order fails atomically");+ broken=*order;broken.nodeCount=0;+ check(!restoreRuntimeOrder(settings,broken,restored).accepted&&restored==preserved,+ "runtime order cannot silently omit enabled stages or disabled parameter slots");+ std::swap(chain.nodes[0],chain.nodes[2]);fromChain(chain,settings);+ const auto interleaved=runtimeOrder(chain);request.nodeOrder=&*interleaved;+ describeStages(request,settings,desc);+ check(desc.fixedExecutionPlan&&desc.fixedExecutionPlan->steps[0].type==EffectType::NrEnhance&&+ desc.preSrColor(0)&&desc.validateFixedExecutionPlan().empty(),+ "NR -> Color -> SR reaches admission intact and consumes the new pre-SR boundary");+ EffectChain empty;empty.mode=ChainMode::Node;settings={};fromChain(empty,settings);+ check(restoreRuntimeOrder(settings,*runtimeOrder(empty),restored).accepted&&restored.nodeCount==0,+ "empty node configuration does not resurrect synthetic list stages");+}++void testNodeTailColorDescription() {+ using namespace veyra;+ using namespace veyra::engine;+ EffectChain chain;chain.mode=ChainMode::Node;chain.nodeCount=4;+ chain.nodes[0].type=EffectType::Color;chain.nodes[0].enabled=true;chain.nodes[0].color.enabled=true;+ chain.nodes[1].type=EffectType::SuperResolution;chain.nodes[1].enabled=true;+ chain.nodes[2].type=EffectType::NrEnhance;chain.nodes[2].enabled=true;+ chain.nodes[3].type=EffectType::Color;chain.nodes[3].enabled=true;chain.nodes[3].color.enabled=true;+ EnhancementSettings settings;fromChain(chain,settings);+ auto order=runtimeOrder(chain);+ StageRequest request;request.width=640;request.height=360;request.sr=true;request.nr=true;request.nodeOrder=&*order;+ pipeline::EnhanceGraphDesc desc;describeStages(request,settings,desc);+ check(desc.validateFixedExecutionPlan().empty()&&!desc.tailColor(0)&&desc.tailColor(1),+ "node Color -> SR -> NR -> Color admits an independently bound tail grade");+ chain.nodes[0].enabled=false;fromChain(chain,settings);order=runtimeOrder(chain);request.nodeOrder=&*order;+ describeStages(request,settings,desc);+ check(desc.validateFixedExecutionPlan().empty()&&!desc.tailColor(0)&&desc.tailColor(1)&&+ desc.fixedExecutionPlan->steps[2].parameterIndex==1&&desc.fixedExecutionPlan->steps[2].resourceIndex==0,+ "disabled ingress Color retains the tail parameter identity without a GPU slot");+ auto broken=desc;broken.fixedExecutionPlan->steps[2].parameterIndex=engine::kMaxColorInstances;+ check(!broken.validateFixedExecutionPlan().empty(),+ "out-of-range tail Color parameter is rejected before GPU allocation");+ std::swap(chain.nodes[2],chain.nodes[3]);fromChain(chain,settings);order=runtimeOrder(chain);request.nodeOrder=&*order;+ describeStages(request,settings,desc);+ check(desc.validateFixedExecutionPlan().empty()&&desc.preNrColor(1)&&!desc.tailColor(1)&&!desc.nodeColor(0),+ "SR -> Color -> NR uses a distinct pre-NR grade without flattening to ingress or tail");+ chain.nodes[1].type=EffectType::NrEnhance;fromChain(chain,settings);order=runtimeOrder(chain);+ request.sr=false;request.nodeOrder=&*order;describeStages(request,settings,desc);+ check(desc.validateFixedExecutionPlan().empty()&&desc.nodeColor(1)&&+ desc.interNrColorTarget(1)==1&&!desc.preNrColor(1)&&!desc.tailColor(1),+ "NR -> Color -> NR binds the grade to the next compact NR resource, not ingress or tail");+ chain.nodeCount=5;chain.nodes[4]=chain.nodes[3];chain.nodes[3]=chain.nodes[2];+ fromChain(chain,settings);order=runtimeOrder(chain);request.nodeOrder=&*order;describeStages(request,settings,desc);+ check(desc.validateFixedExecutionPlan().empty()&&desc.interNrColorTarget(1)==1&&desc.interNrColorTarget(2)==1,+ "consecutive grades between NR layers keep distinct parameter slots with one downstream target");+ chain.nodeCount=6;chain.nodes[5].type=EffectType::SuperResolution;chain.nodes[5].enabled=true;+ fromChain(chain,settings);order=runtimeOrder(chain);request.sr=true;request.nodeOrder=&*order;describeStages(request,settings,desc);+ check(desc.validateFixedExecutionPlan().empty()&&desc.nrBeforeSr&&desc.interNrColorTarget(1)==1&&+ desc.fixedExecutionPlan->steps[1].output==pipeline::Extent{640,360},+ "NR -> Color -> Color -> NR -> SR keeps inter-NR grades at source extent");+ std::swap(chain.nodes[4],chain.nodes[5]);fromChain(chain,settings);order=runtimeOrder(chain);+ request.nodeOrder=&*order;describeStages(request,settings,desc);+ check(desc.validateFixedExecutionPlan().empty()&&desc.splitNrAcrossSr()&&desc.preSrColor(1)&&desc.preSrColor(2),+ "NR -> Color -> Color -> SR -> NR uses the split NR boundary, not the inter-NR boundary");+}++void testNodePreSrColorDescription() {+ using namespace veyra;+ using namespace veyra::engine;+ EffectChain chain;chain.mode=ChainMode::Node;chain.nodeCount=6;+ chain.nodes[0].type=EffectType::Color;chain.nodes[0].enabled=false;chain.nodes[0].color.enabled=true;+ chain.nodes[1].type=EffectType::NrEnhance;chain.nodes[1].enabled=true;+ chain.nodes[2].type=EffectType::Color;chain.nodes[2].enabled=true;chain.nodes[2].color.enabled=true;+ chain.nodes[3]=chain.nodes[2];+ chain.nodes[4].type=EffectType::SuperResolution;chain.nodes[4].enabled=true;+ chain.nodes[5]=chain.nodes[2];+ EnhancementSettings settings;fromChain(chain,settings);+ auto order=runtimeOrder(chain);+ StageRequest request;request.width=640;request.height=360;request.sr=true;request.nr=true;request.nodeOrder=&*order;+ pipeline::EnhanceGraphDesc desc;describeStages(request,settings,desc);+ check(desc.validateFixedExecutionPlan().empty()&&desc.nrBeforeSr&&desc.preSrColor(1)&&desc.preSrColor(2)&&+ !desc.preSrColor(0)&&!desc.preSrColor(3)&&desc.tailColor(3)&&+ desc.fixedExecutionPlan->steps[1].output==pipeline::Extent{640,360}&&+ desc.fixedExecutionPlan->steps[1].parameterIndex==1&&desc.fixedExecutionPlan->steps[1].resourceIndex==0,+ "NR -> Color -> Color -> SR -> Color preserves source-size pre-SR grades and disabled parameter slots");+ check(!desc.preNrColor(1)&&desc.interNrColorTarget(1)==kMaxNrInstances,+ "pre-SR grade is not mistaken for pre-NR or inter-NR");+ chain.nodeCount=7;chain.nodes[6]=chain.nodes[5];chain.nodes[5]=chain.nodes[4];+ chain.nodes[4]=chain.nodes[3];chain.nodes[3]=chain.nodes[2];+ chain.nodes[2].type=EffectType::Protection;chain.nodes[2].enabled=true;+ check(removeLegacyNodeProtection(chain)==1, "legacy pre-SR protection migrates before execution");+ fromChain(chain,settings);order=runtimeOrder(chain);request.nodeOrder=&*order;describeStages(request,settings,desc);+ check(desc.validateFixedExecutionPlan().empty()&&desc.preSrColor(1)&&desc.preSrColor(2),+ "NR -> Color -> Color -> SR retains its grades after protection migration");+ auto fixed=desc;fixed.runtimeNodeOrder=false;+ check(!fixed.preSrColor(1)&&!fixed.validateFixedExecutionPlan().empty(),+ "pre-SR node admission does not change fixed-list execution");+ request.stillImage=true;describeStages(request,settings,desc);+ check(!desc.validateFixedExecutionPlan().empty(),+ "pre-SR support retains the offline NR-before-SR boundary");+}++void testNodeSplitNrDescription() {+ using namespace veyra;using namespace veyra::engine;+ EffectChain chain;chain.mode=ChainMode::Node;chain.nodeCount=7;+ const EffectType types[]={EffectType::NrEnhance,EffectType::NrEnhance,EffectType::Color,+ EffectType::SuperResolution,EffectType::Color,EffectType::NrEnhance,EffectType::Color};+ for(uint32_t i=0;i<chain.nodeCount;++i){+ chain.nodes[i].type=types[i];chain.nodes[i].enabled=i!=0;+ chain.nodes[i].nr.sizePolicy=pipeline::NrSizePolicy::Native;+ chain.nodes[i].color.enabled=true;+ }+ EnhancementSettings settings;fromChain(chain,settings);settings.srTarget=pipeline::SrTarget::Qhd;+ auto order=runtimeOrder(chain);StageRequest request;+ request.width=640;request.height=360;request.sr=true;request.nr=true;request.nodeOrder=&*order;+ pipeline::EnhanceGraphDesc desc;describeStages(request,settings,desc);+ check(desc.validateFixedExecutionPlan().empty()&&desc.splitNrAcrossSr()&&desc.nrBeforeSrLayerCount()==1&&+ desc.nrBeforeSr&&desc.finalNrAfterSr(),+ "split NR has a source-side prefix and a work-side final output");+ check(desc.nrFullExtent(0)==pipeline::Extent{640,360}&&desc.nrFullExtent(1)==pipeline::Extent{2560,1440}&&+ desc.nrLayersExtent==std::vector<pipeline::Extent>{{640,360},{2560,1440}},+ "each native NR allocates the declared input extent on its own side of SR");+ check(desc.preSrColor(0)&&desc.preNrColor(1)&&desc.tailColor(2)&&+ desc.fixedExecutionPlan->steps[0].parameterIndex==1&&desc.fixedExecutionPlan->steps[4].parameterIndex==2,+ "disabled NR preserves parameter identity; boundary grades are neither ingress nor duplicated");+ auto broken=desc;broken.nrLayersExtent[1]={640,360};+ check(!broken.validateFixedExecutionPlan().empty(),+ "a downstream NR cannot reuse the source-side allocation");+ broken=desc;broken.protection.enabled=true;+ check(!broken.validateFixedExecutionPlan().empty(),+ "split protection stays explicitly incomplete until an original-reference stage is supplied");+ broken=desc;broken.noNgx=true;+ check(!broken.validateFixedExecutionPlan().empty(),+ "split graph cannot read unallocated NR intermediates with NGX disabled");+ broken=desc;broken.noFeatures=true;+ check(!broken.validateFixedExecutionPlan().empty(),+ "split graph cannot claim successful execution with all features bypassed");+ request.width=2560;request.height=1440;describeStages(request,settings,desc);+ check(desc.validateFixedExecutionPlan().empty()&&!desc.splitNrAcrossSr()&&!desc.enableSr&&+ desc.nrLayersExtent.size()==2&&desc.nrFullExtent(0)==desc.nrFullExtent(1),+ "same-size SR folds away while both NR stages remain at the same declared extent");+ request.stillImage=true;describeStages(request,settings,desc);+ check(!desc.validateFixedExecutionPlan().empty(),+ "split preview does not bypass offline NR-before-SR guard");+}++static void testNodePreSrProtectionDescription(){+ using namespace veyra;using namespace veyra::engine;+ EffectChain chain;chain.mode=ChainMode::Node;chain.nodeCount=7;+ const EffectType types[]={EffectType::NrEnhance,EffectType::NrEnhance,EffectType::Protection,+ EffectType::Color,EffectType::SuperResolution,EffectType::NrEnhance,EffectType::NrEnhance};+ for(uint32_t i=0;i<chain.nodeCount;++i){+ chain.nodes[i].type=types[i];chain.nodes[i].enabled=true;+ chain.nodes[i].nr.sizePolicy=pipeline::NrSizePolicy::Native;+ chain.nodes[i].color.enabled=true;+ }+ const auto original = chain;+ int selectedNr = 6, selectedColour = 3;+ check(!validateChain(chain).accepted, "new node chains refuse Protection even at a formerly legal boundary");+ check(removeLegacyNodeProtection(chain, &selectedNr, &selectedColour) == 1 &&+ selectedNr == 5 && selectedColour == 2 && chain.nodes[5] == original.nodes[6] &&+ chain.nodes[2] == original.nodes[3], "legacy cleanup retains payload and remaps selected instances");+ EnhancementSettings settings;fromChain(chain,settings);settings.srTarget=pipeline::SrTarget::Qhd;+ auto order=runtimeOrder(chain);StageRequest request;+ request.width=640;request.height=360;request.sr=true;request.nr=true;request.nodeOrder=&*order;+ pipeline::EnhanceGraphDesc desc;describeStages(request,settings,desc);+ check(desc.validateFixedExecutionPlan().empty()&&!desc.protectionBeforeSr()&&!desc.protection.enabled&&+ desc.nrBeforeSrLayerCount()==2&&desc.preSrColor(0),+ "migrated split chain retains Color and SR without any protection execution");+ check(desc.fixedExecutionPlan->steps[2].input==pipeline::Extent{640,360}&&+ desc.nrFullExtent(2)==pipeline::Extent{2560,1440},+ "migrated Color and post-SR NR retain their declared extents");+ auto legacyDisabled = original; legacyDisabled.nodes[2].enabled = false;+ check(!validateChain(legacyDisabled).accepted && removeLegacyNodeProtection(legacyDisabled) == 1 &&+ legacyDisabled == chain, "disabled legacy Protection is removed too, not hidden or retained");+ auto list = original; list.mode = ChainMode::List; const auto listBefore = list;+ check(removeLegacyNodeProtection(list) == 0 && list == listBefore, "node cleanup never edits list protection");+}++static void testNodeInterNrProtectionDescription(){+ using namespace veyra;using namespace veyra::engine;+ const auto nr=EffectType::NrEnhance,sr=EffectType::SuperResolution;+ const auto mask=EffectType::Protection,color=EffectType::Color;+ for(const auto& types:std::vector<std::vector<EffectType>>{+ {nr,mask,nr},{sr,nr,mask,color,nr},{nr,mask,color,nr,sr,nr},+ {nr,nr,mask,color,nr,sr,nr}}){+ EffectChain chain;chain.mode=ChainMode::Node;chain.nodeCount=uint32_t(types.size());+ uint32_t maskIndex=0,nrPrefix=0;+ for(uint32_t i=0;i<chain.nodeCount;++i){+ chain.nodes[i].type=types[i];chain.nodes[i].enabled=true;+ chain.nodes[i].nr.sizePolicy=pipeline::NrSizePolicy::Native;+ chain.nodes[i].color.enabled=true;+ if(types[i]==mask)maskIndex=i;+ if(types[i]==nr&&!maskIndex)++nrPrefix;+ }+ const auto original = chain;+ check(!validateChain(chain).accepted && removeLegacyNodeProtection(chain) == 1,+ "legacy inter-NR Protection must migrate before it can be submitted");+ EnhancementSettings settings;fromChain(chain,settings);settings.srTarget=pipeline::SrTarget::Qhd;+ auto order=runtimeOrder(chain);StageRequest request;+ request.width=640;request.height=360;request.nr=true;+ request.sr=std::find(types.begin(),types.end(),sr)!=types.end();request.nodeOrder=&*order;+ pipeline::EnhanceGraphDesc desc;describeStages(request,settings,desc);+ check(desc.validateFixedExecutionPlan().empty()&&!desc.protection.enabled&&+ desc.interNrProtectionTarget()==kMaxNrInstances,+ "migrated inter-NR chains execute with no Protection resource");+ if(std::find(types.begin(),types.end(),color)!=types.end())+ check(desc.interNrColorTarget(0)==nrPrefix,+ "surviving inter-NR Color still feeds the next NR");+ check(desc.nrFullExtent(nrPrefix)==desc.fixedExecutionPlan->steps[maskIndex].output,+ "migrated downstream consumer retains its extent");+ auto disabled = original; disabled.nodes[maskIndex].enabled = false;+ check(removeLegacyNodeProtection(disabled) == 1 && disabled == chain,+ "disabled protection migration preserves all other node data");+ }+ EffectChain split;split.mode=ChainMode::Node;split.nodeCount=5;+ const EffectType unsafe[]={nr,sr,nr,mask,nr};+ for(uint32_t i=0;i<split.nodeCount;++i){split.nodes[i].type=unsafe[i];split.nodes[i].enabled=true;}+ EnhancementSettings settings;fromChain(split,settings);auto order=runtimeOrder(split);+ StageRequest request;request.width=640;request.height=360;request.nr=request.sr=true;request.nodeOrder=&*order;+ pipeline::EnhanceGraphDesc desc;describeStages(request,settings,desc);+ check(!desc.validateFixedExecutionPlan().empty()&&!settings.protection.enabled,+ "unmigrated cross-SR Protection cannot enter production or inherit a list mask");+}++int main() {+ std::setvbuf(stdout,nullptr,_IONBF,0);+ testNodeEditorGraph();+ testExistingChainContracts();+ testExecutionPlans();+ testGeneratedExecutionPlans();+ testLegacyPlanDimensions();+ testProductionFixedPlanDescription();+ testRuntimeOrderTransport();+ testNodeTailColorDescription();+ testNodePreSrColorDescription();+ testNodeSplitNrDescription();+ testNodePreSrProtectionDescription();+ testNodeInterNrProtectionDescription();std::printf(failures ? "effect chain: %d FAILURES\n" : "effect chain: all checks passed\n", failures);return failures ? 1 : 0;}diff --git a/tests/unit/PresetLibraryTests.cpp b/tests/unit/PresetLibraryTests.cppindex 06ecc2a0..0a695e49 100644--- a/tests/unit/PresetLibraryTests.cpp+++ b/tests/unit/PresetLibraryTests.cpp@@ -2,9 +2,12 @@// with per-preset contents, built-ins, and safe migration from the old stores.#include "veyra/engine/PresetLibrary.h"+#include <algorithm>#include <cstdio>#include <filesystem>#include <fstream>+#include <iomanip>+#include <sstream>using namespace veyra::engine;@@ -29,9 +32,350 @@ EnhancementSettings sample() {s.audioSync = AudioSyncMode::Manual; s.exportBitrateMbps = 77; s.captureCompatible = true;return s;}+std::string readBytes(const std::filesystem::path& path) {+ std::ifstream file(path, std::ios::binary);+ return std::string(std::istreambuf_iterator<char>(file), {});+}+// A legacy node header used the identical linear payload as list mode.+// Change only the two mode fields, leaving all original serialized parameters.+std::string legacyNodeLine(std::string line) {+ std::istringstream input(line); std::string name, note; int value;+ input >> std::quoted(name) >> std::quoted(note) >> std::ws;+ const auto kind = size_t(input.tellg());+ for (int i = 0; i < 8; ++i) input >> value;+ input >> std::ws; const auto mode = size_t(input.tellg());+ if (!input || kind >= line.size() || mode >= line.size()) return {};+ line[kind] = line[mode] = '1'; return line;+}} // namespace-int main() {+__declspec(noinline) void testNodeEditorSession() {+ const auto path = scratch(L"node-editor-session.v1");+ const auto sidecar = std::filesystem::path(path).concat(L".p3-editor");+ std::filesystem::remove(sidecar);+ auto session = std::make_unique<ChainSession>(ChainSession::initial(sample()));+ check(session->select(ChainMode::Node), "editor session: initialize node mode");+ ChainSessionStore writer(path);+ check(writer.save(*session), "editor session: save original v1 rollback file");+ const auto original = readBytes(path);+ auto& configuration = session->configurations[1];+ auto document = std::make_shared<NodeEditorDocument>();+ document->nodes = configuration.chain;+ check(document->layout.initialize(document->nodes).accepted, "editor session: initialize stable IDs");+ uint32_t sourceId = 0;+ for (uint32_t i = 0; i < document->nodes.nodeCount; ++i)+ if (document->nodes.nodes[i].type == EffectType::Color) sourceId = document->layout.ids[i];+ uint32_t copiedId = 0;+ check(document->layout.duplicate(document->nodes, sourceId, copiedId).accepted,+ "editor session: create detached enabled color copy");+ auto& color = document->nodes.nodes[document->layout.indexOf(document->nodes, copiedId)].color;+ color.exposure = 1.375f; color.mixerHue[2] = 17.5f; color.grading[1].hue = 215;+ color.grading[1].saturation = 25; color.curves[0].points[1].y = 0.75f;+ color.lutStrength = 37.5f; color.setLutName(L"saved-copy.cube");+ check(document->layout.disconnect(document->nodes, NodeGraphLayout::Input).accepted,+ "editor session: deliberately incomplete input wire");+ configuration.editor = document;+ configuration.selectedColour = document->layout.indexOf(document->nodes, copiedId);+ check(uint32_t(configuration.selectedColour) >= configuration.chain.nodeCount,+ "editor session: selected detached copy is absent from runtime");+ check(session->valid() && writer.save(*session),+ "editor session: incomplete document saves alongside last accepted runtime");+ check(readBytes(path) == original && readBytes(sidecar).starts_with("VEYRA_CHAIN_SESSION 2"),+ "editor session: new schema sidecar never overwrites v1 file");+ auto restored = std::make_unique<ChainSession>(ChainSession::initial({}));+ ChainSessionStore reopened(path);+ check(reopened.load(*restored) && *restored == *session,+ "editor session: fresh reader restores IDs edges enabled states and complete payloads");+ check(restored->configurations[1].chain == configuration.chain &&+ restored->configurations[1].editor && restored->configurations[1].editor.get() != document.get(),+ "editor session: accepted runtime retained and restored snapshot is independent");+ auto projection = std::make_unique<EffectChain>(configuration.chain);+ check(!document->layout.project(document->nodes, *projection).accepted && *projection == configuration.chain,+ "editor session: reloaded partial graph must not replace runtime");+ const auto validBytes = readBytes(sidecar);+ // Faults: duplicate ID, dangling edge, detached cycle, merge, and an+ // unsupported detached Protection node. Rejection is not migration.+ for (int fault = 0; fault < 5; ++fault) {+ auto damaged = std::make_unique<ChainSession>(*session);+ auto graph = std::make_shared<NodeEditorDocument>(*document);+ damaged->configurations[1].editor = graph;+ const auto detached = graph->layout.indexOf(graph->nodes, copiedId);+ if (fault == 0) graph->layout.ids[1] = graph->layout.ids[0];+ if (fault == 1) graph->layout.next[0] = graph->layout.nextId + 100;+ if (fault == 2) graph->layout.next[detached] = copiedId;+ if (fault == 3) {+ graph->layout.next[detached] = graph->layout.ids[0];+ graph->layout.inputNext = graph->layout.ids[0];+ }+ if (fault == 4) graph->nodes.nodes[detached].type = EffectType::Protection;+ check(!writer.save(*damaged) && readBytes(sidecar) == validBytes, __FUNCTION__);+ // Protection save refusal does not establish old sidecar migration.+ if (fault == 4) continue;+ std::istringstream source(validBytes);+ std::string headers[4], runtimeBody, editorBody;+ for (auto& line : headers) std::getline(source, line);+ source >> std::quoted(runtimeBody);+ uint32_t oldNextId, oldInput, oldCount;+ source >> oldNextId >> oldInput >> oldCount;+ for (uint32_t i = 0; i < oldCount; ++i) {+ uint32_t oldId, oldEdge; int oldFlag;+ source >> oldId >> oldEdge >> oldFlag;+ }+ source >> std::quoted(editorBody);+ check(bool(source) && oldCount == graph->nodes.nodeCount, __FUNCTION__);+ std::ostringstream bytes;+ for (const auto& line : headers) bytes << line << char(10);+ bytes << std::quoted(runtimeBody) << char(10);+ bytes << graph->layout.nextId << ' ' << graph->layout.inputNext << ' ' << oldCount << char(10);+ for (uint32_t i = 0; i < oldCount; ++i)+ bytes << graph->layout.ids[i] << ' ' << graph->layout.next[i] << ' ' << graph->nodes.nodes[i].enabled << char(10);+ bytes << std::quoted(editorBody) << char(10);+ const auto damagedBytes = bytes.str();+ auto retained = std::make_unique<ChainSession>(*session);+ { std::ofstream file(sidecar, std::ios::binary | std::ios::trunc); file << damagedBytes; }+ ChainSessionStore reader(path);+ check(!reader.load(*retained) && *retained == *session && !reader.save(*session) &&+ readBytes(sidecar) == damagedBytes && readBytes(path) == original, __FUNCTION__);+ { std::ofstream file(sidecar, std::ios::binary | std::ios::trunc); file << validBytes; }+ }+ { std::ofstream file(sidecar, std::ios::binary | std::ios::trunc); file << validBytes; }+ auto invalid = std::make_unique<ChainSession>(*session);+ invalid->configurations[1].selectedColour = int(document->nodes.nodeCount);+ check(!writer.save(*invalid) && readBytes(sidecar) == validBytes,+ "editor session: out of editor range selection rejected atomically");+ invalid->configurations[1].selectedColour = configuration.selectedNr;+ if (configuration.selectedNr >= 0)+ check(!writer.save(*invalid) && readBytes(sidecar) == validBytes,+ "editor session: wrong selected node type rejected atomically");+ *invalid = *session;+ auto invalidDocument = std::make_shared<NodeEditorDocument>(*document);+ invalidDocument->layout.ids[1] = invalidDocument->layout.ids[0];+ invalid->configurations[1].editor = invalidDocument;+ check(!writer.save(*invalid) && readBytes(sidecar) == validBytes && readBytes(path) == original,+ "editor session: duplicate-ID save rejected atomically");+ invalidDocument->layout = document->layout;+ invalidDocument->nodes.nodes[0].color.exposure = 9999;+ check(!writer.save(*invalid) && readBytes(sidecar) == validBytes,+ "editor session: invalid detached parameters cannot overwrite session");+ { std::ofstream file(sidecar, std::ios::binary | std::ios::trunc); file << validBytes << "unexpected"; }+ ChainSessionStore corrupt(path);+ check(!corrupt.load(*restored) && *restored == *session && !corrupt.save(*session),+ "editor session: corrupt sidecar retained without falling back or half-loading");+ std::filesystem::remove(sidecar);+}++__declspec(noinline) void testLegacyProtectionMigration() {+ for (int position : {1, 2, 4, 6}) for (bool enabled : {false, true}) {+ const auto path = scratch(L"legacy-protection-library.v1");+ const auto sidecar = std::filesystem::path(path).concat(L".p3-node");+ std::filesystem::remove(sidecar);+ PresetLibrary writer(path); writer.load();+ auto settings = sample(); settings.protection.enabled = enabled; settings.nrLayerCount = 4;+ PresetEntry entry; entry.name = L"legacy-protection"; entry.chain = toChain(settings); entry.color = settings.color;+ entry.chain.nodes[2].viewX = 481; entry.chain.nodes[2].nr.model.tone = .37f;+ auto& fixture = entry.chain;+ uint32_t index = 0;+ while (fixture.nodes[index].type != EffectType::Protection) ++index;+ const auto protection = fixture.nodes[index];+ for (uint32_t i = index; i > uint32_t(position); --i) fixture.nodes[i] = fixture.nodes[i - 1];+ fixture.nodes[position] = protection;+ auto expected = fixture; expected.mode = ChainMode::Node;+ uint32_t count = 0;+ for (uint32_t i = 0; i < fixture.nodeCount; ++i)+ if (fixture.nodes[i].type != EffectType::Protection) expected.nodes[count++] = fixture.nodes[i];+ for (uint32_t i = count; i < expected.nodeCount; ++i) expected.nodes[i] = {};+ expected.nodeCount = count;+ check(writer.put(entry), "create historical library fixture through list serializer");+ auto legacy = readBytes(path); const auto start = legacy.find("\"legacy-protection\"");+ const auto end = legacy.find('\n', start);+ legacy.replace(start, end - start, legacyNodeLine(legacy.substr(start, end - start)));+ { std::ofstream file(path, std::ios::binary | std::ios::trunc); file << legacy; }+ PresetLibrary migrated(path);+ check(migrated.load() && !migrated.error().empty(), "legacy node library reports explicit protection removal notice");+ const auto& restored = migrated.entries().back().chain;+ check(restored == expected && restored.mode == ChainMode::Node && restored.countOf(EffectType::Protection) == 0 &&+ restored.firstOf(EffectType::NrEnhance)->viewX == 481 &&+ restored.firstOf(EffectType::NrEnhance)->nr.model.tone == .37f,+ "library migration preserves layout and non-protection parameters");+ check(migrated.save() && readBytes(path) == legacy && std::filesystem::exists(sidecar),+ "migrated library saves separately without rewriting original bytes");+ PresetLibrary reopened(path);+ check(reopened.load() && reopened.entries() == migrated.entries(), "restart prefers validated migrated library");+ }+ {+ const auto path = scratch(L"legacy-protection-session.v1");+ const auto sidecar = std::filesystem::path(path).concat(L".p3-node");+ std::filesystem::remove(sidecar);+ auto settings = sample(); settings.protection.enabled = true;+ auto session = ChainSession::initial(settings); session.select(ChainMode::Node);+ session.configurations[0].chain.nodes[2].viewX = 731;+ ChainSessionStore writer(path); check(writer.save(session), "create session migration fixture");+ std::istringstream input(readBytes(path));+ std::string headers[4], body; for (auto& line : headers) std::getline(input, line); input >> std::quoted(body);+ std::istringstream records(body); std::string magic, count, list, node;+ std::getline(records, magic); std::getline(records, count); std::getline(records, list); std::getline(records, node);+ node = list; node.replace(1, 4, "node"); node = legacyNodeLine(node);+ body = magic + '\n' + count + '\n' + list + '\n' + node + '\n';+ std::ostringstream bytes; for (const auto& line : headers) bytes << line << '\n'; bytes << std::quoted(body) << '\n';+ const auto legacy = bytes.str();+ { std::ofstream file(path, std::ios::binary | std::ios::trunc); file << legacy; }+ ChainSessionStore migrated(path); auto restored = ChainSession::initial({});+ check(migrated.load(restored) && !migrated.error().empty(), "legacy session migration reports its compatibility action");+ check(restored.configurations[0].chain == session.configurations[0].chain &&+ restored.configurations[1].chain.countOf(EffectType::Protection) == 0 &&+ restored.configurations[1].chain.firstOf(EffectType::NrEnhance)->viewX == 731,+ "session migration keeps list protection and node layout independent");+ check(migrated.save(restored) && readBytes(path) == legacy && std::filesystem::exists(sidecar),+ "migrated session saves sidecar and preserves original file exactly");+ ChainSessionStore reopened(path); auto restarted = ChainSession::initial({});+ check(reopened.load(restarted) && restarted == restored, "new session process selects migrated sidecar");+ }+}+++// 2.0 (2026-09-29): the new interface ships no built-in presets, and a single+// preset round-trips through a standalone file; an import never overwrites.+void testNoBuiltinsAndSingleFile() {+ const auto path = scratch(L"no-builtins.v1");+ {+ PresetLibrary withBuiltins(path);+ check(withBuiltins.load() && withBuiltins.entries().size() == 4, "no-builtins: default library still has 4 built-ins");+ PresetEntry mine; mine.name = L"mine"; mine.chain = toChain(sample());+ check(withBuiltins.put(mine) && withBuiltins.setDefault(0) && withBuiltins.save(), "no-builtins: file with built-ins, default on a built-in");+ }+ PresetLibrary lib(path);+ lib.setIncludeBuiltins(false);+ check(lib.load(), "no-builtins: load");+ check(lib.entries().size() == 1 && lib.entries()[0].name == L"mine" && !lib.entries()[0].builtin,+ "no-builtins: built-in entries in the file are dropped, the user's own kept");+ check(!lib.defaultIndex().has_value(), "no-builtins: a default that pointed at a built-in is cleared");+ const auto file = scratch(L"single.vpreset");+ check(lib.exportEntry(0, file) && std::filesystem::file_size(file) > 0, "single file: export");+ std::wstring name;+ check(lib.importFile(file, name) && name == L"mine 2" && lib.entries().size() == 2,+ "single file: import of an existing name gets a numbered suffix");+ check(lib.entries()[1].chain == lib.entries()[0].chain, "single file: imported chain equals the exported one");+ { std::ofstream bad(file, std::ios::binary | std::ios::trunc); bad << "not a preset"; }+ check(!lib.importFile(file, name) && lib.entries().size() == 2, "single file: a damaged file is refused, nothing added");+ PresetLibrary empty(scratch(L"no-builtins-empty.v1"));+ empty.setIncludeBuiltins(false);+ check(empty.load() && empty.entries().empty(), "no-builtins: a fresh library starts empty");+}++__declspec(noinline) int testExistingPresets() {+ // An editor preset must not canonicalise a hand-ordered chain. Exercise+ // every contents combination, not just full presets or single grades.+ {+ auto baseSettings = sample();+ baseSettings.additionalColorCount = 1;+ baseSettings.additionalColors[0].enabled = true;+ baseSettings.additionalColors[0].exposure = -0.75f;+ auto base = toChain(baseSettings); base.mode = ChainMode::Node;+ removeLegacyNodeProtection(base);+ std::rotate(base.nodes.begin() + 1, base.nodes.begin() + 2, base.nodes.begin() + 4);+ for (uint32_t i = 0; i < base.nodeCount; ++i) {+ base.nodes[i].viewX = 37.0f + i * 113.0f;+ base.nodes[i].viewY = 19.0f + i * 7.0f;+ }+ fromChain(base, baseSettings);+ auto saved = sample(); saved.additionalColorCount = 5;+ for (unsigned i = 0; i < 5; ++i) {+ saved.additionalColors[i].enabled = i != 2;+ saved.additionalColors[i].exposure = 0.2f * (i + 1);+ }+ saved.model.intensity = 0.33f; saved.color.exposure = 1.2f;+ PresetEntry entry; entry.kind = ChainMode::Node;+ entry.chain = toChain(saved); entry.chain.mode = ChainMode::Node;+ removeLegacyNodeProtection(entry.chain);+ entry.color = saved.color; entry.fg = {2, FrameGenerationBackend::XeSS};+ entry.audioSync = AudioSyncMode::Manual; entry.audioOffsetMs = 73;+ for (uint32_t i = 0; i < entry.chain.nodeCount; ++i) entry.chain.nodes[i].viewX = 800 + i * 31.0f;+ bool masks = true, geometry = true, unrelated = true;+ for (uint32_t mask = 0; mask <= kPresetAllContent; ++mask) {+ entry.contents = mask; auto chain = base; auto settings = baseSettings;+ auto expected = settings; PresetLibrary::apply(entry, expected);+ const auto result = PresetLibrary::applyToChain(entry, chain, settings);+ masks = masks && result.accepted && settings.color == expected.color &&+ settings.additionalColorCount == expected.additionalColorCount &&+ settings.additionalColors == expected.additionalColors &&+ settings.multiplier == expected.multiplier &&+ settings.frameGenerationBackend == expected.frameGenerationBackend &&+ settings.audioOffsetMs == expected.audioOffsetMs && settings.audioSync == expected.audioSync;+ unrelated = unrelated && settings.exportBitrateMbps == baseSettings.exportBitrateMbps &&+ settings.captureCompatible == baseSettings.captureCompatible;+ if (!(mask & presetContentMask(PresetContent::Chain))) {+ for (uint32_t i = 0; i < base.nodeCount; ++i) {+ if (base.nodes[i].type == EffectType::Color) continue;+ const auto* actual = chain.firstOf(base.nodes[i].type);+ auto want = base.nodes[i];+ if (want.type == EffectType::FrameGeneration &&+ (mask & presetContentMask(PresetContent::FrameGeneration))) want.enabled = entry.fg.multiplier > 1;+ geometry = geometry && actual && *actual == want;+ }+ geometry = geometry && chain.nodes[0].viewX == base.nodes[0].viewX &&+ chain.nodes[3].type == EffectType::Color && chain.nodes[3].viewX == base.nodes[3].viewX;+ } else if (mask & presetContentMask(PresetContent::Color)) {+ for (uint32_t i = 0; i < chain.nodeCount; ++i)+ geometry = geometry && chain.nodes[i].type == entry.chain.nodes[i].type &&+ chain.nodes[i].viewX == entry.chain.nodes[i].viewX;+ }+ if (mask == presetContentMask(PresetContent::Audio))+ geometry = geometry && chain == base && settings == expected;+ }+ check(masks, "all 16 editor content masks preserve legacy settings semantics and six grades");+ check(geometry, "partial presets preserve hand order/layout and full presets restore saved layout");+ check(unrelated, "editor presets do not overwrite capture or export settings");++ entry.contents = presetContentMask(PresetContent::Color);+ auto chain = base; auto settings = baseSettings;+ check(PresetLibrary::applyToChain(entry, chain, settings).accepted && chain.countOf(EffectType::Color) == 6,+ "colour-only can expand existing interleaved slots to six");+ entry.chain = toChain(sample()); entry.chain.mode = ChainMode::Node;+ removeLegacyNodeProtection(entry.chain);+ check(PresetLibrary::applyToChain(entry, chain, settings).accepted && chain.countOf(EffectType::Color) == 1 &&+ chain.firstOf(EffectType::NrEnhance)->viewX == base.firstOf(EffectType::NrEnhance)->viewX,+ "colour-only can remove surplus grades without moving unrelated nodes");+ entry.contents = presetContentMask(PresetContent::Chain);+ chain = base; settings = baseSettings;+ check(PresetLibrary::applyToChain(entry, chain, settings).accepted && chain.countOf(EffectType::Color) == 2 &&+ settings.additionalColors == baseSettings.additionalColors,+ "chain-only keeps every current grade even when saved topology has fewer slots");++ entry.contents = kPresetAllContent; entry.kind = ChainMode::List;+ chain = base; settings = baseSettings;+ check(!PresetLibrary::applyToChain(entry, chain, settings).accepted && chain == base && settings == baseSettings,+ "wrong preset mode rejects without mutation");+ entry.kind = ChainMode::Node; entry.contents = presetContentMask(PresetContent::Color);+ // Enabling a currently disabled colour slot after HDR is illegal.+ entry.chain = toChain(baseSettings); entry.chain.mode = ChainMode::Node;+ removeLegacyNodeProtection(entry.chain);+ auto invalidBase = base;+ std::swap(invalidBase.nodes[3], invalidBase.nodes[4]);+ invalidBase.nodes[4].enabled = false;+ fromChain(invalidBase, settings); const auto beforeSettings = settings; chain = invalidBase;+ check(validateChain(chain).accepted && !PresetLibrary::applyToChain(entry, chain, settings).accepted &&+ chain == invalidBase && settings == beforeSettings,+ "colour activation that violates HDR tail order rejects atomically");+ }+ {+ const auto path = scratch(L"legacy-single-color.v1");+ auto settings = sample();+ PresetEntry entry; entry.name = L"legacy-color";+ entry.chain = toChain(settings); entry.color = settings.color;+ entry.chain.nodes[0].viewX = 213;+ PresetLibrary writer(path);+ check(writer.load() && writer.put(entry), "legacy single-colour preset saves");+ std::ifstream file(path); std::string magic; int version = 0; file >> magic >> version;+ check(version == 1, "compatibility fixture really uses codec v1");+ PresetLibrary reader(path);+ check(reader.load(), "fresh library reads legacy single-colour preset");+ const auto& restored = reader.entries().back();+ const auto* color = restored.chain.firstOf(EffectType::Color);+ check(color && color->color == entry.color, "v1 chain carries full legacy colour payload");+ auto applied = EnhancementSettings{}; fromChain(restored.chain, applied);+ check(applied.color == entry.color && restored.chain.nodes[0].viewX == 213,+ "direct legacy chain projection preserves colour and layout");+ }// 1. Built-ins exist before anything is saved, and are read-only.{const auto path = scratch(L"builtins.v1");@@ -66,11 +410,15 @@ int main() {check(library.load(), "reload succeeds");auto target = sample();target.color.exposure = -1.0f; // must survive: colour is not in the preset+ target.additionalColorCount = 1;+ target.additionalColors[0].exposure = 1.25f;target.audioOffsetMs = -50; // must survive tooPresetLibrary::apply(library.entries().back(), target);check(target.nr == settings.nr && target.sr == settings.sr && target.multiplier == settings.multiplier,"chain-only apply restores the stages");check(target.color.exposure == -1.0f, "chain-only apply leaves the colour grade alone");+ check(target.additionalColorCount == 1 && target.additionalColors[0].exposure == 1.25f,+ "chain-only apply leaves additional colour grades alone");check(target.audioOffsetMs == -50, "chain-only apply leaves the audio offset alone");}@@ -87,6 +435,7 @@ int main() {entry.contents = kPresetAllContent;entry.chain = toChain(settings);entry.chain.mode = ChainMode::Node;+ removeLegacyNodeProtection(entry.chain);entry.chain.nodes[2].nr.model.style = 2;entry.chain.nodes[2].nr.temporal = true;entry.color = settings.color;@@ -112,6 +461,61 @@ int main() {check(target.captureCompatible == false, "applying a preset never touches capture settings");}+ {+ PresetLibrary library(scratch(L"six-colors.v2"));+ check(library.load(), "multi-colour library initializes");+ auto settings = sample();+ settings.additionalColorCount = 5;+ for (unsigned i = 0; i < 5; ++i) {+ auto& color = settings.additionalColors[i];+ color.enabled = i != 2;+ color.exposure = float(i) * 0.25f;+ color.setLutName(L"independent-" + std::to_wstring(i) + L".cube");+ }+ PresetEntry entry; entry.name = L"六调色";+ entry.chain = toChain(settings); entry.color = settings.color;+ check(library.put(entry) && library.load(), "six-colour preset reloads");+ const auto& loaded = library.entries().back();+ check(loaded.chain == entry.chain, "every colour node and LUT survive serialization");+ auto target = EnhancementSettings{};+ PresetLibrary::apply(loaded, target);+ check(target.color == settings.color && target.additionalColorCount == 5 &&+ target.additionalColors == settings.additionalColors, "all six colour settings apply");+ auto colorOnly = loaded; colorOnly.contents = presetContentMask(PresetContent::Color);+ target = {}; target.exportBitrateMbps = 12;+ PresetLibrary::apply(colorOnly, target);+ check(target.additionalColors == settings.additionalColors && target.additionalColorCount == 5 &&+ !target.nr && !target.sr && target.exportBitrateMbps == 12, "colour-only restores six grades without other stages");+ }++ // Every colour node carries a full grade in v2. The file guard must allow+ // all 64 entries even with dense curves and long UTF-8 LUT references.+ {+ const auto path = scratch(L"six-colors-capacity.v2");+ PresetLibrary library(path);+ bool capacity = library.load();+ auto settings = sample(); settings.additionalColorCount = 5;+ auto fill = [](ColorSettings& color) {+ color.enabled = true; color.setLutName(std::wstring(220, L'色') + L".cube");+ for (auto& curve : color.curves) {+ curve.count = kColorCurvePoints;+ for (int j = 0; j < kColorCurvePoints; ++j)+ curve.points[j] = {float(j) / 7.0f, float(j * j) / 49.0f};+ }+ };+ fill(settings.color); for (auto& color : settings.additionalColors) fill(color);+ PresetEntry entry; entry.chain = toChain(settings); entry.color = settings.color;+ for (unsigned i = unsigned(library.entries().size()); i < 64 && capacity; ++i) {+ entry.name = L"six-grade-" + std::to_wstring(i);+ capacity = library.put(entry);+ }+ PresetLibrary loaded(path);+ capacity = capacity && loaded.load() && loaded.entries().size() == 64;+ for (const auto& preset : loaded.entries())+ if (!preset.builtin) capacity = capacity && preset.chain == entry.chain && preset.color == entry.color;+ check(capacity, "64 full-curve/Unicode six-grade library entries reload");+ }+// 4. Management: rename, duplicate, erase, default.{const auto path = scratch(L"manage.v1");@@ -137,6 +541,28 @@ int main() {check(!reloaded.defaultIndex().has_value(), "erasing the default clears it");}+ {+ const auto path = scratch(L"default-rollback.v1");+ PresetLibrary library(path);+ check(library.load(), "default rollback library initializes");+ PresetEntry entry; entry.name = L"rollback"; entry.chain = toChain(sample());+ check(library.put(entry), "default rollback fixture saves");+ const auto index = library.entries().size() - 1;+ check(library.setDefault(index), "default rollback fixture selects default");+ const auto bytes = readBytes(path);+ const auto temp = std::filesystem::path(path).concat(L".tmp");+ std::filesystem::create_directory(temp);+ { std::ofstream file(temp / L"sentinel"); file << "occupied"; }+ check(!library.clearDefault() && library.defaultIndex() == index && readBytes(path) == bytes,+ "failed default clear keeps memory and original file");+ check(!library.setDefault(0) && library.defaultIndex() == index && readBytes(path) == bytes,+ "failed default replacement keeps memory and original file");+ std::filesystem::remove(temp / L"sentinel"); std::filesystem::remove(temp);+ check(library.clearDefault() && !library.defaultIndex().has_value(), "default clear persists");+ PresetLibrary reopened(path);+ check(reopened.load() && !reopened.defaultIndex().has_value(), "cleared default survives restart");+ }+// 5. Legacy import never overwrites and keeps the chain.{const auto path = scratch(L"legacy.v1");@@ -158,6 +584,15 @@ int main() {[](const PresetEntry& e) { return e.name == L"夜间游戏"; }), "the imported preset is present");}+ {+ const auto path = scratch(L"oversized.v2");+ const size_t bytes = 2u * 1024u * 1024u + 1;+ { std::ofstream f(path, std::ios::binary); f << std::string(bytes, 'x'); }+ PresetLibrary library(path);+ check(!library.load() && library.corrupt() && !library.save(), "oversized library is rejected and protected");+ check(std::filesystem::file_size(path) == bytes, "oversized source remains unchanged");+ }+// 6. A corrupt file is preserved, never overwritten.{const auto path = scratch(L"corrupt.v1");@@ -171,6 +606,290 @@ int main() {check(content.find("nonsense") != std::string::npos, "the original file is untouched");}+ {+ auto s=sample();s.nrLayerCount=4;s.additionalColorCount=1;s.additionalColors[0].exposure=.7f;+ for(unsigned i=0;i<4;++i){auto& n=s.nrLayers[i];n.enabled=i!=1;+ n.sizePolicy=static_cast<veyra::pipeline::NrSizePolicy>(i);n.model.tone=.2f*float(i+1);}+ PresetEntry entry;entry.name=L"NR四层尺寸";entry.contents=kPresetAllContent;entry.chain=toChain(s);entry.color=s.color;+ PresetLibrary library(scratch(L"nr-size.v3"));+ check(library.load()&&library.put(entry)&&library.load(),"NR per-instance library v3 reloads");+ check(library.entries().back().chain==entry.chain,"v3 preserves every node including multiple grades");+ EnhancementSettings restored;PresetLibrary::apply(library.entries().back(),restored);+ check(restored.nrLayerCount==4&&restored.nrLayers==s.nrLayers,"applying NR preset preserves disabled layers and size policies");+ }+ {+ const auto path = scratch(L"chain-session.v1");+ ChainSessionStore store(path);+ auto session = ChainSession::initial(sample());+ const auto initial = session;+ check(store.load(session) && session == initial, "missing session preserves initial settings");+ check(session.select(ChainMode::Node), "session initializes node configuration");+ auto& node = session.configurations[1];+ node.videoSrQuality = 4;+ node.chain.firstOf(EffectType::NrEnhance)->nr.sizePolicy = veyra::pipeline::NrSizePolicy::Native;+ node.chain.firstOf(EffectType::Color)->color.exposure = 1.7f;+ node.chain.nodes[0].viewX = 341.25f;+ node.selectedColour = 0;+ check(store.save(session), "mode session writes validated snapshot");+ auto restored = ChainSession::initial({});+ ChainSessionStore reopened(path);+ check(reopened.load(restored) && restored == session, "fresh store restores both chains parameters layout and active mode");+ auto invalid = session; invalid.configurations[1].videoSrQuality = 99;+ check(!reopened.save(invalid), "invalid session cannot replace valid file");+ check(reopened.load(restored) && restored == session, "invalid save leaves last valid session intact");+ const auto read = [&] { std::ifstream file(path, std::ios::binary); return std::string(std::istreambuf_iterator<char>(file), {}); };+ const auto validBytes = read();+ const auto temporary = std::filesystem::path(path).concat(L".tmp");+ std::filesystem::create_directory(temporary);+ { std::ofstream keep(temporary / L"sentinel"); keep << "occupied"; }+ check(!reopened.save(session) && read() == validBytes, "write failure preserves original session bytes");+ std::filesystem::remove(temporary / L"sentinel"); std::filesystem::remove(temporary);+ { std::ofstream file(path, std::ios::binary | std::ios::trunc); file << "VEYRA_CHAIN_SESSION 999\ncorrupt"; }+ ChainSessionStore corrupt(path);+ const auto before = restored;+ check(!corrupt.load(restored) && restored == before, "corrupt session does not partially mutate live state");+ check(!corrupt.save(session) && read().find("999") != std::string::npos, "corrupt source is never overwritten");+ { std::ofstream file(path, std::ios::binary | std::ios::trunc); file << validBytes << "trailing"; }+ ChainSessionStore trailing(path);+ check(!trailing.load(restored) && restored == before, "trailing session data is rejected transactionally");+ }std::printf(failures ? "preset library: %d FAILURES\n" : "preset library: all checks passed\n", failures);return failures ? 1 : 0;}++void testEditorPresetStorage() {+ const auto path = scratch(L"editor-presets.v1");+ const auto sidecar = std::filesystem::path(path).concat(L".p3-editor");+ std::filesystem::remove(sidecar);+ PresetLibrary library(path); check(library.load() && library.save(), "editor preset store: legacy baseline");+ const auto oldBytes = readBytes(path);+ auto settings = sample(); auto runtime = toChain(settings); runtime.mode = ChainMode::Node;+ removeLegacyNodeProtection(runtime);+ auto doc = std::make_shared<NodeEditorDocument>(); doc->nodes = runtime;+ check(doc->layout.initialize(doc->nodes).accepted, "editor preset store: init");+ uint32_t colorId = 0, duplicate = 0;+ for (uint32_t i = 0; i < doc->nodes.nodeCount; ++i)+ if (doc->nodes.nodes[i].type == EffectType::Color) colorId = doc->layout.ids[i];+ check(doc->layout.duplicate(doc->nodes, colorId, duplicate).accepted &&+ doc->layout.disconnect(doc->nodes, NodeGraphLayout::Input).accepted, "editor preset store: detached incomplete document");+ doc->nodes.nodes[doc->layout.indexOf(doc->nodes, duplicate)].color.exposure = 2.25f;+ PresetEntry entry; entry.name = L"editor-complete"; entry.kind = ChainMode::Node;+ entry.chain = runtime; entry.color = settings.color; entry.fg = {settings.multiplier, settings.frameGenerationBackend};+ entry.nodeConfiguration = ChainConfiguration::capture(runtime, settings); entry.nodeConfiguration->editor = doc;+ check(library.put(entry) && readBytes(path) == oldBytes && readBytes(sidecar).starts_with("VEYRA_PRESET_LIBRARY 4"),+ "editor preset store: sidecar saves without overwriting legacy");+ PresetLibrary reopened(path); check(reopened.load(), "editor preset store: reopen");+ const auto found = std::find_if(reopened.entries().begin(), reopened.entries().end(), [&](const auto& e) {return e.name == entry.name;});+ check(found != reopened.entries().end() && *found == entry, "editor preset store: full configuration round trip");+ NodeEditorDocument applied; applied.nodes.mode = ChainMode::Node;+ check(applied.layout.initialize(applied.nodes).accepted && PresetLibrary::applyToEditor(entry, applied, settings).accepted &&+ applied == *doc, "editor preset store: apply restores detached IDs payloads and edges");+ const auto before = reopened.entries(); const auto bytes = readBytes(sidecar);+ auto invalid = entry; invalid.name = L"invalid-editor"; auto badDoc = std::make_shared<NodeEditorDocument>(*doc);+ badDoc->layout.ids[0] = 0; invalid.nodeConfiguration->editor = badDoc;+ check(!reopened.put(invalid) && reopened.entries() == before && readBytes(sidecar) == bytes,+ "editor preset store: failed save cannot poison memory or disk");+}++void testEditorPresetParts() {+ auto values = sample();+ auto document = std::make_unique<NodeEditorDocument>();+ document->nodes = toChain(values); document->nodes.mode = ChainMode::Node;+ removeLegacyNodeProtection(document->nodes);+ check(document->layout.initialize(document->nodes).accepted, "editor preset: initialize");+ uint32_t colorId = 0, nrId = 0, copied = 0;+ for (uint32_t i = 0; i < document->nodes.nodeCount; ++i) {+ if (document->nodes.nodes[i].type == EffectType::Color) colorId = document->layout.ids[i];+ if (document->nodes.nodes[i].type == EffectType::NrEnhance) nrId = document->layout.ids[i];+ }+ check(document->layout.duplicate(document->nodes, colorId, copied).accepted, "editor preset: detached color after FG");+ const auto original = std::make_unique<NodeEditorDocument>(*document);+ PresetEntry audio; audio.kind = ChainMode::Node; audio.chain.mode = ChainMode::Node;+ audio.contents = presetContentMask(PresetContent::Audio); audio.audioOffsetMs = 73;+ check(PresetLibrary::applyToEditor(audio, *document, values).accepted && *document == *original &&+ values.audioOffsetMs == 73, "editor preset: audio applies without flattening detached tail");+ PresetEntry color; color.kind = ChainMode::Node; color.chain.mode = ChainMode::Node;+ color.contents = presetContentMask(PresetContent::Color); color.color.enabled = true; color.color.exposure = 1.25f;+ color.chain.nodeCount = 3;+ for (uint32_t i = 0; i < 3; ++i) {+ auto& n = color.chain.nodes[i]; n.type = EffectType::Color; n.enabled = true;+ n.color.enabled = true; n.color.exposure = float(i + 1) / 4;+ }+ check(PresetLibrary::applyToEditor(color, *document, values).accepted &&+ document->nodes.countOf(EffectType::Color) == 3, "editor preset: grow color slots");+ const int nr = document->layout.indexOf(document->nodes, nrId);+ check(nr >= 0 && document->nodes.nodes[nr] == original->nodes.nodes[original->layout.indexOf(original->nodes, nrId)] &&+ document->layout.inputNext == original->layout.inputNext, "editor preset: unrelated NR identity payload and source edge retained");+ auto runtime = std::make_unique<EffectChain>();+ check(document->layout.project(document->nodes, *runtime).accepted && runtime->countOf(EffectType::Color) == 1 &&+ document->layout.indexOf(document->nodes, copied) >= 0, "editor preset: added color follows detached slot without entering runtime");+ color.chain.nodeCount = 1;+ check(PresetLibrary::applyToEditor(color, *document, values).accepted && document->nodes.countOf(EffectType::Color) == 1 &&+ document->layout.indexOf(document->nodes, colorId) >= 0 && document->layout.indexOf(document->nodes, copied) < 0,+ "editor preset: shrink keeps surviving stable ID");+ check(document->layout.disconnect(document->nodes, NodeGraphLayout::Input).accepted, "editor preset: disconnect source");+ const auto accepted = values; color.color.exposure = 2.5f;+ check(PresetLibrary::applyToEditor(color, *document, values).accepted && values == accepted &&+ document->nodes.nodes[document->layout.indexOf(document->nodes, colorId)].color.exposure == 2.5f &&+ document->layout.inputNext == NodeGraphLayout::Input, "editor preset: disconnected color changes draft only");+ const auto beforeBad = std::make_unique<NodeEditorDocument>(*document);+ color.color.exposure = 1000;+ check(!PresetLibrary::applyToEditor(color, *document, values).accepted && *document == *beforeBad && values == accepted,+ "editor preset: invalid detached parameter rolls back document and settings");+ PresetEntry fg; fg.kind = ChainMode::Node; fg.chain.mode = ChainMode::Node;+ fg.contents = presetContentMask(PresetContent::FrameGeneration); fg.fg.multiplier = 9;+ check(!PresetLibrary::applyToEditor(fg, *document, values).accepted && *document == *beforeBad && values == accepted,+ "editor preset: invalid detached FG multiplier rolls back");+ PresetEntry whole; whole.kind = ChainMode::Node; whole.chain = original->nodes;+ --whole.chain.nodeCount; whole.contents = kPresetAllContent; whole.color = accepted.color;+ whole.fg.multiplier = accepted.multiplier;+ check(PresetLibrary::applyToEditor(whole, *document, values).accepted &&+ document->layout.project(document->nodes, *runtime).accepted, "editor preset: full replacement accepts incomplete prior editor");+ auto noFg = std::make_unique<NodeEditorDocument>(); noFg->nodes.mode = ChainMode::Node;+ check(noFg->layout.initialize(noFg->nodes).accepted, "editor preset: empty graph");+ fg.fg.multiplier = 2; values = EnhancementSettings{};+ check(PresetLibrary::applyToEditor(fg, *noFg, values).accepted && values.multiplier == 2 &&+ noFg->nodes.countOf(EffectType::FrameGeneration) == 1 && noFg->layout.project(noFg->nodes, *runtime).accepted,+ "editor preset: new FG attaches at complete tail");+}++__declspec(noinline) void testEditorGlobalSettings() {+ const auto path = scratch(L"editor-global-settings.v1");+ const auto editorPath = std::filesystem::path(path).concat(L".p3-editor");+ const auto draftPath = std::filesystem::path(editorPath).concat(L".p3-globals");+ std::filesystem::remove(editorPath); std::filesystem::remove(draftPath);+ auto initial = sample(); initial.multiplier = 6;+ auto session = std::make_unique<ChainSession>(ChainSession::initial(initial));+ check(session->select(ChainMode::Node), "globals: initialize session");+ ChainSessionStore writer(path);+ check(writer.save(*session), "globals: write v1");+ const auto v1 = readBytes(path);+ auto document = std::make_shared<NodeEditorDocument>();+ auto& c = session->configurations[1];+ document->nodes = c.chain; document->layout.initialize(document->nodes);+ document->layout.disconnect(document->nodes, NodeGraphLayout::Input);+ c.editor = document;+ check(writer.save(*session), "globals: write legacy editor v2");+ const auto v2 = readBytes(editorPath);+ document->globals = static_cast<const ChainGlobalSettings&>(c);+ document->globals->srTarget = veyra::pipeline::SrTarget::Qhd;+ document->globals->videoSrQuality = 3;+ document->nodes.fgMultiplier = 4;+ document->globals->fgBackend = FrameGenerationBackend::XeSS;+ document->globals->opticalFlowBackend = OpticalFlowBackend(1);+ const auto runtimeGlobals = static_cast<const ChainGlobalSettings&>(c);+ check(session->valid() && writer.save(*session), "globals: write disconnected draft v3");+ check(readBytes(path) == v1 && readBytes(editorPath) == v2 &&+ readBytes(draftPath).starts_with("VEYRA_CHAIN_SESSION 3"), "globals: preserve both legacy files");+ auto restored = std::make_unique<ChainSession>();+ ChainSessionStore reader(path);+ check(reader.load(*restored) && *restored == *session, "globals: reopen exact runtime and draft");+ check(static_cast<const ChainGlobalSettings&>(restored->configurations[1]) == runtimeGlobals &&+ *restored->configurations[1].editor->globals != runtimeGlobals, "globals: draft never replaces accepted runtime");+ const auto bytes = readBytes(draftPath);+ document->globals->videoSrQuality = 99;+ check(!writer.save(*session) && readBytes(draftPath) == bytes, "globals: invalid detached quality rejected atomically");+ document->globals->videoSrQuality = 3;+ document->nodes.fgMultiplier = 6;+ check(!session->valid(), "globals: XeSS draft rejects six times even while disconnected");+ document->nodes.fgMultiplier = 4;+ auto entry = std::make_unique<PresetEntry>();+ entry->name = L"globals"; entry->kind = ChainMode::Node; entry->contents = kPresetAllContent;+ entry->chain = c.chain; entry->nodeConfiguration = c; entry->fg = {4, FrameGenerationBackend::XeSS};+ const auto presetPath = scratch(L"editor-global-preset.v1");+ const auto presetEditor = std::filesystem::path(presetPath).concat(L".p3-editor");+ const auto presetDraft = std::filesystem::path(presetEditor).concat(L".p3-globals");+ std::filesystem::remove(presetEditor); std::filesystem::remove(presetDraft);+ PresetLibrary library(presetPath); library.load();+ check(library.put(*entry) && readBytes(presetDraft).starts_with("VEYRA_PRESET_LIBRARY 5"),+ "globals: preset v5 writes independent file");+ PresetLibrary reopened(presetPath);+ check(reopened.load(), "globals: reload preset v5");+ const auto found = std::find_if(reopened.entries().begin(), reopened.entries().end(),+ [](const auto& e) { return e.name == L"globals"; });+ check(found != reopened.entries().end() && found->nodeConfiguration == entry->nodeConfiguration,+ "globals: preset v5 keeps runtime and draft separately");+ auto target = std::make_unique<NodeEditorDocument>(); target->nodes.mode = ChainMode::Node;+ target->layout.initialize(target->nodes);+ auto values = initial;+ check(PresetLibrary::applyToEditor(*entry, *target, values).accepted &&+ target->globals == document->globals && target->layout == document->layout,+ "globals: complete preset restores disconnected draft globals");+ auto invalid = std::make_unique<ChainSession>(*restored);+ const auto retained = std::make_unique<ChainSession>(*invalid);+ { std::ofstream file(draftPath, std::ios::binary | std::ios::trunc); file << bytes << "garbage"; }+ ChainSessionStore corrupt(path);+ check(!corrupt.load(*invalid) && *invalid == *retained && !corrupt.save(*session),+ "globals: corrupt v3 decode does not partly mutate output");+ std::filesystem::remove(draftPath); std::filesystem::remove(editorPath);+ std::filesystem::remove(presetDraft); std::filesystem::remove(presetEditor);+}++void testFsrBackendStorage() {+ for(const auto backend : {FrameGenerationBackend::Fsr, FrameGenerationBackend::Fsr4}) {+ auto settings=sample();settings.multiplier=2;settings.frameGenerationBackend=backend;+ const auto path=scratch(backend==FrameGenerationBackend::Fsr?L"fsr3-library.v1":L"fsr4-library.v1");+ PresetLibrary writer(path);writer.setIncludeBuiltins(false);+ PresetEntry entry;entry.name=L"FSR FG";entry.contents=presetContentMask(PresetContent::FrameGeneration);+ entry.chain=toChain(settings);entry.fg={2,backend};+ check(writer.load()&&writer.put(entry), "FSR preset: save distinct backend");+ PresetLibrary reader(path);reader.setIncludeBuiltins(false);+ check(reader.load()&&reader.entries().size()==1&&reader.entries()[0].fg==entry.fg,+ "FSR preset: reopen preserves backend and multiplier");+ auto destination=sample();+ if(!reader.entries().empty())PresetLibrary::apply(reader.entries()[0],destination);+ check(destination.frameGenerationBackend==backend&&destination.multiplier==2&&destination.validate().empty(),+ "FSR preset: apply validates without DLSS relabeling");+ entry.name=L"invalid FSR 4X";entry.fg.multiplier=4;+ const auto retained=readBytes(path);+ check(!writer.put(entry)&&readBytes(path)==retained, "FSR preset: illegal multiplier rejected atomically");++ const auto sessionPath=scratch(backend==FrameGenerationBackend::Fsr?L"fsr3-session.v1":L"fsr4-session.v1");+ const auto session=std::make_unique<ChainSession>(ChainSession::initial(settings));+ check(session->select(ChainMode::Node), "FSR session: select node mode");+ ChainSessionStore sessionWriter(sessionPath);+ auto restored=std::make_unique<ChainSession>(ChainSession::initial({}));+ ChainSessionStore sessionReader(sessionPath);+ check(sessionWriter.save(*session)&&sessionReader.load(*restored)&&*restored==*session,+ "FSR session: list and node configurations reopen independently");+ }+}++__declspec(noinline) void testRenderingChoices(){+ auto s=sample();s.videoHdr.enabled=false;s.srTarget=veyra::pipeline::SrTarget::Uhd6K;+ s.hdrOutputMode=HdrOutputMode::ScRgb;s.fgMotion=s.srMotion=s.nrMotion=MotionSource::Zero;+ const auto path=scratch(L"field-rendering.v1");+ std::filesystem::remove(std::filesystem::path(path).concat(L".field-render"));+ PresetLibrary writer(path);writer.setIncludeBuiltins(false);+ PresetEntry e;e.name=L"rendering";e.kind=ChainMode::List;e.chain=toChain(s);e.globals=ChainGlobalSettings::capture(s);e.fg={s.multiplier,s.frameGenerationBackend};+ check(writer.load()&&writer.put(e),"rendering: save shared globals in list preset");+ PresetLibrary reader(path);reader.setIncludeBuiltins(false);+ check(reader.load()&&reader.entries().size()==1&&reader.entries()[0]==e,"rendering: library roundtrip");+ auto applied=sample();PresetLibrary::apply(e,applied);+ check(applied.srTarget==s.srTarget&&applied.hdrOutputMode==s.hdrOutputMode&&applied.nrMotion==s.nrMotion&&applied.srMotion==s.srMotion&&applied.fgMotion==s.fgMotion,"rendering: list applies resolution HDR and motion");+ e.contents=presetContentMask(PresetContent::Color);auto untouched=sample();auto before=untouched;PresetLibrary::apply(e,untouched);+ check(ChainGlobalSettings::capture(untouched)==ChainGlobalSettings::capture(before),"rendering: color-only preset leaves shared choices intact");+ const auto sessionPath=scratch(L"field-rendering-session.v1");+ std::filesystem::remove(std::filesystem::path(sessionPath).concat(L".field-render"));+ std::filesystem::remove(std::filesystem::path(sessionPath).concat(L".field-render.p3-globals"));+ auto session=std::make_unique<ChainSession>(ChainSession::initial(s));+ auto restored=std::make_unique<ChainSession>();ChainSessionStore sw(sessionPath),sr(sessionPath);+ check(sw.save(*session)&&sr.load(*restored)&&*session==*restored,"rendering: v4 session without editor restores");+ check(session->select(ChainMode::Node),"rendering: select node mode");+ auto doc=std::make_shared<NodeEditorDocument>();doc->nodes=session->configurations[1].chain;doc->layout.initialize(doc->nodes);doc->globals=ChainGlobalSettings::capture(s);+ session->configurations[1].editor=doc;+ check(sw.save(*session),"rendering: v4 session with editor saves");+ ChainSessionStore nr(sessionPath);check(nr.load(*restored)&&*session==*restored,"rendering: v4 editor globals restore exactly");+}+int main() {+ testRenderingChoices();+ std::setvbuf(stdout, nullptr, _IONBF, 0);+ testLegacyProtectionMigration();+ testNodeEditorSession();+ testEditorPresetParts();+ testEditorPresetStorage();+ testEditorGlobalSettings();+ testNoBuiltinsAndSingleFile();+ testFsrBackendStorage();+ return testExistingPresets();+}diff --git a/tests/unit/RepairContractTests.cpp b/tests/unit/RepairContractTests.cppindex 22efe843..870c2e7b 100644--- a/tests/unit/RepairContractTests.cpp+++ b/tests/unit/RepairContractTests.cpp@@ -34,9 +34,35 @@ int thunkReplacementFunction(int value) { ++thunkHookCalls; return thunkOriginal#include "veyra/source/DolbyVision.h"#include "veyra/source/AudioInputRecovery.h"#include "veyra/engine/Subtitles.h"+#include "veyra/engine/PresentationSettings.h"+#include "veyra/engine/PresentationGeometry.h"int main(){using namespace veyra;int failures=0,checks=0;auto check=[&](bool ok,const char* name){++checks;if(!ok)++failures;std::cout<<(ok?"PASS ":"FAIL ")<<name<<'\n';};+ {+ engine::PreviewView v;v.displayAspect=16.0/9;+ auto [w,h]=v.renderedSize(1000,1000,1440,1080);+ check(std::abs(w-1000)<.01&&std::abs(h-562.5)<.01,"anamorphic source uses reported DAR");+ const auto before=v.sourcePoint(850,420,1000,1000,1440,1080);+ v.wheel(2,850,420,1000,1000,1440,1080);+ const auto after=v.sourcePoint(850,420,1000,1000,1440,1080);+ check(std::abs(before.first-after.first)<.00001&&std::abs(before.second-after.second)<.00001,"DAR zoom preserves cursor source coordinate");+ v.zoom=1;v.mode=1;auto native=v.renderedSize(1000,1000,1440,1080);+ check(native.first==1440&&native.second==1080,"native mode maps each output pixel once");+ v.mode=2;auto fill=v.renderedSize(1000,1000,1440,1080);+ check(std::abs(fill.first-1777.7778f)<.01&&fill.second==1000,"fill uses DAR and crops");+ v.mode=3;auto stretch=v.renderedSize(1000,1000,1440,1080);+ check(stretch.first==1000&&stretch.second==1000,"stretch fills client independently");+ for(int mode=4;mode<=6;++mode){v.mode=mode;const auto size=v.renderedSize(1000,1000,1440,1080);+ const double ratio=mode==4?16.0/9:mode==5?4.0/3:21.0/9;+ check(std::abs(size.first/size.second-ratio)<.00001,"forced display ratio shares preview transform");}+ }+ check(std::wstring_view(engine::ngxFailureHint(0xFFFFFFFFBAD00002ull)).find(L"驱动")!=std::wstring_view::npos,"signed NGX PlatformError reports actual driver/platform failure");+ check(std::wstring_view(engine::ngxFailureHint(0xBAD00001)).find(L"不支持")!=std::wstring_view::npos,"NGX FeatureNotSupported has a distinct visible reason");+ for(bool lowQueue:{false,true})for(bool fullscreen:{false,true})for(auto sync:{engine::DisplaySync::Tearing,engine::DisplaySync::Vsync,engine::DisplaySync::Automatic}) {+ engine::PresentationSettings s;s.enabled=lowQueue;s.fullscreen=fullscreen;s.display=sync;+ check(engine::presentationVsync(s)==(sync==engine::DisplaySync::Vsync)&&engine::presentationTearing(s)==(sync==engine::DisplaySync::Tearing),"VSync and tearing only when explicitly selected; Automatic is neither, windowed or fullscreen");+ }{source::AudioInputRecovery retry;retry.reset(1000);check(!retry.due(0,3999)&&retry.due(0,4000),"missing initial PCM retries after bounded startup grace");@@ -159,13 +185,23 @@ int main(){check(p.nr==p.source&&p.flow==p.source,"native mode retains native4K NR and flow");p=pipeline::ResolutionPlan::make({3840,2160},true,pipeline::NrSizePolicy::Realtime,true);check(!p.srApplied&&p.nr==p.base,"native export and 1:1 SR bypass");- for(auto target:{pipeline::SrTarget::Qhd,pipeline::SrTarget::Uhd4K,pipeline::SrTarget::Uhd8K}){+ for(auto target:{pipeline::SrTarget::Qhd,pipeline::SrTarget::Uhd4K,pipeline::SrTarget::Uhd8K,pipeline::SrTarget::Uhd5K,pipeline::SrTarget::Uhd6K,pipeline::SrTarget::Uhd7K}){const auto plan=pipeline::ResolutionPlan::make({1920,1080},true,pipeline::NrSizePolicy::Realtime,false,7,target);check(plan.output==pipeline::srTargetExtent(target)&&plan.nr==pipeline::Extent{1920,1080}&&plan.settingsRevision==7,"SR target changes real output, retains realtime NR and revision");}check(pipeline::ResolutionPlan::make({1448,1086},true,pipeline::NrSizePolicy::Native,true,1,pipeline::SrTarget::Uhd8K).output==pipeline::Extent{5760,4320},"8K 4:3 aspect preserved");+ for(auto target:{pipeline::SrTarget::Uhd5K,pipeline::SrTarget::Uhd6K,pipeline::SrTarget::Uhd7K}){+ const auto limit=pipeline::srTargetExtent(target);+ for(auto source:{pipeline::Extent{1920,1080},pipeline::Extent{1440,1080},pipeline::Extent{2520,1080}}){+ const auto output=pipeline::ResolutionPlan::make(source,true,pipeline::NrSizePolicy::Native,true,1,target).output;+ check(output.width<=limit.width&&output.height<=limit.height&&!(output.width%2)&&!(output.height%2)+ &&std::abs(int64_t(output.width)*source.height-int64_t(output.height)*source.width)<=2*source.width,"5/6/7K contain aspect within two-pixel rounding and even dimensions");+ }+ }check(pipeline::ResolutionPlan::make({8000,2000},true,pipeline::NrSizePolicy::Native,true,1,pipeline::SrTarget::Qhd).output==pipeline::Extent{8000,2000},"small target never shrinks long image");engine::EnhancementSettings s;check(s.validate().empty(),"default settings valid");+ check(engine::motionUsesFlow(s.fgMotion,engine::FrameGenerationBackend::Dlss)&&!engine::motionUsesFlow(s.fgMotion,engine::FrameGenerationBackend::XeSS),"default motion follows provider: DLSS flow, XeSS zero");+ check(!engine::motionUsesFlow(engine::MotionSource::Zero)&&engine::motionUsesFlow(engine::MotionSource::OpticalFlow),"explicit consumer motion choice wins");auto audioOnly=s;audioOnly.revision=2;audioOnly.audioSync=engine::AudioSyncMode::Manual;audioOnly.audioOffsetMs=90;check(audioOnly.sameVideoConfiguration(s),"audio changes do not invalidate video configuration");auto attempted=audioOnly;attempted.model.style=1;@@ -195,7 +231,9 @@ int main(){check(engine::frameGenerationBackendName(engine::FrameGenerationBackend::Dlss)=="DLSS"&&engine::frameGenerationBackendName(engine::FrameGenerationBackend::XeSS)=="XeSS"&&engine::frameGenerationBackendName(engine::FrameGenerationBackend::Fsr)=="AMD-FSR","frame-generation backend names identify every backend");// The present-sink backends own generation inside their swapchain provider;// the in-graph DLSSG path must never try to run for them.- check(engine::presentSinkFrameGeneration(engine::FrameGenerationBackend::XeSS)&&engine::presentSinkFrameGeneration(engine::FrameGenerationBackend::Fsr)&&!engine::presentSinkFrameGeneration(engine::FrameGenerationBackend::Dlss),"present-sink frame generation covers XeSS and AMD FSR only");+ check(engine::presentSinkFrameGeneration(engine::FrameGenerationBackend::XeSS)&&!engine::presentSinkFrameGeneration(engine::FrameGenerationBackend::Fsr)&&!engine::presentSinkFrameGeneration(engine::FrameGenerationBackend::Fsr4)&&!engine::presentSinkFrameGeneration(engine::FrameGenerationBackend::Dlss),"only XeSS owns provider presentation; FSR uses application batches");+ check(engine::crossVendorFrameGeneration(engine::FrameGenerationBackend::Fsr)&&engine::crossVendorFrameGeneration(engine::FrameGenerationBackend::Fsr4)&&!engine::crossVendorFrameGeneration(engine::FrameGenerationBackend::Dlss),"FSR 3/4 admission is independent of NVIDIA requirements");+ check(int(engine::FrameGenerationBackend::Fsr)==2&&int(engine::FrameGenerationBackend::Fsr4)==3,"FSR persisted identities remain stable and distinct");{engine::EnhancementSettings settings;settings.multiplier=4;settings.frameGenerationBackend=engine::FrameGenerationBackend::Fsr;diff --git a/tests/unit/RepairPresetTests.cpp b/tests/unit/RepairPresetTests.cppindex a8886e64..22a2f2e2 100644--- a/tests/unit/RepairPresetTests.cpp+++ b/tests/unit/RepairPresetTests.cpp@@ -34,6 +34,68 @@ bool retiredSrMode(const std::filesystem::path& path) {std::cout<<"retired SR migration and unknown mode preservation=1\n";return true;}+bool schemaVersions(const std::filesystem::path& path) {+ using namespace veyra::engine;+ for(int version=1;version<=21;++version) {+ std::ostringstream fixture;+ fixture<<"VEYRA_PRESETS "<<version<<"\n\"versioned\" 1\n\"versioned\" 1 1 1 -1 0 0 0 1 1 1 1 1 0 0 1 0 1 0";+ if(version>=2) {+ fixture<<" 0 0";+ for(int region=0;region<4;++region)fixture<<" 0 0 0 0";+ }+ if(version>=3)fixture<<" 2";+ if(version>=4)fixture<<" 0";+ if(version>=5)fixture<<" 1";+ if(version>=6)fixture<<" 0 0";+ if(version>=7)fixture<<" 1 137";+ if(version>=9)fixture<<" 0";+ if(version>=10)fixture<<" 1";+ if(version>=11)fixture<<" 0";+ if(version>=12)fixture<<" 0";+ if(version>=14)fixture<<" 0";+ if(version>=15)fixture<<" 60";+ if(version>=16)fixture<<" 1";+ if(version>=17)fixture<<" 1";+ if(version>=18) {+ std::ostringstream color;+ writeColorSettings(color,{},"");+ if(version==18) {+ std::istringstream fields(color.str());+ std::vector<std::string> tokens;+ for(std::string token;fields>>token;)tokens.push_back(token);+ if(tokens.size()<30||tokens[27]!="\"\""||tokens[28]!="0")return false;+ tokens.erase(tokens.begin()+28); // v19 added the bypass mask after the LUT path.+ for(const auto& token:tokens)fixture<<' '<<token;+ } else fixture<<' '<<color.str();+ }+ if(version>=20)fixture<<" 0 100 100 50 1000";+ if(version>=21)fixture<<" 1";+ fixture<<'\n';+ const auto original=fixture.str();+ {std::ofstream file(path,std::ios::binary|std::ios::trunc);file<<original;}+ PresetStore store(path);+ if(!store.load()) {std::cout<<"schema v"<<version<<" load failed\n";return false;}+ if(store.defaultSettings().audioOffsetMs!=(version>=7?137:0)||+ store.defaultSettings().exportBitrateMbps!=(version>=15?60u:0u)||+ store.defaultSettings().captureFlipVertical!=(version>=16)||+ store.defaultSettings().nrTemporal!=(version>=21)) {+ std::cout<<"schema v"<<version<<" fields mismatch\n";return false;+ }+ {+ std::ifstream before(path,std::ios::binary);+ if(std::string(std::istreambuf_iterator<char>(before),{})!=original) {+ std::cout<<"schema v"<<version<<" modified on load\n";return false;+ }+ }+ if(!store.save()) {std::cout<<"schema v"<<version<<" upgrade failed\n";return false;}+ PresetStore upgraded(path);+ if(!upgraded.load()||upgraded.defaultSettings()!=store.defaultSettings()) {+ std::cout<<"schema v"<<version<<" upgrade mismatch\n";return false;+ }+ }+ std::cout<<"v1-v21 preset read, unchanged source, and upgrade roundtrip=1\n";+ return true;+}bool legacyBackends(const std::filesystem::path& path) {using namespace veyra::engine;unsigned checks=0;@@ -66,7 +128,7 @@ bool legacyBackends(const std::filesystem::path& path) {const auto value=store.defaultSettings();if(value.lowLatency||value.forceSdrPreview)return false;if(value.captureCompatible!=(version>=10))return false;- if(value.nrRuntime!=(version>=9?NrRuntime::Community:NrRuntime::Original))return false;+ if(value.nrRuntime!=(version>=9?NrRuntime::Ampere:NrRuntime::Original))return false;const auto expectedBackend=fsr?FrameGenerationBackend::Fsr:xess?FrameGenerationBackend::XeSS:FrameGenerationBackend::Dlss;if(value.frameGenerationBackend!=expectedBackend||value.multiplier!=multiplier||value.videoSrQuality!=2)return false;if(version>=7&&(value.audioSync!=AudioSyncMode::Manual||value.audioOffsetMs!=137))return false;@@ -91,9 +153,17 @@ int main(int argc,char** argv){if(argc!=2)return 2;using namespace veyra::engineauto value=family;const bool expected=selected&&result==0&&(family==0x170u||family==0x171u);ok=ok&&(veyra::ngx::rewriteNrAmpereArchitecture(value,selected,result)==expected)&&value==(expected?0x1B0u:family);}+ // NeuralScreen 310.8.0.0 keeps the rewrite; SF 310.8.2.0 and Lecram 310.8.3.0 do not.+ ok=ok&&veyra::ngx::nrRuntimeNeedsAmpereRewrite((310u<<16)|8u,0u)&&veyra::ngx::nrRuntimeNeedsAmpereRewrite((310u<<16)|8u,1u<<16)+ &&!veyra::ngx::nrRuntimeNeedsAmpereRewrite((310u<<16)|8u,2u<<16)&&!veyra::ngx::nrRuntimeNeedsAmpereRewrite((310u<<16)|8u,3u<<16)+ &&veyra::ngx::nrRuntimeNeedsAmpereRewrite((311u<<16)|0u,0u);s.srTarget=veyra::pipeline::SrTarget::Uhd8K;+ ok=ok&&veyra::ngx::preferSfNr(0x10DE,L"NVIDIA GeForce RTX 2080 Ti")&&veyra::ngx::preferSfNr(0x10DE,L"NVIDIA GeForce RTX 3090")+ &&veyra::ngx::preferSfNr(0x10DE,L"NVIDIA GeForce RTX 4070 SUPER")&&!veyra::ngx::preferSfNr(0x10DE,L"NVIDIA GeForce RTX 5070")+ &&!veyra::ngx::preferSfNr(0x1002,L"RTX 4070")&&!veyra::ngx::preferSfNr(0x10DE,L"Unknown")+ &¤tNrRuntime(NrRuntime::Community)==NrRuntime::Ampere&¤tNrRuntime(NrRuntime::Original)==NrRuntime::Original;s.audioSync=AudioSyncMode::Manual;s.audioOffsetMs=137;-s.nrRuntime=NrRuntime::Community;s.captureCompatible=true;s.lowLatency=true;s.forceSdrPreview=true;+s.nrRuntime=NrRuntime::Ampere;s.captureCompatible=true;s.lowLatency=true;s.forceSdrPreview=true;s.videoHdr={true,110,80,45,800};// Colour grade round-trips through schema v18 (plan P1: named colour presets).s.color.temperature=-40;s.color.tint=7.5f;s.color.exposure=1.25f;s.color.contrast=-12.5f;s.color.highlights=18;s.color.shadows=-22;@@ -115,7 +185,14 @@ auto badExposure=s;badExposure.color.exposure=6;ok=ok&&!b.put(L"invalid exposureauto badHdr=s;badHdr.videoHdr.peakNits=2001;ok=ok&&!b.put(L"invalid HDR peak",badHdr);ok=ok&&b.entries().size()==1&&b.defaultSettings()==s;- auto badTarget=s;badTarget.srTarget=static_cast<veyra::pipeline::SrTarget>(3);ok=ok&&!b.put(L"invalid target",badTarget);+ auto badTarget=s;badTarget.srTarget=static_cast<veyra::pipeline::SrTarget>(6);ok=ok&&!b.put(L"invalid target",badTarget);+ for(auto target:{veyra::pipeline::SrTarget::Uhd5K,veyra::pipeline::SrTarget::Uhd6K,veyra::pipeline::SrTarget::Uhd7K}){+ auto higher=s;higher.srTarget=target;ok=ok&&b.put(L"higher resolution",higher);+ PresetStore reload(p);ok=ok&&reload.load()&&reload.entries().back().settings==higher&&b.erase(1);+ }+ ok=ok&&unsigned(veyra::pipeline::SrTarget::Uhd8K)==2;+ auto rendering=s;rendering.hdrOutputMode=HdrOutputMode::ScRgb;rendering.fgMotion=MotionSource::Zero;rendering.srMotion=MotionSource::Zero;rendering.nrMotion=MotionSource::Zero;+ ok=ok&&b.put(L"rendering",rendering);PresetStore renderReload(p);ok=ok&&renderReload.load()&&renderReload.entries().back().settings==rendering&&b.erase(1);// XeSS presets may request up to 4X since the audited multi-frame unlock; the// engine clamps to the ceiling the provider reports at session start.@@ -130,7 +207,11 @@ ok=ok&&b.entries().size()==1&&b.defaultSettings()==s;fsr.multiplier=2;ok=ok&&b.put(L"FSR 2X",fsr);PresetStore fsrReload(p);ok=ok&&fsrReload.load()&&fsrReload.entries().back().settings==fsr&&b.erase(1);- auto badBackend=s;badBackend.frameGenerationBackend=static_cast<FrameGenerationBackend>(3);ok=ok&&!b.put(L"invalid backend",badBackend);+ auto fsr4=fsr;fsr4.frameGenerationBackend=FrameGenerationBackend::Fsr4;+ ok=ok&&b.put(L"FSR 4 ML 2X",fsr4);PresetStore fsr4Reload(p);+ ok=ok&&fsr4Reload.load()&&fsr4Reload.entries().back().settings==fsr4&&b.erase(1);+ fsr4.multiplier=4;ok=ok&&!b.put(L"FSR 4 ML 4X rejected",fsr4);+ auto badBackend=s;badBackend.frameGenerationBackend=static_cast<FrameGenerationBackend>(4);ok=ok&&!b.put(L"invalid backend",badBackend);auto dis=s;dis.opticalFlowBackend=OpticalFlowBackend::GpuDis;ok=ok&&b.put(L"GPU DIS",dis)&&b.save();PresetStore disReload(p);ok=ok&&disReload.load()&&disReload.entries().back().settings==dis&&b.erase(1);auto badFlow=s;badFlow.opticalFlowBackend=static_cast<OpticalFlowBackend>(3);ok=ok&&!b.put(L"invalid flow backend",badFlow);@@ -162,6 +243,51 @@ ok=ok&&b.entries().size()==1&&b.defaultSettings()==s;auto buffers=s;buffers.captureBuffer=veyra::source::CaptureBufferMode::Minimum;ok=ok&&b.put(L"capture buffer",buffers);PresetStore bufferReload(p);ok=ok&&bufferReload.load()&&bufferReload.entries().size()==1&&bufferReload.entries().back().settings.captureBuffer==veyra::source::CaptureBufferMode::Minimum&&b.erase(0);auto badBuffer=s;badBuffer.captureBuffer=static_cast<veyra::source::CaptureBufferMode>(3);ok=ok&&!b.put(L"invalid buffer",badBuffer);+ auto multi=s;multi.additionalColorCount=5;+ for(unsigned i=0;i<5;++i){multi.additionalColors[i].enabled=i!=2;multi.additionalColors[i].exposure=float(i)*.25f;multi.additionalColors[i].setLutName(L"grade-"+std::to_wstring(i)+L".cube");}+ ok=ok&&b.put(L"six colors",multi);PresetStore multiReload(p);+ ok=ok&&multiReload.load()&&multiReload.entries().size()==1&&multiReload.entries()[0].settings==multi&&b.erase(0);+ // Six grades must not reduce the advertised 64-preset capacity. Exercise+ // full curves and long Unicode LUT names, not just mostly-zero defaults.+ {+ auto dense=multi;+ auto fill=[](ColorSettings& color){+ color.enabled=true;color.setLutName(std::wstring(220,L'色')+L".cube");+ for(auto& curve:color.curves){curve.count=kColorCurvePoints;+ for(int j=0;j<kColorCurvePoints;++j)curve.points[j]={float(j)/7.0f,float(j*j)/49.0f};}+ };+ fill(dense.color);for(auto& color:dense.additionalColors)fill(color);+ auto fullPath=p;fullPath+=L".capacity";PresetStore full(fullPath);bool capacity=full.load();+ for(unsigned i=0;i<64&&capacity;++i)capacity=full.put(L"six-grade-"+std::to_wstring(i),dense);+ PresetStore loaded(fullPath);capacity=capacity&&loaded.load()&&loaded.entries().size()==64;+ for(const auto& entry:loaded.entries())capacity=capacity&&entry.settings==dense;+ std::cout<<"64 six-grade presets full-curve/Unicode roundtrip="<<capacity<<'\n';ok=capacity&&ok;+ auto hugePath=p;hugePath+=L".oversized";const size_t bytes=2u*1024u*1024u+1;+ {std::ofstream f(hugePath,std::ios::binary);f<<std::string(bytes,'x');}+ PresetStore huge(hugePath);ok=!huge.load()&&!huge.put(L"do not overwrite",{})&&std::filesystem::file_size(hugePath)==bytes&&ok;+ }+ {+ auto stackPath=p;stackPath+=L".nr-stack-v23";PresetStore stack(stackPath);+ EnhancementSettings layers;layers.nr=true;layers.nrLayerCount=4;layers.additionalColorCount=1;+ layers.additionalColors[0].exposure=.75f;+ for(unsigned i=0;i<4;++i){auto& n=layers.nrLayers[i];n.enabled=i!=1;+ n.sizePolicy=static_cast<veyra::pipeline::NrSizePolicy>(i);+ n.model.skin=1.5f;n.model.intensity=.25f*float(i+1);n.residual.total=.3f*float(i+1);n.temporal=(i%2)!=0;}+ bool roundtrip=stack.load()&&stack.put(L"four-independent-NR",layers);+ PresetStore loaded(stackPath);roundtrip=roundtrip&&loaded.load()&&loaded.entries().back().settings==layers;+ std::cout<<"NR v23 four layers mixed sizes bypass/model/residual/color roundtrip="<<roundtrip<<'\n';ok=roundtrip&&ok;+ // v24: per-layer tiers and the stabiliser pair, stored beside a default entry+ // in the same file (every row must then carry the v24 fields consistently).+ auto tierPath=p;tierPath+=L".nr-stack-v24";PresetStore tiers(tierPath);+ auto tiered=layers;tiered.nrHoldStrength=.6f;tiered.nrHoldTolerance=.05f;+ const NrAntiFlicker kinds[]={NrAntiFlicker::Off,NrAntiFlicker::Static,NrAntiFlicker::FlowPlus,NrAntiFlicker::LowFrequency};+ for(unsigned i=0;i<4;++i)tiered.nrLayers[i].antiFlicker=kinds[i];+ bool v24=tiers.load()&&tiers.put(L"plain-stack",layers)&&tiers.put(L"tiered-stack",tiered);+ PresetStore tierLoaded(tierPath);v24=v24&&tierLoaded.load()&&tierLoaded.entries().size()==2;+ for(const auto& e:v24?tierLoaded.entries():std::vector<UserPreset>{})v24=v24&&e.settings==(e.name==L"tiered-stack"?tiered:layers);+ std::ifstream header(tierPath);std::string magic;int written=0;v24=v24&&(header>>magic>>written)&&written==24;+ std::cout<<"NR v24 per-layer tiers and stabiliser with a default entry roundtrip="<<v24<<'\n';ok=v24&&ok;+ }{std::ofstream legacy(p);legacy<<"VEYRA_PRESETS 1\n\"legacy\" 1\n\"legacy\" 1 1 1 -1 0 0 0 1 1 1 1 1 1 0 1 0 1 0\n";}PresetStore old(p);ok=ok&&old.load()&&!old.defaultSettings().protection.enabled&&old.defaultSettings().srTarget==veyra::pipeline::SrTarget::Uhd4K&&old.put(L"v2",s);PresetStore upgraded(p);ok=ok&&upgraded.load()&&upgraded.entries().size()==2&&upgraded.entries()[1].settings==s;@@ -169,6 +295,6 @@ ok=ok&&b.entries().size()==1&&b.defaultSettings()==s;{std::ofstream f(p);f<<"VEYRA_PRESETS 99\ncorrupt mediaPath executable must reject";}PresetStore c(p);const bool corruptLoaded=c.load();const bool corruptPut=c.put(L"override",{});std::ifstream f(p);std::string data((std::istreambuf_iterator<char>(f)),{});const bool corruptPreserved=data=="VEYRA_PRESETS 99\ncorrupt mediaPath executable must reject";ok=ok&&!corruptLoaded&&!corruptPut&&corruptPreserved;- f.close();ok=legacyBackends(p)&&ok;ok=retiredSrMode(p)&&ok;+ f.close();ok=legacyBackends(p)&&ok;ok=retiredSrMode(p)&&ok;ok=schemaVersions(p)&&ok;std::cout<<"preset roundtrip, all fields, duplicate, rename-default, delete, validation, unknown schema, corrupt-preservation="<<ok<<'\n';return ok?0:1;}diff --git a/tools/fg_harness/fg_test.cpp b/tools/fg_harness/fg_test.cppindex 5c3528b5..1149c116 100644--- a/tools/fg_harness/fg_test.cpp+++ b/tools/fg_harness/fg_test.cpp@@ -16,6 +16,7 @@#include <cstring>#include <format>#include <fstream>+#include <numeric>#include <string>#include <vector>@@ -27,6 +28,7 @@#include "veyra/gfx/D3D12DeviceContext.h"#include "veyra/ngx/NgxCoreHost.h"#include "veyra/ngx/DlssFgBackend.h"+#include "veyra/ngx/DlssgTransfusion.h"#include "veyra/ngx/NgxParameters.h"namespace veyra::harness {@@ -367,7 +369,8 @@ void copyUploadToTexture(ID3D12GraphicsCommandList* list, ID3D12Resource* dst,// history (F3 precondition, review 2026-09-22). Position/uniqueness checks// apply to every generated frame; group 1 expects the midpoint.static bool runPlanarSix(veyra::gfx::CommandSlotRing& ring,- veyra::ngx::NgxCoreHost& core, NVSDK_NGX_Parameter* params, GpuTextures& t, bool alternateGroups=false)+ veyra::ngx::NgxCoreHost& core, NVSDK_NGX_Parameter* params, GpuTextures& t, bool alternateGroups=false,+ const std::wstring& captureDir={}){veyra::Status status = veyra::Status::Ok;veyra::ngx::DlssFgBackend fg;@@ -376,6 +379,9 @@ static bool runPlanarSix(veyra::gfx::CommandSlotRing& ring,if (!list || !fg.create(core,list,params,create,status) || !ring.submitAndSignal(0) || !ring.waitIdle()) return false;std::vector<uint8_t> previous(kRowPitch*kHeight), current(previous.size());unsigned generated=0, accurate=0, distinct=0;+ std::vector<double> evaluateMs;+ uint64_t sequenceHash=14695981039346656037ull;+ LARGE_INTEGER frequency{};QueryPerformanceFrequency(&frequency);bool ok=true;for (unsigned frame=0; ok && frame<12; ++frame) {for(unsigned y=0;y<kHeight;++y)for(unsigned x=0;x<kWidth;++x){@@ -414,7 +420,10 @@ static bool runPlanarSix(veyra::gfx::CommandSlotRing& ring,list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);list->CopyBufferRegion(t.readbackFlag.Get(),0,t.disableFlag.Get(),0,4);for(unsigned j=3;j<5;++j){barriers[j].Transition.StateBefore=D3D12_RESOURCE_STATE_COPY_SOURCE;barriers[j].Transition.StateAfter=D3D12_RESOURCE_STATE_COMMON;}list->ResourceBarrier(2,barriers+3);+ LARGE_INTEGER begin{},end{};QueryPerformanceCounter(&begin);ok=ring.submitAndSignal(0)&&ring.waitIdle()&&ok;if(!ok)break;+ QueryPerformanceCounter(&end);+ if(frame>=2)evaluateMs.push_back(double(end.QuadPart-begin.QuadPart)*1000.0/double(frequency.QuadPart));if(!frame)continue;uint8_t* pixels=nullptr;uint8_t* flag=nullptr;if(FAILED(t.readbackInterp->Map(0,nullptr,reinterpret_cast<void**>(&pixels)))){ok=false;break;}@@ -435,7 +444,10 @@ static bool runPlanarSix(veyra::gfx::CommandSlotRing& ring,const double expectedShift=16.0*sub/(groupCount+1);const bool position=std::abs(shift-expectedShift)<=1.0;++generated;distinct+=unique;accurate+=position&&unique&&!*flag;previousHash=hash;- log::info("fg-planar6",std::format("frame={} group={} sub={} expected={:.3f} observed={:.3f} distinct={} disabled={} positionPass={}",frame,groupCount,sub,expectedShift,shift,unique,unsigned(*flag),position));+ sequenceHash=(sequenceHash^hash)*1099511628211ull;+ log::info("fg-planar6",std::format("frame={} group={} sub={} expected={:.3f} observed={:.3f} distinct={} disabled={} positionPass={} hash=0x{:016X}",frame,groupCount,sub,expectedShift,shift,unique,unsigned(*flag),position,hash));+ if(!captureDir.empty())+ writeRgbaPng(captureDir+L"\\gen_"+std::to_wstring(frame)+L"_"+std::to_wstring(sub)+L".png",pixels,kWidth,kHeight,kRowPitch);t.readbackInterp->Unmap(0,nullptr);t.readbackFlag->Unmap(0,nullptr);}previous=current;@@ -444,7 +456,10 @@ static bool runPlanarSix(veyra::gfx::CommandSlotRing& ring,// 12 frames: frame 0 is the reset seed (its outputs are not scored).// Fixed 5: 11*5=55. Alternating 1/5 from frame 1: odd frames 5, even frames 1 -> 6*5+5*1=35.const unsigned expectedGenerated=alternateGroups?35u:55u;- log::info("fg-planar6",std::format("directNGX=true alternateGroups={} generated={} distinct={} contentValid={} expected={} graphUsed=false",alternateGroups,generated,distinct,accurate,expectedGenerated));+ std::sort(evaluateMs.begin(),evaluateMs.end());+ const double medianMs=evaluateMs.empty()?0.0:evaluateMs[evaluateMs.size()/2];+ const double meanMs=evaluateMs.empty()?0.0:std::accumulate(evaluateMs.begin(),evaluateMs.end(),0.0)/double(evaluateMs.size());+ log::info("fg-planar6",std::format("directNGX=true alternateGroups={} generated={} distinct={} contentValid={} expected={} graphUsed=false sequenceHash=0x{:016X} evaluateSubmitWaitMs median={:.3f} mean={:.3f} samples={}",alternateGroups,generated,distinct,accurate,expectedGenerated,sequenceHash,medianMs,meanMs,evaluateMs.size()));return ok&&drained&&generated==expectedGenerated&&accurate==expectedGenerated;}@@ -782,10 +797,34 @@ int runFgTest(const FgTestArgs& args)}if (projectId.empty()) { ring.shutdown(); context.shutdown(); return 7; }+ // Diagnostic 310.9.1 provider patches, installed before NGX Init exactly+ // like FgCompatibilitySession::open does in the product.+ HMODULE transfusionProvider = nullptr;+ if (!args.transfusion.empty()) {+ const std::wstring provider = std::wstring(absRuntimeDir) + L"\\nvngx_dlssg.dll";+ if (!veyra::ngx::DlssgTransfusion::moduleIsKnown(provider)) { log::error("fg-test", "transfusion: provider is not the pinned 310.9.1 build"); ring.shutdown(); context.shutdown(); return 13; }+ transfusionProvider = LoadLibraryExW(provider.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32);+ const auto target = args.transfusion == "ampere" ? veyra::ngx::DlssgTransfusion::Target::Ampere : veyra::ngx::DlssgTransfusion::Target::Ada;+ const auto state = transfusionProvider ? veyra::ngx::DlssgTransfusion::apply(transfusionProvider, target,+ veyra::ngx::DlssgTransfusion::defaultOptions(std::wstring(absRuntimeDir) + L"\\dlssg-kernels")) : veyra::ngx::DlssgTransfusion::State{};+ log::info("fg-test", std::format("transfusion target={} applied={} detail={}", args.transfusion, state.applied, narrowText(state.detail)));+ if (!state.applied) { ring.shutdown(); context.shutdown(); return 13; }+ }+ auto releaseTransfusion = [&]() {+ if (!transfusionProvider) return;+ const auto c = veyra::ngx::DlssgTransfusion::counters();+ log::info("fg-test", std::format("transfusion counters nvapi={} modules accepted={} rejected={} rewritten={} exact={} networkReady={} networkFailed={} dl1Runs={} dl2Runs={}",+ c.nvapiResolutions, c.modulesAccepted, c.modulesRejected, c.modulesRewritten, c.exactProviderKernels, c.networkReady, c.networkFailed, c.optimizedDl1Runs, c.optimizedDl2Runs));+ const bool restored = veyra::ngx::DlssgTransfusion::release();+ log::info("fg-test", std::format("transfusion release restored={}", restored));+ FreeLibrary(transfusionProvider);+ transfusionProvider = nullptr;+ };+veyra::ngx::NgxCoreHost coreHost;if (!coreHost.initialize(context.device(), absRuntimeDir,projectId.c_str(), engineVersion.c_str(), status)) {- ring.shutdown(); context.shutdown(); return 8;+ releaseTransfusion(); ring.shutdown(); context.shutdown(); return 8;}// Capability query.@@ -847,8 +886,8 @@ int runFgTest(const FgTestArgs& args)}if(args.planarSix){- const bool passed=caps.multiFrameCountMax>=5&&runPlanarSix(ring,coreHost,params,textures,args.alternateGroups);- coreHost.destroyParameters(params);coreHost.shutdown();ring.shutdown();context.shutdown();+ const bool passed=caps.multiFrameCountMax>=5&&runPlanarSix(ring,coreHost,params,textures,args.alternateGroups,args.captureDir);+ coreHost.destroyParameters(params);coreHost.shutdown();releaseTransfusion();ring.shutdown();context.shutdown();return passed?0:1;}diff --git a/tools/fg_harness/fg_test.h b/tools/fg_harness/fg_test.hindex cf8f0b17..5f2fad4b 100644--- a/tools/fg_harness/fg_test.h+++ b/tools/fg_harness/fg_test.h@@ -19,6 +19,9 @@ struct FgTestArgs {bool capabilityOnly = false; // --fg-cap: query + honest JSON, no createbool planarSix = false; // Direct NGX diagnostic; no player/EnhanceGraph.bool alternateGroups = false; // planarSix with multiFrameCount 1/5 alternating, no reset.+ // "ada" or "ampere": patch the 310.9.1 provider with DlssgTransfusion before+ // NGX Init (diagnostic; on non-Ada/Ampere hosts this forces that path).+ std::string transfusion;};// Runs the full FG truth test and writes JSON to args.jsonFile.diff --git a/tools/fg_harness/main.cpp b/tools/fg_harness/main.cppindex 97503e31..7746e00a 100644--- a/tools/fg_harness/main.cpp+++ b/tools/fg_harness/main.cpp@@ -21,7 +21,7 @@ void printUsage()std::fprintf(stderr,"usage: veyra_fg_harness --fg-cap | --fg-test | --fg-planar6 | --fg-planar-alt | --audio-test\n"" [--runtime-dir DIR] [--run-id ID] [--log-file FILE] [--json-file FILE]\n"- " [--capture-dir DIR]\n");+ " [--capture-dir DIR] [--dlssg-transfusion ada|ampere]\n");}} // namespace@@ -35,6 +35,7 @@ int main(int argc, char** argv)std::wstring runtimeDir;std::string runId = "fg-harness";std::wstring logFile, jsonFile, captureDir;+ std::string transfusion;for (int i = 1; i < argc; ++i) {const std::string arg = argv[i];@@ -44,6 +45,7 @@ int main(int argc, char** argv)else if (arg == "--fg-planar-alt") { doFgTest = true; planarSix = true; alternateGroups = true; }else if (arg == "--audio-test") doAudio = true;else if (arg == "--run-id" && i + 1 < argc) runId = argv[++i];+ else if (arg == "--dlssg-transfusion" && i + 1 < argc) transfusion = argv[++i];else if (arg == "--runtime-dir" && i + 1 < argc) {const std::string value = argv[++i];runtimeDir.assign(value.begin(), value.end());@@ -86,6 +88,7 @@ int main(int argc, char** argv)args.captureDir = captureDir;args.planarSix = planarSix;args.alternateGroups = alternateGroups;+ args.transfusion = transfusion;return runFgTest(args);}AudioTestArgs args{};