Skip to content

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++

Release 1.4.2: screen capture, HDR fixes and fullscreen tooltip repair

Veyra Goal Agent02c413404382
diff --git a/AGENTS.md b/AGENTS.md
index 7c41e3f9..a39ab3f8 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,5 +1,7 @@
# Veyra 项目 Agent 执行规则
+> 2026-09-19 用户授权修复全屏提示后构建并发布 1.4.2 至 Likely7/Veyra-NRVideo,整合本轮隔离修复到 main,更新双语 README 与 Release,重点说明 RTX Video HDR 和帧同步。授权公开本次新交流群二维码与 RTX Video HDR 对比图;赞助图保留,双二维码各 width=220。允许正式包携带已核验 TrueHDR 原件:RTX Video SDK 1.1.0,nvngx_truehdr.dll,3955752 bytes,1.1.0.0,Valid/NVIDIA,SHA256 9A80575F247190C05FE80EAC0C4BAA1D0D4D932348F26808310B5EC4BF9EEB4B,独立 manifest 与 NVIDIA_RTX_VIDEO_SDK_LICENSE.pdf。其余运行组件身份沿用;NVIDIA FSR4 实验保持撤回。执行记录见 docs/RELEASE_1.4.2_EXECUTION.md。本条取代此前仅本地测试包的发布范围限制。
+
> 2026-09-18 用户授权目标模式实施可关闭帧同步、多模式与实际延迟验收。开工存档 `6e69eeb` / `checkpoint/pre-frame-pacing-20260918`,隔离分支 `codex/frame-pacing-20260918`。按 `docs/FRAME_PACING_EXECUTION_PLAN_2026-09-18.md` 施工,默认关闭、直接 NGX、保留 6X,不推送或发布。报告必须区分进程内排队、系统显示事件与未测量的屏幕端到端延迟。
> 本轮交付状态见 `docs/FRAME_PACING_ACCEPTANCE_2026-09-18.md`:本机软件短测完成,原生 Reflex 仅无补帧路径;FG 下显示回退低排队,XeSS 不叠加外部节奏。不得将软件驻留减少冒充屏幕延迟降低,不得把本机 RTX5070 验收扩展为 30/40、实卡采集、PS5 或 VRR 通过。完整 Reflex+FG 与显示延迟验收仍未完成;现有 beta 包不含本轮改动。
diff --git a/CMakeLists.txt b/CMakeLists.txt
index c23f4b4b..56313e6a 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -489,6 +489,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
src/source/NativeCaptureSink.cpp
src/source/MediaFileSource.cpp
src/source/CaptureCardSource.cpp
+ src/source/ScreenCaptureSource.cpp
src/source/AverMediaAudioSwitch.cpp
src/source/CaptureCompressedDecoder.cpp
src/source/WasapiAudioInput.cpp
@@ -502,6 +503,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_include_directories(veyra_sources PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(veyra_sources PUBLIC veyra_pipeline veyra_media veyra_base)
target_link_libraries(veyra_sources PRIVATE ${FFMPEG_LIBRARIES} strmiids ole32 oleaut32 d3d12 dxgi)
+ target_link_libraries(veyra_sources PRIVATE d3d11 windowsapp dwmapi)
if(VEYRA_ENABLE_REMOTEPLAY)
set(VEYRA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}")
@@ -523,6 +525,10 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_link_libraries(veyra_source_tests PRIVATE veyra_sources)
add_executable(veyra_capture_tests tests/integration/CaptureSourceTests.cpp)
+ add_executable(veyra_screen_capture_tests tests/integration/ScreenCaptureTests.cpp)
+ target_compile_features(veyra_screen_capture_tests PRIVATE cxx_std_20)
+ target_compile_definitions(veyra_screen_capture_tests PRIVATE UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)
+ target_link_libraries(veyra_screen_capture_tests PRIVATE veyra_engine dwmapi)
add_executable(veyra_wasapi_input_tests tests/integration/WasapiInputTests.cpp)
target_compile_features(veyra_wasapi_input_tests PRIVATE cxx_std_20)
target_compile_definitions(veyra_wasapi_input_tests PRIVATE UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)
@@ -828,6 +834,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_compile_definitions(veyra_hdr_color_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
target_link_libraries(veyra_hdr_color_tests PRIVATE veyra_engine)
add_executable(veyra WIN32 apps/veyra/main.cpp apps/veyra/ui/AppShell.cpp apps/veyra/ui/CapturePanel.cpp apps/veyra/ui/SubtitleOverlay.cpp apps/veyra/SettingsWindow.cpp apps/veyra/TelemetryWindow.cpp)
+ target_sources(veyra PRIVATE apps/veyra/ui/ScreenCapturePanel.cpp)
if(VEYRA_ENABLE_REMOTEPLAY)
add_executable(veyra_ps5_hw_image_tests tests/integration/Ps5HardwareImageTests.cpp)
add_executable(veyra_ps5_quality_tests tests/integration/Ps5SourceQualityTests.cpp)
diff --git a/README.md b/README.md
index ca7877b2..2d66f18a 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,11 @@
[English](README_EN.md) | 简体中文
-[当前状态与开发任务](docs/CURRENT_STATUS.md) · [本机构建](docs/BUILD.md)。正式版为 1.4.1;1.4.2beta 已本地交付 RTX Video HDR 内测,NVIDIA FSR 4.1 实验已撤回。隔离分支已实现默认关闭的帧同步,入口为专业模式 → 运动 → 帧同步;[本机验收与延迟报告](docs/FRAME_PACING_ACCEPTANCE_2026-09-18.md)记录适用范围,尚未加入现有内测包。
+[当前状态与开发任务](docs/CURRENT_STATUS.md) · [本机构建](docs/BUILD.md)。正式版 **1.4.2** 新增 RTX Video HDR、可关闭的帧同步、屏幕采集、图形字幕和命名调色预设,并修复采集 HDR、XeSS 与界面细节。[完整更新说明](docs/RELEASE_NOTES_1.4.2.md)。
+
+采集卡连接设置新增 **设备帧率 FPS**:手输 30、40 或小数,0 沿用所选格式,重新连接生效。直接请求设备输出该帧率,失败明确报错;不是软件丢帧限速,也不承诺识别并删除游戏重复画面。实卡是否接受由驱动与所选分辨率/格式决定。
+
+新增 **专业模式 → 左侧屏幕采集(窗口图标)**:窗口 / 显示器选择、预览、裁剪、鼠标指针与帧率上限,默认跟随采集目标所在显示器的刷新率,也可手动选择,接入现有增强链。只采集画面,声音由原应用直接播放,可能领先经过增强的画面。本机 WGC / DXGI 采集和 NR + DLSS 4X 短测通过;多显卡和各类游戏兼容性仍需按设备验证。详见[实现与验证记录](docs/SCREEN_CAPTURE_PLAN_2026-09-19.md)。
<p align="center">
<a href="https://github.com/Likely7/Veyra-NRVideo/blob/main/REAMDE%20MP4.mp4">
@@ -15,7 +19,18 @@
Windows 视频播放器与采集卡增强工具。支持视频、图片、采集卡实时预览和 PS5 局域网串流,可组合使用超分辨率、NR 画面增强与补帧。
-[下载 1.4.1 免安装版](https://github.com/Likely7/Veyra-NRVideo/releases/tag/v1.4.1) · [更新记录](docs/RELEASE_NOTES_1.4.1.md) · [反馈问题](https://github.com/Likely7/Veyra-NRVideo/issues)
+[下载 1.4.2 免安装版](https://github.com/Likely7/Veyra-NRVideo/releases/tag/v1.4.2) · [更新记录](docs/RELEASE_NOTES_1.4.2.md) · [反馈问题](https://github.com/Likely7/Veyra-NRVideo/issues)
+
+## 1.4.2 更新
+
+**RTX Video HDR**:在专业模式的增强设置中开启,将 SDR 视频转换为 HDR,可调整对比度、饱和度、中间灰和峰值亮度,与 NR、超分和补帧组合,支持 HEVC Main10 HDR 导出。HDR 预览需要兼容的 HDR 显示器并开启 Windows HDR;SDR 屏保持 SDR,导出不要求 HDR 屏。集成的是视频版技术,不是游戏 RTX HDR。
+
+**帧同步**:专业模式 → 运动 → 帧同步,默认关闭,可选低排队、均匀呈现(前端同步)、NVIDIA Reflex(实验)。用于控制排队与提交节奏,不凭空提高性能;开启补帧时 Reflex 明确回退低排队,XeSS 保持自身调度。[延迟实测与边界](docs/FRAME_PACING_ACCEPTANCE_2026-09-18.md)。
+
+**其他更新**:窗口/显示器画面采集、手动协商采集卡设备帧率、MKV 图形字幕、命名调色预设;修复全屏提示残留、PS5 入口遮挡、滚动残影、选框闪烁、部分 HDR 红色异常和 XeSS 呈现资源问题。撤回 NVIDIA FSR 4.1 画质实验,保留 RTX 超分。
+
+<p align="center"><img src="docs/images/1.4.2/rtx-video-hdr-comparison.jpg" alt="用户提供 RTX Video HDR 关闭与开启对比" width="720"></p>
+<p align="center"><small>用户拍摄对比:上图关闭,下图开启。照片仅展示该设备下的观感,不是原始 HDR 像素或显示器亮度测量。</small></p>
## 1.4.1 更新
@@ -46,7 +61,7 @@ Windows 视频播放器与采集卡增强工具。支持视频、图片、采集
## 下载与运行
-1. 在 [Releases](https://github.com/Likely7/Veyra-NRVideo/releases) 下载 **Veyra-1.4.1-win64-portable.zip**,不要下载 Source code。
+1. 在 [Releases](https://github.com/Likely7/Veyra-NRVideo/releases) 下载 **Veyra-1.4.2-win64-portable.zip**,不要下载 Source code。
2. 完整解压到一个可写文件夹,双击 **Veyra.exe**。无需安装 SDK、Python 或开发工具。
首次启动 NR、超分和内部补帧均关闭,确认基础画面后按需开启;导入旧设置会恢复原来的开关。
3. 使用当前显卡驱动。要使用 NVIDIA NR、DLSS、RTX Video SR 和 NVENC,需兼容的 NVIDIA RTX 显卡;本版本主要在 RTX 5070 上验证。
@@ -141,13 +156,13 @@ NR 与 DLSS 帧生成属于 **community experimental / 社区实验集成**,
## 开发与许可
-[构建说明](docs/BUILD.md) · [组件清单](docs/RUNTIME_COMPONENTS_1.4.1.md) · [第三方许可](THIRD_PARTY_NOTICES.md)
+[构建说明](docs/BUILD.md) · [组件清单](docs/RUNTIME_COMPONENTS_1.4.2.md) · [第三方许可](THIRD_PARTY_NOTICES.md)
Veyra 原有源码采用 [GPLv3](LICENSE);含串流的组合程序同时适用 [AGPLv3 与上游 OpenSSL 例外](licenses/remoteplay/CHIAKI_AGPL3_OPENSSL.txt)。应用源码对应版本标签,Release 另附串流依赖与 FFmpeg 对应源码包,普通用户无需下载。SDK、模型和运行时不进入源码仓库;Release 组件按各自许可与实验发布范围单独提供。
-## HDR 与 5.1(当前 1.4.1)
+## HDR 与 5.1(当前 1.4.2)
-原生 HDR 能力自 1.2.0 引入并保留至 1.4.1;SDR 转 RTX Video HDR 是独立的新开发任务。真实 HDR 屏、5.1 扬声器和不同采集卡仍须逐台验收。1.4.0 起采集 Dolby/DTS 可解码到 PCM,不等于压缩码流直通。
+保留原生 HDR 能力,1.4.2 新增 SDR 转 RTX Video HDR。真实 HDR 屏、5.1 扬声器和不同采集卡仍须逐台验收。1.4.0 起采集 Dolby/DTS 可解码到 PCM,不等于压缩码流直通。
- **HDR 输入 / 增强**:文件、P010/P016 采集与 PS5 HDR;支持明确标记的 BT.2020 NCL / PQ 或 HLG。Windows HDR 开启时,可组合 NR、DLSS SR / RTX Video SR、DLSS / XeSS 补帧。NR / Video SR 使用 SDR 代理和 HDR 基底合成,压缩高光和近黑区域的增强会衰减;不把 SDR 结果逆造为原始 HDR。HLG 使用 1000nit / gamma 1.2 参考转换。
- **SDR 显示开关**:采集卡面板的“转为 SDR 显示”默认关闭,控制所有实时预览。打开后将 HDR 映射为 SDR,增强照常可用;播放中切换无需重连,可能短暂停顿。关闭后跟随显示器 HDR 状态。截图跟随当前画面,视频导出保持原有 HDR 规则。
@@ -170,6 +185,6 @@ Veyra 原有源码采用 [GPLv3](LICENSE);含串流的组合程序同时适用
<p align="center">
<img src="docs/images/1.4.0/donate-wechat.jpg" alt="微信赞助" width="220">
&nbsp;&nbsp;&nbsp;&nbsp;
- <img src="docs/images/1.4.0/community-group.jpg" alt="Veyra 交流群 / bug 反馈 / beta 测试" width="220">
+ <img src="docs/images/1.4.2/community-group.png" alt="Veyra 交流群 / bug 反馈 / beta 测试" width="220">
</p>
<p align="center"><small>左:微信赞助(自愿,不影响任何功能的可用性) 右:Veyra 交流群——bug 反馈与 beta 版本发布</small></p>
diff --git a/README_EN.md b/README_EN.md
index 85b291c5..935a0606 100644
--- a/README_EN.md
+++ b/README_EN.md
@@ -4,7 +4,7 @@
English | [简体中文](README.md)
-[Current status and development](docs/CURRENT_STATUS.md) · [Build instructions](docs/BUILD.md). The released version is 1.4.1. The local 1.4.2beta package includes RTX Video HDR; the NVIDIA FSR 4.1 experiment was reverted. Optional frame pacing is implemented on an isolated branch, disabled by default, under Professional mode > Motion. See the [local acceptance and latency report](docs/FRAME_PACING_ACCEPTANCE_2026-09-18.md); this change is not in the existing beta package. Native Reflex is experimental without frame generation; with FG it explicitly falls back to low queue mode while preserving the multiplier.
+[Current status](docs/CURRENT_STATUS.md) · [Build instructions](docs/BUILD.md). **1.4.2** adds RTX Video HDR, optional frame pacing, window/display capture, bitmap subtitles and named grading presets. See the [release notes](docs/RELEASE_NOTES_1.4.2.md).
<p align="center">
<a href="https://github.com/Likely7/Veyra-NRVideo/blob/main/REAMDE%20MP4.mp4">
@@ -16,7 +16,18 @@ English | [简体中文](README.md)
A Windows video player and capture-card enhancement tool. Play videos, process images, and preview capture devices with optional super resolution, NR enhancement, and frame generation.
-[Download 1.4.1 Portable](https://github.com/Likely7/Veyra-NRVideo/releases/tag/v1.4.1) · [Release Notes](docs/RELEASE_NOTES_1.4.1.md) · [Report an Issue](https://github.com/Likely7/Veyra-NRVideo/issues)
+[Download 1.4.2 Portable](https://github.com/Likely7/Veyra-NRVideo/releases/tag/v1.4.2) · [Release Notes](docs/RELEASE_NOTES_1.4.2.md) · [Report an Issue](https://github.com/Likely7/Veyra-NRVideo/issues)
+
+## 1.4.2 Update
+
+**RTX Video HDR** converts SDR content to HDR under Professional mode > Enhancement, with contrast, saturation, middle gray and peak brightness controls. It combines with NR, SR and frame generation and supports HEVC Main10 HDR export. HDR preview requires an HDR display with Windows HDR enabled; SDR displays retain SDR, and HDR export needs no HDR display. This is the video technology, not game RTX HDR.
+
+**Optional frame pacing** under Professional mode > Motion defaults to Off. Choose Low Queue, Uniform Presentation (front-end pacing), or experimental NVIDIA Reflex. With FG, Reflex explicitly falls back to Low Queue; XeSS retains provider scheduling. These options manage queuing and cadence, not GPU throughput. See the [measured latency report](docs/FRAME_PACING_ACCEPTANCE_2026-09-18.md).
+
+Also adds window/display video capture (no audio), editable device FPS negotiated directly with the capture driver, MKV bitmap subtitles and named grading presets. Fixes fullscreen tooltip residue, the obscured PS5 button, scrolling/hover repaint issues, partial HDR metadata/color handling and XeSS presentation resources. The NVIDIA FSR 4.1 experiment was reverted.
+
+<p align="center"><img src="docs/images/1.4.2/rtx-video-hdr-comparison.jpg" alt="User RTX Video HDR off/on comparison" width="720"></p>
+<p align="center"><small>User camera comparison: top off, bottom on. This illustrates one setup; it is not raw HDR pixel fidelity or display luminance measurement.</small></p>
## 1.4.1 Update
@@ -68,7 +79,7 @@ Features introduced in 1.2.0 include HDR file/capture enhancement, HDR10 export
## Download and Run
-1. Download **Veyra-1.4.1-win64-portable.zip** from [Releases](https://github.com/Likely7/Veyra-NRVideo/releases). The Source code archives are for developers.
+1. Download **Veyra-1.4.2-win64-portable.zip** from [Releases](https://github.com/Likely7/Veyra-NRVideo/releases). The Source code archives are for developers.
2. Extract the entire archive into a writable directory and run **Veyra.exe**. No SDK, Python, or development tools are needed.
NR, upscaling and internal frame generation start disabled. Enable them as needed; importing old preferences restores their switches.
3. Use a current GPU driver. NVIDIA NR, DLSS, RTX Video SR, and NVENC require compatible NVIDIA RTX hardware; this version was primarily tested on an RTX 5070.
@@ -153,7 +164,7 @@ NR and DLSS frame generation are **community-experimental integrations**, not NV
## Development and License
-[Build Instructions](docs/BUILD.md) · [Runtime Components](docs/RUNTIME_COMPONENTS_1.4.1.md) · [Third-Party Notices](THIRD_PARTY_NOTICES.md)
+[Build Instructions](docs/BUILD.md) · [Runtime Components](docs/RUNTIME_COMPONENTS_1.4.2.md) · [Third-Party Notices](THIRD_PARTY_NOTICES.md)
Original Veyra source is [GPLv3](LICENSE); the combined streaming program also falls under [AGPLv3 and the upstream OpenSSL exception](licenses/remoteplay/CHIAKI_AGPL3_OPENSSL.txt). Application source matches the release tag. The RemotePlay-source and FFmpeg-source assets provide dependency source and are not needed to run the player. SDKs, models, and runtimes are excluded from this source repository. Release components retain their separate licenses and experimental distribution boundaries.
@@ -171,9 +182,9 @@ multiple instances to the same target file.
In Professional mode, click **Screenshot** in the top toolbar to save the latest processed full-resolution picture under **Pictures / Veyra Screenshots**: PNG for SDR and floating-point JPEG XR (`.jxr`) for HDR output. Use an HDR-capable viewer. Application UI and window zoom are excluded.
-## HDR and 5.1 (current 1.4.1)
+## HDR and 5.1 (current 1.4.2)
-Native HDR support was introduced in 1.2.0 and is retained in 1.4.1. SDR conversion using RTX Video HDR is a separate development task. Since 1.4.0, supported Dolby/DTS capture streams can be decoded to PCM; this is not compressed bitstream passthrough. Individual HDR displays, 5.1 endpoints, and capture cards still require hardware acceptance.
+Native HDR support is retained. Version 1.4.2 adds SDR conversion using RTX Video HDR. Since 1.4.0, supported Dolby/DTS capture streams can be decoded to PCM; this is not compressed bitstream passthrough. Individual HDR displays, 5.1 endpoints, and capture cards still require hardware acceptance.
- Files, P010/P016 capture and PS5 can use explicitly described BT.2020 NCL PQ/HLG input. Windows HDR enables retained HDR output with NR, DLSS SR / RTX Video SR and DLSS / XeSS FG. NR / Video SR use an SDR proxy plus the retained HDR base, with reduced changes near black and compressed highlights. This is not native HDR NR inference. HLG uses a 1000-nit, gamma-1.2 reference conversion.
- Capture defaults to device color metadata. Manual PQ / HLG is available for devices that omit it, requiring P010/P016. Ten-bit storage alone does not identify HDR. RGB/YUY2 HDR and BT.2020 constant-luminance input are unsupported.
@@ -197,6 +208,6 @@ If this project helped you, you can buy the author a coffee (WeChat QR below). F
<p align="center">
<img src="docs/images/1.4.0/donate-wechat.jpg" alt="WeChat donation" width="220">
&nbsp;&nbsp;&nbsp;&nbsp;
- <img src="docs/images/1.4.0/community-group.jpg" alt="Veyra community group / bug reports / beta builds" width="220">
+ <img src="docs/images/1.4.2/community-group.png" alt="Veyra community group / bug reports / beta builds" width="220">
</p>
<p align="center"><small>Left: WeChat donation (voluntary; no feature is ever gated behind it) - Right: Veyra community group for bug reports and beta builds.</small></p>
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 0703024c..b3325002 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -348,6 +348,18 @@ 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.
+## Win32CaptureSample (screen capture)
+
+Source: https://github.com/robmikh/Win32CaptureSample
+Fixed commit: `49fefe79fd9b11025f0b5eb91783a98888516070`.
+License: MIT, Copyright (c) 2019 Robert Mikhayelyan.
+Full license: `licenses/WIN32_CAPTURE_SAMPLE_MIT.txt`.
+`src/source/ScreenCaptureSource.cpp` adapts `SimpleCapture.cpp/.h` free-threaded
+WGC session/frame-pool creation and resize lifecycle. Veyra replaces the
+upstream swapchain with bounded leased D3D11/D3D12 shared textures and fences,
+latest-frame polling, crop, explicit scRGB color, timestamps and shared graph
+ingress. DXGI duplication is a Veyra addition. Screen capture is video-only.
+
## dav1d (1.3.0 AV1 playback)
FFmpeg dynamically links dav1d 1.5.4 from the pinned local vcpkg build. The portable package includes its complete aggregated copyright/license text in `licenses/DAV1D-COPYRIGHT.txt` and provenance in `licenses/DAV1D-SPDX.json`. The FFmpeg corresponding-source ZIP includes dav1d source and its vcpkg port. Upstream: https://code.videolan.org/videolan/dav1d . License set recorded by the build: Apache-2.0, BSD-2-Clause, ISC and MIT; retain all notices supplied with the source.
diff --git a/apps/veyra/SettingsWindow.cpp b/apps/veyra/SettingsWindow.cpp
index 7be31284..738d5e7c 100644
--- a/apps/veyra/SettingsWindow.cpp
+++ b/apps/veyra/SettingsWindow.cpp
@@ -1110,7 +1110,7 @@ void arrange(){
auto batch=BeginDeferWindowPos(int(items.size()));
for(auto& entry:items){bool fixed=entry.page==-1,visible=!entry.hidden&&(entry.page==page||fixed)&&(GetDlgCtrlID(entry.h)!=1120||smoothMotionHelpExpanded);int w=entry.w<0?width-entry.x-12:entry.w;int y=fixed?(GetDlgCtrlID(entry.h)==400?0:(GetDlgCtrlID(entry.h)==211||GetDlgCtrlID(entry.h)==219)?86:42):entry.y+helpOffset(entry)-scroll;
if(fixed){SetWindowPos(entry.h,nullptr,dip(window,entry.x),dip(window,y),dip(window,std::max(1,w)),dip(window,42),SWP_NOACTIVATE|SWP_NOZORDER|SWP_NOREDRAW);continue;}batch=DeferWindowPos(batch,entry.h,nullptr,dip(window,entry.x),dip(window,y),dip(window,std::max(1,w)),dip(window,entry.height),SWP_NOACTIVATE|SWP_NOZORDER|SWP_NOREDRAW|SWP_NOCOPYBITS|(visible?SWP_SHOWWINDOW:SWP_HIDEWINDOW));}
- EndDeferWindowPos(batch);RedrawWindow(body,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);InvalidateRect(window,nullptr,FALSE);
+ EndDeferWindowPos(batch);RedrawWindow(body,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN|RDW_UPDATENOW);InvalidateRect(window,nullptr,FALSE);
}
HWND add(const wchar_t* cls,const wchar_t* text,int id,DWORD style,int group,int x,int y,int width,int height){auto h=CreateWindowExW(0,cls,text,WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|style,0,0,1,1,group==-1?window:body,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(h,WM_SETFONT,WPARAM(font),TRUE);themeControl(h);if(group!=-1)SetWindowSubclass(h,scrollOnly,950,0);items.push_back({h,group,x,y,width,height});return h;}
@@ -1314,7 +1314,8 @@ LRESULT CALLBACK proc(HWND h,UINT msg,WPARAM wp,LPARAM lp){
switch(msg){
case WM_CREATE:{window=h;font=makeFont(h);items.clear();displayedBackendWarning.clear();smoothMotionHelpExpanded=false;
WNDCLASSW bodyClass{};bodyClass.lpfnWndProc=bodyProc;bodyClass.hInstance=GetModuleHandleW(nullptr);bodyClass.lpszClassName=L"VeyraInspectorBody";bodyClass.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&bodyClass);
- body=CreateWindowExW(WS_EX_CONTROLPARENT,bodyClass.lpszClassName,L"滚动参数",WS_CHILD|WS_VISIBLE|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,0,88,300,300,h,nullptr,bodyClass.hInstance,nullptr);
+ // Composite only the scrolling controls, never the video/swapchain window.
+ body=CreateWindowExW(WS_EX_CONTROLPARENT|WS_EX_COMPOSITED,bodyClass.lpszClassName,L"滚动参数",WS_CHILD|WS_VISIBLE|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,0,88,300,300,h,nullptr,bodyClass.hInstance,nullptr);
add(L"BUTTON",L"实验性 NVIDIA NR 增强",200,BS_AUTOCHECKBOX|WS_TABSTOP,0,12,12,-1,36);
add(L"BUTTON",L"超分辨率",201,BS_AUTOCHECKBOX|WS_TABSTOP,0,12,56,-1,36);
combo(203,0,104,{L"1080p NR · 实时默认",L"原生NR · 高性能成本",L"480p NR",L"720p NR",L"900p NR",L"1440p NR"});
diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cpp
index 0306d91d..37f563b8 100644
--- a/apps/veyra/ui/AppShell.cpp
+++ b/apps/veyra/ui/AppShell.cpp
@@ -11,6 +11,7 @@
#include "UiPreferenceStore.h"
#include "PlaybackPowerGuard.h"
#include "CapturePanel.h"
+#include "ScreenCapturePanel.h"
#ifdef VEYRA_ENABLE_REMOTEPLAY
#include "RemotePlayPanel.h"
#include "veyra/remoteplay/ControllerInput.h"
@@ -54,6 +55,8 @@ enum {Open=101,Play,Stop,Save,Nr,Sr,Fg,Seek,Info,Capture,Export,Realtime,Recent,
// Settings-panel status text: it belongs to the player's bottom bar now, next to
// the submitted-FPS readout (id 64 is free in the main window's id space).
constexpr int ColourStatus=64;
+constexpr int ScreenCapture=901;
+bool screenFill=false;SIZE screenFitClient{},screenFitImage{};
veyra::engine::EngineController engine;
#ifdef VEYRA_ENABLE_REMOTEPLAY
veyra::remoteplay::ControllerInput remoteController;
@@ -246,7 +249,7 @@ std::wstring screenshotPath;ULONGLONG screenshotTick=0;bool screenshotPending=fa
void openFile(const std::wstring&);
void layout();
void updateComparison(){engine.comparison(holdOriginal?1:compareMode,referenceBase,compareSplit);}
-void toggleFullscreen(){endTransition();full=!full;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();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));}
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();}
@@ -305,7 +308,7 @@ std::wstring fileDialog(bool save){std::vector<wchar_t> name(32768);OPENFILENAME
ofn.lpstrFilter=save?L"PNG图片\0*.png\0JPEG图片\0*.jpg\0":L"视频 / 图片\0*.mp4;*.mkv;*.mov;*.avi;*.ts;*.png;*.jpg;*.jpeg\0所有文件\0*.*\0";
ofn.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST|(save?OFN_OVERWRITEPROMPT:OFN_FILEMUSTEXIST);ofn.lpstrDefExt=save?L"png":nullptr;
return (save?GetSaveFileNameW(&ofn):GetOpenFileNameW(&ofn))?name.data():L"";}
-void openFile(const std::wstring& file){if(file.empty())return;cancelProtection();auto openOptions=options();if(file!=currentFile){openOptions.settings.protection={};uiState.configured.protection={};}auto ext=std::filesystem::path(file).extension().wstring();for(auto& c:ext)c=towlower(c);if((ext==L".png"||ext==L".jpg"||ext==L".jpeg")&&uiState.mode==veyra::ui::Mode::Daily)switchMode();engine.previewView({});currentFile=file;refreshSubtitleTracks(file);paused=false;SetWindowTextW(GetDlgItem(mainWindow,Play),L"暂停");engine.open(video,file,openOptions);SetWindowTextW(mainWindow,veyra::ui::windowTitleForSource(file).c_str());if(smokeSeconds<=0)WritePrivateProfileStringW(L"Player",L"最近打开",file.c_str(),(veyra::runtime::localDataDirectory()/"veyra.ini").wstring().c_str());}
+void openFile(const std::wstring& file){if(file.empty())return;cancelProtection();auto openOptions=options();if(file!=currentFile){openOptions.settings.protection={};uiState.configured.protection={};}auto ext=std::filesystem::path(file).extension().wstring();for(auto& c:ext)c=towlower(c);if((ext==L".png"||ext==L".jpg"||ext==L".jpeg")&&uiState.mode==veyra::ui::Mode::Daily)switchMode();engine.previewView({});currentFile=file;refreshSubtitleTracks(file);paused=false;SetWindowTextW(GetDlgItem(mainWindow,Play),L"暂停");engine.open(video,file,openOptions);SetWindowTextW(mainWindow,veyra::ui::windowTitleForSource(file).c_str());if(smokeSeconds<=0&&!file.starts_with(L"screen:"))WritePrivateProfileStringW(L"Player",L"最近打开",file.c_str(),(veyra::runtime::localDataDirectory()/"veyra.ini").wstring().c_str());}
HWND control(const wchar_t* cls,const wchar_t* label,int id,DWORD style,int x,int y,int w,int h){auto hwnd=CreateWindowExW(0,cls,label,WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|style|(_wcsicmp(cls,L"STATIC")?WS_TABSTOP:0),x,y,w,h,mainWindow,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(hwnd,WM_SETFONT,reinterpret_cast<WPARAM>(font),TRUE);veyra::ui::themeControl(hwnd);if(id>=Open&&id<=Fullscreen&&id!=Seek)toolbar.push_back({hwnd,w});return hwnd;}
void selectInspector(int page){uiState.inspector=page;veyra::ui::settingsPage(page);for(int i=0;i<4;++i)veyra::ui::selected(GetDlgItem(mainWindow,TabEnhance+i),i==page);veyra::ui::selected(GetDlgItem(mainWindow,TabAudio),page==4);}
void switchMode(){
@@ -341,7 +344,7 @@ void layout(){
put(InspectorDrawer,w-384,14,76,32,!full&&pro&&w<960);
put(Master,g.left+(w<960?120:190),14,116,32,!full&&pro);
put(Save,g.left+(w>=1080?502:w>=960?318:244),14,76,32,!full&&pro);
- put(ProRailVideo,12,92,44,44,!full&&pro);put(ProRailCapture,12,148,44,44,!full&&pro);put(ImageOpen,12,204,44,44,!full&&pro);
+ put(ProRailVideo,12,92,44,44,!full&&pro);put(ProRailCapture,12,148,44,44,!full&&pro);put(ImageOpen,12,204,44,44,!full&&pro);put(ScreenCapture,12,260,44,44,!full&&pro);
for(int id:{ProRailVideo,ProRailCapture,ImageOpen})surface(GetDlgItem(mainWindow,id),RGB(16,17,18));
const int tabs[]={TabEnhance,TabFg,TabAudio,TabColor,TabExport};for(int i=0;i<5;++i)put(tabs[i],g.right+12+i*((g.panelWidth-24)/5),g.top+12,(g.panelWidth-24)/5,32,rightVisible);
pos(inspector,g.right+12,g.top+56,g.panelWidth-24,g.statusTop-g.top-68,rightVisible);
@@ -362,7 +365,7 @@ void layout(){
put(MediaTitle,tx+timeWidth+8+remoteSpace,barTop+10,std::max(1,tw-timeWidth-170-remoteSpace),20,transport);
put(FpsLabel,tx+tw-154,barTop+10,154,20,transport);
auto slot=[&](int id,TransportSlot item,int height=34,int offset=36){put(id,tx+item.x,barTop+offset,item.width,height,transport&&item.width>0);};
- slot(Open,controls.open);slot(Capture,controls.capture);slot(Recent,controls.recent);if(!full&&pro)put(Recent,12,260,44,44);
+ slot(Open,controls.open);slot(Capture,controls.capture);slot(Recent,controls.recent);if(!full&&pro)put(Recent,12,372,44,44);
if(daily)slot(Master,controls.master);slot(Sr,controls.sr);
slot(Play,controls.play,44,30);slot(Stop,controls.stop);slot(Mute,controls.mute);slot(Volume,controls.volume,18,44);slot(Subtitle,controls.subtitle);slot(Fullscreen,controls.fullscreen);
if(daily){slot(ModeSwitch,controls.mode);slot(WindowMin,controls.minimize);slot(WindowClose,controls.close);}
@@ -542,6 +545,7 @@ SetWindowSubclass(brand,veyra::ui::brandIconProc,Brand,0);
control(L"BUTTON",L"专业模式",ModeSwitch,BS_PUSHBUTTON,0,0,164,36);
control(L"BUTTON",L"增强已开启",Master,BS_PUSHBUTTON,0,0,126,36);
control(L"BUTTON",L"视频",ProRailVideo,BS_PUSHBUTTON,0,0,64,44);control(L"BUTTON",L"采集",ProRailCapture,BS_PUSHBUTTON,0,0,64,44);control(L"BUTTON",L"图片",ImageOpen,BS_PUSHBUTTON,0,0,64,44);control(L"BUTTON",L"参数",InspectorDrawer,BS_PUSHBUTTON,0,0,84,36);
+control(L"BUTTON",L"屏幕采集",ScreenCapture,BS_PUSHBUTTON,0,0,44,44);veyra::ui::icon(GetDlgItem(hwnd,ScreenCapture),veyra::ui::Icon::ScreenCapture);veyra::ui::ghost(GetDlgItem(hwnd,ScreenCapture));SetPropW(GetDlgItem(hwnd,ScreenCapture),L"veyra.tip",HANDLE(L"屏幕采集 · 窗口 / 显示器"));
control(L"BUTTON",L"音频",TabAudio,BS_PUSHBUTTON,0,0,60,36);
const wchar_t* tabs[]={L"增强",L"运动",L"色彩",L"导出"};for(int i=0;i<4;++i)control(L"BUTTON",tabs[i],TabEnhance+i,BS_PUSHBUTTON,0,0,76,36);
control(L"BUTTON",L"音量",Mute,BS_PUSHBUTTON,0,0,54,36);auto vol=control(TRACKBAR_CLASSW,L"音量",Volume,TBS_HORZ|TBS_NOTICKS,0,0,80,26);SendMessageW(vol,TBM_SETRANGE,TRUE,MAKELPARAM(0,100));SendMessageW(vol,TBM_SETPOS,TRUE,100);
@@ -601,6 +605,7 @@ case WM_SIZE:cancelProtection();if(wp!=SIZE_MINIMIZED){endTransition();layout();
case WM_DROPFILES:{std::vector<wchar_t> file(32768);DragQueryFileW(reinterpret_cast<HDROP>(wp),0,file.data(),32768);DragFinish(reinterpret_cast<HDROP>(wp));openFile(file.data());layout();return 0;}
case WM_COMMAND:switch(LOWORD(wp)){
case Open:case ProRailVideo:case ImageOpen:openFile(fileDialog(false));layout();break;
+case ScreenCapture:veyra::ui::showScreenCapturePanel(hwnd,[](const std::wstring& path){openFile(path);layout();},[]{engine.stop();},[]{return engine.snapshot();},[](bool fill){screenFill=fill;screenFitClient={};screenFitImage={};engine.previewView({});});break;
case ModeSwitch:switchMode();break;
case WindowMin:ShowWindow(hwnd,SW_MINIMIZE);break;case WindowMax:toggleFullscreen();break;case WindowClose:SendMessageW(hwnd,WM_CLOSE,0,0);break;
@@ -685,6 +690,13 @@ 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();
+if(screenFill&&currentFile.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))){
+ screenFitClient={r.right,r.bottom};screenFitImage={LONG(extent.width),LONG(extent.height)};
+ const float x=float(r.right)/extent.width,y=float(r.bottom)/extent.height;veyra::engine::PreviewView view;view.zoom=std::max(x,y)/std::min(x,y);engine.previewView(view);
+ }
+}
{
std::vector<veyra::ui::SubtitleLine> draw;
const bool showSubtitles=uiState.subtitles&&!subtitleTracks.empty()&&!(showDiagnostics&&uiState.mode==veyra::ui::Mode::Professional&&!full);
@@ -1172,5 +1184,5 @@ if(!editing&&msg.message==WM_KEYDOWN&&(GetKeyState(VK_CONTROL)&0x8000)&&msg.wPar
if(!editing&&msg.message==WM_KEYDOWN&&(GetKeyState(VK_CONTROL)&0x8000)&&msg.wParam=='E'){if(uiState.mode==veyra::ui::Mode::Daily)switchMode();selectInspector(3);continue;}
const bool key=(!editing)&&(msg.wParam==VK_F11||msg.wParam==VK_ESCAPE||(msg.wParam==VK_SPACE&&(GetFocus()==hwnd||GetFocus()==video))||msg.wParam=='V'||(msg.wParam==VK_RETURN&&msg.message==WM_SYSKEYDOWN));if(key){SendMessageW(hwnd,msg.message,msg.wParam,msg.lParam);continue;}}
if(msg.message==WM_MOUSEWHEEL&&uiState.mode==veyra::ui::Mode::Professional&&GetAncestor(msg.hwnd,GA_ROOT)==hwnd){POINT p{GET_X_LPARAM(msg.lParam),GET_Y_LPARAM(msg.lParam)};if(WindowFromPoint(p)==video){SendMessageW(video,msg.message,msg.wParam,msg.lParam);continue;}}
-if(IsDialogMessageW(hwnd,&msg))continue;TranslateMessage(&msg);DispatchMessageW(&msg);}CoUninitialize();return int(msg.wParam);
+if(veyra::ui::screenCaptureDialogMessage(msg)||IsDialogMessageW(hwnd,&msg))continue;TranslateMessage(&msg);DispatchMessageW(&msg);}CoUninitialize();return int(msg.wParam);
}
diff --git a/apps/veyra/ui/CapturePanel.cpp b/apps/veyra/ui/CapturePanel.cpp
index 540ce620..fc0d6b1a 100644
--- a/apps/veyra/ui/CapturePanel.cpp
+++ b/apps/veyra/ui/CapturePanel.cpp
@@ -55,10 +55,13 @@ void query(int device){if(busy)return;busy=true;queriedDevice=device;queryStarte
const std::wstring videoPath=device>=0&&size_t(device)<videoDevices.size()?videoDevices[size_t(device)].path:L"";
pending=std::async(std::launch::async,[device,videoPath]{CoInitializeEx(nullptr,COINIT_MULTITHREADED);Query result;result.device=device;try{if(device<0){result.video=source::CaptureCardSource::deviceDetails();result.audio=source::CaptureCardSource::deviceDetails(true);}else result.formats=videoPath.empty()?source::CaptureCardSource::formats(unsigned(device)):source::CaptureCardSource::formatsByPath(videoPath);}catch(...){}CoUninitialize();return result;});
}
-void arrange(){RECT r{};GetClientRect(window,&r);const int width=MulDiv(r.right,96,veyra::ui::layoutDpi(window));const int ys[]={0,44,114,184,412,412,14,84,344,154,254,224,294,478,448,566,530,506};for(int id=1;id<=17;++id){int x=id==5?width-152:16;int w=id==4?width-184:id==5?136:width-32;MoveWindow(GetDlgItem(window,id),dip(window,x),dip(window,ys[id]),dip(window,w),dip(window,(id<=3||id==10||id==13||id==16)?180:id==8?56:id==4||id==5?36:24),TRUE);}}
+void arrange(){RECT r{};GetClientRect(window,&r);const int width=MulDiv(r.right,96,veyra::ui::layoutDpi(window));const int ys[]={0,44,114,184,448,448,14,84,380,154,254,224,294,514,484,602,566,542,338,342};for(int id=1;id<=19;++id){int x=id==5?width-152:id==18?width-156:16;int w=id==4?width-184:id==5||id==18?136:id==19?width-184:width-32;MoveWindow(GetDlgItem(window,id),dip(window,x),dip(window,ys[id]),dip(window,w),dip(window,(id<=3||id==10||id==13||id==16)?180:id==8?56:id==4||id==5?36:id==18?32:24),TRUE);}}
LRESULT CALLBACK proc(HWND h,UINT msg,WPARAM wp,LPARAM lp){switch(msg){
case WM_CREATE:{window=h;font=makeFont(h);titleTheme(h);auto add=[&](const wchar_t* cls,const wchar_t* label,int id,DWORD style){auto c=CreateWindowExW(0,cls,label,WS_CHILD|WS_VISIBLE|style,0,0,1,1,h,HMENU(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(c,WM_SETFONT,WPARAM(font),TRUE);themeControl(c);};
remembered=CapturePreferenceStore(runtime::localDataDirectory()).load();
+ add(L"EDIT",std::format(L"{:g}",remembered.requestedFps).c_str(),18,ES_AUTOHSCROLL|WS_TABSTOP);
+ SendDlgItemMessageW(h,18,EM_SETLIMITTEXT,16,0);
+ add(L"STATIC",L"设备帧率 FPS(0 = 默认,需重连)",19,0);
refreshAfterQuery=busy;
for(int i=1;i<=3;++i)add(L"COMBOBOX",L"",i,CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP);
add(L"COMBOBOX",L"",10,CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP);add(L"STATIC",L"输入颜色(变更需重连)",11,0);
@@ -74,6 +77,7 @@ case WM_CREATE:{window=h;font=makeFont(h);titleTheme(h);auto add=[&](const wchar
add(L"BUTTON",L"连接并开始观看",4,BS_PUSHBUTTON|WS_TABSTOP);marked(GetDlgItem(h,4));add(L"BUTTON",L"刷新设备",5,BS_PUSHBUTTON|WS_TABSTOP);
add(L"STATIC",L"视频输入设备",6,0);add(L"STATIC",L"设备实际支持的格式",7,0);add(L"STATIC",L"",8,0);add(L"STATIC",L"音频监听(仅采集所选输入,默认关闭)",9,0);
installDialogHelp(h,{{16,L"采集卡往软件送帧用的驱动缓冲数量。缓冲越多,卡可以提前排队,但每多一帧就多一帧的等待;缓冲太少,驱动来不及取走就会丢帧。自动:1080p 及以下建议 2 帧、更高分辨率建议 3 帧;最小:1 帧,延迟最低但高负载可能丢帧;驱动默认:不干预。改这个要重新连接采集卡,连接日志里会写建议值和驱动实际给的值(协商未生效时如实标注)。"},{15,L"给方向声明和实际画面不一致的采集卡用:常见于某些 RGB24 格式——设备在媒体类型里写的是底行在前,实际送来的却是顶行在前,于是画面上下颠倒。勾选后把采集画面上下翻转一次,立即生效;只影响本机采集预览、截图和从这里导出的画面,不改设备也不动其他格式。画面正常时不要勾选;换成不颠倒的格式后记得取消。"},{13,L"采集卡把 Dolby Atmos / Dolby Audio / DTS 以位流送来时,这里决定用哪条路。设备本身的音频格式不受影响;改这个要重新连接采集卡。自动优先 PCM,PCM 不可用时才走位流解码;位流优先则反过来:先尝试把位流原样直通给功放/回音壁(独占输出,卡不经过软件解码,只有接收端才能解出 Atmos/DTS:X 的对象声场;需要输出设备支持,探测见日志 bitstream-out),没有支持的输出端点时自动回退到解码。适合 PS5 已设成 Dolby 输出、但设备同时提供 PCM 的情况。"},{12,L"收到HDR也转成SDR显示,不用改PS5或Windows。增强照常用;只改预览,视频导出不受影响。切换会短暂停顿,截图跟随当前画面。关闭后跟随显示器。"},{10,L"设备没报HDR信息时手动指定,需选P010/P016。P010也可能装SDR,别给普通画面强戴HDR帽子。"},{1,L"选采集卡的视频设备。别把摄像头误请来直播PS5。"},{2,L"选设备真实提供的分辨率、帧率和像素格式。清晰度、带宽和延迟都受它影响。"},{3,L"如果设备自带 HDMI 音频,会显示“使用视频设备内置音频”;否则选择独立音频设备,也可不采声音。"},{4,L"按当前格式连接采集卡,并应用当前增强设置。"},{5,L"重新扫描设备和格式。设备被其他软件占用时,刷新不一定能抢回来。"}});
+ installDialogHelp(h,{{18,L"直接请求采集卡按此帧率送帧,支持小数。0 沿用所选格式;更改后重新连接。设备不支持或返回其他帧率时会报错,不在软件中偷偷丢帧。采集卡不能判断哪些画面是游戏重复帧,降帧率不保证消除重复画面。"}});
EnableWindow(GetDlgItem(h,4),FALSE);arrange();SetTimer(h,1,100,nullptr);if(!busy)query(-1);return 0;}
case WM_TIMER:
SendDlgItemMessageW(h,12,BM_SETCHECK,readSdr()?BST_CHECKED:BST_UNCHECKED,0);
@@ -103,6 +107,7 @@ case WM_TIMER:
restore=-1;for(size_t i=0;i<formats.size();++i)if(formats[i].key==remembered.formatKey)restore=int(i);
SendDlgItemMessageW(h,10,CB_SETCURSEL,remembered.colorOverride,0);
}else SendDlgItemMessageW(h,10,CB_SETCURSEL,0,0);
+ SetDlgItemTextW(h,18,std::format(L"{:g}",sameDevice?remembered.requestedFps:0).c_str());
SendDlgItemMessageW(h,2,CB_SETCURSEL,restore,0);EnableWindow(GetDlgItem(h,4),restore>=0);
SetDlgItemTextW(h,8,formats.empty()?L"未读到有效的4K以内采集格式,或设备正被其他应用占用。":L"连接后使用当前增强设置。格式与音频变更需要重新连接。");
if(!formats.empty()&&restore<0)SetDlgItemTextW(h,8,L"上次格式已不可用,请重新选择格式。");
@@ -138,12 +143,14 @@ case WM_COMMAND:
const int device=int(SendDlgItemMessageW(h,1,CB_GETCURSEL,0,0));
const int format=int(SendDlgItemMessageW(h,2,CB_GETCURSEL,0,0));
const int audio=selectedAudio(h,device);
+ wchar_t rateText[32]{};GetDlgItemTextW(h,18,rateText,32);double requestedFps=0;
+ if(!source::parseCaptureFrameRate(rateText,requestedFps)){SetDlgItemTextW(h,8,L"采集帧率请输入 1–1000 的数字(可带小数),或填 0 沿用设备默认。 ");SetFocus(GetDlgItem(h,18));return 0;}
const bool audioIndexValid=SendDlgItemMessageW(h,3,CB_GETCURSEL,0,0)!=CB_ERR&&(audio<0||size_t(audio)<audioDevices.size());
if(!busy&&device==queriedDevice&&format>=0&&size_t(format)<formats.size()&&device>=0&&size_t(device)<videoDevices.size()&&audioIndexValid){
const auto* audioDevice=audio>=0?&audioDevices[size_t(audio)]:nullptr;
- const auto path=source::CaptureCardSource::makeCapturePath(unsigned(device),videoDevices[size_t(device)],formats[size_t(format)].index,audio,audioDevice,unsigned(SendDlgItemMessageW(h,10,CB_GETCURSEL,0,0)));
+ const auto path=source::CaptureCardSource::makeCapturePath(unsigned(device),videoDevices[size_t(device)],formats[size_t(format)].index,audio,audioDevice,unsigned(SendDlgItemMessageW(h,10,CB_GETCURSEL,0,0)),requestedFps);
if(!path.empty()){
- remembered={videoDevices[size_t(device)].path,formats[size_t(format)].key,audioDevice?audioDevice->path:L"",audioDevice?(audioDevice->wasapi?source::kCaptureAudioWasapi:0):audio,unsigned(SendDlgItemMessageW(h,10,CB_GETCURSEL,0,0)),remembered.formatHintDismissed};
+ remembered={videoDevices[size_t(device)].path,formats[size_t(format)].key,audioDevice?audioDevice->path:L"",audioDevice?(audioDevice->wasapi?source::kCaptureAudioWasapi:0):audio,unsigned(SendDlgItemMessageW(h,10,CB_GETCURSEL,0,0)),remembered.formatHintDismissed,requestedFps};
if(!CapturePreferenceStore(runtime::localDataDirectory()).save(remembered))log::warn("capture","Failed to save capture selection");
start(path);DestroyWindow(h);
}
@@ -158,5 +165,5 @@ case WM_CLOSE:DestroyWindow(h);return 0;
case WM_DESTROY:KillTimer(h,1);DeleteObject(font);window=nullptr;return 0;
}return DefWindowProcW(h,msg,wp,lp);}
}
-void showCapturePanel(HWND parent,std::function<void(const std::wstring&)> callback,std::function<bool()> read,std::function<bool(bool)> write,std::function<int()> readIngress,std::function<bool(int)> writeIngress,std::function<bool()> readFlipped,std::function<bool(bool)> writeFlipped,std::function<int()> readBuffered,std::function<bool(int)> writeBuffered){start=std::move(callback);readSdr=std::move(read);setSdr=std::move(write);readAudioIngress=std::move(readIngress);setAudioIngress=std::move(writeIngress);readFlip=std::move(readFlipped);setFlip=std::move(writeFlipped);readBuffer=std::move(readBuffered);setBuffer=std::move(writeBuffered);if(window){SetForegroundWindow(window);return;}WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraCaptureSetup";wc.hbrBackground=panelBrush();wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&wc);CreateWindowExW(WS_EX_TOOLWINDOW,wc.lpszClassName,L"采集卡 · 连接设置",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,dip(parent,560),dip(parent,640),parent,nullptr,wc.hInstance,nullptr);}
+void showCapturePanel(HWND parent,std::function<void(const std::wstring&)> callback,std::function<bool()> read,std::function<bool(bool)> write,std::function<int()> readIngress,std::function<bool(int)> writeIngress,std::function<bool()> readFlipped,std::function<bool(bool)> writeFlipped,std::function<int()> readBuffered,std::function<bool(int)> writeBuffered){start=std::move(callback);readSdr=std::move(read);setSdr=std::move(write);readAudioIngress=std::move(readIngress);setAudioIngress=std::move(writeIngress);readFlip=std::move(readFlipped);setFlip=std::move(writeFlipped);readBuffer=std::move(readBuffered);setBuffer=std::move(writeBuffered);if(window){SetForegroundWindow(window);return;}WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraCaptureSetup";wc.hbrBackground=panelBrush();wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&wc);CreateWindowExW(WS_EX_TOOLWINDOW,wc.lpszClassName,L"采集卡 · 连接设置",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,dip(parent,560),dip(parent,680),parent,nullptr,wc.hInstance,nullptr);}
}
diff --git a/apps/veyra/ui/CapturePreferenceStore.h b/apps/veyra/ui/CapturePreferenceStore.h
index 38785a89..b331943b 100644
--- a/apps/veyra/ui/CapturePreferenceStore.h
+++ b/apps/veyra/ui/CapturePreferenceStore.h
@@ -5,6 +5,7 @@
#include <iomanip>
#include <sstream>
#include <string>
+#include "veyra/source/CaptureFrameRate.h"
namespace veyra::ui {
struct CapturePreferences {
@@ -13,6 +14,7 @@ struct CapturePreferences {
unsigned colorOverride=0;
// N3: the one-time "this format is high cost" hint was already shown.
bool formatHintDismissed=false;
+ double requestedFps=0;
};
class CapturePreferenceStore {
std::filesystem::path path_;
@@ -27,14 +29,15 @@ public:
if(!file.read(reinterpret_cast<char*>(data.data()),size))return {};
std::wistringstream in(data);std::wstring magic;int version=0;CapturePreferences result;
if(!(in>>magic>>version>>std::quoted(result.videoPath)>>std::quoted(result.formatKey)>>result.audioMode>>std::quoted(result.audioPath)>>result.colorOverride)||
- magic!=L"VEYRA_CAPTURE"||(version!=1&&version!=2)||result.audioMode< -3||result.audioMode>0||result.colorOverride>2)return {};
+ magic!=L"VEYRA_CAPTURE"||(version<1||version>3)||result.audioMode< -3||result.audioMode>0||result.colorOverride>2)return {};
if(version>=2){int dismissed=0;if(!(in>>dismissed)||(dismissed!=0&&dismissed!=1))return {};result.formatHintDismissed=dismissed!=0;}
+ if(version>=3&&(!(in>>result.requestedFps)||!source::validCaptureFrameRate(result.requestedFps)))return {};
in>>std::ws;return in.eof()?result:CapturePreferences{};
}
bool save(const CapturePreferences& p)const {
- if(p.audioMode< -3||p.audioMode>0||p.colorOverride>2)return false;
+ if(p.audioMode< -3||p.audioMode>0||p.colorOverride>2||!source::validCaptureFrameRate(p.requestedFps))return false;
std::error_code ec;std::filesystem::create_directories(path_.parent_path(),ec);if(ec)return false;
- std::wostringstream out;out<<L"VEYRA_CAPTURE 2\n"<<std::quoted(p.videoPath)<<L' '<<std::quoted(p.formatKey)<<L' '<<p.audioMode<<L' '<<std::quoted(p.audioPath)<<L' '<<p.colorOverride<<L' '<<(p.formatHintDismissed?1:0)<<L'\n';
+ std::wostringstream out;out<<L"VEYRA_CAPTURE 3\n"<<std::quoted(p.videoPath)<<L' '<<std::quoted(p.formatKey)<<L' '<<p.audioMode<<L' '<<std::quoted(p.audioPath)<<L' '<<p.colorOverride<<L' '<<(p.formatHintDismissed?1:0)<<L' '<<std::setprecision(12)<<p.requestedFps<<L'\n';
const auto data=out.str();if(data.size()>65536/sizeof(wchar_t))return false;const DWORD bytes=DWORD(data.size()*sizeof(wchar_t));
auto tmp=path_;tmp+=L".tmp-"+std::to_wstring(GetCurrentProcessId());
HANDLE file=CreateFileW(tmp.c_str(),GENERIC_WRITE,0,nullptr,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,nullptr);if(file==INVALID_HANDLE_VALUE)return false;
diff --git a/apps/veyra/ui/LucideIcons.h b/apps/veyra/ui/LucideIcons.h
index 00dbdd14..486724ed 100644
--- a/apps/veyra/ui/LucideIcons.h
+++ b/apps/veyra/ui/LucideIcons.h
@@ -3,7 +3,7 @@
#pragma once
#include "GlassMaterial.h"
namespace veyra::ui {
-enum class Icon { None,Play,Pause,Stop,Volume,Muted,Fullscreen,Video,Capture,Image,Subtitle,Minimize,Maximize,Close,Back,Settings,Recent,Enhance,Upscale,PanelOpen,PanelClose,Check,Chevron,Load,Type };
+enum class Icon { None,Play,Pause,Stop,Volume,Muted,Fullscreen,Video,Capture,Image,Subtitle,Minimize,Maximize,Close,Back,Settings,Recent,Enhance,Upscale,PanelOpen,PanelClose,Check,Chevron,Load,Type,ScreenCapture };
inline void drawIcon(HDC dc,Icon icon,float x,float y,float size,COLORREF c){
using namespace Gdiplus; AlphaGraphics drawing(dc);auto& g=drawing.get();
g.SetSmoothingMode(SmoothingModeAntiAlias);g.TranslateTransform(x-size/2,y-size/2);g.ScaleTransform(size/24,size/24);
@@ -384,6 +384,24 @@ p.AddLine(20.0000000f,5.0000000f,20.0000000f,7.0000000f);
p.StartFigure();
p.AddLine(9.0000000f,20.0000000f,15.0000000f,20.0000000f);
break;
+case Icon::ScreenCapture: // app-window.svg
+p.StartFigure();
+p.AddLine(4.0000000f,4.0000000f,20.0000000f,4.0000000f);
+p.AddBezier(20.0000000f,4.0000000f,21.1045695f,4.0000000f,22.0000000f,4.8954305f,22.0000000f,6.0000000f);
+p.AddLine(22.0000000f,6.0000000f,22.0000000f,18.0000000f);
+p.AddBezier(22.0000000f,18.0000000f,22.0000000f,19.1045695f,21.1045695f,20.0000000f,20.0000000f,20.0000000f);
+p.AddLine(20.0000000f,20.0000000f,4.0000000f,20.0000000f);
+p.AddBezier(4.0000000f,20.0000000f,2.8954305f,20.0000000f,2.0000000f,19.1045695f,2.0000000f,18.0000000f);
+p.AddLine(2.0000000f,18.0000000f,2.0000000f,6.0000000f);
+p.AddBezier(2.0000000f,6.0000000f,2.0000000f,4.8954305f,2.8954305f,4.0000000f,4.0000000f,4.0000000f);
+p.CloseFigure();
+p.StartFigure();
+p.AddLine(10.0000000f,4.0000000f,10.0000000f,8.0000000f);
+p.StartFigure();
+p.AddLine(2.0000000f,8.0000000f,22.0000000f,8.0000000f);
+p.StartFigure();
+p.AddLine(6.0000000f,4.0000000f,6.0000000f,8.0000000f);
+break;
default: return;}g.DrawPath(&pen,&p);
}
}
diff --git a/apps/veyra/ui/PopupSelector.h b/apps/veyra/ui/PopupSelector.h
index 96949511..bdfcbab9 100644
--- a/apps/veyra/ui/PopupSelector.h
+++ b/apps/veyra/ui/PopupSelector.h
@@ -18,8 +18,9 @@ inline LRESULT CALLBACK listProc(HWND h,UINT m,WPARAM w,LPARAM l,UINT_PTR,DWORD_
auto& s=*reinterpret_cast<State*>(context);
if(m==WM_KEYDOWN){if(w==VK_ESCAPE||w==VK_F4||w==VK_TAB){if(w==VK_TAB)s.tab=(GetKeyState(VK_SHIFT)&0x8000)?-1:1;s.done=true;return 0;}if(w==VK_RETURN||w==VK_SPACE){accept(s);return 0;}}
if(m==WM_SYSKEYDOWN&&w==VK_UP){s.done=true;return 0;}
- if(m==WM_MOUSEMOVE){auto item=SendMessageW(h,LB_ITEMFROMPOINT,0,l);if(!HIWORD(item))SendMessageW(h,LB_SETCURSEL,LOWORD(item),0);}
- if(m==WM_LBUTTONUP){auto item=SendMessageW(h,LB_ITEMFROMPOINT,0,l);auto result=DefSubclassProc(h,m,w,l);if(!HIWORD(item)){SendMessageW(h,LB_SETCURSEL,LOWORD(item),0);accept(s);}return result;}
+ if(m==WM_MOUSEMOVE){auto item=SendMessageW(h,LB_ITEMFROMPOINT,0,l);if(!HIWORD(item)&&SendMessageW(h,LB_GETCURSEL,0,0)!=LOWORD(item))SendMessageW(h,LB_SETCURSEL,LOWORD(item),0);return 0;}
+ if(m==WM_LBUTTONDOWN||m==WM_LBUTTONDBLCLK){auto item=SendMessageW(h,LB_ITEMFROMPOINT,0,l);if(!HIWORD(item))SendMessageW(h,LB_SETCURSEL,LOWORD(item),0);return 0;}
+ if(m==WM_LBUTTONUP){auto item=SendMessageW(h,LB_ITEMFROMPOINT,0,l);if(!HIWORD(item)){SendMessageW(h,LB_SETCURSEL,LOWORD(item),0);accept(s);}return 0;}
if(m==WM_ERASEBKGND)return 1;
if(m==WM_PAINT||m==WM_PRINTCLIENT){PaintBuffer paint(h,reinterpret_cast<HDC>(w));fillSurface(paint.dc,paint.rect,h);int first=int(SendMessageW(h,LB_GETTOPINDEX,0,0));int selected=int(SendMessageW(h,LB_GETCURSEL,0,0));
for(int i=std::max(0,first);size_t(i)<s.options->size();++i){RECT r{};if(SendMessageW(h,LB_GETITEMRECT,i,LPARAM(&r))==LB_ERR||r.top>=paint.rect.bottom)break;DRAWITEMSTRUCT draw{ODT_LISTBOX,1,UINT(i),ODA_DRAWENTIRE,UINT(i==selected?ODS_SELECTED:0),h,paint.dc,r,0};SendMessageW(s.window,WM_DRAWITEM,1,LPARAM(&draw));}return 0;}
diff --git a/apps/veyra/ui/ScreenCapturePanel.cpp b/apps/veyra/ui/ScreenCapturePanel.cpp
new file mode 100644
index 00000000..19074d30
--- /dev/null
+++ b/apps/veyra/ui/ScreenCapturePanel.cpp
@@ -0,0 +1,120 @@
+#include "ScreenCapturePanel.h"
+#include "Theme.h"
+#include "ProtectionOverlay.h"
+#include "veyra/source/ScreenCaptureSource.h"
+#include "veyra/RuntimePaths.h"
+#include <format>
+
+namespace veyra::ui {
+namespace {
+HWND panelWindow=nullptr,outline=nullptr;HFONT font=nullptr;
+std::function<void(const std::wstring&)> start;std::function<void()> stop;
+std::function<engine::PlayerSnapshot()> state;std::function<void(bool)> displayFit;
+std::unique_ptr<engine::EngineController> preview;
+std::vector<source::ScreenCaptureTarget> targets;
+enum {Kind=101,Target,Refresh,Method,Cursor,Fps,Left,Top,Right,Bottom,Start,Stop,State,Preview,PreviewStart,Fit,ResetCrop};
+struct Placement {HWND window;int x,y,w,h;};std::vector<Placement> placements;
+bool active=false,dragging=false;POINT dragStart{};unsigned previewWidth=0,previewHeight=0;
+std::wstring validationError;
+HWND child(int id){return GetDlgItem(panelWindow,id);}
+int selection(int id){return int(SendMessageW(child(id),CB_GETCURSEL,0,0));}
+void add(HWND w,const wchar_t* value){SendMessageW(w,CB_ADDSTRING,0,LPARAM(value));}
+std::wstring ini(){return (runtime::localDataDirectory()/"veyra.ini").wstring();}
+void persist(){for(auto [id,key]:{std::pair{Kind,L"Kind"},{Method,L"Method"},{Fps,L"RateMode"},{Fit,L"Fit"}})WritePrivateProfileStringW(L"ScreenCapture",key,std::to_wstring(selection(id)).c_str(),ini().c_str());WritePrivateProfileStringW(L"ScreenCapture",L"Cursor",SendMessageW(child(Cursor),BM_GETCHECK,0,0)==BST_CHECKED?L"1":L"0",ini().c_str());}
+void layout(){
+ RECT client{};GetClientRect(panelWindow,&client);
+ const int available=MulDiv(client.bottom,96,layoutDpi(panelWindow));
+ const int reduction=std::clamp(640-available,0,148);
+ for(auto& p:placements){const int y=p.y>=278?p.y-reduction:p.y;const int height=p.window==child(Preview)?p.h-reduction:p.h;
+ SetWindowPos(p.window,nullptr,dip(panelWindow,p.x),dip(panelWindow,y),dip(panelWindow,p.w),dip(panelWindow,height),SWP_NOZORDER);}
+}
+void methods(){const bool monitor=selection(Kind)==1;EnableWindow(child(Method),monitor);if(!monitor)SendMessageW(child(Method),CB_SETCURSEL,0,0);const bool wgc=selection(Method)==0;EnableWindow(child(Cursor),wgc);if(!wgc)SendMessageW(child(Cursor),BM_SETCHECK,BST_UNCHECKED,0);}
+void stopPreview(){if(preview){preview.reset();preview=std::make_unique<engine::EngineController>();}previewWidth=previewHeight=0;if(outline)ShowWindow(outline,SW_HIDE);}
+void resetCrop(){for(int id=Left;id<=Bottom;++id)SetDlgItemInt(panelWindow,id,0,FALSE);if(outline)ShowWindow(outline,SW_HIDE);}
+void enumerate(){
+ auto old=selection(Target);uint64_t handle=old>=0&&size_t(old)<targets.size()?targets[old].handle:0;
+ targets=source::ScreenCaptureSource::targets(selection(Kind)==1?source::ScreenTargetKind::Monitor:source::ScreenTargetKind::Window);
+ SendMessageW(child(Target),CB_RESETCONTENT,0,0);int selected=0;
+ for(size_t i=0;i<targets.size();++i){add(child(Target),targets[i].name.c_str());if(targets[i].handle==handle)selected=int(i);}
+ SendMessageW(child(Target),CB_SETCURSEL,selected,0);EnableWindow(child(Start),!targets.empty());EnableWindow(child(PreviewStart),!targets.empty());methods();
+ if(targets.empty())SetWindowTextW(child(State),L"没有可采集的目标");
+}
+bool options(source::ScreenCaptureOptions& value,bool cropped){
+ const auto index=selection(Target);if(index<0||size_t(index)>=targets.size())return false;
+ value.kind=targets[index].kind;value.target=targets[index].handle;value.method=source::ScreenCaptureMethod(selection(Method));
+ constexpr unsigned rates[]={0,30,60,120,144,240};value.fps=rates[std::clamp(selection(Fps),0,5)];value.cursor=SendMessageW(child(Cursor),BM_GETCHECK,0,0)==BST_CHECKED;
+ if(cropped){unsigned* margins[]={&value.left,&value.top,&value.right,&value.bottom};for(int i=0;i<4;++i){BOOL valid=FALSE;*margins[i]=GetDlgItemInt(panelWindow,Left+i,&valid,FALSE);if(!valid||*margins[i]>16384){validationError=L"裁剪值须为 0 到 16384 的整数";SetWindowTextW(child(State),validationError.c_str());return false;}}}
+ return true;
+}
+std::pair<float,float> point(HWND window,POINT p){RECT rect{};GetClientRect(window,&rect);return engine::PreviewView{}.sourcePoint(float(p.x),float(p.y),float(rect.right),float(rect.bottom),float(previewWidth),float(previewHeight));}
+LRESULT CALLBACK previewProc(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR){
+ if(message==WM_LBUTTONDOWN&&previewWidth&&previewHeight){dragStart={GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};auto uv=point(window,dragStart);if(uv.first>=0&&uv.first<=1&&uv.second>=0&&uv.second<=1){dragging=true;SetCapture(window);}return 0;}
+ if(message==WM_MOUSEMOVE&&dragging){POINT p{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};if(!outline)outline=createSubtitleOverlay(window);protectionOutline(outline,window,{std::min(p.x,dragStart.x),std::min(p.y,dragStart.y),std::max(p.x,dragStart.x),std::max(p.y,dragStart.y)});return 0;}
+ if(message==WM_LBUTTONUP&&dragging){POINT p{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};auto a=point(window,dragStart),b=point(window,p);dragging=false;ReleaseCapture();if(std::abs(p.x-dragStart.x)>3&&std::abs(p.y-dragStart.y)>3){
+ SetDlgItemInt(panelWindow,Left,unsigned(std::clamp(std::min(a.first,b.first),0.f,1.f)*previewWidth),FALSE);SetDlgItemInt(panelWindow,Right,unsigned((1-std::clamp(std::max(a.first,b.first),0.f,1.f))*previewWidth),FALSE);
+ SetDlgItemInt(panelWindow,Top,unsigned(std::clamp(std::min(a.second,b.second),0.f,1.f)*previewHeight),FALSE);SetDlgItemInt(panelWindow,Bottom,unsigned((1-std::clamp(std::max(a.second,b.second),0.f,1.f))*previewHeight),FALSE);
+ }return 0;}
+ if(message==WM_CAPTURECHANGED)dragging=false;
+ if(message==WM_RBUTTONUP){resetCrop();return 0;}
+ if(message==WM_ERASEBKGND)return 1;
+ if(message==WM_PAINT){PAINTSTRUCT ps;auto dc=BeginPaint(window,&ps);if(!preview||!preview->snapshot().frames)FillRect(dc,&ps.rcPaint,HBRUSH(GetStockObject(BLACK_BRUSH)));EndPaint(window,&ps);return 0;}
+ return DefSubclassProc(window,message,wp,lp);
+}
+HWND make(const wchar_t* cls,const wchar_t* label,int id,DWORD style,int x,int y,int w,int h){
+ auto control=CreateWindowExW(0,cls,label,WS_CHILD|WS_VISIBLE|style,dip(panelWindow,x),dip(panelWindow,y),dip(panelWindow,w),dip(panelWindow,h),panelWindow,HMENU(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);
+ SendMessageW(control,WM_SETFONT,WPARAM(font),TRUE);if(id!=Preview)themeControl(control);placements.push_back({control,x,y,w,h});return control;
+}
+LRESULT CALLBACK proc(HWND window,UINT message,WPARAM wp,LPARAM lp){
+ switch(message){
+ case WM_CREATE:{panelWindow=window;placements.clear();validationError.clear();font=makeFont(window);titleTheme(window);preview=std::make_unique<engine::EngineController>();
+ auto kind=make(L"COMBOBOX",L"",Kind,CBS_DROPDOWNLIST|WS_TABSTOP,20,16,126,160);add(kind,L"窗口");add(kind,L"显示器");
+ make(L"COMBOBOX",L"",Target,CBS_DROPDOWNLIST|WS_TABSTOP|WS_VSCROLL,158,16,330,400);make(L"BUTTON",L"刷新",Refresh,BS_PUSHBUTTON|WS_TABSTOP,500,16,80,32);
+ auto viewport=make(L"STATIC",L"",Preview,SS_NOTIFY,20,60,560,208);SetWindowSubclass(viewport,previewProc,1,0);
+ make(L"BUTTON",L"预览",PreviewStart,BS_PUSHBUTTON|WS_TABSTOP,20,278,110,32);icon(child(PreviewStart),Icon::Play,true);
+ make(L"BUTTON",L"重置裁剪",ResetCrop,BS_PUSHBUTTON|WS_TABSTOP,142,278,120,32);
+ auto fit=make(L"COMBOBOX",L"",Fit,CBS_DROPDOWNLIST|WS_TABSTOP,390,278,190,160);add(fit,L"适应窗口");add(fit,L"填满窗口");
+ make(L"STATIC",L"采集方式",0,0,20,330,100,26);auto method=make(L"COMBOBOX",L"",Method,CBS_DROPDOWNLIST|WS_TABSTOP,140,326,440,180);add(method,L"Windows Graphics Capture");add(method,L"DXGI 显示器兼容(无指针)");
+ make(L"STATIC",L"帧率上限",0,0,20,374,100,26);auto fps=make(L"COMBOBOX",L"",Fps,CBS_DROPDOWNLIST|WS_TABSTOP,140,370,230,220);for(auto value:{L"跟随显示器刷新率",L"30",L"60",L"120",L"144",L"240"})add(fps,value);
+ make(L"BUTTON",L"显示鼠标指针",Cursor,BS_AUTOCHECKBOX|WS_TABSTOP,386,370,194,28);
+ make(L"STATIC",L"裁剪 / 像素",0,0,20,420,180,24);const wchar_t* labels[]={L"左",L"上",L"右",L"下"};for(int i=0;i<4;++i){make(L"STATIC",labels[i],0,0,20+i*140,462,30,24);make(L"EDIT",L"0",Left+i,WS_BORDER|ES_NUMBER|WS_TABSTOP,52+i*140,458,84,30);}
+ make(L"STATIC",L"",State,0,20,504,560,68);make(L"BUTTON",L"开始 / 切换",Start,BS_DEFPUSHBUTTON|WS_TABSTOP,300,582,160,38);icon(child(Start),Icon::Play,true);
+ make(L"BUTTON",L"停止",Stop,BS_PUSHBUTTON|WS_TABSTOP,474,582,106,38);icon(child(Stop),Icon::Stop,true);
+ for(auto [id,key]:{std::pair{Kind,L"Kind"},{Method,L"Method"},{Fps,L"RateMode"},{Fit,L"Fit"}}){auto value=GetPrivateProfileIntW(L"ScreenCapture",key,0,ini().c_str());auto count=SendMessageW(child(id),CB_GETCOUNT,0,0);SendMessageW(child(id),CB_SETCURSEL,value<unsigned(count)?value:0,0);}
+ SendMessageW(child(Cursor),BM_SETCHECK,GetPrivateProfileIntW(L"ScreenCapture",L"Cursor",1,ini().c_str())?BST_CHECKED:BST_UNCHECKED,0);enumerate();SetTimer(window,1,250,nullptr);return 0;}
+ case WM_TIMER:{
+ if(!validationError.empty())return 0;
+ auto p=preview->snapshot();if(p.running&&p.frames){previewWidth=p.metrics.resolution.source.width;previewHeight=p.metrics.resolution.source.height;}
+ auto s=active&&state?state():p;std::wstring text;
+ if(s.failed)text=s.status;else if(s.transport==engine::TransportState::Opening)text=L"正在打开目标";
+ else if(s.running){text=!s.sourceNotice.empty()?s.sourceNotice:std::format(L"{} {} x {} {:.1f} FPS",active?L"采集中":L"预览",s.metrics.resolution.source.width,s.metrics.resolution.source.height,s.fps);}
+ else text=L"已停止";
+ SetWindowTextW(child(State),text.c_str());return 0;}
+ case WM_COMMAND:{const int id=LOWORD(wp);validationError.clear();
+ if(id==Refresh||(id==Kind&&HIWORD(wp)==CBN_SELCHANGE)){stopPreview();resetCrop();enumerate();return 0;}
+ if(id==Target&&HIWORD(wp)==CBN_SELCHANGE){stopPreview();resetCrop();return 0;}
+ if(id==Method&&HIWORD(wp)==CBN_SELCHANGE){stopPreview();methods();return 0;}
+ if(id==Fit&&HIWORD(wp)==CBN_SELCHANGE){if(displayFit)displayFit(selection(Fit)==1);persist();return 0;}
+ if(id==Fps&&HIWORD(wp)==CBN_SELCHANGE){persist();return 0;}
+ if(id==ResetCrop){resetCrop();return 0;}
+ if(id==Stop){stopPreview();if(stop)stop();active=false;return 0;}
+ if(id==Start||id==PreviewStart){source::ScreenCaptureOptions value;if(!options(value,id==Start))return 0;persist();
+ if(id==PreviewStart){if(stop)stop();active=false;engine::PlayerOptions settings;preview->open(child(Preview),value.uri(),settings);}
+ else{stopPreview();if(start)start(value.uri());if(displayFit)displayFit(selection(Fit)==1);active=true;}return 0;}
+ break;}
+ case WM_DPICHANGED:{auto rect=reinterpret_cast<RECT*>(lp);SetWindowPos(window,nullptr,rect->left,rect->top,rect->right-rect->left,rect->bottom-rect->top,SWP_NOZORDER);auto old=font;font=makeFont(window);for(auto& p:placements)SendMessageW(p.window,WM_SETFONT,WPARAM(font),TRUE);DeleteObject(old);layout();return 0;}
+ case WM_SIZE:layout();return 0;
+ case WM_CTLCOLORSTATIC:case WM_CTLCOLOREDIT:case WM_CTLCOLORBTN:return colors(message,wp,lp);
+ case WM_CLOSE:persist();DestroyWindow(window);return 0;
+ case WM_DESTROY:KillTimer(window,1);preview.reset();if(outline)DestroyWindow(outline);outline=nullptr;DeleteObject(font);font=nullptr;panelWindow=nullptr;placements.clear();return 0;
+ }return DefWindowProcW(window,message,wp,lp);
+}
+}
+void showScreenCapturePanel(HWND parent,std::function<void(const std::wstring&)> onStart,std::function<void()> onStop,std::function<engine::PlayerSnapshot()> getState,std::function<void(bool)> fit){
+ start=std::move(onStart);stop=std::move(onStop);state=std::move(getState);displayFit=std::move(fit);if(panelWindow){SetForegroundWindow(panelWindow);return;}
+ WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraScreenCapture";wc.hbrBackground=panelBrush();wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&wc);
+ MONITORINFO monitor{sizeof(monitor)};GetMonitorInfoW(MonitorFromWindow(parent,MONITOR_DEFAULTTONEAREST),&monitor);
+ const int width=dip(parent,618),height=std::min(dip(parent,674),int(monitor.rcWork.bottom-monitor.rcWork.top));
+ CreateWindowExW(WS_EX_TOOLWINDOW|WS_EX_CONTROLPARENT,wc.lpszClassName,L"屏幕采集",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_VISIBLE,monitor.rcWork.left+(monitor.rcWork.right-monitor.rcWork.left-width)/2,monitor.rcWork.top+(monitor.rcWork.bottom-monitor.rcWork.top-height)/2,width,height,parent,nullptr,wc.hInstance,nullptr);
+}
+bool screenCaptureDialogMessage(MSG& message){return panelWindow&&IsDialogMessageW(panelWindow,&message);}
+}
diff --git a/apps/veyra/ui/ScreenCapturePanel.h b/apps/veyra/ui/ScreenCapturePanel.h
new file mode 100644
index 00000000..258b8323
--- /dev/null
+++ b/apps/veyra/ui/ScreenCapturePanel.h
@@ -0,0 +1,9 @@
+#pragma once
+#include <windows.h>
+#include <functional>
+#include <string>
+#include "veyra/engine/EngineController.h"
+namespace veyra::ui {
+void showScreenCapturePanel(HWND,std::function<void(const std::wstring&)>,std::function<void()>,std::function<engine::PlayerSnapshot()>,std::function<void(bool)>);
+bool screenCaptureDialogMessage(MSG&);
+}
diff --git a/apps/veyra/ui/SourceTitle.h b/apps/veyra/ui/SourceTitle.h
index 3906d984..1589b339 100644
--- a/apps/veyra/ui/SourceTitle.h
+++ b/apps/veyra/ui/SourceTitle.h
@@ -23,6 +23,7 @@ inline std::wstring windowTitleForSource(const std::wstring& source) {
if (source.empty()) return L"Veyra — 本地实验版";
if (isCaptureCardSource(source)) return L"Veyra — 采集卡 · LIVE";
if (isRemotePlaySource(source)) return L"Veyra — PS5 Remote Play";
+ if (source.starts_with(L"screen:")) return L"Veyra — 屏幕采集 · LIVE";
return L"Veyra — " + std::filesystem::path(source).filename().wstring();
}
diff --git a/apps/veyra/ui/Theme.h b/apps/veyra/ui/Theme.h
index 931533ae..0b09dcd2 100644
--- a/apps/veyra/ui/Theme.h
+++ b/apps/veyra/ui/Theme.h
@@ -80,6 +80,7 @@ inline LRESULT CALLBACK labelPaint(HWND h,UINT m,WPARAM w,LPARAM l,UINT_PTR,DWOR
}
inline void icon(HWND h,Icon icon,bool caption=false){if(INT_PTR(GetPropW(h,L"veyra.icon"))==INT_PTR(icon)&&(GetPropW(h,L"veyra.caption")!=nullptr)==caption)return;SetPropW(h,L"veyra.icon",HANDLE(INT_PTR(icon)));if(caption)SetPropW(h,L"veyra.caption",HANDLE(1));else RemovePropW(h,L"veyra.caption");InvalidateRect(h,nullptr,FALSE);}
inline LRESULT CALLBACK buttonPaint(HWND h,UINT m,WPARAM w,LPARAM l,UINT_PTR,DWORD_PTR){
+ if(m==BM_SETCHECK&&SendMessageW(h,BM_GETCHECK,0,0)==LRESULT(w))return 0;
if(m==WM_ERASEBKGND)return 1;
if(m==WM_MOUSEMOVE){if(!GetPropW(h,L"veyra.hover")){SetPropW(h,L"veyra.hover",HANDLE(1));TRACKMOUSEEVENT t{sizeof(t),TME_LEAVE,h,0};TrackMouseEvent(&t);InvalidateRect(h,nullptr,FALSE);}}
if(m==WM_MOUSELEAVE){RemovePropW(h,L"veyra.hover");InvalidateRect(h,nullptr,FALSE);}
@@ -91,17 +92,20 @@ inline LRESULT CALLBACK buttonPaint(HWND h,UINT m,WPARAM w,LPARAM l,UINT_PTR,DWO
if(ico!=Icon::None){drawIcon(dc,ico,caption?float(dip(h,18)):r.right/2.f,r.bottom/2.f,float(dip(h,ico==Icon::Play||ico==Icon::Pause?22:17)),ink);if(caption){r.left=dip(h,34);glassText(dc,value,-1,&r,DT_LEFT|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS);}}
else if((GetWindowLongPtrW(h,GWL_STYLE)&BS_TYPEMASK)==BS_AUTOCHECKBOX){RECT toggle{r.right-dip(h,40),r.bottom/2-dip(h,8),r.right-dip(h,10),r.bottom/2+dip(h,8)};roundRect(dc,toggle,check?accent:line,dip(h,8));RECT knob{toggle.left+dip(h,check?16:3),toggle.top+dip(h,3),toggle.left+dip(h,check?26:13),toggle.top+dip(h,13)};roundRect(dc,knob,check?panel:secondary,dip(h,5));r.left=dip(h,12);r.right-=dip(h,46);glassText(dc,value,-1,&r,DT_LEFT|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS);}else glassText(dc,value,-1,&r,DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS);
if(GetFocus()==h&&!(SendMessageW(h,WM_QUERYUISTATE,0,0)&UISF_HIDEFOCUS)){RECT outline{};GetClientRect(h,&outline);InflateRect(&outline,-3,-3);AlphaGraphics focusDrawing(dc);auto& focus=focusDrawing.get();focus.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);Gdiplus::GraphicsPath path;rounded(path,{float(outline.left),float(outline.top),float(outline.right-outline.left),float(outline.bottom-outline.top)},float(dip(h,6)));Gdiplus::Pen stroke(color(accent,145),1);focus.DrawPath(&stroke,&path);}SelectObject(dc,old);return 0;}
- if(controlVisualChange(m)||m==BM_SETCHECK||m==BM_SETSTATE||m==BM_SETSTYLE)return updateControlModel(h,m,w,l);
+ if(controlVisualChange(m)||m==BM_SETCHECK||m==BM_SETSTATE||m==BM_SETSTYLE||m==WM_MOUSEMOVE||m==WM_MOUSELEAVE||m==WM_LBUTTONDOWN||m==WM_LBUTTONUP)return updateControlModel(h,m,w,l);
return DefSubclassProc(h,m,w,l);
}
}
#include "PopupSelector.h"
namespace veyra::ui {
inline LRESULT CALLBACK comboPaint(HWND h,UINT m,WPARAM w,LPARAM l,UINT_PTR,DWORD_PTR){
+ if(m==CB_SETCURSEL&&SendMessageW(h,CB_GETCURSEL,0,0)==LRESULT(w))return LRESULT(w);
if(m==CB_GETDROPPEDSTATE)return GetPropW(h,L"Veyra.ComboOpen")!=nullptr;
if(m==CB_SHOWDROPDOWN&&!w){if(GetPropW(h,L"Veyra.ComboOpen")){SetPropW(h,L"Veyra.ComboCancel",HANDLE(1));cancelPopupSelector();}return 0;}
if(m==WM_LBUTTONDOWN||m==CB_SHOWDROPDOWN&&w||m==WM_KEYDOWN&&(w==VK_F4||w==VK_SPACE||w==VK_RETURN)||m==WM_SYSKEYDOWN&&w==VK_DOWN){if(IsWindowEnabled(h))comboSelector(h);return 0;}
- if(m==WM_LBUTTONUP||m==WM_LBUTTONDBLCLK)return 0;
+ // The custom selector owns pointer interaction; native hot tracking draws
+ // directly into the window DC and would overwrite the buffered artwork.
+ if(m==WM_LBUTTONUP||m==WM_LBUTTONDBLCLK||m==WM_MOUSEMOVE||m==WM_MOUSELEAVE)return 0;
if(m==WM_ERASEBKGND)return 1;if(m==WM_PAINT||m==WM_PRINTCLIENT){PaintBuffer paint(h,reinterpret_cast<HDC>(w));HDC dc=paint.dc;RECT r=paint.rect;fillSurface(dc,r,h);if(glassBackdrop(h))translucentRound(dc,r,16,dip(h,7));else roundRect(dc,r,raised,dip(h,7));int index=int(SendMessageW(h,CB_GETCURSEL,0,0));wchar_t value[512]{};if(index>=0&&SendMessageW(h,CB_GETLBTEXTLEN,index,0)<512)SendMessageW(h,CB_GETLBTEXT,index,LPARAM(value));auto old=SelectObject(dc,HFONT(SendMessageW(h,WM_GETFONT,0,0)));SetBkMode(dc,TRANSPARENT);SetTextColor(dc,IsWindowEnabled(h)?secondary:RGB(85,88,92));RECT label=r;label.left+=dip(h,12);label.right-=dip(h,26);glassText(dc,value,-1,&label,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS);{AlphaGraphics drawing(dc);auto& g=drawing.get();g.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);Gdiplus::Pen pen(color(secondary),float(dip(h,1)));float x=float(r.right-dip(h,15)),y=r.bottom/2.f;g.DrawLine(&pen,x-dip(h,3),y-dip(h,1),x,y+dip(h,2));g.DrawLine(&pen,x,y+dip(h,2),x+dip(h,3),y-dip(h,1));}SelectObject(dc,old);return 0;}
if(controlVisualChange(m)||m==CB_SETCURSEL||m==CB_RESETCONTENT||m==CB_ADDSTRING||m==CB_DELETESTRING||m==WM_KEYDOWN||m==WM_CHAR)return updateControlModel(h,m,w,l);
return DefSubclassProc(h,m,w,l);
diff --git a/assets/icons/lucide/app-window.svg b/assets/icons/lucide/app-window.svg
new file mode 100644
index 00000000..815548bc
--- /dev/null
+++ b/assets/icons/lucide/app-window.svg
@@ -0,0 +1,16 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <rect x="2" y="4" width="20" height="16" rx="2" />
+ <path d="M10 4v4" />
+ <path d="M2 8h20" />
+ <path d="M6 4v4" />
+</svg>
diff --git a/assets/icons/lucide/manifest.json b/assets/icons/lucide/manifest.json
index 1af8ee0f..55f8a7d7 100644
--- a/assets/icons/lucide/manifest.json
+++ b/assets/icons/lucide/manifest.json
@@ -4,6 +4,7 @@
"generator": "fonttools 4.64.0; SVG paths converted to GDI+ cubic paths",
"sha256": {
"LICENSE": "b495047bd93a9b06913511076f504daba17d5bbeb3e0650f3bb53a4220329c57",
+ "app-window.svg": "78635d0da597104f526ea01dede8ab4d04ccabc7a2229c4baf17f921b15985de",
"captions.svg": "37c4e3ed84224b7d07ee6f5b0f51cc2c5d17e8bf80f86c48059cdcc747607a55",
"check.svg": "7f33acc9a77a61659531044525fc008edebe215bf4dcf1c789c8674ad3277db0",
"chevron-down.svg": "66ea878e72ed3488bb3b464c39dfdccee8d1f78e560dccea40e5e12da0e87e87",
diff --git a/docs/CAPTURE_HDR_REPAIR_2026-09-19.md b/docs/CAPTURE_HDR_REPAIR_2026-09-19.md
new file mode 100644
index 00000000..dc822601
--- /dev/null
+++ b/docs/CAPTURE_HDR_REPAIR_2026-09-19.md
@@ -0,0 +1,55 @@
+# P010 采集 HDR 识别与颜色排查
+
+## 范围与结论
+
+用户确认输入 P010;尚未提供采集卡型号、HDR/SDR 显示器状态和问题日志。
+在 `codex/5060-presets-subtitles-20260918` 现有隔离区继续,保留 XeSS 回退与测试。
+不发布、不合并、不改变补帧调度;P010 是位深/存储格式,不能单独证明 HDR。
+
+已复现并修复的软件缺陷:
+
+- `CaptureMediaType.h`:明确 PQ/HLG、缺少 matrix/primaries 时,旧代码保留 SDR 默认值,无法满足共享图的 HDR 合同。现在只针对明确 HDR transfer,为缺失字段补 BT.2100 / BT.2020 NCL 默认值,并保留 assumed 标志;明确的相冲突字段不覆盖。补充 BT.709/BT.601 primaries 解析。
+- 同处丢失设备声明的 chroma siting。现在传递 MPEG2 left、MPEG1 center、cosited top-left(可带 progressive 位),未声明或不能表达的布局不猜测;颜色位置变化需要重新建立合同。
+- `ColorGrade.hlsli`:曝光等非中性调色先将 BT.709 工作色域中的合法负分量截成 0,HSV 还原和函数返回再次截断。BT.2020 饱和色会因此改变色相/亮度。改为保留有符号线性光、signed gamma 和扩展饱和度范围;最终映射仍由原有 HDR/SDR 输出负责。纯中性设置已有旁路,旧版该测试通过,不能宣称只打开中性开关就必然变色。
+- `CaptureCardSource.cpp`:记录原始 controlFlags、元数据存在位、transfer/matrix/primaries/chroma、手动覆盖及 HDR 推定字段;未声明 HDR 的 10 位输入明确记录保留 SDR 的原因。
+
+## 实测
+
+日志目录:`E:/项目/Veyra/logs/capture-hdr-20260919/`。
+临时目录:`E:/项目/Veyra/tmp/capture-hdr-20260919/`。
+
+先在已有 `E:/项目/Veyra/build/xess-view-reset-20260919` 构建回归测试。
+`unit-before.log` 有 PQ/HLG 缺失字段失败;显式 BT709 测试最初错用了保留值 1,
+查本机 SDK 后改为 `DXVA2_VideoPrimaries_BT709`(2),该次失败不能作为产品缺陷证据。
+`gpu-before.stdout.log`:+1 EV 四组 PQ/HLG、full/limited 失败,负分量误差达到 1;中性四组通过。
+
+修复后 `unit-final.log` failures=0;`gpu-final.stdout.log` exit 0:
+
+- 8 组 untagged AVFrame + DirectShow P010 部分 HDR 元数据,与完整文件元数据输出逐像素一致;覆盖 PQ/HLG、full/limited、scRGB/PQ 输出。
+- 8 组 HDR 调色中性/+1 EV 检查通过,包括纯 BT.2020 红绿蓝与 0..10000 nit 灰阶;+1 EV 最大归一化误差 0.000625,中性误差 0。
+- 原有 HDR 往返、真实呈现缓冲一致性、HDR→SDR 色域/亮度映射与 SDR/采集格式 GPU 回归通过。
+- `grade-final.stdout.log` exit 0:SDR 调色关闭/中性、曝光、曲线、饱和度、混色、抖动、实际 LUT 和错误 LUT 空间拒绝测试通过。
+
+增量构建发现 MSVC 本地化 showIncludes 前缀乱码,header-only 变化没有可靠触发消费者重编译。
+已显式重编译测试入口取得上述最终结果,另用全新目录做完整构建消除旧对象影响;不把早期缺少新增测试行的运行算作新测试通过。
+
+命令(PowerShell,工作目录为现有隔离源码区):
+
+```powershell
+./scripts/build-isolated.ps1 -Root . -BuildDirectory E:/项目/Veyra/build/capture-hdr-20260919 -DependencyCache E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt -TempDirectory E:/项目/Veyra/tmp/capture-hdr-20260919 -DisplayVersion 1.4.2beta -Targets veyra_capture_color_tests,veyra_hdr_color_tests,veyra_color_grade_gpu_tests,veyra
+```
+
+测试使用 `scripts/run-short-test.ps1`,每项最多 150 秒;仅测试进程 TEMP/TMP 指向本轮 tmp,PATH 使用已有便携包 FFmpeg DLL。没有新增或修改专有运行库。
+
+全新目录构建最终 exit 0(`build-clean.log`);该目录的三个测试程序分别再次运行,
+`unit-clean.log` failures=0、`gpu-clean.stdout.log` / `grade-clean.stdout.log` 均 exit 0,
+8 条 `HDR_CAPTURE_PARTIAL_TAGS exact=1`、8 条 `HDR_GRADE_SIGNED pass=1` 均实际出现。
+主程序已构建为 `E:/项目/Veyra/build/capture-hdr-20260919/veyra.exe`,未制作新便携包。
+
+## 未验证与下一步
+
+这是确定软件缺陷的回归证据,不能据此断言反馈者的全部症状已根治。
+没有元数据的 P010 仍无法可靠区分 SDR/PQ/HLG;只报 BT.2020 也不足以确定 HDR transfer。
+动态采集中 SDR/HDR 切换仍需重开输入和处理图,本轮未扩展该生命周期。
+未执行反馈者实卡、物理 HDR 显示器、NGX NR/SR/FG Create/Evaluate 或 LUT 全空间 HDR 主观验收。
+下一步使用本轮程序取得反馈者 `capture-color` 日志和卡型号,确认是未报元数据、部分元数据还是动态切换,再决定是否需要厂商信号查询。
diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.md
index 218e3878..1791a13b 100644
--- a/docs/CURRENT_STATUS.md
+++ b/docs/CURRENT_STATUS.md
@@ -1,6 +1,10 @@
# 当前项目状态 / Current Status
-更新:2026-09-18。发布状态与开发状态分别记录,历史计划不代表当前验收。
+更新:2026-09-19。发布状态与开发状态分别记录,历史计划不代表当前验收。
+
+当前任务:用户已授权正式发布 **1.4.2**,整合 RTX Video HDR、帧同步及后续采集/字幕/UI 修复,并修复全屏操作提示残留。新群二维码与用户 HDR 对比照片纳入 README/Release,赞助图保留。正式发布进度、验收与资产以 [1.4.2 发布记录](RELEASE_1.4.2_EXECUTION.md) 为准,下方“仅本地”“未合并”等均是先前阶段记录。
+
+最新本地交付准备:`codex/screen-capture-20260919` 汇总此前隔离修复,构建显示版本 1.4.2,新增设备帧率手动协商、恢复专业模式 PS5 入口、修复设置滚动及选框重绘。下方“未打包”等描述为各阶段当时状态,本轮以 [1.4.2 验收记录](UI_CAPTURE_RATE_1.4.2_2026-09-19.md) 和 WORKLOG 为准。仅本地测试包,无 main 合并、推送或 GitHub Release。
## 已发布 1.4.1
diff --git a/docs/RELEASE_1.4.2_EXECUTION.md b/docs/RELEASE_1.4.2_EXECUTION.md
new file mode 100644
index 00000000..cde778e5
--- /dev/null
+++ b/docs/RELEASE_1.4.2_EXECUTION.md
@@ -0,0 +1,26 @@
+# 1.4.2 发布执行记录
+
+## 范围与授权
+
+2026-09-19 用户要求修复全屏提示、重新打包并发布 GitHub 1.4.2,更新报告重点为 RTX Video HDR 与帧同步。整合 codex/screen-capture-20260919 当前修改及其祖先隔离功能,NVIDIA FSR4 已撤回。远端用户 README 更新 5034212 一并保留。
+
+新群二维码、HDR 对比图由本次用户提供,分别进入 docs/images/1.4.2/community-group.png 和 rtx-video-hdr-comparison.jpg。赞助原图未改,两图各 width=220。新群截图自身标明二维码有效期至9月26日,之后需用户提供新码。
+
+TrueHDR 原件身份及许可证见 RUNTIME_COMPONENTS_1.4.2.md,逐文件打包校验;其余组件沿用,不含 SDK、模型、凭据、日志、PDB 或测试媒体。用户图片为明确授权的文档资产。
+
+## 修复与验证
+
+- AppShell.cpp:全屏切换 TTM_POP 清除已弹出的提示,TTM_ACTIVATE 在全屏期间禁用,退出恢复。
+- delivery.ps1:显式 OutputDirectory/FixtureRoot,旧质量探针使用相对输出路径,避免 narrow path 损坏中文目录;不改变测试通过条件。
+- 构建:scripts/build-isolated.ps1 -Root . -BuildDirectory E:/项目/Veyra/build/screen-capture-20260919 -DependencyCache E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt -TempDirectory E:/项目/Veyra/tmp/release-1.4.2-20260919 -DisplayVersion 1.4.2 -Targets veyra,veyra_quality_probe,veyra_capture_compressed_tests。exit0。
+- 真实 GUI:打开 visible-scene.mkv,专业模式进入全屏检查。后续退出/再次悬停与正式包回归结果待补充。
+- 首次 delivery 失败为质量探针依赖工作目录下 runtime_local/config;第二次图像保存失败为旧探针 narrow Unicode 路径。已隔离运行配置并用相对输出路径修正,保留失败日志,不作为产品通过证据。
+
+此前本轮 UI、设备 FPS、WGC/DXGI、NR/DLSS4X 与便携包七组通过证据见 UI_CAPTURE_RATE_1.4.2_2026-09-19.md。30/40 HDR、反馈者5060、VC-007PRO设备限帧与PS5本轮未执行。
+
+## 产物与当前状态
+
+构建目录 E:/项目/Veyra/build/screen-capture-20260919。
+本次 logs/tests/tmp 位于 E:/项目/Veyra/ 对应 release-1.4.2-20260919 子目录。
+正式包计划位于 E:/项目/Veyra/releases/1.4.2,包含便携包、对应源码与 SHA256。
+当前尚在本地验证,未发布;发布后补充远端 tag、资产、哈希与图片访问核对结果。
diff --git a/docs/RELEASE_NOTES_1.4.2.md b/docs/RELEASE_NOTES_1.4.2.md
index 47da9018..46056576 100644
--- a/docs/RELEASE_NOTES_1.4.2.md
+++ b/docs/RELEASE_NOTES_1.4.2.md
@@ -1,23 +1,52 @@
-# Veyra 1.4.2beta 内测版
+# Veyra 1.4.2
-基于 1.4.1 的隔离内测构建,尚未发布正式版。
+本次重点:**RTX Video HDR** 与 **可完全关闭的帧同步**,同时整合 1.4.1 之后的播放器、采集、字幕和界面修复。
-## 本次变化
+## RTX Video HDR:SDR 视频转 HDR
-- 新增 RTX Video HDR:将 SDR 视频转换为 HDR,接入共享增强链,可与现有 NR、SR、补帧组合。
-- 增强设置中勾选「RTX Video HDR」,可调整对比度、饱和度、中间灰和峰值亮度。
-- 支持转换后的 HEVC Main10 HDR 导出;原生 HDR 输入不重复转换。
-- 开关下显示实际预览状态。显示器和 Windows 必须启用 HDR 才会进行 HDR 预览;SDR 显示器保持 SDR,不会故意显示灰蒙蒙的画面。HDR 导出不要求本机显示器支持 HDR。
-- 撤回画质不达标的 NVIDIA FSR 4.1 实验,保留 DLSS SR、RTX 视频超分和原有官方 FSR。旧实验预设自动转为 RTX 视频超分「高」,其余设置保留。
-- 保留 1.4.1 的 RTX30/40 DLSS 兼容、最高 6X、持续播放补帧受限、MKV 字幕/音轨切换、设置保存等修复。
+- 专业模式 → 增强 → **RTX Video HDR**,可调对比度、饱和度、中间灰和峰值亮度。
+- 接入共享增强链,可与 NR、DLSS / RTX 超分和补帧组合;原生 HDR 输入不重复转换。
+- 支持转换后的 HEVC Main10 HDR 导出。HDR 预览需要兼容的 HDR 显示器,并开启 Windows HDR;SDR 屏保持 SDR,不会故意变灰。HDR 导出不要求本机有 HDR 屏。
+- 开关下显示实际预览状态,区分“请求开启”与“实际运行”。本次集成视频版 RTX Video HDR,不是游戏版 RTX HDR。
-## 内测重点
+<p align="center"><img src="https://raw.githubusercontent.com/Likely7/Veyra-NRVideo/v1.4.2/docs/images/1.4.2/rtx-video-hdr-comparison.jpg" alt="RTX Video HDR 用户实测:上关闭,下开启" width="720"></p>
+<p align="center"><small>用户提供的同一设备相机拍摄对比:上图关闭,下图开启。照片展示该设备的观感,不代表原始 HDR 像素或屏幕亮度测量;软件 FPS 也不是屏幕物理刷新率。</small></p>
-请在 HDR 显示器上开启 Windows HDR,再比较同一 SDR 片段的开关效果;同时反馈显卡、驱动、显示器型号和日志。重点观察高光、肤色、字幕、调节即时生效、切换视频以及与 NR/SR/补帧组合时的稳定性。
+## 帧同步:按需控制排队和呈现节奏
-现有证据来自 RTX5070 / 616.56;TrueHDR 创建、执行、组合增强和 Main10 导出在前序隔离测试通过。实际 HDR 屏幕显示、RTX30/40 HDR、采集卡和 PS5 本轮仍需内测,不宣称全设备验收。实验运行组件不代表 NVIDIA 官方认证或支持。
+入口:专业模式 → **运动 → 帧同步**。默认关闭,选项与设置可保存。
-完整解压后运行 Veyra.exe。包内不含个人配置;原配置可自行保留。对应源码见同目录 Veyra-1.4.2beta-source.zip。
+| 选项 | 实际作用 |
+| --- | --- |
+| 关闭 | 关闭新增帧同步策略,保留正常媒体时钟及必要的补帧依赖 |
+| 低排队 | 减少提前处理与呈现排队,控制积压 |
+| 均匀呈现 · 前端同步 | 在低排队基础上按媒体时间安排提交,避免一串帧挤着提交 |
+| NVIDIA Reflex · 实验 | 无补帧时使用 NVAPI Sleep/markers;开启补帧时明确回退低排队,保留补帧倍率 |
+
+显示同步另可选择允许撕裂、垂直同步或自动;自动当前采用 VSync,不会替你修改 G-SYNC。XeSS 保持提供方调度,不叠加这套前端节奏控制。
+
+修复过期生成帧阻挡已就绪原帧的等待;降低部分采集 DLSS 路径的额外相位余量。帧同步不等于提高 GPU 算力,也不保证所有组合降低延迟。[软件侧延迟对照与测试口径](https://github.com/Likely7/Veyra-NRVideo/blob/v1.4.2/docs/FRAME_PACING_ACCEPTANCE_2026-09-18.md)。
+
+## 其他新增与修复
+
+- **窗口 / 显示器采集**:专业模式左侧窗口图标进入,支持 WGC、DXGI 显示器兼容、目标选择、裁剪、鼠标指针和帧率上限。默认沿用目标显示器刷新率;仅采画面,声音由原应用播放。静止画面不重复填帧凑 FPS。
+- **采集卡设备帧率**:手输 30、40 或小数,0 沿用所选格式。重新连接后直接向 DirectShow 设备协商;拒绝或返回其他档位时明确报错,不偷偷改用软件丢帧限速。设备是否支持取决于驱动与格式;不能保证自动去除游戏重复画面。
+- **图形字幕**:增加 MKV 内嵌 PGS、DVD、DVB 字幕显示,保留文本字幕及音轨切换。
+- **调色预设**:保存时可命名,并提供明确反馈,修复保存无反应。
+- **采集 HDR**:修复 P010 明确 PQ/HLG、但缺少色域字段时的默认值,以及调色截断 HDR 负分量造成的颜色异常。设备不报 HDR 元数据时仍需手选,P010 本身不等于 HDR。
+- **XeSS**:修复缩放时重建呈现资源等问题;撤回导致无法开启的拖动暂停生成方案,拖动画面时继续补帧。
+- **界面**:修复全屏操作提示残留、专业模式 PS5 按钮被遮挡、设置滚动残影与选框悬停闪烁。
+- **诊断**:细分“补帧受限”原因,避免把输入不足一概显示为 GPU 瓶颈。5060 反馈者的具体实卡根因尚未确认,不宣称全部解决。
+- **撤回 NVIDIA FSR 4.1 实验**:画质未达预期,旧实验配置迁移至 RTX 视频超分“高”;保留原有 DLSS SR、RTX 视频超分和官方 FSR 能力。
+- 保留 1.4.1 的 RTX30/40 DLSS 最高 6X 兼容修复、持续播放补帧受限修复、MKV 打开与拖动优化、设置保存及导出修复。RTX50 保持原生 DLSS 路径。
+
+## 下载与验证范围
+
+下载 **Veyra-1.4.2-win64-portable.zip**,完整解压运行 Veyra.exe。首次效果全关。升级请解压至新目录,需要时迁移旧配置,不要整体覆盖旧运行库。
+
+**Veyra-1.4.2-source.zip** 包含对应应用源码,以及未改变的 FFmpeg / Remote Play 依赖源码包;运行播放器不需要下载源码。
+
+本机 GPU 验证环境 RTX5070 / 616.56;已有 TrueHDR 创建、执行、NR/SR/FG 组合及 Main10 导出证据。用户提供了本次 HDR 显示对比照片。采集卡手动帧率已在 OBS 虚拟摄像头验证 30/40/默认60 FPS,VC-007PRO 本轮未连接;RTX30/40 HDR、不同物理采集卡与 PS5 本轮未逐台验收。NR、补帧兼容层和相关集成仍为实验功能,不代表 NVIDIA 官方认证或支持。
## 支持与反馈
@@ -26,6 +55,6 @@
<p align="center">
<img src="https://raw.githubusercontent.com/Likely7/Veyra-NRVideo/v1.4.0/docs/images/1.4.0/donate-wechat.jpg" alt="微信赞助" width="220">
&nbsp;&nbsp;&nbsp;&nbsp;
- <img src="https://raw.githubusercontent.com/Likely7/Veyra-NRVideo/v1.4.0/docs/images/1.4.0/community-group.jpg" alt="Veyra 交流群 / bug 反馈 / beta 版本" width="220">
+ <img src="https://raw.githubusercontent.com/Likely7/Veyra-NRVideo/v1.4.2/docs/images/1.4.2/community-group.png" alt="Veyra 交流群 / bug 反馈 / beta 版本" width="220">
</p>
<p align="center"><small>左:微信赞助 右:Veyra 交流群(bug 反馈与 beta 版本发布)</small></p>
diff --git a/docs/RELEASE_SUPPORT.md b/docs/RELEASE_SUPPORT.md
index 5744803e..49f49365 100644
--- a/docs/RELEASE_SUPPORT.md
+++ b/docs/RELEASE_SUPPORT.md
@@ -5,6 +5,6 @@
<p align="center">
<img src="https://raw.githubusercontent.com/Likely7/Veyra-NRVideo/v1.4.0/docs/images/1.4.0/donate-wechat.jpg" alt="微信赞助" width="220">
&nbsp;&nbsp;&nbsp;&nbsp;
- <img src="https://raw.githubusercontent.com/Likely7/Veyra-NRVideo/v1.4.0/docs/images/1.4.0/community-group.jpg" alt="Veyra 交流群 / bug 反馈 / beta 版本" width="220">
+ <img src="https://raw.githubusercontent.com/Likely7/Veyra-NRVideo/v1.4.2/docs/images/1.4.2/community-group.png" alt="Veyra 交流群 / bug 反馈 / beta 版本" width="220">
</p>
<p align="center"><small>左:微信赞助 右:Veyra 交流群(bug 反馈与 beta 版本发布)</small></p>
diff --git a/docs/REMOTEPLAY_BUILD_1.4.2.md b/docs/REMOTEPLAY_BUILD_1.4.2.md
index 7b013cf9..026bf694 100644
--- a/docs/REMOTEPLAY_BUILD_1.4.2.md
+++ b/docs/REMOTEPLAY_BUILD_1.4.2.md
@@ -1,11 +1,11 @@
-# Veyra 1.4.2beta 构建与对应源码
+# Veyra 1.4.2构建与对应源码
-本内测构建启用 Remote Play,源码来自隔离分支 codex/fsr41-nvidia-20260918(分支名沿用历史;NVIDIA FSR4 实验已回退),不是 GitHub 正式版本。
+本发布构建启用 Remote Play,应用源码对应 Git tag v1.4.2,整合此前隔离分支的已验证修改。NVIDIA FSR4 实验已回退。
-Veyra-1.4.2beta-source.zip 提供当前应用源码与构建脚本,并附未改变的 1.4.1 FFmpeg 和 RemotePlay 对应源码 ZIP。依赖版本未改变,保留原文件名以准确标注来源。
+Veyra-1.4.2-source.zip 提供当前应用源码与构建脚本,并附未改变的 1.4.1 FFmpeg 和 RemotePlay 对应源码 ZIP。依赖版本未改变,保留原文件名以准确标注来源。source-manifest.json 记录发布提交、分支、工作树状态和逐文件 SHA256。
Chiaki 固定于 streetpea/chiaki-ng 的 0e16950165f06e5c3291537c2eeba6e852be7120,补丁位于 scripts/remoteplay/patches。组合程序适用 Chiaki 的 AGPL-3.0-only 及 OpenSSL exception,Veyra 自身源码为 GPLv3。各依赖许可证见 licenses/remoteplay。
FFmpeg 使用现有 32→256 slices 的 PS5 H.264 修补版本和 dav1d,便携包 licenses/FFMPEG-VEYRA-BUILD.json 记录二进制身份;依赖源码包保留实际补丁与构建说明。
-用 VS2022 x64、CMake/Ninja 和自行准备的授权 SDK 构建;详见 BUILD.md。隔离构建脚本 scripts/build-isolated.ps1 接受 Root、BuildDirectory、DependencyCache、TempDirectory 与 DisplayVersion=1.4.2beta。运行库、NVIDIA/Intel SDK、凭据和测试媒体不在源码包内。
+用 VS2022 x64、CMake/Ninja 和自行准备的授权 SDK 构建;详见 BUILD.md。隔离构建脚本 scripts/build-isolated.ps1 接受 Root、BuildDirectory、DependencyCache、TempDirectory 与 DisplayVersion=1.4.2。运行库、NVIDIA/Intel SDK、凭据和测试媒体不在源码包内。
diff --git a/docs/RUNTIME_COMPONENTS_1.4.2.md b/docs/RUNTIME_COMPONENTS_1.4.2.md
index 56303896..9235455c 100644
--- a/docs/RUNTIME_COMPONENTS_1.4.2.md
+++ b/docs/RUNTIME_COMPONENTS_1.4.2.md
@@ -1,10 +1,10 @@
-# Veyra 1.4.2beta Runtime Components
+# Veyra 1.4.2 Runtime Components
发布包组件清单 / Shipped components. NVIDIA and Intel DLLs are separate Release assets and never source Git content. NR and DLSS FG are community-experimental integrations, not vendor endorsement or certification.
-1.4.2beta 沿用 1.4.1 的全部增强运行组件身份,新增以下官方 TrueHDR 原件,不修改磁盘 DLL。
+1.4.2 正式包沿用 1.4.2beta 已审计的全部组件身份,包括以下官方 TrueHDR 原件,不修改磁盘 DLL。本轮设备帧率与 UI 修复没有新增运行组件。
-TrueHDR 来源:RTX Video SDK 1.1.0,文件 nvngx_truehdr.dll,3955752 bytes,版本 1.1.0.0,签名 Valid(NVIDIA),SHA256 `9A80575F247190C05FE80EAC0C4BAA1D0D4D932348F26808310B5EC4BF9EEB4B`。放在 runtime/experimental/,许可证为 licenses/NVIDIA_RTX_VIDEO_SDK_LICENSE.pdf,单独登记 manifest。本次仅用户授权的内测群包,不是 GitHub 正式发布。
+TrueHDR 来源:RTX Video SDK 1.1.0,文件 nvngx_truehdr.dll,3955752 bytes,版本 1.1.0.0,签名 Valid(NVIDIA),SHA256 `9A80575F247190C05FE80EAC0C4BAA1D0D4D932348F26808310B5EC4BF9EEB4B`。放在 runtime/experimental/,许可证为 licenses/NVIDIA_RTX_VIDEO_SDK_LICENSE.pdf,单独登记 manifest。用户于 2026-09-19 授权随 1.4.2 GitHub Release 分发该原件。
NVIDIA FSR4 INT8 研究 provider 已撤回,不在包内;官方 AMD upscaler 保留原文件与原有 FSR3 能力。
RTX30/40 补帧兼容修复在进程内完成,RTX50 保持原生路径;FSR 补帧界面入口继续隐藏。
@@ -26,6 +26,7 @@ only and do not lock user replacement; ABI, API, driver, and hardware compatibil
| `runtime/experimental/nvngx_dlss.dll` | 310.7.0.0 | `BE6E434A94CA32499515EB62CA0E6C274526055D568D0426E4C652DCDFB6EE6E` | Valid; DLSS SR |
| `runtime/experimental/nvngx_dlssg.dll` | 310.7.0.0 | `135EAF0733C1E37381A8C28ABCF7A862404A54132B81787C04E35D09EFC5E36F` | Valid; experimental DLSS FG |
| `runtime/experimental/nvngx_dlssnr.dll` | 310.8.0.0 | `E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E` | Valid; pinned experimental NR |
+| `runtime/experimental/nvngx_truehdr.dll` | 1.1.0.0 | `9A80575F247190C05FE80EAC0C4BAA1D0D4D932348F26808310B5EC4BF9EEB4B` | Valid (NVIDIA); RTX Video HDR |
| `runtime/experimental/nvngx_vsr.dll` | 1.6.0.0 | `C3D88EEA5FF7A548EDEFA66414CF6E77464D0947277C904F324DD23ABF58A1ED` | Valid; RTX Video SR |
| `runtime_local/intel/experimental/libxess_fg.dll` | 1.3.1.78 | `EC5E0C65E075570C6EDE72618BB666D0BE0C2E10B2EA9762C0FE8CB8E375AB27` | Valid; XeSS preview FG |
| `runtime_local/intel/experimental/libxell.dll` | 1.3.2.10 | `D2030DCD694FDA8F2EC7E044B13E6DB8F0B56D4BA9113A5EFAD334E3F3DED8C7` | Valid; XeLL timing |
diff --git a/docs/SCREEN_CAPTURE_PLAN_2026-09-19.md b/docs/SCREEN_CAPTURE_PLAN_2026-09-19.md
new file mode 100644
index 00000000..762fdc84
--- /dev/null
+++ b/docs/SCREEN_CAPTURE_PLAN_2026-09-19.md
@@ -0,0 +1,130 @@
+# Screen capture implementation, 2026-09-19
+
+User approved a professional-mode screen input alongside the existing sources.
+Branch: `codex/screen-capture-20260919`, base `12238df`. Existing uncommitted
+P010 HDR fixes and XeSS pan regressions are retained, not reverted.
+
+## Contract
+
+- Window and monitor WGC capture; monitor DXGI duplication compatibility mode.
+- Same EngineController / EnhanceGraph / presenter as other live inputs.
+- Bounded GPU texture pool, latest available frame, real QPC timestamps.
+- Shared D3D11/D3D12 textures and producer fence; AVFrame leases prevent reuse
+ until graph consumers and cached frames have released the source texture.
+- Explicit SDR sRGB and HDR scRGB contracts, no GPU pixel readback in playback.
+- Target selection, preview/start/switch/stop, cursor, rate, crop and display fit.
+- Video only. The source application continues playing its own audio; no
+ loopback capture, audio monitoring controls or extra audio playback.
+- Closed/minimized targets, source resize, display changes and errors surfaced.
+- No game injection, input forwarding or claims of exclusive-fullscreen support.
+
+## Upstream
+
+`robmikh/Win32CaptureSample`, MIT, commit
+`49fefe79fd9b11025f0b5eb91783a98888516070`.
+Adapt SimpleCapture's free-threaded WGC pool, session lifecycle and resize
+pattern; replace its swapchain with Veyra's leased GPU ingress. Keep attribution
+in source and THIRD_PARTY_NOTICES.md.
+
+## Verification / Current State
+
+Local implementation and targeted verification completed; not merged or released.
+The sidebar uses Lucide `app-window`, distinct from the capture-card `monitor`.
+Audio controls and the provisional loopback implementation were removed at the
+user's request. Original application audio is neither captured nor delayed;
+enhancement can therefore make the displayed picture lag behind that audio.
+
+Build: `scripts/build-isolated.ps1 -Root . -BuildDirectory E:/项目/Veyra/build/screen-capture-20260919 -DependencyCache E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt -TempDirectory E:/项目/Veyra/tmp/screen-capture-20260919 -DisplayVersion 1.4.2beta -Targets veyra_screen_capture_tests,veyra`.
+Latest `build9.log` linked both targets successfully. `build8.log` also built
+the HDR color, capture color contract and existing WASAPI test targets.
+
+Tests used `scripts/run-short-test.ps1` with explicit LogPrefix and task-local
+TEMP/TMP. `veyra_screen_capture_tests.exe --engine` used a 120-second timeout;
+`--base` used 60 seconds. Logs are under the artifact log directory below.
+
+- `screen-test3.stdout.log`: failures=0; actual RGB stripe pixels via WGC window,
+ WGC monitor and DXGI monitor; monotonic timestamps, bounded pool leases,
+ minimize/restore, resize, crop, close/reopen and engine stop/drain.
+ Four-second producer sample: 138 delivered, 139 received, one dropped.
+- RTX 5070 NR + DLSS 4X: Feature 18 Create `0x1`, SEH=0; 652 source frames,
+ 1956 FG evaluations, 1665 generated presentations, 287 generated frames expired
+ after evaluation; slotWaitCount=0. This proves actual execution, not perfect
+ pacing, physical refresh rate or absence of drops.
+- `screen-test4.stdout.log`: latest source, failures=0; additionally checked
+ monitor capture excludes existing own windows and stop restores their original
+ display affinity for both WGC and DXGI.
+- `hdr-test.log`: four SCREEN_SCRGB cases passed (native/tone-mapped output,
+ exposure 0/1), alongside existing HDR GPU cases. Physical HDR not tested.
+- `veyra_wasapi_input_tests.exe --offline`: 18 checks, zero failures
+ (`wasapi-offline.stdout.log`); `veyra_capture_color_tests.exe`:
+ failures=0 (`capture-color.stdout.log`). No new screen audio code remains.
+- GUI preview observed with readable controls, distinct icon and no audio row.
+ Interactive crop/start/stop were not independently exercised through UI;
+ integration tests exercise the underlying capture and engine lifecycle.
+
+Earlier failures: mixed int/LONG compilation corrected; an initial test wrongly
+required 60 FPS from a slower GDI producer, and an immediate resize assertion
+did not allow the queued old frame to drain. Both assertions now test the actual
+contract. The removed loopback experiment had a timestamp failure; it is not
+part of this implementation. Initial GUI launch lacked FFmpeg DLL lookup;
+existing approved portable root DLLs were staged beside the build EXE.
+
+Known limits: no game injection, exclusive-fullscreen guarantee or input
+forwarding; physical HDR, protected content, multi-GPU and real games untested.
+DXGI has no cursor and rejects rotated displays. Own windows created after a
+monitor session starts are not automatically excluded. Full release/file/export
+regressions were not run. Existing teardown logs include an unsubmitted-command
+list discard HRESULT `0x80004005`; no content test failed, but it is not being
+claimed as fixed. Next validation is user testing with their actual target app.
+
+Artifacts: `E:/项目/Veyra/{build,tests,logs,tmp,deps}/screen-capture-20260919/`.
+Upstream checkout: `E:/项目/Veyra/deps/screen-capture-20260919/Win32CaptureSample`.
+
+## User feedback: static 0 FPS / moving 50 FPS
+
+### Follow display refresh (default)
+
+The rate selector now defaults to following the captured target's display.
+Window capture uses MonitorFromWindow; monitor capture uses the selected monitor.
+DisplayConfig preserves fractional refresh rates, with EnumDisplaySettings as
+fallback. A failed initial query uses 60 FPS with a warning; transient failures
+retain the last known rate. The existing one-second display check updates the
+limit and flags a temporal discontinuity when the rate changes. Manual
+30/60/120/144/240 limits remain. Preview now obeys this setting too.
+
+UI preference `ScreenCapture/RateMode` starts at automatic (0); the previous
+experimental `Fps` index is not reused because its index meaning has changed.
+Subsequent explicit selections persist. This is still a ceiling, not constant
+output resampling or a claim that capture runs at the monitor's refresh rate.
+
+`build10.log`: application and capture tests built successfully with the command
+above. `screen-test5.stdout.log` (`--base`, timeout 60 seconds): failures=0;
+automatic default/URI, target monitor rate and first-frame duration passed.
+Actual local rate was 100/1 Hz, independently compared with display settings.
+WGC window, WGC monitor and DXGI monitor all produced verified RGB pixels in
+automatic mode. Manual 60 FPS regression delivered 131 frames in four seconds,
+131 received and zero dropped, reflecting this test producer's cadence.
+Physical fractional modes, moving between different-refresh displays and live
+display-mode changes have not been exercised. NR/FG were not rerun this revision.
+GUI screenshot and accessibility tree confirmed the automatic default is selected
+and its full label fits beside the cursor toggle. The test GUI remains open.
+
+The current option is a rate ceiling, not fixed-rate resampling. WGC/DXGI
+deliver changed frames; no frame means Waiting, and no cached frame is emitted
+with a fabricated capture timestamp. The user requested clarification about
+fixed 30/60 output. No fixed-rate mode has been implemented in this revision.
+
+Read-only verification of `gui.log` found 300 delivered / 300 received over
+six seconds (04:20:16.353 to 04:20:22.353 UTC), with zero drops. Later intervals
+also show 300 frames in six seconds and an unchanged dropped counter. In this
+sample, WGC delivery itself is 50 FPS, not a 60 FPS source reduced to 50 by our
+limiter. Win32_VideoController reports the RTX 5070 display at 2560x1440, 100 Hz.
+Half-refresh content is plausible, but neither browser video cadence nor DWM
+behavior was independently measured; the 100 Hz value alone does not prove it.
+
+Fixed output would require a separate output clock and reuse of the latest
+image when no new one arrives. Repeats must be counted separately from new
+capture and AI-generated frames, retaining original capture timestamps. It
+would stabilize presentation submissions, not invent missing motion or ensure
+60 physical refreshes on a 100 Hz screen. Uniform 60 Hz physical cadence would
+also require a suitable display refresh/VRR configuration.
diff --git a/docs/UI_CAPTURE_RATE_1.4.2_2026-09-19.md b/docs/UI_CAPTURE_RATE_1.4.2_2026-09-19.md
new file mode 100644
index 00000000..1bf81e7f
--- /dev/null
+++ b/docs/UI_CAPTURE_RATE_1.4.2_2026-09-19.md
@@ -0,0 +1,50 @@
+# 1.4.2 UI 与采集设备帧率验收
+
+## 范围
+
+分支 `codex/screen-capture-20260919`,工作树基线 `12238df`。保留此前屏幕采集、P010 HDR、XeSS 拖动回退及全部隔离修复,构建显示版本 1.4.2。只做本地测试包,不合并 main、不推送、不发布。
+
+- AppShell.cpp:最近打开与 PS5 原本同在 y=316,移动最近打开到 372,恢复 PS5 点击入口。
+- Theme.h / PopupSelector.h / SettingsWindow.cpp:原生热跟踪和自绘竞争改为统一缓冲绘制,重复选中值不再重绘;滚动容器组合绘制并刷新子控件,弹出列表同一行反复悬停不重复 invalidate。
+- CapturePanel.cpp / CapturePreferenceStore.h:设备帧率数字输入、0 默认、小数、重连应用及 v3 持久化;v1/v2 配置默认帧率为0。
+- CaptureCardSource.h/.cpp / CaptureFrameRate.h / EngineController.cpp:URI 携带帧率、DirectShow VIDEOINFOHEADER/2 的 AvgTimePerFrame 协商、连接后检查实际媒体类型、具体错误反馈与重连保留参数。
+- UiContractTests.cpp / PopupSelectorTests.cpp / CaptureSourceTests.cpp:非法值、旧配置迁移、悬停重绘和设备实际回调帧率回归。
+- package-portable.ps1:补齐窗口采集上游 MIT 许可。
+
+## 帧率边界
+
+输入范围为 1–1000 FPS,0 沿用所选格式。范围不是设备能力承诺。接受约0.11%差异以兼容30/29.97等标称档位。驱动拒绝或返回其他媒体帧率时明确报错,未增加软件丢帧限速。
+
+设备媒体类型仍是驱动报告值,不能保证每个驱动诚实执行;日志另有实际回调速率可核对。本机虚拟设备实收验证不是物理采集卡支持证明。精确60→30且游戏每帧重复两次时,均匀采样通常能得到连续独立帧;50→30、可变帧率或游戏节奏不稳时无法保证112233变123。没有新增画面去重或伪造时间戳。
+
+## 实际验证
+
+产物:`E:/项目/Veyra/{build/screen-capture-20260919,logs/ui-1.4.2-20260919,tests/ui-1.4.2-20260919,tmp/ui-1.4.2-20260919}`。
+
+构建:`scripts/build-isolated.ps1 -Root . -BuildDirectory E:/项目/Veyra/build/screen-capture-20260919 -DependencyCache E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt -TempDirectory E:/项目/Veyra/tmp/ui-1.4.2-20260919 -DisplayVersion 1.4.2`,目标 veyra、veyra_ui_contract_tests、veyra_capture_tests、veyra_popup_selector_tests。build1/2/3 均 exit0。
+
+测试均通过 scripts/run-short-test.ps1 执行,单次限时60秒,屏幕引擎120秒:
+
+| 测试 | 实际结果 |
+| --- | --- |
+| UI contracts(prefs2) | exit0,含旧v1/v2配置、帧率保存和非法值检查 |
+| PopupSelector --test | exit0,case0–14;重复悬停不重绘,点击提交正确 |
+| Capture --list | 只有 WebcastMate/OBS 虚拟摄像头;VC-007PRO 未连接 |
+| Capture --rate-test capture:1:0:-1?fps=30 30 | exit0;重连前/后实收29.981/29.989 FPS,PTS单调 |
+| Capture --rate-test capture:1:0:-1?fps=40 40 | exit0;39.796/40.156 FPS,PTS单调 |
+| Capture --rate-test capture:1:0:-1 0 | exit0;默认59.956/60.202 FPS,PTS单调 |
+| ScreenCapture --engine | exit0,failures=0;含WGC/DXGI真实RGB、自动100Hz、生命周期、NR+DLSS4X与停止释放 |
+
+最后一项实际 NR CreateFeature18=0x1、seh=0,584 源帧进入处理、1752 FG 执行、1455 生成帧呈现、294 生成帧过期;不宣称零丢帧或屏幕端满4X。
+
+Computer Use 目视检查:PS5 与最近打开分离,PS5 面板可打开;设置连续滚动、SR下拉打开/关闭没有发现残留重影,帧率输入及全部采集设置显示完整。静态截图不能证明所有机器动态无闪烁,交付后仍需用户观察。
+
+测试失误:首次 rate30 使用旧 capture URI,实际29.78FPS通过但重连失败,因为生产重连只支持稳定设备身份。修正测试装配使用产品 makeCapturePath 后重测通过。首次 GUI 启动传入不存在的 --log 参数,被当成媒体路径;随后用正确 --smoke-empty --smoke-seconds 240 --smoke-view pro 重开通过。
+
+## 交付与未执行项
+
+目标包:`E:/项目/Veyra/test-packages/1.4.2/Veyra-1.4.2-test-win64-portable.zip` 与对应 `Veyra-1.4.2-test-source.zip`。运行库沿用已批准身份,保留 patched FFmpeg、RemotePlay 对应源码、许可证和双二维码。
+
+便携包已生成,467110278字节,SHA256 `23E4427065B36AE94D9FA118A0441DA12F5017D3EAB8047E8DB87A183826BD7E`。压缩包114文件按manifest回读核验通过;支持区两图width=220。`scripts/acceptance/portable-smoke.ps1` 七组均通过,包含默认效果全关、基础播放、原版/社区SR+NR+FG、视频SR及Ampere NR;仅证明这些运行库在本机5070执行,不代表30/40硬件验收。实际输出截图已检查。日志见 `portable-smoke.log`,结果见tests同任务`portable-smoke/result.json`。
+
+未执行反馈者5060、RTX30/40实机、VC-007PRO硬件帧率协商及物理HDR显示。本轮没有更换NVIDIA/Intel运行组件。下一步是用户实卡验证30/40 FPS是否接受及游戏节奏。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index a8ce99f5..59270240 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,95 @@
# Veyra 工作记录
+## 2026-09-19 1.4.2 测试包、设备帧率与 UI 修复
+
+隔离分支 `codex/screen-capture-20260919`,保留全部既有工作树改动。具体文件、实现与边界见 [验收记录](UI_CAPTURE_RATE_1.4.2_2026-09-19.md)。采集设置新增手输设备帧率,DirectShow AvgTimePerFrame 协商及连接结果检查、v3 保存/旧配置迁移和重连保留。没有新增软件丢帧器或画面去重。恢复被最近打开遮挡的 PS5 按钮;统一控件热跟踪重绘,滚动面板组合绘制。更新 README、CURRENT_STATUS、1.4.2 notes、组件与源码说明,打包添加窗口采集 MIT 许可。
+
+实际命令与证据:`scripts/build-isolated.ps1 -Root . -BuildDirectory E:/项目/Veyra/build/screen-capture-20260919 -DependencyCache E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt -TempDirectory E:/项目/Veyra/tmp/ui-1.4.2-20260919 -DisplayVersion 1.4.2`,目标 veyra / veyra_ui_contract_tests / veyra_capture_tests / veyra_popup_selector_tests;build1/2/3 均 exit0。`scripts/run-short-test.ps1` 执行 UI contracts、popup --test、capture --list、capture --rate-test 30/40/0 及 screen --engine 均 exit0。日志 `E:/项目/Veyra/logs/ui-1.4.2-20260919/`,设置与截图 `E:/项目/Veyra/tests/ui-1.4.2-20260919/`,子进程 TEMP/TMP 为对应 tmp。虚拟OBS摄像头30FPS重连前后29.981/29.989,40FPS为39.796/40.156,默认60FPS为59.956/60.202。VC-007PRO未连接,没有物理卡降帧率验收。
+
+RTX5070屏幕源NR+DLSS4X短测:NR CreateFeature id=18 result=0x1 seh=0,DLSSG Create result=0x1;584源帧、1752FG执行、1455生成呈现、294生成帧过期,failures=0。GUI观察PS5面板可打开、采集FPS输入和滚动/下拉显示正常。首次rate测试用旧URI导致重连失败,修正测试用稳定设备身份后通过;首次GUI误传不存在的--log,被解析为媒体,正确参数重开通过。均没有当作产品通过证据掩盖。
+
+打包命令:`scripts/package-portable.ps1 -Root . -Version 1.4.2 -Label '-test' -OutputDirectory E:/项目/Veyra/test-packages/1.4.2 -BuildDirectory E:/项目/Veyra/build/screen-capture-20260919 -DependencyRoot 'C:/Users/123/Desktop/Veyra DLSS Video Player' -LocalVideoHdr`,exit0。便携ZIP 467110278字节,SHA256 `23E4427065B36AE94D9FA118A0441DA12F5017D3EAB8047E8DB87A183826BD7E`。包内114文件逐一按manifest校验通过,两个二维码width=220保留;运行组件沿用已批准身份,无SDK/个人配置/媒体/日志。
+
+`scripts/acceptance/portable-smoke.ps1 -PackageDirectory <package-stage> -InputFile E:/项目/Veyra/tests/1.4.2beta/visible-scene.mp4 -OutputDirectory E:/项目/Veyra/tests/ui-1.4.2-20260919/portable-smoke -CaseSeconds 7`,exit0,7组通过;临时关闭manifest及限制PATH后仍能播放和增强,依赖来自包内。检查实际截图非空、有正常内容。源码包使用本轮tmp/package-source.ps1生成当前工作树快照,包括未跟踪新源码及未改动的1.4.1 FFmpeg/RemotePlay对应源码,每项SHA256回读核对。保留最终ZIP、当前构建和证据,包stage仅为本轮中间副本,可清理。
+
+本轮没有合并main、提交、push或GitHub发布。尚未执行反馈者5060、RTX30/40本轮实卡、物理HDR和采集卡30/40FPS验收;不宣称游戏重复画面去重或所有卡顿根治。下一步由用户测试设备实际接受的帧率及UI动态表现。
+
+## 2026-09-19 屏幕采集默认跟随显示器刷新率
+
+GUI 实际打开专业模式的屏幕采集面板,截图及可访问性树确认默认选中“跟随显示器刷新率”,下拉框与指针开关无重叠、文字完整;保留测试窗口供用户试用。最初 Hidden 启动无法获取可交互窗口,停止该次自建进程后通过 computer-use 正常打开。`git diff --check` 通过,仅已有换行转换提示。
+
+用户要求新增并默认选择跟随显示器。修改 ScreenCaptureSource.h/.cpp、ScreenCapturePanel.cpp、ScreenCaptureTests.cpp:fps=0 表示自动,窗口取所在屏幕、显示器取目标屏幕;保留 DisplayConfig 有理数刷新率,每秒检查变化;查询失败保留已有值,首次失败警告并回退 60。保留手动 30/60/120/144/240,预览不再强制 30;新 RateMode 配置避免旧索引错位,初次升级默认自动,此后记忆选择。仍为采集上限,不重复静止帧凑数。
+
+实际命令:`./scripts/build-isolated.ps1 -Root . -BuildDirectory E:/项目/Veyra/build/screen-capture-20260919 -DependencyCache E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt -TempDirectory E:/项目/Veyra/tmp/screen-capture-20260919 -DisplayVersion 1.4.2beta -Targets veyra_screen_capture_tests,veyra`,exit 0,日志 `E:/项目/Veyra/logs/screen-capture-20260919/build10.log`。
+`scripts/run-short-test.ps1 -Exe E:/项目/Veyra/build/screen-capture-20260919/veyra_screen_capture_tests.exe -Arguments --base -TimeoutSeconds 60 -LogPrefix E:/项目/Veyra/logs/screen-capture-20260919/screen-test5`,测试工作目录为同任务 tests,TEMP/TMP 为同任务 tmp;exit 0 / failures=0。本机自动识别 100/1 Hz;自动窗口、WGC 显示器与 DXGI 显示器真实 RGB 像素通过,首帧时长、URI、租约、恢复、缩放、关闭及手动 60 回归通过。实际小数刷新率、不同刷新率跨屏及实时系统改刷新率未测试,本轮未执行 NR/FG Create/Evaluate。没有新增专有组件、打包、推送或发布。
+
+## 2026-09-19 窗口 / 显示器采集与纯画面收尾
+
+用户追加反馈静止 0 FPS、网页视频约 50 FPS,询问固定 30/60。只读核对 gui.log:04:20:16.353 到 04:20:22.353 UTC 收到和交付均新增 300 帧、dropped=0,即此样本 WGC 实际交付 50 FPS;后续多个六秒区间相同。`Get-CimInstance Win32_VideoController` 显示当前 RTX5070 输出 2560x1440@100Hz,但未独立证明浏览器/DWM 半刷新率是原因。现有选项是上限、没有固定输出时钟;本轮未新增重复呈现机制,不将重复画面宣称为新采集/AI 插帧。详见本轮实现记录末节。
+
+隔离分支 `codex/screen-capture-20260919`,基线 `12238df`;保留已有 P010 HDR 修复和 XeSS 回退测试改动。
+专业模式左侧新增屏幕采集,使用独立 Lucide app-window 图标;支持 WGC 窗口/显示器、DXGI 显示器兼容、预览、裁剪、帧率上限、指针及开始/切换/停止。用户明确不采集声音,已撤去本轮 loopback 实现、音频控件和参数;原应用直接发声,Veyra 不补偿这一路声音与增强画面的时差。
+
+主要文件:ScreenCaptureSource.h/.cpp、ScreenCapturePanel.h/.cpp、AppShell.cpp、EngineController.cpp、FramePacket.h、EnhanceGraph.cpp、RgbToLinear.hlsl、Subtitles.cpp、SourceTitle.h、CMakeLists.txt、Lucide 资源生成脚本与头文件、ScreenCaptureTests.cpp / ScreenScRgbCases.h;上游固定提交和 MIT 许可写入 THIRD_PARTY_NOTICES.md 与 licenses/WIN32_CAPTURE_SAMPLE_MIT.txt。README 与[本轮实现记录](SCREEN_CAPTURE_PLAN_2026-09-19.md)同步更新。
+
+实际构建命令:`./scripts/build-isolated.ps1 -Root . -BuildDirectory E:/项目/Veyra/build/screen-capture-20260919 -DependencyCache E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt -TempDirectory E:/项目/Veyra/tmp/screen-capture-20260919 -DisplayVersion 1.4.2beta -Targets veyra_screen_capture_tests,veyra`,build9 成功;build8 另含 HDR/采集颜色/原有音频测试目标。
+通过 `scripts/run-short-test.ps1 -Exe <build>/veyra_screen_capture_tests.exe -Arguments --engine -TimeoutSeconds 120 -LogPrefix <logs>/screen-test3`,以及 `--base / 60 / screen-test4` 执行真实采集,均 failures=0。WGC/DXGI 实际 RGB 内容、时间戳、六槽租约、缩放、最小化恢复、关闭重开、引擎停止和自身窗口排除/恢复通过。NR CreateFeature18=0x1、seh=0;652 源帧 / 1956 FG 执行 / 1665 生成呈现,287 生成帧过期,不能宣称零丢帧或物理显示满 4X。
+
+`veyra_wasapi_input_tests.exe --offline`:18 checks / 0 failures;采集颜色合同 failures=0;HDR GPU 测试四组 SCREEN_SCRGB 通过。GUI 已观察预览、无音频选项和新图标;未独立完成全部鼠标交互验收。物理 HDR、实际游戏、多 GPU、全发布/导出回归未执行。详细失败过程和边界见实现记录。
+
+产物统一在 `E:/项目/Veyra/{build,tests,logs,tmp,deps}/screen-capture-20260919`;日志含 build8/9、screen-test3/4、hdr-test、wasapi-offline、capture-color、gui。fonttools 仅安装到本任务 deps/python;没有新增专有运行库或包。构建目录借用已批准 portable runtime,并复制其根目录 FFmpeg/MSVC DLL 供测试 EXE 启动。临时目录为空,测试进程已结束,保留用户正在使用的 GUI。未合并 main、推送、打包或发布;下一步由用户验收实际窗口采集效果。
+
+## 2026-09-19 P010 HDR 识别与调色修复
+
+见 [排查与验证记录](CAPTURE_HDR_REPAIR_2026-09-19.md)。修复明确 PQ/HLG 但色域字段缺失时的错误 SDR 默认值;保留驱动声明的 chroma siting,补充原始颜色元数据日志。GPU 复现非中性调色截断 HDR 合法负分量,修复有符号线性光及 HSV 往返。
+采集合同单测、P010 部分元数据与文件输入 8 组逐像素对照、HDR 调色 8 组、原有 HDR/SDR GPU 回归和 SDR 调色专项通过;详细命令、失败记录、日志见报告。
+新产物统一在 `E:/项目/Veyra/{build,logs,tmp}/capture-hdr-20260919/`,早期增量验证复用已有 `build/xess-view-reset-20260919`。未发布/合并/打包,未执行反馈者实卡及物理 HDR 显示验收,不能把 P010 位深当 HDR 检测依据。
+
+## 2026-09-19 XeSS 拖动方案完整回退
+
+首次尝试把 `PreviewView` 变化作为 present-sink 时域边界,并在拖动期间暂停 XeSS/FSR generation。
+用户实测反馈 XeSS 无法打开,确认该策略回归严重,已完整撤回:删除视图历史状态机、拖动期间禁用生成、
+稳定后 reset 以及对应测试,恢复原有拖动时继续生成、偶发掉帧的行为。
+
+同批 `HUDLESS_COLOR` 裁剪修改也已撤回,产品代码恢复本轮修改前的路径。
+闪烁原因仍待独立复现,不能宣称已经修复。
+
+回退后重新构建命令:
+`./scripts/build-isolated.ps1 -Root . -BuildDirectory E:/项目/Veyra/build/xess-view-reset-20260919 -DependencyCache E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt -TempDirectory E:/项目/Veyra/tmp/xess-view-reset-20260919 -DisplayVersion 1.4.2beta -Targets veyra_presentation_worker_tests,veyra_preview_geometry_tests,veyra`
+构建 exit 0,`veyra_presentation_worker_tests.exe` 与 `veyra_preview_geometry_tests.exe` 全部通过,
+日志为 `E:/项目/Veyra/logs/xess-view-reset-20260919/build.log`。
+
+便携包已替换为回退后的主程序:
+`E:/项目/Veyra/test-packages/xess-view-reset-20260919/Veyra-xess-view-reset-20260919-win64-portable/`。
+首次回退(仍带裁剪修改)`Veyra.exe` SHA-256 为 `E842F9B9FFD9635B6EF4447BC42BBEF5ABE23E2EF5F1D42A01A7DCDE8C731C64`,已被下述完整回退构建替换。
+直接 `--no-nr --no-sr --no-fg --smoke-seconds 3` 启动 exit 0,日志为
+`E:/项目/Veyra/logs/xess-view-reset-20260919/package-smoke-after-revert.log`。
+该 smoke 关闭了 FG,只证明普通播放启动,不能作为 XeSS 验收。
+
+完整回退后沿用上述构建参数,目标改为 `veyra,veyra_experimental_backend_tests`,exit 0;
+日志 `E:/项目/Veyra/logs/xess-view-reset-20260919/build-full-revert.log`。
+本机 RTX 5070 / 616.56 实际执行:
+
+- `veyra_experimental_backend_tests.exe xess-pan2 E:/项目/Veyra/tests/xess-view-reset-20260919/pan2`:
+ 48 个源帧,总生成提交 43,连续平移区间生成 37,D3D debugErrors=0,exit 0。
+- 同命令 `xess-pan4` / `pan4`:总生成提交 129,连续平移区间生成 111,debugErrors=0,exit 0。
+ 两项均使用真实 NVOF/XeSS,包含重复源帧不额外生成与窗口尺寸变化检查。
+- 便携版 `Veyra.exe E:/项目/Veyra/tests/1.4.2beta/visible-scene.mkv --no-nr --no-sr --fg-xess --fg-multiplier 2 --smoke-seconds 12`:
+ 276 处理帧、272 生成提交、failed=false、exit 0。4X 同参数改倍率 4:276 / 816,failed=false、exit 0。
+ 两项 XeSS Create/Init result=0;稳态 framesPresented 分别为 2/4,result=0。
+ 日志 `E:/项目/Veyra/logs/xess-view-reset-20260919/package-xess2.engine.log` 和 `package-xess4.engine.log`,
+ 包含此前追加的历史会话,当前两次从 02:46:59Z / 02:47:26Z 起。
+
+上述测试均经 `scripts/run-short-test.ps1`,TimeoutSeconds=60,LogPrefix 显式指向本任务 logs;
+仅进程 TEMP/TMP 指向本任务 tmp。测试程序通过 build 下 runtime_local junction 使用已有便携运行库,未引入新 DLL。
+便携 EXE 已更新,package-manifest.json 的 EXE 大小和哈希同步;最终 SHA-256:
+`DE81DC0C84C2845B8D933695B2CD92DAEECBB8F07292FFAB1EF5DD5519D17A6A`。
+
+产品源码与本轮修改前 HEAD 一致,剩余源码差异只有后端测试;新增文档记录于本文件。
+以上生成计数为 SDK 提交,不是扫描输出/人眼画质证明;未实际模拟鼠标消息、未执行 NR/SR 组合或其他显卡回归。
+下一步由用户使用此 EXE 确认原故障恢复;闪烁和偶发拖动掉帧仍待独立复现。
+未合并 main、未推送、未发布。
+
## 2026-09-19 次日交付复核
核对 `4c41ffa` 干净工作区及已交付EXE SHA256一致。Windows System事件1074/6006确认00:08关机、6005确认08:41再次启动;本次仅补记实际结果,不再次关机。5060旧日志无更新,仍需该用户在新构建启用DLSS后回传复现日志;不将现有5070短测扩大为5060故障根治证明。详见本轮报告末尾。
@@ -4407,3 +4497,15 @@ Blackwell 上会改变一条已经正常工作的路径,无法区分"补丁生
已更新:构建依赖与便携打包命令改为1.3.0,补充dav1d/RemotePlay对应说明;本地整合状态新增当前1.3.0发布、main/tag和远端资产核验,并把dc44c48候选、未发布结论和待办明确标为历史快照。没有改动运行时代码、SDK、DLL、版本标签或发布资产。
验证:`git diff --check`通过(仅换行格式提示);随后提交文档并推送`nrvideo/main`。本次不重新构建、不替换便携包,功能与硬件验收边界继续以`docs/RELEASE_NOTES_1.3.0.md`为准。
+
+## 2026-09-19 XeSS 回退验证补充
+
+曾将旧 `XessGenerationGate` 推测为本次回归根因,但该门控早于拖动修改,现有证据不能支持此结论。
+相关额外删除已全部撤销。此次只回退拖动暂停方案及同批未验证的裁剪修改。
+现有普通播放 smoke 使用 `--no-fg`,不能证明 XeSS 可用;新增现有后端集成测试的
+`xess-pan2` / `xess-pan4` 模式,核对开启、连续平移时 SDK 实际生成计数、重复原帧和 D3D 错误。
+# 2026-09-19 1.4.2 正式发布
+
+用户授权本轮修复、整合 main、GitHub 发布及新群/HDR 对比图片公开。AppShell 全屏切换先 TTM_POP,再按 full 状态 TTM_ACTIVATE,退出恢复正常提示。更新中英文 README、1.4.2 notes、组件与对应源码说明、RELEASE_SUPPORT;打包正式纳入已授权 TrueHDR,附 README 图片与窗口采集 MIT 许可。具体命令与最终状态见 RELEASE_1.4.2_EXECUTION.md。
+
+产物统一在 E:/项目/Veyra/releases/1.4.2、build/screen-capture-20260919,以及 logs/tests/tmp/release-1.4.2-20260919。未覆盖上一轮内测包。
diff --git a/docs/images/1.4.2/community-group.png b/docs/images/1.4.2/community-group.png
new file mode 100644
index 00000000..3c4d60c6
Binary files /dev/null and b/docs/images/1.4.2/community-group.png differ
diff --git a/docs/images/1.4.2/rtx-video-hdr-comparison.jpg b/docs/images/1.4.2/rtx-video-hdr-comparison.jpg
new file mode 100644
index 00000000..f24c5347
Binary files /dev/null and b/docs/images/1.4.2/rtx-video-hdr-comparison.jpg differ
diff --git a/include/veyra/pipeline/FramePacket.h b/include/veyra/pipeline/FramePacket.h
index 2fa33257..264e0425 100644
--- a/include/veyra/pipeline/FramePacket.h
+++ b/include/veyra/pipeline/FramePacket.h
@@ -43,6 +43,7 @@ enum class SourceKind : uint8_t {
RemotePlay, // PS5 Remote Play stream (Chiaki transport)
Image, // WIC single image
TestPattern, // synthetic harness input
+ ScreenCapture,
};
inline const char* sourceKindName(SourceKind k) {
@@ -52,6 +53,7 @@ inline const char* sourceKindName(SourceKind k) {
case SourceKind::RemotePlay: return "RemotePlay";
case SourceKind::Image: return "Image";
case SourceKind::TestPattern: return "TestPattern";
+ case SourceKind::ScreenCapture: return "ScreenCapture";
default: return "Unknown";
}
}
@@ -127,9 +129,10 @@ struct ColorDescription {
// Static HDR metadata in cd/m2; zero means absent/unspecified. These are
// declarations, not measured frame peaks or dynamic Dolby Vision metadata.
float hdrMaxCllNits = 0, hdrMaxFallNits = 0, hdrMasteringPeakNits = 0;
+ bool scRgb = false; // Explicit WGC FP16 linear BT.709, 1.0 = 80 nits.
bool isHdrPath() const {
- return transfer == TransferFunction::PQ || transfer == TransferFunction::HLG;
+ return scRgb || transfer == TransferFunction::PQ || transfer == TransferFunction::HLG;
}
};
diff --git a/include/veyra/source/CaptureCardSource.h b/include/veyra/source/CaptureCardSource.h
index 345bf3cc..2eb5e192 100644
--- a/include/veyra/source/CaptureCardSource.h
+++ b/include/veyra/source/CaptureCardSource.h
@@ -30,7 +30,7 @@ public:
static std::vector<CaptureDevice> deviceDetails(bool audio=false);
static std::vector<std::wstring> devices(bool audio=false);
static std::wstring makeCapturePath(unsigned videoIndex,const CaptureDevice& video,
- int format,int audioMode,const CaptureDevice* audio,unsigned colorOverride=0);
+ int format,int audioMode,const CaptureDevice* audio,unsigned colorOverride=0,double requestedFps=0);
static std::vector<CaptureFormat> formats(unsigned device);
static std::vector<CaptureFormat> formatsByPath(std::wstring_view devicePath);
bool open(const SourceOpenDesc&)override;
@@ -61,11 +61,13 @@ public:
void setAudioSync(unsigned mode,int offsetMs);
sink::CaptureAudioState audioState()const;
const SourceInfo& info()const override;
+ const std::wstring& errorMessage()const{return error_;}
SourceReadStatus read(pipeline::FramePacket&,const AVFrame**)override;
SourceReadStatus tryRead(pipeline::FramePacket&,const AVFrame**);
bool seek(const pipeline::Rational&)override{return false;}
void close()noexcept override;
private:
+ std::wstring error_;
bool connectDirectShowAudio(const SourceOpenDesc&);
// AVerMedia capture cards need their installed vendor component to arm
// non-PCM (Dolby/DTS) passthrough before the audio pin is negotiated.
diff --git a/include/veyra/source/CaptureFrameRate.h b/include/veyra/source/CaptureFrameRate.h
new file mode 100644
index 00000000..5f00c1e4
--- /dev/null
+++ b/include/veyra/source/CaptureFrameRate.h
@@ -0,0 +1,26 @@
+#pragma once
+#include <cmath>
+#include <cstdint>
+#include <locale>
+#include <sstream>
+#include <string>
+#include <string_view>
+
+namespace veyra::source {
+inline bool validCaptureFrameRate(double fps) {
+ return std::isfinite(fps)&&(fps==0||(fps>=1&&fps<=1000));
+}
+inline bool parseCaptureFrameRate(std::wstring_view text,double& fps) {
+ if(text.empty()||text.size()>16||text.find_first_not_of(L"0123456789.")!=std::wstring_view::npos)return false;
+ std::wistringstream input{std::wstring(text)};input.imbue(std::locale::classic());
+ double value=0;if(!(input>>value)||!input.eof()||!validCaptureFrameRate(value))return false;
+ fps=value;return true;
+}
+inline int64_t captureFrameInterval(double fps) {
+ return validCaptureFrameRate(fps)&&fps>0?int64_t(std::llround(10000000.0/fps)):0;
+}
+inline bool captureFrameRateMatches(double requested,int64_t interval) {
+ // Permit integer 100ns rounding and nominal 30 vs 30000/1001 modes.
+ return requested>0&&interval>0&&std::abs(10000000.0/interval-requested)<=requested*.0011;
+}
+}
diff --git a/include/veyra/source/CaptureMediaType.h b/include/veyra/source/CaptureMediaType.h
index 41d21de5..c6ceb421 100644
--- a/include/veyra/source/CaptureMediaType.h
+++ b/include/veyra/source/CaptureMediaType.h
@@ -17,6 +17,7 @@ struct CaptureMediaLayout {
bool bottomUp=false;
AVPixelFormat format=AV_PIX_FMT_NONE;
REFERENCE_TIME duration=0;
+ DWORD colorControlFlags=0;
pipeline::ColorDescription color;
CapturePacking packing=CapturePacking::Unknown;
unsigned planes=1,chromaStride=0,chromaRowBytes=0;
@@ -97,6 +98,7 @@ inline bool captureMediaLayout(const AM_MEDIA_TYPE& type,CaptureMediaLayout& out
// the old RGB ingress, instead of applying a camera OETF a second time.
out.color.transfer=pipeline::TransferFunction::SRGB;out.color.transferAssumed=true;
out.color.preserveSdrCodeValues=true;
+ out.colorControlFlags=flags;
if(flags&AMCONTROL_COLORINFO_PRESENT){
DXVA2_ExtendedFormat ext{};ext.value=flags;
if(ext.NominalRange==DXVA2_NominalRange_0_255){out.color.range=pipeline::ColorRange::Full;out.color.rangeAssumed=false;}
@@ -109,11 +111,26 @@ inline bool captureMediaLayout(const AM_MEDIA_TYPE& type,CaptureMediaLayout& out
else if(ext.VideoTransferMatrix==4||ext.VideoTransferMatrix==5){out.color.matrix=pipeline::YuvMatrix::BT2020NCL;out.color.matrixAssumed=false;}
else if(ext.VideoTransferMatrix!=DXVA2_VideoTransferMatrix_Unknown)return false;
if(ext.VideoPrimaries==9){out.color.primaries=pipeline::ColorPrimaries::BT2020;out.color.primariesAssumed=false;}
+ else if(ext.VideoPrimaries==DXVA2_VideoPrimaries_BT709){out.color.primaries=pipeline::ColorPrimaries::BT709;out.color.primariesAssumed=false;}
+ else if(ext.VideoPrimaries==DXVA2_VideoPrimaries_BT470_2_SysBG){out.color.primaries=pipeline::ColorPrimaries::BT601_625;out.color.primariesAssumed=false;}
+ else if(ext.VideoPrimaries==DXVA2_VideoPrimaries_SMPTE170M){out.color.primaries=pipeline::ColorPrimaries::BT601_525;out.color.primariesAssumed=false;}
if(ext.VideoTransferFunction==DXVA2_VideoTransFunc_10){out.color.transfer=pipeline::TransferFunction::Linear;out.color.transferAssumed=false;}
else if(ext.VideoTransferFunction==DXVA2_VideoTransFunc_sRGB){out.color.transferAssumed=false;}
else if(ext.VideoTransferFunction==DXVA2_VideoTransFunc_709){out.color.transfer=pipeline::TransferFunction::BT709;out.color.transferAssumed=false;}
else if(ext.VideoTransferFunction==15||ext.VideoTransferFunction==16){out.color.transfer=ext.VideoTransferFunction==15?pipeline::TransferFunction::PQ:pipeline::TransferFunction::HLG;out.color.transferAssumed=false;}
else if(ext.VideoTransferFunction!=DXVA2_VideoTransFunc_Unknown&&ext.VideoTransferFunction!=DXVA2_VideoTransFunc_709&&ext.VideoTransferFunction!=DXVA2_VideoTransFunc_22)return false;
+ // BT.2100 fallback needs an explicit HDR transfer, never just P010.
+ // Keep missing fields marked assumed and preserve conflicting tags.
+ if(out.color.isHdrPath()){
+ if(ext.VideoTransferMatrix==DXVA2_VideoTransferMatrix_Unknown)out.color.matrix=pipeline::YuvMatrix::BT2020NCL;
+ if(ext.VideoPrimaries==DXVA2_VideoPrimaries_Unknown)out.color.primaries=pipeline::ColorPrimaries::BT2020;
+ }
+ if(out.planes>1){
+ const unsigned chroma=ext.VideoChromaSubsampling&~DXVA2_VideoChromaSubsampling_ProgressiveChroma;
+ if(chroma==DXVA2_VideoChromaSubsampling_MPEG2)out.color.chromaLocation=pipeline::ChromaLocation::Left;
+ else if(chroma==DXVA2_VideoChromaSubsampling_MPEG1)out.color.chromaLocation=pipeline::ChromaLocation::Center;
+ else if(chroma==DXVA2_VideoChromaSubsampling_Cosited)out.color.chromaLocation=pipeline::ChromaLocation::TopLeft;
+ }
}
return true;
}
@@ -171,6 +188,7 @@ inline bool equivalentCaptureTypes(const AM_MEDIA_TYPE& a,const AM_MEDIA_TYPE& b
return x.packing==y.packing&&x.format==y.format&&x.width==y.width&&x.height==y.height&&x.stride==y.stride&&x.bottomUp==y.bottomUp&&x.duration==y.duration&&
x.color.range==y.color.range&&x.color.matrix==y.color.matrix&&x.color.transfer==y.color.transfer&&
x.color.primaries==y.color.primaries&&x.color.displayReferred709==y.color.displayReferred709&&x.color.preserveSdrCodeValues==y.color.preserveSdrCodeValues&&
- x.color.rangeAssumed==y.color.rangeAssumed&&x.color.matrixAssumed==y.color.matrixAssumed&&x.color.transferAssumed==y.color.transferAssumed;
+ x.color.rangeAssumed==y.color.rangeAssumed&&x.color.matrixAssumed==y.color.matrixAssumed&&x.color.transferAssumed==y.color.transferAssumed&&
+ x.color.primariesAssumed==y.color.primariesAssumed&&x.color.chromaLocation==y.color.chromaLocation;
}
}
diff --git a/include/veyra/source/ScreenCaptureSource.h b/include/veyra/source/ScreenCaptureSource.h
new file mode 100644
index 00000000..3793089a
--- /dev/null
+++ b/include/veyra/source/ScreenCaptureSource.h
@@ -0,0 +1,41 @@
+#pragma once
+#include "veyra/source/IFrameSource.h"
+#include <memory>
+#include <vector>
+
+namespace veyra::source {
+enum class ScreenTargetKind { Window, Monitor };
+enum class ScreenCaptureMethod { Wgc, Duplication };
+struct ScreenCaptureOptions {
+ ScreenTargetKind kind=ScreenTargetKind::Window;
+ ScreenCaptureMethod method=ScreenCaptureMethod::Wgc;
+ uint64_t target=0;
+ unsigned fps=0; // 0 follows the captured target's display refresh rate
+ bool cursor=true;
+ unsigned left=0,top=0,right=0,bottom=0; // crop margins in source pixels
+ std::wstring uri() const;
+ static bool parse(const std::wstring&,ScreenCaptureOptions&);
+};
+struct ScreenCaptureTarget {
+ ScreenTargetKind kind;
+ uint64_t handle;
+ uint32_t processId=0;
+ std::wstring name;
+ unsigned width=0,height=0,refresh=0;
+};
+struct ScreenCaptureMetrics {uint64_t received=0,delivered=0,dropped=0;double ageMs=0;};
+class ScreenCaptureSource final:public IFrameSource {
+public:
+ ScreenCaptureSource();~ScreenCaptureSource() override;
+ static std::vector<ScreenCaptureTarget> targets(ScreenTargetKind);
+ bool open(const SourceOpenDesc&) override;
+ const SourceInfo& info()const override;
+ SourceReadStatus read(pipeline::FramePacket&,const AVFrame**) override;
+ bool seek(const pipeline::Rational&) override{return false;}
+ void close()noexcept override;
+ std::wstring status()const;
+ ScreenCaptureMetrics metrics()const;
+private:
+ struct Impl;std::unique_ptr<Impl> p_;
+};
+}
diff --git a/licenses/WIN32_CAPTURE_SAMPLE_MIT.txt b/licenses/WIN32_CAPTURE_SAMPLE_MIT.txt
new file mode 100644
index 00000000..87fe8776
--- /dev/null
+++ b/licenses/WIN32_CAPTURE_SAMPLE_MIT.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2019 Robert Mikhayelyan
+
+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/scripts/gates/delivery.ps1 b/scripts/gates/delivery.ps1
index 862df13d..9007d8e7 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,[string]$BuildDirectory,[string]$PlayerExe,[switch]$PortablePlayer,
+ [Parameter(Mandatory=$true)][string]$OutputDirectory,
+ [Parameter(Mandatory=$true)][string]$FixtureRoot)
# User-authorized local software acceptance, <=300s for this entire suite.
# Native-4K realtime60 is NOT asserted: user selected an explicit 1080 working realtime profile.
# Real capture acceptance and proprietary distribution are separate, never synthetic PASS.
@@ -11,8 +13,11 @@ $Root=(Resolve-Path -LiteralPath $Root).Path
Set-Location -LiteralPath $Root
$timer=[Diagnostics.Stopwatch]::StartNew()
$run=[Guid]::NewGuid().ToString('N')
-$dir=Join-Path $Root ('logs/delivery/'+$run)
+$dir=Join-Path ([IO.Path]::GetFullPath($OutputDirectory)) $run
[IO.Directory]::CreateDirectory($dir)|Out-Null
+# The legacy quality probe accepts narrow paths; relative output avoids losing
+# Unicode directory names while keeping all artifacts in OutputDirectory.
+$qualityDir=(Resolve-Path -LiteralPath $dir -Relative)
$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'}
@@ -43,12 +48,12 @@ function Run([string]$Name,[string]$Exe,[string[]]$Argv,[int]$Limit=30,[int]$Exp
}
try{
$ffprobe=(Get-Command ffprobe -ErrorAction Stop).Source
- $clip1080=(Resolve-Path 'loop/local/fixed_clips/test_av_1080p.mp4').Path
- $clip4k=(Resolve-Path 'loop/local/fixed_clips/test_av_4k.mp4').Path
- Run quality1080 "$bin/veyra_quality_probe.exe" @('--input',$clip1080,'--native','--guidance','motion','--frames','60','--diag','--json-file',"$dir/quality1080.json",'--dump',"$dir/enhanced.png") 45
+ $clip1080=(Resolve-Path -LiteralPath (Join-Path $FixtureRoot 'test_av_1080p.mp4')).Path
+ $clip4k=(Resolve-Path -LiteralPath (Join-Path $FixtureRoot 'test_av_4k.mp4')).Path
+ Run quality1080 "$bin/veyra_quality_probe.exe" @('--input',$clip1080,'--native','--guidance','motion','--frames','60','--diag','--json-file',"$qualityDir/quality1080.json",'--dump',"$qualityDir/enhanced.png") 45
$q=Get-Content "$dir/quality1080.json" -Raw|ConvertFrom-Json
Check core-correct ($q.failures -eq 0 -and $q.processedFrames -eq 60 -and $q.nrEvaluateCount -eq 60 -and $q.nrMotionFrames -gt 0 -and $q.nvofExecuteCount -gt 0 -and $q.nonZeroMotionCount -gt 0 -and $q.diagnosticsEnabled -and $q.d3dDiagErrors -eq 0 -and $q.normalPathReadbackCount -eq 0) 'actual NR/NVOF/motion/GBV/diagnostic PNG'
- Run quality4k "$bin/veyra_quality_probe.exe" @('--input',$clip4k,'--native','--guidance','motion','--frames','12','--json-file',"$dir/quality4k.json",'--dump',"$dir/enhanced4k.png")
+ Run quality4k "$bin/veyra_quality_probe.exe" @('--input',$clip4k,'--native','--guidance','motion','--frames','12','--json-file',"$qualityDir/quality4k.json",'--dump',"$qualityDir/enhanced4k.png")
$q4=Get-Content "$dir/quality4k.json" -Raw|ConvertFrom-Json
Check native4k ($q4.failures -eq 0 -and $q4.sourceExtent.width -eq 3840 -and $q4.workingExtent.width -eq 3840 -and $q4.nrEvaluateCount -eq 12) 'native4K correctness only; not a realtime60 claim'
Run player $PlayerExe @($clip4k,'--nr','--realtime','--fg','--smoke-seconds','6') 20
diff --git a/scripts/generate-lucide-icons.py b/scripts/generate-lucide-icons.py
index c5a4a780..a325af61 100644
--- a/scripts/generate-lucide-icons.py
+++ b/scripts/generate-lucide-icons.py
@@ -19,7 +19,8 @@ ICONS = dict(Play="play", Pause="pause", Stop="square", Volume="volume-2",
Minimize="minus", Maximize="square", Close="x", Back="chevron-left",
Settings="sliders-horizontal", Recent="clock", Enhance="sparkles",
Upscale="scan", PanelOpen="panel-right-open", PanelClose="panel-right-close",
- Check="check", Chevron="chevron-down", Load="file-plus", Type="type")
+ Check="check", Chevron="chevron-down", Load="file-plus", Type="type",
+ ScreenCapture="app-window")
DEST = ROOT / "assets/icons/lucide"
DEST.mkdir(parents=True, exist_ok=True)
manifest = {"repository": "https://github.com/lucide-icons/lucide", "revision": REVISION,
diff --git a/scripts/package-portable.ps1 b/scripts/package-portable.ps1
index b9976dc0..2b5f9b8c 100644
--- a/scripts/package-portable.ps1
+++ b/scripts/package-portable.ps1
@@ -63,9 +63,9 @@ 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 ($LocalVideoHdr) {
- if (-not $Label) { throw 'Local HDR package requires an explicit test label.' }
- $runtimeFiles += @{ Name='nvngx_truehdr.dll'; Folder='runtime/experimental'; Source='third_party_local/nvidia/RTX_Video_SDK_1.1.0/bin/Windows/x64/rel/nvngx_truehdr.dll'; Hash='9A80575F247190C05FE80EAC0C4BAA1D0D4D932348F26808310B5EC4BF9EEB4B'; Size=3955752; Version='1.1.0.0'; Category='official-rtx-video-sdk-1.1.0-local-evaluation'; 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.' }
+ $runtimeFiles += @{ Name='nvngx_truehdr.dll'; Folder='runtime/experimental'; Source='third_party_local/nvidia/RTX_Video_SDK_1.1.0/bin/Windows/x64/rel/nvngx_truehdr.dll'; Hash='9A80575F247190C05FE80EAC0C4BAA1D0D4D932348F26808310B5EC4BF9EEB4B'; Size=3955752; Version='1.1.0.0'; Category='official-rtx-video-sdk-1.1.0'; Experimental=$true }
}
function Runtime-Source($Item) {
if ([IO.Path]::IsPathRooted($Item.Source)) { return $Item.Source }
@@ -101,6 +101,10 @@ foreach ($name in @('vcruntime140.dll','vcruntime140_1.dll','msvcp140.dll')) {
Copy-Payload (Join-Path $crt.FullName "x64/Microsoft.VC143.CRT/$name") $name
}
foreach ($name in @('LICENSE','README.md','README_EN.md','THIRD_PARTY_NOTICES.md')) { Copy-Payload (Join-Path $resolvedRoot $name) $name }
+foreach ($image in Get-ChildItem -LiteralPath (Join-Path $resolvedRoot 'docs/images') -Recurse -File) {
+ $relative = $image.FullName.Substring((Join-Path $resolvedRoot 'docs/images').Length+1).Replace('\','/')
+ Copy-Payload $image.FullName "docs/images/$relative"
+}
foreach ($name in @('BUILD.md',"RUNTIME_COMPONENTS_$Version.md","RELEASE_NOTES_$Version.md")) { Copy-Payload (Join-Path $resolvedRoot "docs/$name") "docs/$name" }
Copy-Payload (Join-Path $resolvedRoot "docs/RELEASE_NOTES_$Version.md") 'RELEASE_NOTES.md'
# Remote Play is statically linked. Retain all dependency notices and source instructions.
@@ -141,6 +145,7 @@ if (Test-Path -LiteralPath $ffmpegLocalBuild) {
Copy-Payload $ffmpegLocalBuild 'licenses/FFMPEG-VEYRA-BUILD.json'
}
Copy-Payload (Join-Path $resolvedRoot 'assets/icons/lucide/LICENSE') 'licenses/LUCIDE-LICENSE.txt'
+Copy-Payload (Join-Path $resolvedRoot 'licenses/WIN32_CAPTURE_SAMPLE_MIT.txt') 'licenses/WIN32_CAPTURE_SAMPLE_MIT.txt'
foreach ($name in @('RTX40MFG_LICENSE.txt','HDE_LICENSE.txt')) {
Copy-Payload (Join-Path $resolvedRoot "src/ngx/compat/$name") "licenses/$name"
}
diff --git a/shaders/ColorGrade.hlsli b/shaders/ColorGrade.hlsli
index 623ff1dd..7306aab5 100644
--- a/shaders/ColorGrade.hlsli
+++ b/shaders/ColorGrade.hlsli
@@ -166,7 +166,7 @@ float3 ColorGradeApply(float3 lin, ColorGradeParams p)
const float3x3 matrix = float3x3(p.row0.xyz, p.row1.xyz, p.row2.xyz);
const float exposure = p.controls.x, saturation = p.controls.y, vibrance = p.controls.z, lutStrength = p.controls.w;
const int lutInputSpace = int(p.flags.y + 0.5);
- float3 rgb = max(mul(matrix, lin), 0.0) * exp2(exposure);
+ float3 rgb = mul(matrix, lin) * exp2(exposure);
// Tone response: per-channel table lookup in the log domain.
const float3 encoded = ColorGradeEncodeLog(rgb);
@@ -182,7 +182,9 @@ float3 ColorGradeApply(float3 lin, ColorGradeParams p)
// linear-light HSV pulls skin towards red, which made the red band grab
// faces. Encode with a monotone gamma (no clipping, so HDR highlights are
// safe), mix there, decode back to the linear working image.
- const float3 mixEncoded = pow(max(rgb, 0.0), 1.0 / 2.2);
+ // scRGB contains legitimate negative components for wide-gamut HDR.
+ // A signed gamma round trip retains them even with neutral grading.
+ const float3 mixEncoded = sign(rgb) * pow(abs(rgb), 1.0 / 2.2);
const float3 hsv = RgbToHsv(mixEncoded);
const float4 hueResponse = ColorGradeHue(hsv.x / 360.0);
if (p.flags.z > 0.5)
@@ -196,7 +198,9 @@ float3 ColorGradeApply(float3 lin, ColorGradeParams p)
}
else
{
- rgb = pow(max(HsvToRgb(float3(hsv.x + hueResponse.r, saturate(hsv.y * hueResponse.g), max(hsv.z * hueResponse.b, 0.0))), 0.0), 2.2);
+ const float saturationLimit = max(1.0, hsv.y);
+ const float3 mixed = HsvToRgb(float3(hsv.x + hueResponse.r, clamp(hsv.y * hueResponse.g, 0.0, saturationLimit), max(hsv.z * hueResponse.b, 0.0)));
+ rgb = sign(mixed) * pow(abs(mixed), 2.2);
}
// Luminance-zone grading + calibration shadow tint.
@@ -227,5 +231,5 @@ float3 ColorGradeApply(float3 lin, ColorGradeParams p)
else decoded = ColorGradeDecodeLog(lutOutput);
rgb = lerp(rgb, decoded, saturate(lutStrength));
}
- return max(rgb, 0.0);
+ return rgb;
}
diff --git a/shaders/RgbToLinear.hlsl b/shaders/RgbToLinear.hlsl
index 7448cb3f..949647ec 100644
--- a/shaders/RgbToLinear.hlsl
+++ b/shaders/RgbToLinear.hlsl
@@ -1,4 +1,5 @@
#include "HdrColor.hlsli"
+#include "HdrToSdr.hlsli"
#include "ColorGrade.hlsli"
cbuffer RgbParams : register(b0) { uint width; uint height; uint transfer; uint limited; float2 reserved; float primaries2020; float padding;
float4 colorRow0; float4 colorRow1; float4 colorRow2; float4 colorControls; float4 colorFlags; };
@@ -18,6 +19,8 @@ void main(uint3 p : SV_DispatchThreadID) {
// Present onto the player's opaque black canvas; never discard RGB chroma.
float3 decoded=float3(decode(c.r),decode(c.g),decode(c.b));
if(primaries2020>0.5)decoded=HdrTo709(decoded);
- if(colorFlags.x>0.5){ColorGradeParams grade={colorRow0,colorRow1,colorRow2,colorControls,colorFlags};decoded=ColorGradeApply(decoded,grade);}
+ 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(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/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 7e145008..36f27edf 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -18,6 +18,7 @@
#include "veyra/engine/CaptureHalfRate.h"
#include "veyra/source/MediaFileSource.h"
#include "veyra/source/CaptureCardSource.h"
+#include "veyra/source/ScreenCaptureSource.h"
#ifdef VEYRA_ENABLE_REMOTEPLAY
#include "veyra/source/RemotePlaySessionSource.h"
#endif
@@ -169,6 +170,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
sink::AudioPipeline audioPipe;sink::AudioRenderer audio;VideoPresenter presenter;
pipeline::EnhanceGraph graph(ctx,ring);AVFrame* imageFrame=nullptr;AVFrame* cachedFrame=nullptr;pipeline::FramePacket cachedPacket;
source::CaptureCardSource captureSource;const bool physicalCapture=path.starts_with(L"capture:")||path.starts_with(L"capture2:");
+ source::ScreenCaptureSource screenSource;const bool isScreen=path.starts_with(L"screen:");
// Set when a live parameter change arrives while paused (or on a still
// image): the cached source frame must be re-rendered before the next
// present, otherwise the new colour tables never reach the GPU.
@@ -180,11 +182,12 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
#else
(void)remoteRequest;const bool isRemote=false;
#endif
- const bool isCapture=physicalCapture||options.captureReplayForTest||isRemote;
+ const bool isCapture=physicalCapture||options.captureReplayForTest||isRemote||isScreen;
// File replay has no hardware arrival clock; retain its continuous PTS anchor.
- const bool pairAnchoredLive=physicalCapture||isRemote;
+ const bool pairAnchoredLive=physicalCapture||isRemote||isScreen;
const bool useLiveFgAdmission=!options.captureReplayDisableFgAdmissionForTest;
source::IFrameSource* activeSource=physicalCapture?static_cast<source::IFrameSource*>(&captureSource):&source;
+ if(isScreen)activeSource=&screenSource;
#ifdef VEYRA_ENABLE_REMOTEPLAY
if(remote)activeSource=remote.get();
#endif
@@ -251,7 +254,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(stop_||!cachedFrame)break;
}else{
#endif
- if(!(physicalCapture?captureSource.configure(od):activeSource->open(od))){status(!isCapture&&!source.errorMessage().empty()?source.errorMessage():L"无法打开视频,请查看诊断",true);break;}
+ if(!(physicalCapture?captureSource.configure(od):activeSource->open(od))){status(isScreen?screenSource.status():physicalCapture&&!captureSource.errorMessage().empty()?captureSource.errorMessage():!isCapture&&!source.errorMessage().empty()?source.errorMessage():L"无法打开视频,请查看诊断",true);break;}
#ifdef VEYRA_ENABLE_REMOTEPLAY
}
#endif
@@ -278,7 +281,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(!pipeline::Extent{width,height}.valid()){status(L"图像尺寸超出单张GPU纹理能力,需要分块处理",true);break;}
pipeline::EnhanceGraphDesc gd;gd.sourceWidth=width;gd.sourceHeight=height;gd.hdrInput=!isImage&&activeSource->info().color.isHdrPath();
gd.highQualityPresentation=isRemote&&activeSource->info().color.reconstructChroma;
- gd.rgbInput=isImage||(isCapture&&activeSource->info().color.pixelFormat==pipeline::SourcePixelFormat::Bgra8);
+ gd.rgbInput=isImage||isScreen||(isCapture&&activeSource->info().color.pixelFormat==pipeline::SourcePixelFormat::Bgra8);
gd.captureBitDepth=activeSource->info().color.pixelFormat==pipeline::SourcePixelFormat::P010?10:activeSource->info().color.pixelFormat==pipeline::SourcePixelFormat::P016?16:8;
gd.yuy2Input=isCapture&&activeSource->info().color.pixelFormat==pipeline::SourcePixelFormat::Yuy2;gd.stillImage=isImage;
gd.packedInput=isCapture?pipeline::packedInputCode(activeSource->info().color.pixelFormat):0;
@@ -926,7 +929,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
advanceLive();waitLive();rs=physicalCapture?captureSource.tryRead(pkt,&frame):activeSource->read(pkt,&frame);
}
if(stop_)break;
- if(rs==source::SourceReadStatus::Waiting){advanceLive();waitLive();continue;}
+ if(rs==source::SourceReadStatus::Waiting){if(isScreen){std::lock_guard lock(mutex_);snapshot_.sourceNotice=screenSource.status();}advanceLive();waitLive();continue;}
if(rs==source::SourceReadStatus::Eos){
fileInputEnded=true;
while(liveScheduler&&liveScheduler->occupancy()&&!stop_&&(!paused_||seekPreviewPending)&&!liveScheduler->failed()){advanceLive();if(liveScheduler->occupancy())waitLive();}
@@ -946,9 +949,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
#ifdef VEYRA_ENABLE_REMOTEPLAY
if(remote){const auto recovery=remote->recoveryStatus();status(recovery.message.empty()?L"PS5 串流异常,请检查主机状态后重新连接。":recovery.message,true);break;}
#endif
- status(isCapture?L"采集信号中断,请检查设备连接或格式":source.errorMessage().empty()?L"视频解码或时间戳错误":source.errorMessage(),true);break;}
+ status(isScreen?screenSource.status():isCapture?L"采集信号中断,请检查设备连接或格式":source.errorMessage().empty()?L"视频解码或时间戳错误":source.errorMessage(),true);break;}
}
- if(isRemote&&frame&&(uint32_t(frame->width)!=width||uint32_t(frame->height)!=height)){
+ if(isScreen){std::lock_guard lock(mutex_);snapshot_.sourceNotice=screenSource.status();}
+ if((isRemote||isScreen)&&frame&&(uint32_t(frame->width)!=width||uint32_t(frame->height)!=height||(isScreen&&gd.hdrInput!=activeSource->info().color.isHdrPath()))){
drainLivePresentation();if(!ring.drainQueue()){status(L"串流尺寸切换排空失败",true);break;}
width=uint32_t(frame->width);height=uint32_t(frame->height);
auto plan=pipeline::ResolutionPlan::make({width,height},options.sr,options.settings.nrPolicy,false,options.settings.revision,options.settings.srTarget,options.settings.lowLatency&&options.nr);
@@ -1395,6 +1399,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(!paused_&&!isCapture){latenessSamples.push_back(std::abs(lateness));if(latenessSamples.size()>1200)latenessSamples.pop_front();}
std::vector<double> sorted(latenessSamples.begin(),latenessSamples.end());std::sort(sorted.begin(),sorted.end());
auto captureStats=physicalCapture?captureSource.metrics():source::CaptureMetrics{};
+ if(isScreen){const auto screen=screenSource.metrics();captureStats.received=screen.received;captureStats.delivered=screen.delivered;captureStats.dropped=screen.dropped;captureStats.readAgeMs=screen.ageMs;captureStats.frameAgeMs=double(std::max<int64_t>(0,host100ns()-pkt.pts.to100ns()))/10000;}
#ifdef VEYRA_ENABLE_REMOTEPLAY
if(remote){const auto rp=remote->sessionSnapshot();captureStats.received=rp.video.accessUnits;captureStats.dropped=remote->skipped();captureStats.delivered=sourceFrames;
captureStats.readAgeMs=double(std::max<int64_t>(0,host100ns()-pkt.arrivalHost100ns))/10000;
@@ -1492,7 +1497,7 @@ 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();source.close();av_frame_free(&cachedFrame);av_frame_free(&imageFrame);ring.shutdown();ctx.shutdown();
+ 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();
{std::lock_guard lock(mutex_);snapshot_.running=false;snapshot_.audioEndpointRecovering=false;snapshot_.audioRebuffering=false;}
CoUninitialize();
}
diff --git a/src/engine/Subtitles.cpp b/src/engine/Subtitles.cpp
index 590556b0..49324831 100644
--- a/src/engine/Subtitles.cpp
+++ b/src/engine/Subtitles.cpp
@@ -579,7 +579,7 @@ struct SubtitleLoader::Impl {
};
try{
std::vector<SubtitleTrack> external;
- if(path.empty()||path.starts_with(L"capture:")||path.starts_with(L"capture2:")||path.starts_with(L"remoteplay:")){publish({},true);continue;}
+ if(path.empty()||path.starts_with(L"capture:")||path.starts_with(L"capture2:")||path.starts_with(L"remoteplay:")||path.starts_with(L"screen:")){publish({},true);continue;}
for(const wchar_t* extension:{L".srt",L".ass",L".ssa",L".vtt"}){
if(stop.stop_requested())break;
auto candidate=std::filesystem::path(path);candidate.replace_extension(extension);
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index 9112d5a4..b8223b3f 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -1282,11 +1282,11 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
veyra::log::error("hdr","HDR source transfer changed to SDR; reopen/rebuild required");return false;
}
if(resolved.matrix==YuvMatrix::BT2020CL){veyra::log::error("graph","BT.2020 constant-luminance requires a dedicated conversion; refusing NCL substitution");return false;}
- if(resolved.isHdrPath()&&(resolved.matrix!=YuvMatrix::BT2020NCL||resolved.primaries!=ColorPrimaries::BT2020)){
+ if(resolved.isHdrPath()&&!resolved.scRgb&&(resolved.matrix!=YuvMatrix::BT2020NCL||resolved.primaries!=ColorPrimaries::BT2020)){
veyra::log::error("hdr","Unsupported PQ/HLG colorimetry: requires signaled/fallback BT2020 NCL and BT2020 primaries");return false;
}
if(reset||!realFrameIndex_)veyra::log::info("color",std::format("range={} assumed={} matrix={} assumed={} transfer={} assumed={} display709={} preserveSdrCodes={} workingTransfer={}",int(resolved.range),resolved.rangeAssumed,int(resolved.matrix),resolved.matrixAssumed,int(resolved.transfer),resolved.transferAssumed,resolved.displayReferred709,resolved.preserveSdrCodeValues,workingTransferCode(resolved)));
- if(resolved.isHdrPath()&&(reset||!realFrameIndex_)){
+ if(resolved.isHdrPath()&&!resolved.scRgb&&(reset||!realFrameIndex_)){
veyra::log::info("hdr-route",std::format("input={} range={} matrix=BT2020-NCL primaries=BT2020 decode={} working={} output={} toneMap={} hdrReferenceWhiteNits=203 hlgReferencePeakNits=1000; SDR workingTransfer field is unused for PQ/HLG",
resolved.transfer==TransferFunction::HLG?"HLG":"PQ",resolved.range==ColorRange::Full?"full":"limited",
resolved.transfer==TransferFunction::HLG?"inverse-OETF+OOTF-gamma1.2":"ST2084-EOTF-absolute-nits",
@@ -1294,7 +1294,9 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
hdr10Output()?"PQ-BT2020-RGB10":desc_.hdrOutput?"scRGB-FP16":"sRGB-RGB8",
desc_.hdrOutput?"none":"BT2390-luminance+neutral-ray-gamut-compression"));
}
- if (resolved.isHdrPath()&&(!desc_.hdrInput||desc_.rgbInput||desc_.yuy2Input||desc_.packedInput)) {
+ const bool gpuRgb=desc_.rgbInput&&frame->format==AV_PIX_FMT_D3D11&&hardwareSurface&&hardwareSurface->present();
+ if(resolved.scRgb&&(!gpuRgb||resolved.transfer!=TransferFunction::Linear||resolved.primaries!=ColorPrimaries::BT709||hardwareSurface->texture->GetDesc().Format!=DXGI_FORMAT_R16G16B16A16_FLOAT))return false;
+ if (resolved.isHdrPath()&&(!desc_.hdrInput||(!resolved.scRgb&&desc_.rgbInput)||desc_.yuy2Input||desc_.packedInput)) {
veyra::log::error("graph", "HDR input requires an explicit YUV HDR contract; RGB/YUY2 HDR ingress is unsupported"); return false;
}
if(std::abs(ptsMs)>9e13){veyra::log::error("timeline","PTS outside representable range");return false;}
@@ -1361,7 +1363,15 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
previousLuma_=std::move(sample);
};
- if(desc_.rgbInput||desc_.yuy2Input||desc_.packedInput){
+ if(gpuRgb){
+ auto* texture=hardwareSurface->texture;const auto td=texture->GetDesc();
+ if(td.Width!=srcW_||td.Height!=srcH_||(td.Format!=DXGI_FORMAT_B8G8R8A8_UNORM&&td.Format!=DXGI_FORMAT_R16G16B16A16_FLOAT))return false;
+ if(hardwareSurface->waitFence&&FAILED(context_.directQueue()->Wait(hardwareSurface->waitFence,hardwareSurface->waitValue)))return false;
+ D3D12_SHADER_RESOURCE_VIEW_DESC srv{};srv.Format=td.Format;srv.ViewDimension=D3D12_SRV_DIMENSION_TEXTURE2D;
+ srv.Shader4ComponentMapping=D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;srv.Texture2D.MipLevels=1;
+ stager_.stageSrv(texture,&srv,rgbPass_.heap.Get(),3+parity);
+ tracker_.transition(list,texture,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ }else if(desc_.rgbInput||desc_.yuy2Input||desc_.packedInput){
const bool packed=desc_.packedInput!=0;
if(packed?frame->format!=packedIngressFormat(desc_.packedInput):(desc_.yuy2Input?frame->format!=AV_PIX_FMT_YUYV422:(frame->format!=AV_PIX_FMT_RGBA&&frame->format!=AV_PIX_FMT_BGRA&&frame->format!=AV_PIX_FMT_RGB0&&frame->format!=AV_PIX_FMT_BGR0))){
veyra::log::error("graph",std::format("direct capture input contract mismatch packing={} frameFormat={}",desc_.packedInput,int(frame->format)));return false;
@@ -1525,7 +1535,8 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
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(colorActive_)packColorGradeConstants(colorTables_,c+8);
- rgbPass_.bind(list,c,gpuHandleOf(rgbPass_,0).ptr,gpuHandleOf(rgbPass_,1).ptr,gpuHandleOf(rgbPass_,8).ptr);
+ 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);
list->Dispatch((srcW_+15)/16,(srcH_+15)/16,1);
}else{
float constants[12+kColorGradeConstantCount] = { resolved.range==ColorRange::Full?0.0f:1.0f,
@@ -1539,6 +1550,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
}
tracker_.uavBarrier(list, srcRgba_.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) {
tracker_.transition(list, nv12Texture, D3D12_RESOURCE_STATE_COMMON);
}
diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cpp
index e05ee605..5e018419 100644
--- a/src/source/CaptureCardSource.cpp
+++ b/src/source/CaptureCardSource.cpp
@@ -1,4 +1,5 @@
#include "veyra/source/CaptureCardSource.h"
+#include "veyra/source/CaptureFrameRate.h"
#include "veyra/source/WasapiAudioInput.h"
#include "veyra/source/CaptureTiming.h"
#include "veyra/source/CaptureMediaType.h"
@@ -190,9 +191,14 @@ bool parseInt(std::wstring_view text,int& value){
if(text.empty())return false;const std::wstring copy(text);size_t consumed=0;try{value=std::stoi(copy,&consumed);}catch(...){return false;}return consumed==copy.size();
}
bool parseUnsigned(std::wstring_view text,unsigned& value){int parsed=0;if(!parseInt(text,parsed)||parsed<0)return false;value=static_cast<unsigned>(parsed);return true;}
-struct CaptureSelection {unsigned videoIndex=0;int format=0;int audio=kCaptureAudioDisabled;unsigned colorOverride=0;bool stable=false;std::wstring videoPath,audioPath;};
+struct CaptureSelection {unsigned videoIndex=0;int format=0;int audio=kCaptureAudioDisabled;unsigned colorOverride=0;double requestedFps=0;bool stable=false;std::wstring videoPath,audioPath;};
bool parseCapturePath(std::wstring_view path,CaptureSelection& selection){
selection={};
+ if(const auto query=path.find(L'?');query!=std::wstring_view::npos){
+ const auto value=path.substr(query+1);
+ if(!value.starts_with(L"fps=")||!parseCaptureFrameRate(value.substr(4),selection.requestedFps))return false;
+ path=path.substr(0,query);
+ }
constexpr std::wstring_view prefix=L"capture2:";
if(path.starts_with(prefix)){
std::array<std::wstring_view,5> fields{};size_t cursor=prefix.size();
@@ -416,13 +422,15 @@ std::vector<CaptureDevice> CaptureCardSource::deviceDetails(bool audio){
return result;
}
std::vector<std::wstring> CaptureCardSource::devices(bool audio){std::vector<std::wstring> result;for(auto& device:deviceDetails(audio))result.push_back(std::move(device.name));return result;}
-std::wstring CaptureCardSource::makeCapturePath(unsigned videoIndex,const CaptureDevice& video,int format,int audioMode,const CaptureDevice* audio,unsigned colorOverride){
+std::wstring CaptureCardSource::makeCapturePath(unsigned videoIndex,const CaptureDevice& video,int format,int audioMode,const CaptureDevice* audio,unsigned colorOverride,double requestedFps){
+ if(!validCaptureFrameRate(requestedFps))return {};
+ const auto suffix=requestedFps>0?std::format(L"?fps={:.6f}",requestedFps):L"";
if(audio&&audio->wasapi){
if(video.path.empty()||audio->path.empty())return {};
- return std::format(L"capture2:{}:{}:{}:{}:{}",encodePath(video.path),format,kCaptureAudioWasapi,encodePath(audio->path),colorOverride);
+ return std::format(L"capture2:{}:{}:{}:{}:{}{}",encodePath(video.path),format,kCaptureAudioWasapi,encodePath(audio->path),colorOverride,suffix);
}
- if(video.path.empty()||(audioMode>=0&&(!audio||audio->path.empty())))return std::format(L"capture:{}:{}:{}:{}",videoIndex,format,audioMode,colorOverride);
- return std::format(L"capture2:{}:{}:{}:{}:{}",encodePath(video.path),format,audioMode,audioMode>=0?encodePath(audio->path):L"",colorOverride);
+ if(video.path.empty()||(audioMode>=0&&(!audio||audio->path.empty())))return std::format(L"capture:{}:{}:{}:{}{}",videoIndex,format,audioMode,colorOverride,suffix);
+ return std::format(L"capture2:{}:{}:{}:{}:{}{}",encodePath(video.path),format,audioMode,audioMode>=0?encodePath(audio->path):L"",colorOverride,suffix);
}
std::vector<CaptureFormat> enumerateFormats(IAMStreamConfig* config){
std::vector<CaptureFormat> out;if(!config)return out;int count=0,size=0;
@@ -495,12 +503,20 @@ void CaptureCardSource::videoReset(bool resetAudio){if(p_->wasapi)p_->wasapi->vi
void CaptureCardSource::setAudioSync(unsigned mode,int offset){if(p_->wasapi)p_->wasapi->setSync(mode,offset);else if(p_->audioSession)p_->audioSession->setSync(mode,offset);}
sink::CaptureAudioState CaptureCardSource::audioState()const{auto state=p_->wasapi?p_->wasapi->snapshot():p_->audioSession?p_->audioSession->snapshot():sink::CaptureAudioState{};if(!p_->audioError.empty())state.error=p_->audioError;return state;}
bool CaptureCardSource::open(const SourceOpenDesc& desc){return configure(desc)&&start();}
-bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAudioGain=-1;auto& p=*p_;CaptureSelection selection;if(!parseCapturePath(desc.path,selection))return false;const unsigned index=selection.videoIndex;const int format=selection.format;const int audio=selection.audio;
+bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.clear();p_->lastAudioGain=-1;auto& p=*p_;CaptureSelection selection;if(!parseCapturePath(desc.path,selection))return false;const unsigned index=selection.videoIndex;const int format=selection.format;const int audio=selection.audio;
if(selection.stable?!configuration(selection.videoPath,p.graph,p.builder,p.device,p.config):!configuration(index,p.graph,p.builder,p.device,p.config))return false;
int count=0,size=0;if(FAILED(p.config->GetNumberOfCapabilities(&count,&size))||format<0||format>=count||size<=0||size>65536)return false;
std::vector<BYTE> caps(size);AM_MEDIA_TYPE* native=nullptr;if(FAILED(p.config->GetStreamCaps(format,&native,caps.data())))return false;
+ if(selection.requestedFps>0){
+ REFERENCE_TIME* interval=nullptr;
+ if(native->formattype==FORMAT_VideoInfo&&native->cbFormat>=sizeof(VIDEOINFOHEADER))interval=&reinterpret_cast<VIDEOINFOHEADER*>(native->pbFormat)->AvgTimePerFrame;
+ else if(native->formattype==FORMAT_VideoInfo2&&native->cbFormat>=sizeof(VIDEOINFOHEADER2))interval=&reinterpret_cast<VIDEOINFOHEADER2*>(native->pbFormat)->AvgTimePerFrame;
+ if(!interval){error_=L"该采集格式不支持设备帧率协商,请将采集帧率设为 0。";freeType(native);return false;}
+ *interval=captureFrameInterval(selection.requestedFps);
+ log::info("capture-rate",std::format("requestFps={:.6f} interval100ns={} deviceNegotiation=1 softwareLimiter=0",selection.requestedFps,*interval));
+ }
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))return false;
+ 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
// directly to our terminal filter: no intelligent-connect converter.
native=nullptr;hr=p.config->GetFormat(&native);if(FAILED(hr)||!native){freeType(native);return false;}
@@ -628,6 +644,7 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAu
if(!layoutValid){log::error("capture",std::format("unsupported negotiated layout/connect failure hr=0x{:08X}",uint32_t(hr)));return false;}
if(p.cpuUnpack&&captureLegacyCpuLayout(p.layout))log::warn("capture-unpack",std::format("legacy CPU unpack path active packing={} format={} (per-pixel conversion stays on the callback thread)",int(p.layout.packing),int(p.layout.format)));
const unsigned colorOverride=selection.colorOverride;
+ log::info("capture-color",std::format("driver controlFlags=0x{:08X} colorInfoPresent={} transfer={} matrix={} primaries={} chroma={} override={}",p.layout.colorControlFlags,bool(p.layout.colorControlFlags&AMCONTROL_COLORINFO_PRESENT),int(p.layout.color.transfer),int(p.layout.color.matrix),int(p.layout.color.primaries),int(p.layout.color.chromaLocation),colorOverride));
if(colorOverride>2)return false;
if(colorOverride&&!compressedPath){
if(p.layout.format!=AV_PIX_FMT_P010&&p.layout.format!=AV_PIX_FMT_P016){log::error("capture-color","Explicit HDR requires P010/P016; select a 10/16-bit capture format");return false;}
@@ -637,6 +654,14 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAu
log::info("capture-color",std::format("manual override={} BT2020; range retains negotiated metadata",colorOverride==1?"PQ":"HLG"));
}
p.info={};p.info.kind=pipeline::SourceKind::CaptureCard;p.info.width=p.layout.width;p.info.height=p.layout.height;p.info.averageFps=p.layout.duration>0?1e7/p.layout.duration:0;p.info.duration=pipeline::Rational::unknown();p.info.color=p.layout.color;
+ if(selection.requestedFps>0){
+ const bool accepted=captureFrameRateMatches(selection.requestedFps,p.layout.duration);
+ log::info("capture-rate",std::format("requestedFps={:.6f} connectedFps={:.6f} accepted={} softwareLimiter=0",selection.requestedFps,p.info.averageFps,accepted));
+ if(!accepted){error_=std::format(L"请求 {:.3f} FPS,但采集卡返回 {:.3f} FPS;请改用支持的帧率,或填 0。",selection.requestedFps,p.info.averageFps);return false;}
+ }
+ if(!compressedPath&&!colorOverride&&(p.layout.format==AV_PIX_FMT_P010||p.layout.format==AV_PIX_FMT_P016)&&p.info.color.transferAssumed)
+ log::warn("capture-color","No explicit HDR transfer from driver; bit depth does not identify HDR. Keeping SDR fallback; manual PQ/HLG remains available.");
+ if(p.info.color.isHdrPath())log::info("capture-color",std::format("HDR input transfer={} matrix={} assumed={} primaries={} assumed={}",int(p.info.color.transfer),int(p.info.color.matrix),p.info.color.matrixAssumed,int(p.info.color.primaries),p.info.color.primariesAssumed));
p.nominalDuration100ns=p.layout.duration;
log::info("capture-color",std::format("format={} stride={} rowBytes={} bytes={} bottomUp={} matrix={} assumed={} range={} assumed={} workingTransfer={} assumed={} (explicit transfer contract)",int(p.layout.format),p.layout.stride,p.layout.rowBytes,p.layout.sampleBytes,p.layout.bottomUp,int(p.info.color.matrix),p.info.color.matrixAssumed,int(p.info.color.range),p.info.color.rangeAssumed,int(p.info.color.transfer),p.info.color.transferAssumed));
if(audio==kCaptureAudioWasapi){
@@ -1047,6 +1072,7 @@ bool CaptureCardSource::reconnect(float gain,unsigned syncMode,int offsetMs){
int format=-1;for(const auto& candidate:formatsByPath(selection.videoPath))if(candidate.key==key){format=candidate.index;break;}
if(format<0)return false;
auto reopen=desc;reopen.path=std::format(L"capture2:{}:{}:{}:{}:{}",encodePath(selection.videoPath),format,selection.audio,encodePath(selection.audioPath),selection.colorOverride);
+ if(selection.requestedFps>0)reopen.path+=std::format(L"?fps={:.6f}",selection.requestedFps);
bool ok=configure(reopen);
if(ok){const auto& current=p_->info;
ok=current.width==expected.width&&current.height==expected.height&&current.color.pixelFormat==expected.color.pixelFormat&&
diff --git a/src/source/ScreenCaptureSource.cpp b/src/source/ScreenCaptureSource.cpp
new file mode 100644
index 00000000..83e7dc90
--- /dev/null
+++ b/src/source/ScreenCaptureSource.cpp
@@ -0,0 +1,317 @@
+// WGC lifecycle adapted from robmikh/Win32CaptureSample SimpleCapture.cpp,
+// commit 49fefe79fd9b11025f0b5eb91783a98888516070, MIT, (c) 2019 Robert Mikhayelyan.
+// Veyra changes: polling latest frames, leased shared textures/fences, crop,
+// timestamp contract, DXGI compatibility ingress and shared enhancement graph.
+#include "veyra/source/ScreenCaptureSource.h"
+#include "veyra/Log.h"
+#include <d3d11_4.h>
+#include <dxgi1_6.h>
+#include <dwmapi.h>
+#include <windows.graphics.capture.interop.h>
+#include <windows.graphics.directx.direct3d11.interop.h>
+#include <winrt/Windows.Foundation.Metadata.h>
+#include <winrt/Windows.Graphics.Capture.h>
+#include <winrt/Windows.Graphics.DirectX.Direct3D11.h>
+#include <wrl/client.h>
+#include <algorithm>
+#include <array>
+#include <chrono>
+#include <climits>
+#include <format>
+#include <sstream>
+#include <mutex>
+extern "C" {
+#include <libavutil/frame.h>
+#include <libavutil/buffer.h>
+}
+
+namespace veyra::source {
+using Microsoft::WRL::ComPtr;
+using namespace winrt::Windows::Graphics::Capture;
+using winrt::Windows::Graphics::DirectX::DirectXPixelFormat;
+namespace {
+int64_t host100ns(){return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count()/100;}
+int64_t qpc100ns(){LARGE_INTEGER q{},f{};QueryPerformanceCounter(&q);QueryPerformanceFrequency(&f);return int64_t(static_cast<long double>(q.QuadPart)*10000000/f.QuadPart);}
+void check(HRESULT hr,const char* op){if(FAILED(hr)){log::error("screen",std::format("{} hr=0x{:08X}",op,uint32_t(hr)));winrt::check_hresult(hr);}}
+struct NativeHandle {HANDLE value=nullptr;~NativeHandle(){if(value)CloseHandle(value);}};
+std::mutex exclusionMutex;
+unsigned exclusionUsers=0;
+std::vector<std::pair<HWND,DWORD>> excludedWindows;
+void excludeOwnWindows(){
+ std::lock_guard lock(exclusionMutex);
+ if(exclusionUsers++!=0)return;
+ EnumWindows([](HWND w,LPARAM)->BOOL{
+ DWORD pid=0;GetWindowThreadProcessId(w,&pid);
+ if(pid!=GetCurrentProcessId()||!IsWindowVisible(w))return TRUE;
+ DWORD previous=0;
+ if(GetWindowDisplayAffinity(w,&previous)&&SetWindowDisplayAffinity(w,WDA_EXCLUDEFROMCAPTURE))excludedWindows.emplace_back(w,previous);
+ else log::warn("screen",std::format("window exclusion failed hwnd={} error={}",uint64_t(w),GetLastError()));
+ return TRUE;
+ },0);
+}
+void restoreOwnWindows(){
+ std::lock_guard lock(exclusionMutex);
+ if(!exclusionUsers||--exclusionUsers)return;
+ for(auto [window,affinity]:excludedWindows)if(IsWindow(window)&&!SetWindowDisplayAffinity(window,affinity))log::warn("screen","window exclusion restore failed");
+ excludedWindows.clear();
+}
+struct Surface {
+ ComPtr<ID3D11Texture2D> producer;
+ ComPtr<ID3D12Resource> consumer;
+ ComPtr<ID3D12Fence> fence;
+ unsigned width=0,height=0;DXGI_FORMAT format=DXGI_FORMAT_UNKNOWN;
+};
+DXGI_RATIONAL monitorRate(HMONITOR monitor){
+ MONITORINFOEXW mi{};mi.cbSize=sizeof(mi);
+ if(!GetMonitorInfoW(monitor,&mi))return {};
+ // DisplayConfig retains fractional modes such as 60000/1001 Hz.
+ for(unsigned attempt=0;attempt<3;++attempt){
+ UINT32 pathCount=0,modeCount=0;
+ if(GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS,&pathCount,&modeCount)!=ERROR_SUCCESS)break;
+ std::vector<DISPLAYCONFIG_PATH_INFO> paths(pathCount);
+ std::vector<DISPLAYCONFIG_MODE_INFO> modes(modeCount);
+ const auto result=QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS,&pathCount,paths.data(),&modeCount,modes.data(),nullptr);
+ if(result==ERROR_INSUFFICIENT_BUFFER)continue;
+ if(result!=ERROR_SUCCESS)break;
+ for(UINT32 i=0;i<pathCount;++i){
+ const auto& path=paths[i];DISPLAYCONFIG_SOURCE_DEVICE_NAME name{};
+ name.header.type=DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;name.header.size=sizeof(name);
+ name.header.adapterId=path.sourceInfo.adapterId;name.header.id=path.sourceInfo.id;
+ if(DisplayConfigGetDeviceInfo(&name.header)!=ERROR_SUCCESS||wcscmp(name.viewGdiDeviceName,mi.szDevice))continue;
+ const auto r=path.targetInfo.refreshRate;
+ if(r.Denominator&&r.Numerator<=INT_MAX&&r.Denominator<=INT_MAX&&double(r.Numerator)/r.Denominator>1&&double(r.Numerator)/r.Denominator<=1000)
+ return {r.Numerator,r.Denominator};
+ }
+ break;
+ }
+ DEVMODEW mode{};mode.dmSize=sizeof(mode);
+ if(EnumDisplaySettingsW(mi.szDevice,ENUM_CURRENT_SETTINGS,&mode)&&mode.dmDisplayFrequency>1&&mode.dmDisplayFrequency<=1000)return {mode.dmDisplayFrequency,1};
+ return {};
+}
+bool hdrMonitor(HMONITOR monitor){
+ ComPtr<IDXGIFactory1> factory;if(FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))))return false;
+ for(UINT a=0;;++a){ComPtr<IDXGIAdapter1> adapter;if(factory->EnumAdapters1(a,&adapter)==DXGI_ERROR_NOT_FOUND)break;
+ for(UINT o=0;;++o){ComPtr<IDXGIOutput> output;if(adapter->EnumOutputs(o,&output)==DXGI_ERROR_NOT_FOUND)break;
+ DXGI_OUTPUT_DESC d{};if(FAILED(output->GetDesc(&d))||d.Monitor!=monitor)continue;
+ ComPtr<IDXGIOutput6> six;DXGI_OUTPUT_DESC1 one{};
+ return SUCCEEDED(output.As(&six))&&SUCCEEDED(six->GetDesc1(&one))&&one.ColorSpace==DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020;
+ }
+ }return false;
+}
+}
+std::wstring ScreenCaptureOptions::uri()const{
+ return std::format(L"screen:{}:{}:{}:{}:{}:{}:{}:{}:{}",unsigned(kind),target,unsigned(method),fps,unsigned(cursor),left,top,right,bottom);
+}
+bool ScreenCaptureOptions::parse(const std::wstring& uri,ScreenCaptureOptions& out){
+ if(!uri.starts_with(L"screen:"))return false;
+ auto body=uri.substr(7);std::replace(body.begin(),body.end(),L':',L' ');
+ std::wistringstream in(body);unsigned kind=0,method=0,cursor=0;ScreenCaptureOptions v;
+ if(!(in>>kind>>v.target>>method>>v.fps>>cursor>>v.left>>v.top>>v.right>>v.bottom))return false;
+ in>>std::ws;if(!in.eof()||kind>1||method>1||cursor>1||!v.target||v.fps>240||
+ v.left>16384||v.top>16384||v.right>16384||v.bottom>16384||(!kind&&method))return false;
+ v.kind=ScreenTargetKind(kind);v.method=ScreenCaptureMethod(method);v.cursor=cursor!=0;out=v;return true;
+}
+std::vector<ScreenCaptureTarget> ScreenCaptureSource::targets(ScreenTargetKind kind){
+ std::vector<ScreenCaptureTarget> result;
+ if(kind==ScreenTargetKind::Window){
+ EnumWindows([](HWND window,LPARAM param)->BOOL{
+ DWORD pid=0;GetWindowThreadProcessId(window,&pid);
+ if(pid==GetCurrentProcessId()||!IsWindowVisible(window)||GetWindow(window,GW_OWNER)||GetWindowTextLengthW(window)==0)return TRUE;
+ DWORD cloaked=0;DwmGetWindowAttribute(window,DWMWA_CLOAKED,&cloaked,sizeof(cloaked));if(cloaked)return TRUE;
+ wchar_t title[1024]{};GetWindowTextW(window,title,1024);RECT r{};GetClientRect(window,&r);
+ if(r.right<=0||r.bottom<=0)return TRUE;
+ reinterpret_cast<std::vector<ScreenCaptureTarget>*>(param)->push_back({ScreenTargetKind::Window,uint64_t(window),pid,title,unsigned(r.right),unsigned(r.bottom),0});return TRUE;
+ },reinterpret_cast<LPARAM>(&result));
+ }else{
+ EnumDisplayMonitors(nullptr,nullptr,[](HMONITOR monitor,HDC,LPRECT,LPARAM param)->BOOL{
+ MONITORINFOEXW info{};info.cbSize=sizeof(info);if(!GetMonitorInfoW(monitor,&info))return TRUE;
+ DEVMODEW mode{};mode.dmSize=sizeof(mode);EnumDisplaySettingsW(info.szDevice,ENUM_CURRENT_SETTINGS,&mode);
+ auto& list=*reinterpret_cast<std::vector<ScreenCaptureTarget>*>(param);
+ list.push_back({ScreenTargetKind::Monitor,uint64_t(monitor),0,std::format(L"{} {} x {} {} Hz",info.szDevice,mode.dmPelsWidth,mode.dmPelsHeight,mode.dmDisplayFrequency),mode.dmPelsWidth,mode.dmPelsHeight,mode.dmDisplayFrequency});return TRUE;
+ },reinterpret_cast<LPARAM>(&result));
+ }return result;
+}
+struct ScreenCaptureSource::Impl {
+ ScreenCaptureOptions options;SourceInfo info;ScreenCaptureMetrics metrics;
+ ComPtr<ID3D11Device5> device;ComPtr<ID3D11DeviceContext4> context;
+ ComPtr<ID3D12Device> consumer;ComPtr<ID3D11Fence> producerFence;ComPtr<ID3D12Fence> fence;
+ ComPtr<IDXGIOutputDuplication> duplication;
+ winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice wrapped{nullptr};
+ GraphicsCaptureItem item{nullptr};Direct3D11CaptureFramePool pool{nullptr};GraphicsCaptureSession session{nullptr};
+ winrt::Windows::Graphics::SizeInt32 poolSize{};
+ std::array<std::shared_ptr<Surface>,6> slots;
+ AVFrame* frame=nullptr;
+ uint64_t signal=0,sequence=0;int64_t lastPts=0,nextPts=0,clockOffset=0,lastColorCheck=0;
+ DWORD targetPid=0;bool hdr=false,wasWaiting=false,exclusion=false;
+ std::wstring message;DXGI_FORMAT format=DXGI_FORMAT_B8G8R8A8_UNORM;
+ ~Impl(){av_frame_free(&frame);}
+ int64_t interval()const{return 10000000LL*info.nominalRateDen/info.nominalRateNum;}
+ void updateRate(HMONITOR monitor){
+ auto rate=options.fps?DXGI_RATIONAL{options.fps,1}:monitorRate(monitor);
+ if(!rate.Numerator||!rate.Denominator){
+ if(info.nominalRateNum)return; // Retain the last known rate on a transient query failure.
+ rate={60,1};log::warn("screen","display refresh query failed; using 60 FPS limit");
+ }
+ if(info.nominalRateNum==int(rate.Numerator)&&info.nominalRateDen==int(rate.Denominator))return;
+ info.nominalRateNum=int(rate.Numerator);info.nominalRateDen=int(rate.Denominator);
+ info.averageFps=double(rate.Numerator)/rate.Denominator;nextPts=0;
+ if(sequence)wasWaiting=true;
+ log::info("screen-rate",std::format("followDisplay={} limit={}/{} ({:.3f} Hz) monitor={}",options.fps==0,rate.Numerator,rate.Denominator,info.averageFps,uint64_t(monitor)));
+ }
+ void color(){
+ auto& c=info.color;c={};c.pixelFormat=hdr?pipeline::SourcePixelFormat::Rgba16F:pipeline::SourcePixelFormat::Bgra8;
+ c.range=pipeline::ColorRange::Full;c.matrix=pipeline::YuvMatrix::BT709;
+ c.transfer=hdr?pipeline::TransferFunction::Linear:pipeline::TransferFunction::SRGB;
+ c.primaries=pipeline::ColorPrimaries::BT709;c.scRgb=hdr;
+ }
+ std::shared_ptr<Surface> acquire(unsigned width,unsigned height){
+ for(auto& slot:slots){if(slot&&slot.use_count()!=1)continue;
+ if(!slot||slot->width!=width||slot->height!=height||slot->format!=format){
+ auto next=std::make_shared<Surface>();next->width=width;next->height=height;next->format=format;next->fence=fence;
+ D3D11_TEXTURE2D_DESC td{};td.Width=width;td.Height=height;td.MipLevels=td.ArraySize=1;td.Format=format;td.SampleDesc.Count=1;
+ td.Usage=D3D11_USAGE_DEFAULT;td.BindFlags=D3D11_BIND_SHADER_RESOURCE;td.MiscFlags=D3D11_RESOURCE_MISC_SHARED_NTHANDLE|D3D11_RESOURCE_MISC_SHARED;
+ check(device->CreateTexture2D(&td,nullptr,&next->producer),"Create shared texture");
+ ComPtr<IDXGIResource1> resource;check(next->producer.As(&resource),"shared IDXGIResource1");NativeHandle handle;
+ check(resource->CreateSharedHandle(nullptr,DXGI_SHARED_RESOURCE_READ|DXGI_SHARED_RESOURCE_WRITE,nullptr,&handle.value),"texture NT handle");
+ check(consumer->OpenSharedHandle(handle.value,IID_PPV_ARGS(&next->consumer)),"Open texture D3D12");slot=std::move(next);
+ }return slot;
+ }return {};
+ }
+ void startDuplication(){
+ ComPtr<IDXGIDevice> dxgi;check(device.As(&dxgi),"DXGI device");ComPtr<IDXGIAdapter> adapter;check(dxgi->GetAdapter(&adapter),"adapter");
+ for(UINT i=0;;++i){ComPtr<IDXGIOutput> output;const auto hr=adapter->EnumOutputs(i,&output);if(hr==DXGI_ERROR_NOT_FOUND)break;check(hr,"EnumOutputs");
+ DXGI_OUTPUT_DESC d{};check(output->GetDesc(&d),"output description");if(uint64_t(d.Monitor)!=options.target)continue;
+ if(d.Rotation!=DXGI_MODE_ROTATION_IDENTITY)throw winrt::hresult_error(E_NOTIMPL,L"旋转显示器请使用 Windows 采集方式");
+ ComPtr<IDXGIOutput5> five;check(output.As(&five),"IDXGIOutput5");
+ const DXGI_FORMAT formats[]={format};check(five->DuplicateOutput1(device.Get(),0,1,formats,&duplication),"DuplicateOutput1");return;
+ }throw winrt::hresult_error(DXGI_ERROR_NOT_FOUND,L"兼容方式要求显示器连接在处理显卡上;请选择 Windows 采集");
+ }
+};
+ScreenCaptureSource::ScreenCaptureSource():p_(std::make_unique<Impl>()){}
+ScreenCaptureSource::~ScreenCaptureSource(){close();}
+bool ScreenCaptureSource::open(const SourceOpenDesc& desc){
+ close();p_=std::make_unique<Impl>();auto& p=*p_;
+ try{
+ if(!ScreenCaptureOptions::parse(desc.path,p.options)||!desc.d3d12Device)throw winrt::hresult_error(E_INVALIDARG,L"屏幕采集参数无效");
+ const auto& o=p.options;HWND window=o.kind==ScreenTargetKind::Window?reinterpret_cast<HWND>(o.target):nullptr;
+ if(window){GetWindowThreadProcessId(window,&p.targetPid);if(!IsWindow(window)||p.targetPid==GetCurrentProcessId())throw winrt::hresult_error(E_INVALIDARG,L"窗口已关闭或属于 Veyra");}
+ HMONITOR monitor=window?MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST):reinterpret_cast<HMONITOR>(o.target);
+ p.hdr=hdrMonitor(monitor);p.format=p.hdr?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_B8G8R8A8_UNORM;
+ p.consumer=static_cast<ID3D12Device*>(desc.d3d12Device);
+ ComPtr<IDXGIFactory4> factory;check(CreateDXGIFactory1(IID_PPV_ARGS(&factory)),"factory");ComPtr<IDXGIAdapter> adapter;
+ check(factory->EnumAdapterByLuid(p.consumer->GetAdapterLuid(),IID_PPV_ARGS(&adapter)),"processing adapter");
+ ComPtr<ID3D11Device> device;ComPtr<ID3D11DeviceContext> context;
+ check(D3D11CreateDevice(adapter.Get(),D3D_DRIVER_TYPE_UNKNOWN,nullptr,D3D11_CREATE_DEVICE_BGRA_SUPPORT,nullptr,0,D3D11_SDK_VERSION,&device,nullptr,&context),"D3D11CreateDevice");
+ check(device.As(&p.device),"D3D11 device5");check(context.As(&p.context),"D3D11 context4");
+ check(p.device->CreateFence(0,D3D11_FENCE_FLAG_SHARED,IID_PPV_ARGS(&p.producerFence)),"producer fence");NativeHandle handle;
+ check(p.producerFence->CreateSharedHandle(nullptr,GENERIC_ALL,nullptr,&handle.value),"fence NT handle");
+ check(p.consumer->OpenSharedHandle(handle.value,IID_PPV_ARGS(&p.fence)),"Open fence D3D12");
+ if(o.kind==ScreenTargetKind::Monitor){excludeOwnWindows();p.exclusion=true;}
+ if(o.method==ScreenCaptureMethod::Duplication){
+ if(o.cursor)throw winrt::hresult_error(E_NOTIMPL,L"兼容方式请关闭鼠标指针,或改用 Windows 采集");
+ p.startDuplication();DXGI_OUTDUPL_DESC d{};p.duplication->GetDesc(&d);p.poolSize={int(d.ModeDesc.Width),int(d.ModeDesc.Height)};
+ }else{
+ if(!GraphicsCaptureSession::IsSupported())throw winrt::hresult_error(E_NOTIMPL,L"系统不支持 Windows Graphics Capture");
+ auto interop=winrt::get_activation_factory<GraphicsCaptureItem,IGraphicsCaptureItemInterop>();
+ if(window)check(interop->CreateForWindow(window,winrt::guid_of<GraphicsCaptureItem>(),winrt::put_abi(p.item)),"CreateForWindow");
+ else check(interop->CreateForMonitor(monitor,winrt::guid_of<GraphicsCaptureItem>(),winrt::put_abi(p.item)),"CreateForMonitor");
+ ComPtr<IDXGIDevice> dxgi;check(device.As(&dxgi),"DXGI device");winrt::com_ptr<IInspectable> inspectable;
+ check(CreateDirect3D11DeviceFromDXGIDevice(dxgi.Get(),inspectable.put()),"WinRT device");p.wrapped=inspectable.as<winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice>();
+ p.poolSize=p.item.Size();p.pool=Direct3D11CaptureFramePool::CreateFreeThreaded(p.wrapped,DirectXPixelFormat(p.format),2,p.poolSize);
+ p.session=p.pool.CreateCaptureSession(p.item);p.session.IsCursorCaptureEnabled(o.cursor);p.session.StartCapture();
+ }
+ if(p.poolSize.Width<=int(o.left+o.right)||p.poolSize.Height<=int(o.top+o.bottom))throw winrt::hresult_error(E_INVALIDARG,L"裁剪范围超出画面");
+ p.info.opened=true;p.info.kind=pipeline::SourceKind::ScreenCapture;p.info.width=p.poolSize.Width-o.left-o.right;p.info.height=p.poolSize.Height-o.top-o.bottom;
+ p.updateRate(monitor);p.info.hardwareDecodeActive=true;
+ p.info.videoDecodePath=o.method==ScreenCaptureMethod::Wgc?"WGC shared GPU":"DXGI duplication shared GPU";
+ p.info.containerName="screen";p.info.videoCodecName="GPU RGB";p.info.videoPixelFormatName=p.hdr?"scRGB FP16":"BGRA8 sRGB";p.color();
+ p.clockOffset=host100ns()-qpc100ns();p.frame=av_frame_alloc();if(!p.frame)throw std::bad_alloc();
+ log::info("screen",std::format("opened method={} target={} size={}x{} hdr={} fpsLimit={:.3f} followDisplay={} cursor={} pool=6 cpuReadback=0 audioCapture=0",unsigned(o.method),o.target,p.info.width,p.info.height,p.hdr,p.info.averageFps,o.fps==0,o.cursor));
+ return true;
+ }catch(const winrt::hresult_error& e){p.message=std::format(L"屏幕采集失败 0x{:08X}:{}",uint32_t(e.code()),e.message().c_str());log::error("screen",winrt::to_string(p.message));}
+ catch(const std::exception& e){p.message=L"屏幕采集资源分配失败";log::error("screen",e.what());}
+ auto error=p.message;close();p.message=error;return false;
+}
+SourceReadStatus ScreenCaptureSource::read(pipeline::FramePacket& packet,const AVFrame** output){
+ auto& p=*p_;*output=nullptr;if(!p.info.opened)return SourceReadStatus::Error;
+ try{
+ HWND window=p.options.kind==ScreenTargetKind::Window?reinterpret_cast<HWND>(p.options.target):nullptr;
+ if(window){DWORD pid=0;GetWindowThreadProcessId(window,&pid);if(!IsWindow(window)||pid!=p.targetPid){p.message=L"采集窗口已关闭,请重新选择窗口";return SourceReadStatus::Error;}
+ if(IsIconic(window)){p.message=L"窗口已最小化,等待恢复";p.wasWaiting=true;return SourceReadStatus::Waiting;}}
+ const auto now=host100ns();
+ if(now-p.lastColorCheck>10000000){
+ p.lastColorCheck=now;
+ const auto monitor=window?MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST):reinterpret_cast<HMONITOR>(p.options.target);
+ MONITORINFO mi{sizeof(mi)};
+ if(!GetMonitorInfoW(monitor,&mi)){p.message=L"显示器已断开,请重新选择目标";return SourceReadStatus::Error;}
+ if(!p.options.fps)p.updateRate(monitor);
+ const bool hdr=hdrMonitor(monitor);
+ if(hdr!=p.hdr){
+ p.hdr=hdr;p.format=hdr?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_B8G8R8A8_UNORM;p.color();p.wasWaiting=true;
+ p.info.videoPixelFormatName=hdr?"scRGB FP16":"BGRA8 sRGB";
+ if(p.duplication){p.duplication.Reset();p.startDuplication();}
+ else p.pool.Recreate(p.wrapped,DirectXPixelFormat(p.format),2,p.poolSize);
+ log::info("screen",std::format("source color changed scRgb={}",hdr));return SourceReadStatus::Waiting;
+ }
+ }
+ ComPtr<ID3D11Texture2D> texture;Direct3D11CaptureFrame captured{nullptr};int64_t pts=0;
+ struct FrameLease {Direct3D11CaptureFrame& frame;~FrameLease(){if(frame)try{frame.Close();}catch(...){}}} frameLease{captured};
+ struct DupLease {IDXGIOutputDuplication* value=nullptr;~DupLease(){if(value)value->ReleaseFrame();}} lease;
+ if(p.duplication){DXGI_OUTDUPL_FRAME_INFO fi{};ComPtr<IDXGIResource> resource;const auto hr=p.duplication->AcquireNextFrame(0,&fi,&resource);
+ if(hr==DXGI_ERROR_WAIT_TIMEOUT)return SourceReadStatus::Waiting;
+ if(hr==DXGI_ERROR_ACCESS_LOST){p.duplication.Reset();p.startDuplication();p.wasWaiting=true;return SourceReadStatus::Waiting;}
+ check(hr,"AcquireNextFrame");lease.value=p.duplication.Get();check(resource.As(&texture),"duplication texture");
+ if(!fi.LastPresentTime.QuadPart)return SourceReadStatus::Waiting;
+ LARGE_INTEGER freq{};QueryPerformanceFrequency(&freq);pts=int64_t(static_cast<long double>(fi.LastPresentTime.QuadPart)*10000000/freq.QuadPart)+p.clockOffset;++p.metrics.received;
+ }else{
+ for(unsigned i=0;i<2;++i){auto next=p.pool.TryGetNextFrame();if(!next)break;if(captured){captured.Close();++p.metrics.dropped;}captured=std::move(next);++p.metrics.received;}
+ if(!captured)return SourceReadStatus::Waiting;
+ const auto size=captured.ContentSize();
+ if(size.Width!=p.poolSize.Width||size.Height!=p.poolSize.Height){captured.Close();captured=nullptr;if(size.Width>0&&size.Height>0){p.poolSize=size;p.pool.Recreate(p.wrapped,DirectXPixelFormat(p.format),2,size);}p.wasWaiting=true;return SourceReadStatus::Waiting;}
+ auto access=captured.Surface().as<::Windows::Graphics::DirectX::Direct3D11::IDirect3DDxgiInterfaceAccess>();check(access->GetInterface(IID_PPV_ARGS(&texture)),"capture surface");
+ pts=captured.SystemRelativeTime().count()+p.clockOffset;
+ }
+ // Accumulate deadlines: comparing each jittery interval to an exact
+ // 1/60 would accidentally discard nearly half of a 60 Hz stream.
+ if(pts<=p.lastPts||pts<p.nextPts-5000){++p.metrics.dropped;return SourceReadStatus::Waiting;}
+ D3D11_TEXTURE2D_DESC td{};texture->GetDesc(&td);
+ if(td.Format!=p.format)throw winrt::hresult_error(E_UNEXPECTED,L"采集颜色格式发生变化,请重新连接");
+ const auto& o=p.options;unsigned w=std::min(td.Width,unsigned(p.poolSize.Width)),h=std::min(td.Height,unsigned(p.poolSize.Height));
+ if(w<=o.left+o.right||h<=o.top+o.bottom){p.message=L"窗口小于裁剪范围,等待尺寸恢复";p.wasWaiting=true;return SourceReadStatus::Waiting;}
+ w-=o.left+o.right;h-=o.top+o.bottom;
+ av_frame_unref(p.frame);auto slot=p.acquire(w,h);if(!slot){++p.metrics.dropped;return SourceReadStatus::Waiting;}
+ D3D11_BOX box{o.left,o.top,0,o.left+w,o.top+h,1};p.context->CopySubresourceRegion(slot->producer.Get(),0,0,0,0,texture.Get(),0,&box);
+ check(p.context->Signal(p.producerFence.Get(),++p.signal),"producer Signal");p.context->Flush();
+ auto* owner=new std::shared_ptr<Surface>(slot);
+ p.frame->buf[0]=av_buffer_create(reinterpret_cast<uint8_t*>(owner),sizeof(*owner),[](void*,uint8_t* bytes){delete reinterpret_cast<std::shared_ptr<Surface>*>(bytes);},nullptr,0);
+ if(!p.frame->buf[0]){delete owner;throw std::bad_alloc();}
+ p.frame->data[0]=reinterpret_cast<uint8_t*>(slot->producer.Get());p.frame->format=AV_PIX_FMT_D3D11;p.frame->width=int(w);p.frame->height=int(h);p.frame->pts=pts;
+ packet={};packet.sequence=++p.sequence;packet.pts={pts,10000000};packet.duration=p.lastPts?pipeline::Rational{pts-p.lastPts,10000000}:pipeline::Rational{p.info.nominalRateDen,p.info.nominalRateNum};
+ packet.sourceKind=pipeline::SourceKind::ScreenCapture;packet.colorInfo=p.info.color;
+ packet.arrivalHost100ns=host100ns();packet.decodedHost100ns=packet.arrivalHost100ns;
+ if(p.sequence==1)packet.flags|=uint32_t(pipeline::FrameFlagBits::Open);
+ if(w!=p.info.width||h!=p.info.height){packet.flags|=uint32_t(pipeline::FrameFlagBits::Resize);p.info.width=w;p.info.height=h;}
+ if(p.wasWaiting||p.lastPts&&pts-p.lastPts>std::max<int64_t>(p.interval()*2,1000000))packet.flags|=uint32_t(pipeline::FrameFlagBits::Discontinuity);
+ packet.hardwareSurface={slot->consumer.Get(),0,p.fence.Get(),p.signal,w,h};
+ p.nextPts=std::max(p.nextPts+p.interval(),pts+p.interval()/2);
+ p.lastPts=pts;p.wasWaiting=false;p.message.clear();++p.metrics.delivered;
+ // WGC's compositor timestamp can be ahead of the CPU callback. Keep
+ // that signed delta in diagnostics, not in the ingress CPU duration.
+ p.metrics.ageMs=double(packet.arrivalHost100ns-now)/10000;
+ if(p.metrics.delivered==1||p.metrics.delivered%300==0)log::info("screen-timing",std::format("readCpuMs={:.3f} compositorToReadMs={:.3f} delivered={} received={} dropped={}",p.metrics.ageMs,double(packet.arrivalHost100ns-pts)/10000,p.metrics.delivered,p.metrics.received,p.metrics.dropped));
+ *output=p.frame;return SourceReadStatus::Frame;
+ }catch(const winrt::hresult_error& e){p.message=std::format(L"屏幕采集错误 0x{:08X}:{}",uint32_t(e.code()),e.message().c_str());log::error("screen",winrt::to_string(p.message));return SourceReadStatus::Error;}
+ catch(const std::exception& e){p.message=L"屏幕采集资源分配失败";log::error("screen",e.what());return SourceReadStatus::Error;}
+}
+void ScreenCaptureSource::close()noexcept{
+ if(!p_)return;
+ try{if(p_->session)p_->session.Close();}catch(...){}
+ try{if(p_->pool)p_->pool.Close();}catch(...){}
+ p_->session=nullptr;p_->pool=nullptr;p_->item=nullptr;p_->wrapped=nullptr;p_->duplication.Reset();
+ if(p_->exclusion){restoreOwnWindows();p_->exclusion=false;}
+ av_frame_free(&p_->frame);p_->slots={};p_->fence.Reset();p_->producerFence.Reset();p_->context.Reset();p_->device.Reset();p_->consumer.Reset();p_->info.opened=false;
+}
+const SourceInfo& ScreenCaptureSource::info()const{return p_->info;}
+std::wstring ScreenCaptureSource::status()const{return p_->message;}
+ScreenCaptureMetrics ScreenCaptureSource::metrics()const{return p_->metrics;}
+}
diff --git a/tests/integration/CaptureSourceTests.cpp b/tests/integration/CaptureSourceTests.cpp
index c2224621..1c0b0efc 100644
--- a/tests/integration/CaptureSourceTests.cpp
+++ b/tests/integration/CaptureSourceTests.cpp
@@ -1,6 +1,7 @@
// Optional real-device integration test. Saves no media; validates the product
// source's deferred Run, bounded mailbox, and reader-buffer lifetime.
#include "veyra/source/CaptureCardSource.h"
+#include "veyra/source/CaptureFrameRate.h"
#include <windows.h>
#include <chrono>
#include <thread>
@@ -13,6 +14,42 @@ extern "C" {
#include <libavutil/imgutils.h>
}
int wmain(int argc,wchar_t** argv){
+ if(argc==4&&wcscmp(argv[1],L"--rate-test")==0){
+ double expected=0;if(!veyra::source::parseCaptureFrameRate(argv[3],expected))return 2;
+ CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ veyra::source::CaptureCardSource source;veyra::source::SourceOpenDesc desc;desc.path=argv[2];
+ if(desc.path.starts_with(L"capture:")){
+ unsigned device=0;int format=0,audio=0;
+ if(swscanf_s(argv[2],L"capture:%u:%d:%d",&device,&format,&audio)!=3||audio!=-1)return 2;
+ const auto devices=veyra::source::CaptureCardSource::deviceDetails();if(device>=devices.size())return 2;
+ desc.path=veyra::source::CaptureCardSource::makeCapturePath(device,devices[device],format,audio,nullptr,0,expected);
+ }
+ if(!source.configure(desc)){wprintf(L"RATE_REJECTED %ls\n",source.errorMessage().c_str());return 3;}
+ if(!source.start())return 4;
+ int failures=0;
+ for(int pass=0;pass<2;++pass){
+ // Check physical callbacks, independent of the consumer's mailbox drops.
+ std::this_thread::sleep_for(std::chrono::seconds(1));
+ const auto before=source.metrics();const auto begin=std::chrono::steady_clock::now();
+ const auto until=begin+std::chrono::seconds(6);
+ const AVFrame* frame=nullptr;veyra::pipeline::FramePacket packet;
+ double lastPts=-1;unsigned read=0;bool monotonic=true;
+ while(std::chrono::steady_clock::now()<until){
+ if(source.read(packet,&frame)==veyra::source::SourceReadStatus::Frame){
+ const double pts=packet.pts.toDouble();monotonic&=pts>lastPts;lastPts=pts;++read;
+ }
+ }
+ const auto after=source.metrics();
+ const double seconds=std::chrono::duration<double>(std::chrono::steady_clock::now()-begin).count();
+ const double actual=(after.received-before.received)/seconds;
+ const double target=expected>0?expected:source.info().averageFps;
+ const bool ok=read>0&&monotonic&&std::abs(actual-target)<std::max(1.0,target*.05);
+ printf("%s RATE pass=%d requested=%.6f connected=%.6f callback=%.6f reads=%u monotonic=%d\n",ok?"PASS":"FAIL",pass,expected,source.info().averageFps,actual,read,monotonic);
+ if(!ok)++failures;
+ if(pass==0&&!source.reconnect(0,0,0)){printf("FAIL reconnect\n");++failures;break;}
+ }
+ source.close();CoUninitialize();return failures?1:0;
+ }
if(argc==2&&wcscmp(argv[1],L"--list")==0){
CoInitializeEx(nullptr,COINIT_MULTITHREADED);auto videos=veyra::source::CaptureCardSource::deviceDetails();auto audios=veyra::source::CaptureCardSource::deviceDetails(true);
for(unsigned d=0;d<videos.size();++d){wprintf(L"VIDEO %u %ls embeddedAudio=%d path=%ls\n",d,videos[d].name.c_str(),videos[d].hasEmbeddedAudio?1:0,videos[d].path.c_str());const auto formats=videos[d].path.empty()?veyra::source::CaptureCardSource::formats(d):veyra::source::CaptureCardSource::formatsByPath(videos[d].path);for(const auto& f:formats)wprintf(L"FORMAT %u:%d %ls\n",d,f.index,f.label.c_str());}
diff --git a/tests/integration/ExperimentalBackendTests.cpp b/tests/integration/ExperimentalBackendTests.cpp
index afede69d..6c327f98 100644
--- a/tests/integration/ExperimentalBackendTests.cpp
+++ b/tests/integration/ExperimentalBackendTests.cpp
@@ -126,7 +126,8 @@ bool readCanonicalFlow(gfx::D3D12DeviceContext& ctx, gfx::CommandSlotRing& ring,
int wmain(int argc,wchar_t** argv){
if(argc!=3)return 2;
const bool dis=std::wstring(argv[1]).find(L"dis")==0;
- const bool xess=wcscmp(argv[1],L"xess")==0||wcscmp(argv[1],L"dis-xess")==0;
+ const bool pan=wcscmp(argv[1],L"xess-pan2")==0||wcscmp(argv[1],L"xess-pan4")==0;
+ const bool xess=pan||wcscmp(argv[1],L"xess")==0||wcscmp(argv[1],L"dis-xess")==0;
const bool amd=wcscmp(argv[1],L"amd")==0;
const bool sr=std::wstring(argv[1]).find(L"sr")==0;
if(!xess&&!amd&&!sr&&!dis&&wcscmp(argv[1],L"nvof1080")!=0)return 2;
@@ -149,6 +150,7 @@ int wmain(int argc,wchar_t** argv){
desc.rgbInput=true;desc.enableNr=false;desc.enableFg=xess;desc.noNgx=true;
desc.enableNvofStandalone=true;
desc.frameGenerationBackend=engine::FrameGenerationBackend::XeSS;
+ if(wcscmp(argv[1],L"xess-pan4")==0)desc.fgMultiplier=4;
desc.opticalFlowBackend=dis?engine::OpticalFlowBackend::GpuDis:amd?engine::OpticalFlowBackend::AmdFidelityFx:engine::OpticalFlowBackend::Nvidia;
if(sr){
desc.sourceWidth=width;desc.sourceHeight=height;
@@ -165,6 +167,9 @@ int wmain(int argc,wchar_t** argv){
ok=ok&&av_frame_get_buffer(frame,32)>=0;
pipeline::EnhanceGraph::FrameOutputs out;
FlowSample rightward{}, leftward{};
+ engine::PreviewView view;
+ uint64_t panGenerated=0;
+ if(pan)view.zoom=1.5f;
for(unsigned i=0;ok&&i<frames;++i){
MSG msg;while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}
const int phase = i < 24 ? int(i) : int(i - 24);
@@ -178,10 +183,14 @@ int wmain(int argc,wchar_t** argv){
p[0]=uint8_t(hash);p[1]=uint8_t(hash>>8);p[2]=uint8_t(hash>>16);p[3]=255;
}
out={};ok=graph.process(frame,i*1000.0/30,i==0||i==24,out,i+1);
- if(ok)ok=presenter.present(ctx,ring,graph,out.videoSlot,false,false,0,false,.5f,out.batch.identity);
+ const bool moving=pan&&i>=4&&i<44;
+ if(moving)view.pan(i<24?3.0f:-3.0f,1.0f,960,540,float(width),float(height));
+ const auto beforePresent=presenter.xessGeneratedCount();
+ if(ok)ok=presenter.present(ctx,ring,graph,out.videoSlot,false,false,0,false,.5f,out.batch.identity,view);
+ if(moving)panGenerated+=presenter.xessGeneratedCount()-beforePresent;
if(ok&&i==16){
const auto before=presenter.xessGeneratedCount();
- ok=presenter.present(ctx,ring,graph,out.videoSlot,false,false,0,false,.5f,out.batch.identity);
+ ok=presenter.present(ctx,ring,graph,out.videoSlot,false,false,0,false,.5f,out.batch.identity,view);
if(xess)ok=ok&&presenter.xessGeneratedCount()==before;
}
if(i==24)SetWindowPos(window,nullptr,0,0,800,600,SWP_NOACTIVATE|SWP_NOZORDER);
@@ -203,6 +212,10 @@ int wmain(int argc,wchar_t** argv){
std::cout<<"SR extent="<<image.width<<"x"<<image.height<<" evaluate="<<graph.metrics().srEvaluateCount<<" nonblack="<<nonblack<<" pass="<<ok<<std::endl;
}
if(xess)ok=ok&&generated>10;
+ if(pan){
+ ok=ok&&panGenerated>10;
+ std::cout<<"PAN multiplier="<<desc.fgMultiplier<<" generatedWhileMoving="<<panGenerated<<" pass="<<ok<<std::endl;
+ }
if(amd||dis){
// The source moves right then left. Canonical current->previous motion
// must therefore point left then right with no material vertical drift.
diff --git a/tests/integration/HdrColorTests.cpp b/tests/integration/HdrColorTests.cpp
index 9dee24bc..580eaea6 100644
--- a/tests/integration/HdrColorTests.cpp
+++ b/tests/integration/HdrColorTests.cpp
@@ -11,6 +11,7 @@
#include "SdrColorGpuCases.h"
#include "HdrNativeRoundTripCases.h"
#include "HdrToneMapGpuCases.h"
+#include "ScreenScRgbCases.h"
#include <iostream>
#include <cmath>
extern "C" {
@@ -21,7 +22,7 @@ int wmain(int argc,wchar_t** argv){
CoInitializeEx(nullptr,COINIT_MULTITHREADED);
gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status st;gfx::DeviceContextDesc dd;
if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,st))return 2;
- int failures=captureGpuCases(ctx,ring)+sdrColorGpuCases(ctx,ring)+hdrRoundTrip::run(ctx,ring)+hdrToneTests::run(ctx,ring);
+ int failures=captureGpuCases(ctx,ring)+sdrColorGpuCases(ctx,ring)+hdrRoundTrip::run(ctx,ring)+hdrToneTests::run(ctx,ring)+screenScRgbCases(ctx,ring);
if(argc>1){
std::vector<uint8_t> software;const float expectedPeak=argc>2?float(_wtof(argv[2])):0;
for(bool hardware:{false,true}){
diff --git a/tests/integration/HdrNativeRoundTripCases.h b/tests/integration/HdrNativeRoundTripCases.h
index 910a193c..c2afa05c 100644
--- a/tests/integration/HdrNativeRoundTripCases.h
+++ b/tests/integration/HdrNativeRoundTripCases.h
@@ -3,6 +3,7 @@
#include <algorithm>
#include <cmath>
#include <cstring>
+#include "veyra/source/CaptureMediaType.h"
namespace hdrRoundTrip {
inline double pq(double nits){const double p=std::pow(std::max(nits,0.0)/10000,2610.0/16384);return std::pow((3424.0/4096+2413.0/128*p)/(1+2392.0/128*p),2523.0/32);}
@@ -53,6 +54,37 @@ inline int run(veyra::gfx::D3D12DeviceContext& ctx,veyra::gfx::CommandSlotRing&
gd.hdrInput=gd.hdrOutput=true;gd.noFeatures=gd.noNgx=true;gd.enableNr=gd.enableSr=false;gd.enableFg=packed;
pipeline::EnhanceGraph::FrameOutputs out;std::vector<float> output;
bool ok=graph.initialize(gd)&&graph.createViews()&&graph.process(f,0,true,out,1)&&read(ctx,ring,graph.videoFrameResource(out.videoSlot),output);
+ if(ok&&!planar){
+ VIDEOINFOHEADER2 vi{};vi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);vi.bmiHeader.biWidth=f->width;vi.bmiHeader.biHeight=f->height;
+ DXVA2_ExtendedFormat flags{};flags.NominalRange=full?DXVA2_NominalRange_0_255:DXVA2_NominalRange_16_235;flags.VideoTransferFunction=hlg?16:15;
+ vi.dwControlFlags=flags.value|AMCONTROL_COLORINFO_PRESENT;
+ AM_MEDIA_TYPE mt{};mt.majortype=MEDIATYPE_Video;mt.subtype={source::captureFourcc('P','0','1','0'),0,0x10,{0x80,0,0,0xaa,0,0x38,0x9b,0x71}};
+ mt.formattype=FORMAT_VideoInfo2;mt.pbFormat=reinterpret_cast<BYTE*>(&vi);mt.cbFormat=sizeof(vi);
+ source::CaptureMediaLayout layout;AVFrame* capture=av_frame_clone(f);
+ bool pass=capture&&source::captureMediaLayout(mt,layout);
+ if(capture){capture->color_range=AVCOL_RANGE_UNSPECIFIED;capture->colorspace=AVCOL_SPC_UNSPECIFIED;capture->color_trc=AVCOL_TRC_UNSPECIFIED;capture->color_primaries=AVCOL_PRI_UNSPECIFIED;}
+ pipeline::EnhanceGraph captureGraph(ctx,ring);pipeline::EnhanceGraph::FrameOutputs captureOut;std::vector<float> captured;
+ auto captureDesc=gd;captureDesc.hdrInput=layout.color.isHdrPath();captureDesc.captureBitDepth=10;
+ pass=pass&&captureGraph.initialize(captureDesc)&&captureGraph.createViews()&&captureGraph.process(capture,0,true,captureOut,1,&layout.color)&&read(ctx,ring,captureGraph.videoFrameResource(captureOut.videoSlot),captured)&&captured==output;
+ std::cout<<"HDR_CAPTURE_PARTIAL_TAGS hlg="<<hlg<<" full="<<full<<" pqOutput="<<packed<<" exact="<<pass<<std::endl;
+ failures+=!pass;captureOut={};ring.drainQueue();captureGraph.shutdown();av_frame_free(&capture);
+ }
+ if(ok&&!planar&&!packed){
+ // HDR primaries extend beyond BT.709. Enabling neutral grading
+ // must preserve them; exposure must multiply signed light equally.
+ std::vector<float> baseline;
+ bool gradeOk=captureReadFp16(ctx,ring,graph.diagnosticLinearInput(),baseline);
+ for(float exposure:{0.0f,1.0f}){
+ auto gradedDesc=gd;gradedDesc.color.enabled=true;gradedDesc.color.exposure=exposure;
+ pipeline::EnhanceGraph gradedGraph(ctx,ring);pipeline::EnhanceGraph::FrameOutputs gradedOut;std::vector<float> graded;
+ bool pass=gradeOk&&gradedGraph.initialize(gradedDesc)&&gradedGraph.createViews()&&gradedGraph.process(f,0,true,gradedOut,1)&&captureReadFp16(ctx,ring,gradedGraph.diagnosticLinearInput(),graded);
+ double error=0;
+ if(pass)for(size_t p=0;p<baseline.size();++p)if(p%4!=3)error=std::max(error,double(std::abs(graded[p]-baseline[p]*std::exp2(exposure))/std::max(1.0f,std::abs(baseline[p]*std::exp2(exposure)))));
+ pass=pass&&error<.003;
+ std::cout<<"HDR_GRADE_SIGNED hlg="<<hlg<<" full="<<full<<" exposure="<<exposure<<" relativeError="<<error<<" pass="<<pass<<std::endl;
+ failures+=!pass;gradedOut={};ring.drainQueue();gradedGraph.shutdown();
+ }
+ }
double relative=0,nearBlack=0,neutralSpread=0,neutralRelative=0;
if(ok)for(unsigned i=0;i<patches.size();++i){const auto* p=output.data()+(i*4+2)*3;std::array<double,3> actual;
if(packed)actual={nits(p[0]),nits(p[1]),nits(p[2])};
diff --git a/tests/integration/PopupSelectorTests.cpp b/tests/integration/PopupSelectorTests.cpp
index 53c77f5d..d7c1ae3d 100644
--- a/tests/integration/PopupSelectorTests.cpp
+++ b/tests/integration/PopupSelectorTests.cpp
@@ -21,6 +21,7 @@ LRESULT CALLBACK proc(HWND h,UINT m,WPARAM w,LPARAM l){
case 10:DestroyWindow(owner);break;
case 11:SendMessageW(list,WM_KEYDOWN,VK_DOWN,0);SendMessageW(list,WM_KEYDOWN,VK_RETURN,0);break;
case 13:{BYTE saved[256]{},shifted[256]{};GetKeyboardState(saved);std::copy_n(saved,256,shifted);shifted[VK_SHIFT]|=0x80;SetKeyboardState(shifted);SendMessageW(list,WM_KEYDOWN,VK_TAB,0);SetKeyboardState(saved);break;}
+ case 14:{RECT row{};SendMessageW(list,LB_GETITEMRECT,5,LPARAM(&row));const auto point=MAKELPARAM(row.left+8,(row.top+row.bottom)/2);SendMessageW(list,WM_MOUSEMOVE,0,point);UpdateWindow(list);for(int i=0;i<50;++i)SendMessageW(list,WM_MOUSEMOVE,0,point);require(!GetUpdateRect(list,nullptr,FALSE),"same-row pointer motion must not repeatedly invalidate");SendMessageW(list,WM_LBUTTONDOWN,MK_LBUTTON,point);SendMessageW(list,WM_LBUTTONUP,0,point);break;}
}return 0;
}return DefWindowProcW(h,m,w,l);
}
@@ -29,7 +30,7 @@ bool notified(int code){return std::find(notifications.begin(),notifications.end
int wmain(){ULONG_PTR gdiplus=0;Gdiplus::GdiplusStartupInput input;Gdiplus::GdiplusStartup(&gdiplus,&input,nullptr);int result=0;
try{
INITCOMMONCONTROLSEX common{sizeof(common),ICC_STANDARD_CLASSES};InitCommonControlsEx(&common);WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.lpszClassName=L"VeyraSelectorContract";wc.hInstance=GetModuleHandleW(nullptr);RegisterClassW(&wc);
- for(action=0;action<=13;++action){
+ for(action=0;action<=14;++action){
owner=CreateWindowExW(WS_EX_CONTROLPARENT,wc.lpszClassName,L"Veyra popup interaction test",WS_OVERLAPPEDWINDOW,20,20,480,320,nullptr,nullptr,wc.hInstance,nullptr);
previous=CreateWindowExW(0,L"BUTTON",L"previous",WS_CHILD|WS_VISIBLE|WS_TABSTOP,20,5,100,24,owner,HMENU(9),wc.hInstance,nullptr);
combo=CreateWindowExW(0,L"COMBOBOX",L"choices",WS_CHILD|WS_VISIBLE|WS_TABSTOP|CBS_DROPDOWNLIST,20,40,300,200,owner,HMENU(10),wc.hInstance,nullptr);veyra::ui::themeControl(combo);
@@ -40,7 +41,7 @@ try{
SendMessageW(combo,CB_SHOWDROPDOWN,TRUE,0);if(IsWindow(owner))KillTimer(owner,1);require(action==8||action==12?steps==0:steps>0&&steps<=10,"bounded popup closed including synchronous cancellation");require(!veyra::ui::popupSelectorOpen()&&!veyra::ui::activeSelector,"popup releases all active state");
if(action>=9&&action<=12){require(!IsWindow(combo),"destroyed combo stays destroyed");if(action==10||action==12)require(!IsWindow(owner),"destroyed owner stays destroyed");if(IsWindow(owner))DestroyWindow(owner);std::cout<<"PASS popup case "<<action<<"\n";continue;}
require(!SendMessageW(combo,CB_GETDROPPEDSTATE,0,0),"collapse reports closed");require(notified(CBN_DROPDOWN)&&notified(CBN_CLOSEUP),"native dropdown lifecycle notifications");
- if(action==0||action==5){require(SendMessageW(combo,CB_GETCURSEL,0,0)==(action==0?5:32),"arrow/end commits selected option including scrolled items");require(notified(CBN_SELCHANGE)&&notified(CBN_SELENDOK),"commit notifies owning panel");}
+ if(action==0||action==5||action==14){require(SendMessageW(combo,CB_GETCURSEL,0,0)==(action==5?32:5),"arrow/end/mouse commits selected option including scrolled items");require(notified(CBN_SELCHANGE)&&notified(CBN_SELENDOK),"commit notifies owning panel");}
else{require(notified(CBN_SELENDCANCEL)&&!notified(CBN_SELCHANGE),"cancel never submits a setting");if(action!=4)require(SendMessageW(combo,CB_GETCURSEL,0,0)==4,"cancel keeps original selection");}
if(action==3)require(GetFocus()==next,"Tab advances to next control");
if(action==13)require(GetFocus()==previous,"Shift+Tab returns to previous control");
diff --git a/tests/integration/ScreenCaptureTests.cpp b/tests/integration/ScreenCaptureTests.cpp
new file mode 100644
index 00000000..e02a800b
--- /dev/null
+++ b/tests/integration/ScreenCaptureTests.cpp
@@ -0,0 +1,107 @@
+#include "veyra/source/ScreenCaptureSource.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/sink/ImageExportSink.h"
+#include "veyra/engine/EngineController.h"
+#include <windows.h>
+#include <dwmapi.h>
+#include <chrono>
+#include <cmath>
+#include <iostream>
+#include <thread>
+extern "C" {
+#include <libavutil/frame.h>
+}
+using namespace veyra;
+namespace {
+int failures=0;
+void check(bool pass,const char* name){std::cout<<"SCREEN "<<name<<" pass="<<pass<<std::endl;failures+=!pass;}
+void pump(){MSG msg;while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}}
+LRESULT CALLBACK pattern(HWND w,UINT m,WPARAM wp,LPARAM lp){
+ if(m==WM_TIMER){InvalidateRect(w,nullptr,FALSE);return 0;}
+ if(m==WM_PAINT){PAINTSTRUCT ps;auto dc=BeginPaint(w,&ps);RECT r;GetClientRect(w,&r);
+ const COLORREF colors[]={RGB(225,30,45),RGB(20,210,70),RGB(25,60,225)};
+ for(int i=0;i<3;++i){RECT band{r.right*i/3,0,r.right*(i+1)/3,r.bottom};auto brush=CreateSolidBrush(colors[i]);FillRect(dc,&band,brush);DeleteObject(brush);}
+ RECT moving{int(GetTickCount64()/10%std::max(1L,r.right-24)),8,0,32};moving.right=moving.left+24;FillRect(dc,&moving,HBRUSH(GetStockObject(WHITE_BRUSH)));EndPaint(w,&ps);return 0;}
+ if(m==WM_CLOSE){DestroyWindow(w);return 0;}if(m==WM_DESTROY){PostQuitMessage(0);return 0;}
+ return DefWindowProcW(w,m,wp,lp);
+}
+bool next(source::ScreenCaptureSource& source,pipeline::FramePacket& p,const AVFrame** f,unsigned timeout=3000){
+ const auto end=GetTickCount64()+timeout;while(GetTickCount64()<end){auto status=source.read(p,f);if(status==source::SourceReadStatus::Frame)return true;if(status==source::SourceReadStatus::Error){std::wcerr<<source.status()<<std::endl;return false;}pump();Sleep(2);}return false;
+}
+bool content(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,source::ScreenCaptureSource& source,pipeline::FramePacket& p,const AVFrame* f){
+ pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc gd;gd.sourceWidth=gd.workWidth=f->width;gd.sourceHeight=gd.workHeight=f->height;gd.rgbInput=true;gd.noFeatures=true;gd.enableNr=gd.enableSr=gd.enableFg=false;gd.hdrInput=p.colorInfo.isHdrPath();
+ pipeline::EnhanceGraph::FrameOutputs out;sink::RgbaImage image;
+ bool ok=graph.initialize(gd)&&graph.createViews()&&graph.process(f,double(p.pts.to100ns())/10000,true,out,1,&p.colorInfo, &p.hardwareSurface);
+ if(ok)ok=sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),image);
+ if(ok){const unsigned y=image.height/2;for(unsigned i=0;i<3;++i){unsigned x=image.width*(2*i+1)/6;auto* pixel=&image.pixels[(size_t(y)*image.width+x)*4];std::cout<<"PIXEL "<<i<<" "<<int(pixel[0])<<","<<int(pixel[1])<<","<<int(pixel[2])<<std::endl;ok&=pixel[i]>160&&pixel[(i+1)%3]<110&&pixel[(i+2)%3]<110;}}
+ out={};ring.drainQueue();graph.shutdown();return ok;
+}
+}
+int wmain(int argc,wchar_t** argv){
+ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ if(argc>1&&std::wstring(argv[1])==L"--target"){
+ WNDCLASSW wc{};wc.lpfnWndProc=pattern;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraScreenTestPattern";RegisterClassW(&wc);
+ auto window=CreateWindowW(wc.lpszClassName,L"Veyra capture test pattern",WS_OVERLAPPEDWINDOW|WS_VISIBLE,40,40,660,420,nullptr,nullptr,wc.hInstance,nullptr);SetTimer(window,1,16,nullptr);
+ auto end=GetTickCount64()+240000;MSG msg;while(GetTickCount64()<end){if(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){if(msg.message==WM_QUIT)break;TranslateMessage(&msg);DispatchMessageW(&msg);}else Sleep(2);}return 0;
+ }
+ wchar_t path[32768];GetModuleFileNameW(nullptr,path,32768);std::wstring command=L"\""+std::wstring(path)+L"\" --target";
+ STARTUPINFOW si{sizeof(si)};PROCESS_INFORMATION process{};if(!CreateProcessW(path,command.data(),nullptr,nullptr,FALSE,0,nullptr,nullptr,&si,&process))return 2;
+ struct Child {PROCESS_INFORMATION p;HWND window=nullptr;~Child(){if(window)PostMessageW(window,WM_CLOSE,0,0);if(WaitForSingleObject(p.hProcess,3000)==WAIT_TIMEOUT)TerminateProcess(p.hProcess,1);CloseHandle(p.hThread);CloseHandle(p.hProcess);}} child{process};
+ for(int i=0;i<100&&!child.window;++i){for(auto& t:source::ScreenCaptureSource::targets(source::ScreenTargetKind::Window))if(t.processId==process.dwProcessId)child.window=HWND(t.handle);Sleep(20);}if(!child.window)return 3;
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status st;gfx::DeviceContextDesc dd;dd.enableDebugLayer=true;
+ if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,st))return 4;
+ source::ScreenCaptureOptions options;check(options.fps==0,"default follows display refresh");options.target=uint64_t(child.window);options.fps=60;options.cursor=false;
+ source::ScreenCaptureOptions parsed;check(source::ScreenCaptureOptions::parse(options.uri(),parsed)&&parsed.target==options.target,"URI round trip");check(!source::ScreenCaptureOptions::parse(options.uri()+L":3",parsed),"reject malformed URI");
+ source::SourceOpenDesc desc;desc.path=options.uri();desc.d3d12Device=ctx.device();desc.d3d12Queue=ctx.directQueue();source::ScreenCaptureSource source;
+ bool opened=source.open(desc);check(opened,"WGC open");if(!opened){std::wcerr<<source.status()<<std::endl;return 5;}
+ pipeline::FramePacket p;const AVFrame* f=nullptr;bool frame=next(source,p,&f);check(frame,"WGC first real frame");if(!frame)return 6;
+ check(content(ctx,ring,source,p,f),"WGC shared GPU graph RGB stripe content");
+ const auto initialReceived=source.metrics().received,initialDropped=source.metrics().dropped;
+ auto end=GetTickCount64()+4000;unsigned frames=0;int64_t last=0;bool monotonic=true;
+ while(GetTickCount64()<end){if(source.read(p,&f)==source::SourceReadStatus::Frame){monotonic&=p.pts.to100ns()>last;last=p.pts.to100ns();++frames;}pump();Sleep(2);}
+ const auto received=source.metrics().received-initialReceived,dropped=source.metrics().dropped-initialDropped;
+ check(monotonic&&frames>60&&frames<=245&&frames+2>=received-dropped&&dropped<received/10+2,"sustained capture follows producer with monotonic PTS and bounded loss");std::cout<<"RATE fourSecondsFrames="<<frames<<" received="<<received<<" dropped="<<dropped<<std::endl;
+ // Hold every lease: source must stop producing rather than overwrite.
+ std::vector<AVFrame*> held;for(int i=0;i<6;++i)if(next(source,p,&f))held.push_back(av_frame_clone(f));
+ auto before=source.metrics().delivered;end=GetTickCount64()+200;while(GetTickCount64()<end){source.read(p,&f);Sleep(2);}check(held.size()==6&&source.metrics().delivered==before,"bounded pool refuses reuse while all leases held");
+ for(auto* value:held)av_frame_free(&value);held.clear();check(next(source,p,&f),"pool resumes after lease release");
+ ShowWindow(child.window,SW_MINIMIZE);Sleep(100);check(source.read(p,&f)==source::SourceReadStatus::Waiting,"minimized waits");ShowWindow(child.window,SW_RESTORE);check(next(source,p,&f)&&pipeline::breaksHistory(p.flags),"restore resets temporal history");
+ SetWindowPos(child.window,nullptr,40,40,820,510,SWP_NOZORDER);end=GetTickCount64()+3000;bool resized=false;
+ while(GetTickCount64()<end&&next(source,p,&f)){if(f->width>660){resized=true;break;}}
+ check(resized&&unsigned(f->width)==source.info().width,"resize updates dimensions");check(content(ctx,ring,source,p,f),"resize retains RGB content");
+ source.close();options.left=30;options.right=30;options.top=20;options.bottom=20;desc.path=options.uri();check(source.open(desc)&&next(source,p,&f)&&f->width<820,"cropped source opens");source.close();
+ options.left=options.right=options.top=options.bottom=0;
+ options.fps=0;check(source::ScreenCaptureOptions::parse(options.uri(),parsed)&&parsed.fps==0,"automatic rate URI round trip");
+ MONITORINFOEXW monitorInfo{};monitorInfo.cbSize=sizeof(monitorInfo);DEVMODEW displayMode{};displayMode.dmSize=sizeof(displayMode);
+ const bool displayKnown=GetMonitorInfoW(MonitorFromWindow(child.window,MONITOR_DEFAULTTONEAREST),&monitorInfo)&&EnumDisplaySettingsW(monitorInfo.szDevice,ENUM_CURRENT_SETTINGS,&displayMode);
+ desc.path=options.uri();const bool autoOpened=source.open(desc)&&next(source,p,&f);
+ check(autoOpened&&displayKnown&&source.info().nominalRateNum>0&&source.info().nominalRateDen>0&&std::abs(source.info().averageFps-displayMode.dmDisplayFrequency)<1.1,"automatic window rate matches target display");
+ check(autoOpened&&p.duration.to100ns()>0&&std::abs(double(p.duration.to100ns())*source.info().averageFps-10000000)<1000,"automatic first frame has valid nominal duration");
+ std::cout<<"AUTO rate="<<source.info().nominalRateNum<<"/"<<source.info().nominalRateDen<<" displayHz="<<displayMode.dmDisplayFrequency<<std::endl;
+ if(autoOpened)check(content(ctx,ring,source,p,f),"automatic window capture actual RGB content");source.close();
+ if(argc>1&&std::wstring(argv[1])==L"--engine"){
+ HWND host=CreateWindowW(L"STATIC",L"Screen engine test",WS_OVERLAPPEDWINDOW|WS_VISIBLE,880,40,720,480,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
+ SetWindowDisplayAffinity(host,WDA_EXCLUDEFROMCAPTURE);engine::EngineController engine;engine::PlayerOptions settings;settings.nr=true;settings.fg=true;settings.fgMultiplier=4;engine.open(host,options.uri(),settings);
+ end=GetTickCount64()+20000;while(GetTickCount64()<end){pump();Sleep(10);}auto snapshot=engine.snapshot();check(snapshot.running&&!snapshot.failed&&snapshot.frames>100&&snapshot.generated>100&&snapshot.nrEvaluated>100,"screen NR and DLSS4x actual evaluation");std::wcout<<L"ENGINE "<<snapshot.status<<L" frames="<<snapshot.frames<<L" generated="<<snapshot.generated<<L" nr="<<snapshot.nrEvaluated<<std::endl;
+ engine.stop();end=GetTickCount64()+10000;while(!engine.idle()&&GetTickCount64()<end){pump();Sleep(10);}check(engine.idle(),"engine stop drains");DestroyWindow(host);
+ }
+ HWND excluded=CreateWindowW(L"STATIC",L"Screen exclusion test",WS_OVERLAPPEDWINDOW|WS_VISIBLE,880,40,200,160,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
+ DWORD affinity=0;check(GetWindowDisplayAffinity(excluded,&affinity)&&affinity==WDA_NONE,"initial own window remains capturable");
+ auto monitors=source::ScreenCaptureSource::targets(source::ScreenTargetKind::Monitor);check(!monitors.empty(),"enumerate monitors");
+ if(!monitors.empty())for(auto method:{source::ScreenCaptureMethod::Wgc,source::ScreenCaptureMethod::Duplication}){
+ const auto monitor=MonitorFromWindow(child.window,MONITOR_DEFAULTTONEAREST);MONITORINFO mi{sizeof(mi)};GetMonitorInfoW(monitor,&mi);
+ RECT client{};GetClientRect(child.window,&client);POINT origin{};ClientToScreen(child.window,&origin);
+ SetWindowPos(child.window,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);Sleep(150);
+ options.kind=source::ScreenTargetKind::Monitor;options.target=uint64_t(monitor);options.method=method;
+ options.left=origin.x-mi.rcMonitor.left;options.top=origin.y-mi.rcMonitor.top;options.right=mi.rcMonitor.right-origin.x-client.right;options.bottom=mi.rcMonitor.bottom-origin.y-client.bottom;
+ desc.path=options.uri();bool ok=source.open(desc)&&next(source,p,&f);check(ok&&content(ctx,ring,source,p,f),method==source::ScreenCaptureMethod::Wgc?"WGC monitor actual RGB content":"DXGI monitor actual RGB content");if(!ok)std::wcerr<<source.status()<<std::endl;
+ check(GetWindowDisplayAffinity(excluded,&affinity)&&affinity==WDA_EXCLUDEFROMCAPTURE,"monitor capture excludes own window");
+ source.close();check(GetWindowDisplayAffinity(excluded,&affinity)&&affinity==WDA_NONE,"stop restores original window affinity");
+ }
+ DestroyWindow(excluded);
+ options.left=options.top=options.right=options.bottom=0;
+ options.kind=source::ScreenTargetKind::Window;options.target=uint64_t(child.window);options.method=source::ScreenCaptureMethod::Wgc;desc.path=options.uri();check(source.open(desc),"window reopen");PostMessageW(child.window,WM_CLOSE,0,0);WaitForSingleObject(process.hProcess,3000);check(source.read(p,&f)==source::SourceReadStatus::Error,"closed target reports error");source.close();
+ std::cout<<"SCREEN failures="<<failures<<std::endl;return failures?1:0;
+}
diff --git a/tests/integration/ScreenScRgbCases.h b/tests/integration/ScreenScRgbCases.h
new file mode 100644
index 00000000..469e2d13
--- /dev/null
+++ b/tests/integration/ScreenScRgbCases.h
@@ -0,0 +1,37 @@
+#pragma once
+
+// Synthetic GPU ingress isolates the HDR contract from desktop HDR hardware.
+inline int screenScRgbCases(veyra::gfx::D3D12DeviceContext& ctx,veyra::gfx::CommandSlotRing& ring){
+ using namespace veyra;using Microsoft::WRL::ComPtr;
+ D3D12_RESOURCE_DESC td{};td.Dimension=D3D12_RESOURCE_DIMENSION_TEXTURE2D;td.Width=64;td.Height=16;
+ td.DepthOrArraySize=td.MipLevels=1;td.Format=DXGI_FORMAT_R16G16B16A16_FLOAT;td.SampleDesc.Count=1;
+ D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_DEFAULT;ComPtr<ID3D12Resource> texture,upload;
+ if(FAILED(ctx.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&td,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&texture))))return 1;
+ D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};UINT64 bytes=0;ctx.device()->GetCopyableFootprints(&td,0,1,0,&fp,nullptr,nullptr,&bytes);
+ auto bd=td;bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=bytes;bd.Height=1;bd.Format=DXGI_FORMAT_UNKNOWN;bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;hp.Type=D3D12_HEAP_TYPE_UPLOAD;
+ if(FAILED(ctx.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_GENERIC_READ,nullptr,IID_PPV_ARGS(&upload))))return 1;
+ const float patches[4][4]={{0,0,0,1},{1.25f,1.25f,1.25f,1},{12.5f,12.5f,12.5f,1},{4,-.2f,.1f,1}};
+ void* data=nullptr;if(FAILED(upload->Map(0,nullptr,&data)))return 1;
+ for(unsigned y=0;y<16;++y)for(unsigned x=0;x<64;++x)for(unsigned c=0;c<4;++c)
+ reinterpret_cast<uint16_t*>(static_cast<uint8_t*>(data)+fp.Offset+y*fp.Footprint.RowPitch)[x*4+c]=DirectX::PackedVector::XMConvertFloatToHalf(patches[x/16][c]);
+ upload->Unmap(0,nullptr);Status status;unsigned slot=0;auto* list=ring.acquireNext(slot,status);if(!list)return 1;
+ D3D12_TEXTURE_COPY_LOCATION from{},to{};from.pResource=upload.Get();from.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;from.PlacedFootprint=fp;to.pResource=texture.Get();to.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;list->CopyTextureRegion(&to,0,0,0,&from,nullptr);
+ D3D12_RESOURCE_BARRIER barrier{};barrier.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;barrier.Transition={texture.Get(),0,D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_COMMON};list->ResourceBarrier(1,&barrier);
+ if(!ring.submitAndSignal(slot)||!ring.drainQueue())return 1;
+ AVFrame* frame=av_frame_alloc();frame->format=AV_PIX_FMT_D3D11;frame->width=64;frame->height=16;frame->buf[0]=av_buffer_alloc(1);frame->data[0]=frame->buf[0]->data;
+ pipeline::ColorDescription color;color.scRgb=true;color.pixelFormat=pipeline::SourcePixelFormat::Rgba16F;color.range=pipeline::ColorRange::Full;color.transfer=pipeline::TransferFunction::Linear;color.primaries=pipeline::ColorPrimaries::BT709;color.matrix=pipeline::YuvMatrix::BT709;
+ pipeline::HardwareSurfaceInput surface{texture.Get(),0,nullptr,0,64,16};int failures=0;
+ for(bool native:{false,true})for(float exposure:{0.f,1.f}){
+ pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc d;d.sourceWidth=d.workWidth=64;d.sourceHeight=d.workHeight=16;d.rgbInput=d.hdrInput=d.noFeatures=true;d.enableNr=d.enableSr=d.enableFg=false;d.hdrOutput=native;d.color.enabled=true;d.color.exposure=exposure;
+ pipeline::EnhanceGraph::FrameOutputs out;bool ok=graph.initialize(d)&&graph.createViews()&&graph.process(frame,0,true,out,1,&color,&surface);double error=0;
+ if(native){std::vector<float> actual;ok=ok&&captureReadFp16(ctx,ring,graph.diagnosticLinearInput(),actual);
+ if(ok)for(unsigned p=0;p<4;++p)for(unsigned c=0;c<3;++c)error=std::max(error,double(std::abs(actual[(p*16+8)*4+c]-patches[p][c]*std::exp2(exposure))));
+ ok=ok&&error<.02;
+ }else{sink::RgbaImage image;ok=ok&&sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),image);
+ if(ok)for(unsigned p=0;p<3;++p){const double linear=hdrToneTests::luminance(std::min(double(patches[p][0]*80*std::exp2(exposure)),1000.),1000);const double srgb=linear<=.0031308?12.92*linear:1.055*std::pow(linear,1/2.4)-.055;error=std::max(error,std::abs(image.pixels[(p*16+8)*4]/255.-srgb));}
+ ok=ok&&error<.012;
+ }
+ std::cout<<"SCREEN_SCRGB native="<<native<<" exposure="<<exposure<<" error="<<error<<" pass="<<ok<<std::endl;failures+=!ok;out={};ring.drainQueue();graph.shutdown();
+ }
+ av_frame_free(&frame);return failures;
+}
diff --git a/tests/unit/CaptureColorContractTests.cpp b/tests/unit/CaptureColorContractTests.cpp
index fb3f07ba..54c0c151 100644
--- a/tests/unit/CaptureColorContractTests.cpp
+++ b/tests/unit/CaptureColorContractTests.cpp
@@ -115,6 +115,20 @@ int main(){
for(unsigned transfer:{15u,16u}){hdrFlags.VideoTransferFunction=transfer;hdrVi.dwControlFlags=hdrFlags.value|AMCONTROL_COLORINFO_PRESENT;
check(source::captureMediaLayout(hdrType,layout)&&layout.color.isHdrPath()&&layout.color.primaries==pipeline::ColorPrimaries::BT2020&&layout.color.matrix==pipeline::YuvMatrix::BT2020NCL&&!layout.color.transferAssumed,"capture negotiates explicit PQ/HLG BT2020 metadata");
}
+ hdrFlags.VideoTransferMatrix=0;hdrFlags.VideoPrimaries=0;
+ for(unsigned transfer:{15u,16u}){hdrFlags.VideoTransferFunction=transfer;hdrVi.dwControlFlags=hdrFlags.value|AMCONTROL_COLORINFO_PRESENT;
+ check(source::captureMediaLayout(hdrType,layout)&&layout.color.isHdrPath()&&layout.color.matrix==pipeline::YuvMatrix::BT2020NCL&&layout.color.primaries==pipeline::ColorPrimaries::BT2020&&layout.color.matrixAssumed&&layout.color.primariesAssumed&&!layout.color.transferAssumed,"explicit HDR transfer supplies labelled BT2100 fallback for missing gamut");
+ }
+ hdrFlags.VideoTransferMatrix=DXVA2_VideoTransferMatrix_BT709;hdrFlags.VideoPrimaries=DXVA2_VideoPrimaries_BT709;hdrVi.dwControlFlags=hdrFlags.value|AMCONTROL_COLORINFO_PRESENT;
+ check(source::captureMediaLayout(hdrType,layout)&&layout.color.matrix==pipeline::YuvMatrix::BT709&&layout.color.primaries==pipeline::ColorPrimaries::BT709&&!layout.color.primariesAssumed,"explicit conflicting gamut is never overwritten by HDR fallback");
+ hdrVi.dwControlFlags=0;
+ check(source::captureMediaLayout(hdrType,layout)&&!layout.color.isHdrPath()&&layout.color.transferAssumed,"untagged P010 is not proof of HDR");
+ for(auto [code,location]:{std::pair{DXVA2_VideoChromaSubsampling_MPEG2,pipeline::ChromaLocation::Left},std::pair{DXVA2_VideoChromaSubsampling_MPEG1,pipeline::ChromaLocation::Center},std::pair{DXVA2_VideoChromaSubsampling_Cosited,pipeline::ChromaLocation::TopLeft}}){
+ hdrFlags.VideoChromaSubsampling=code|DXVA2_VideoChromaSubsampling_ProgressiveChroma;hdrVi.dwControlFlags=hdrFlags.value|AMCONTROL_COLORINFO_PRESENT;
+ check(source::captureMediaLayout(hdrType,layout)&&layout.color.chromaLocation==location,"capture preserves explicit chroma siting");
+ auto otherVi=hdrVi;otherVi.dwControlFlags&=~(15u<<8);auto otherType=hdrType;otherType.pbFormat=reinterpret_cast<BYTE*>(&otherVi);
+ check(!source::equivalentCaptureTypes(hdrType,otherType),"chroma siting change cannot reuse stale capture contract");
+ }
auto multi=sink::floatWave({6,0x60f});AM_MEDIA_TYPE mt=audio;mt.subtype=KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;mt.cbFormat=sizeof(multi);mt.pbFormat=reinterpret_cast<BYTE*>(&multi);
output.Attach(new OutputPin);auto* peer=static_cast<OutputPin*>(output.Get());peer->supportsBuffering=true;
check(source::suggestCaptureAudioBuffering(output.Get(),multi.Format)==S_OK&&peer->suggested.cbBuffer==11520,"six-channel float upstream negotiation retains 10ms target");
diff --git a/tests/unit/UiContractTests.cpp b/tests/unit/UiContractTests.cpp
index 0bee2687..6a674e36 100644
--- a/tests/unit/UiContractTests.cpp
+++ b/tests/unit/UiContractTests.cpp
@@ -61,6 +61,20 @@ int wmain(int argc,wchar_t** argv){try{
ui::CapturePreferenceStore store(argv[1]);ui::CapturePreferences p{L"\\\\?\\usb#video-\u91c7\u96c6",L"1920:1080:166833:{SUBTYPE}:RGB32",L"{audio-endpoint}",-3,2};
require(store.load().videoPath.empty(),"fresh capture preference empty");require(store.save(p),"capture preference atomic save");
const auto restored=store.load();require(restored.videoPath==p.videoPath&&restored.formatKey==p.formatKey&&restored.audioPath==p.audioPath&&restored.audioMode==p.audioMode&&restored.colorOverride==p.colorOverride,"capture stable identifiers and Unicode round trip");
+ for(double fps:{0.0,29.97,30.0,40.0,50.0,60.0}){p.requestedFps=fps;require(store.save(p)&&store.load().requestedFps==fps,"device capture rate survives restart");}
+ p.requestedFps=-1;require(!store.save(p),"invalid capture rate not persisted");
+ for(int version:{1,2}){
+ std::wstring legacy=L"VEYRA_CAPTURE "+std::to_wstring(version)+L"\n\"video\" \"format\" -1 \"\" 0"+(version==2?L" 1":L"")+L"\n";
+ {std::ofstream file(std::filesystem::path(argv[1])/"capture-preferences.v1",std::ios::binary|std::ios::trunc);file.write(reinterpret_cast<const char*>(legacy.data()),std::streamsize(legacy.size()*sizeof(wchar_t)));}
+ const auto old=store.load();require(old.videoPath==L"video"&&old.requestedFps==0&&old.formatHintDismissed==(version==2),"old capture preferences migrate without changing device rate");
+ }
+ }
+ {
+ double fps=0;
+ for(auto value:{L"nan",L"inf",L"-1",L"0.5",L"1001",L"30x",L"30.0.1",L"",L"30?fps=60"})require(!source::parseCaptureFrameRate(value,fps),"invalid device rate rejected");
+ require(source::parseCaptureFrameRate(L"29.97",fps)&&fps==29.97,"fractional rate accepted");
+ require(source::captureFrameInterval(30)==333333&&source::captureFrameInterval(40)==250000,"device receives 100ns intervals");
+ require(source::captureFrameRateMatches(30,333667)&&!source::captureFrameRateMatches(30,166667)&&!source::captureFrameRateMatches(40,333333),"driver rounded or ignored rate distinguished");
}
require(ResolutionPlan::make({1448,1086},true,NrSizePolicy::Native,true).output==Extent{2880,2160},"4:3 SR preserves aspect");
{