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

Deliver local Veyra player capture and native NVENC export with reviewed short gate

Veyra Goal Agentd681541a8fca
diff --git a/AGENTS.md b/AGENTS.md
index be339584..927993c9 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,5 +1,9 @@
# Veyra 项目 Agent 执行规则
+> 2026-09-07 新用户决定:默认明确标注的实时档(4K输入可用1080内部处理),保留原生4K可选;视频导出仍原生4K。不得要求以本机原生4K NR达到60fps作为本次默认档门槛,也不得把实时档冒充native4K。最终统一软件短测为 `scripts/gates/delivery.ps1`(phase5–7本次合同的合并检查),实卡仍由用户验收。其他安全/许可规则不变。
+
+> 2026-09-06 用户授权接管修订:当前推进、五分钟短测与用户实卡验收以 `docs/ACTIVE_DELIVERY_PLAN.md` 为准,取代下文旧的严格串行施工/30分钟测试/未接设备阻塞全部交付规则。历史记录不是当前通过证明。
+
本文件对在本目录工作的所有 Agent 生效。不要只扫标题;开工前必须完整阅读:
1. `README.md`——当前状态和唯一入口;
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 3544dfc4..d9e7e947 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -149,6 +149,7 @@ veyra_add_compute_shader(veyra_shader_nv12_upload Nv12Upload)
veyra_add_graphics_shader_pair(veyra_shader_present_blit PresentBlit)
# NvofDensify: SHORT2 S10.5 raw flow -> workingExtent float2 + confidence.
veyra_add_compute_shader(veyra_shader_nvof_densify NvofDensify)
+veyra_add_compute_shader(veyra_shader_rgb_nv12 RgbToNv12)
# ---------------------------------------------------------------------------
# veyra_parity: RenoDX-equivalent codec reference (CPU golden + shaders later).
@@ -302,7 +303,7 @@ endif()
# EnhanceGraph (the real GPU chain) needs the NGX + NVOF backends; wire it
# into veyra_pipeline only when both exist so bare contract builds still work.
if(TARGET veyra_ngx AND TARGET veyra_nvof AND VEYRA_FFMPEG_ROOT)
- target_sources(veyra_pipeline PRIVATE src/pipeline/EnhanceGraph.cpp)
+ target_sources(veyra_pipeline PRIVATE src/pipeline/EnhanceGraph.cpp src/core/SceneCadenceAnalyzer.cpp)
target_include_directories(veyra_pipeline PRIVATE ${FFMPEG_INCLUDE_DIRS})
target_link_libraries(veyra_pipeline PRIVATE veyra_ngx veyra_nvof ${FFMPEG_LIBRARIES})
add_dependencies(veyra_pipeline
@@ -352,6 +353,8 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
# currently lives in veyra_gfx and moves here when the migration completes.
add_library(veyra_sinks STATIC
src/sink/WasapiAudioSink.cpp
+ src/sink/ImageExportSink.cpp
+ src/sink/NvencD3D12Encoder.cpp
)
veyra_apply_warnings(veyra_sinks)
target_compile_options(veyra_sinks PRIVATE /WX-)
@@ -360,13 +363,17 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)
target_include_directories(veyra_sinks PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_include_directories(veyra_sinks PRIVATE ${FFMPEG_INCLUDE_DIRS})
- target_link_libraries(veyra_sinks PUBLIC veyra_base ole32 mmdevapi avrt)
+ target_include_directories(veyra_sinks PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/third_party_local/nvidia/nv-codec-headers/include")
+ target_compile_definitions(veyra_sinks PRIVATE VEYRA_SHADER_DIR="${CMAKE_BINARY_DIR}/shaders")
+ add_dependencies(veyra_sinks veyra_shader_rgb_nv12)
+ target_link_libraries(veyra_sinks PUBLIC veyra_base veyra_gfx ole32 windowscodecs mmdevapi avrt)
target_link_libraries(veyra_sinks PRIVATE ${FFMPEG_LIBRARIES})
# veyra_sources: product input sources (Playbook R3/R7). MediaFileSource
# composes veyra_media; no second decode implementation exists.
add_library(veyra_sources STATIC
src/source/MediaFileSource.cpp
+ src/source/CaptureCardSource.cpp
)
veyra_apply_warnings(veyra_sources)
target_compile_options(veyra_sources PRIVATE /WX-)
@@ -375,7 +382,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)
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})
+ target_link_libraries(veyra_sources PRIVATE ${FFMPEG_LIBRARIES} strmiids ole32 oleaut32)
add_executable(veyra_source_tests
tests/integration/MediaFileSourceTests.cpp
@@ -389,6 +396,17 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_link_libraries(veyra_source_tests PRIVATE veyra_sources)
# Headless quality-core runner (Playbook R3.3): the phase5 gate's quality
+ add_library(veyra_engine STATIC src/engine/EngineController.cpp src/engine/VideoPresenter.cpp src/engine/VideoExportJob.cpp src/engine/Subtitles.cpp)
+ target_compile_features(veyra_engine PUBLIC cxx_std_20)
+ target_compile_options(veyra_engine PRIVATE /utf-8)
+ target_compile_definitions(veyra_engine PUBLIC VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}" VEYRA_SHADER_DIR="${CMAKE_BINARY_DIR}/shaders")
+ target_link_libraries(veyra_engine PUBLIC veyra_pipeline veyra_sources veyra_sinks veyra_ngx veyra_nvof)
+ add_executable(veyra WIN32 apps/veyra/main.cpp)
+ target_compile_features(veyra PRIVATE cxx_std_20)
+ target_compile_options(veyra PRIVATE /utf-8)
+ target_link_libraries(veyra PRIVATE veyra_engine comctl32 comdlg32 shell32)
+ add_dependencies(veyra veyra_shader_present_blit)
+
# matrix executes through the shared product libraries only.
add_executable(veyra_quality_probe
tools/quality_probe/main.cpp
@@ -402,7 +420,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
VEYRA_SHADER_DIR="${CMAKE_BINARY_DIR}/shaders")
target_include_directories(veyra_quality_probe PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(veyra_quality_probe PRIVATE
- veyra_pipeline veyra_sources veyra_media veyra_ngx veyra_nvof
+ veyra_pipeline veyra_sources veyra_media veyra_ngx veyra_nvof veyra_sinks
${FFMPEG_LIBRARIES} psapi dxgi)
add_dependencies(veyra_quality_probe
veyra_shader_yuv_to_rgb veyra_shader_parity_encode
diff --git a/README.md b/README.md
index 7cda0870..0c260df3 100644
--- a/README.md
+++ b/README.md
@@ -1,53 +1,36 @@
# Veyra
-Veyra V1 是一个 Windows x64 / C++20 / D3D12 的本地首发产品候选,不以“最小 MVP”作为完成标准。首版必须同时交付三个入口、4K SDR 全链路和可恢复的产品行为,三者只共享一套增强引擎:
+Windows x64 / C++20 / Win32 / D3D12 的本机视频增强软件,三个入口共用 `FrameSource -> EnhanceGraph -> FrameSink`。直接 NGX 实验 Feature 18,不依赖 ReShade 注入。
-1. **采集卡实时模式**:读取 Windows DirectShow/UVC 采集设备,支持设备真实提供的 1080p/4K SDR 30/60 fps,提供低延迟与有界后帧缓冲两种模式,执行 DLSS SR(可选)→ Feature 18 → DLSSG 2X(可选)并播放 HDMI 音频。
-2. **播放器模式**:打开最高 3840×2160 的本地 H.264/HEVC 视频,保持正确 PTS、字幕和 A/V 同步,执行同一条增强链后播放。
-3. **导出模式**:对 PNG/JPEG 图片或最高 3840×2160 的 H.264/HEVC 视频应用增强;视频可选 2X 补帧,以原生 D3D12 NVENC 输出 H.264/HEVC,并保留或明确转换音频与基础元数据。
+**运行:双击 `Veyra.cmd`。** 使用说明见 [docs/USER_GUIDE.md](docs/USER_GUIDE.md),最新实测与未完成项见 [docs/DELIVERY_STATUS.md](docs/DELIVERY_STATUS.md)。不再用旧 Phase 数量或百分比表示产品交付。
-这里的“DLSS 5”指项目根目录中用户提供的实验性 `nvngx_dlssnr.dll` 所暴露的 Feature 18。NVIDIA 已于 2026-09 正式面向游戏发布 DLSS 5,但截至本次重基线,公开 Developer 页面和公开 Streamline SDK 尚未提供可供本项目直接替换的通用 DLSS 5 开发接口。用户决定继续使用当前实验 runtime 做本机研发;这不构成 NVIDIA 授权,也不允许 Veyra 将该 DLL 打包、上传或分发。
+## 当前交付合同
-## 当前真实状态
+用户授权接管全部实现,自动联合测试不超过五分钟;当前采集卡没接入,由用户亲自验收。用户随后明确接受默认实时档、保留原生 4K 可选。
-- 2026-09-06 对抗式复核后的 Launch V1 交付进度约为 **40%(误差约 5%)**。Phase 数量不能当百分比;Phase 7 承担 UI、采集和两类导出,工作量远大于早期 harness。
-- Phase 0–4 的 D3D12、Feature 18、颜色 parity、FFmpeg 解码与 DLSS SR harness 有可复现实测证据,继续有效。
-- 历史 Phase 5 的组件证据保留:Frame/Reset 契约、scene/cadence、NVOF 合成位移与 endurance probe 已运行;但原 gate 把 manifest 当作 depth 完成、把第二次 1080p endurance 放在 4K 检查位置,而且 `src/core/EnhanceGraph.cpp` 只计数,真实 GPU 链仍由 harness 编排。因此 Phase 5 的产品级 `passed` 已撤销,必须重开修复。
-- Phase 6 已有未提交的实验资产:真实 DLSSG capability/Create/Evaluate、59/59 非重复/非 blend 中间帧、NVOF、WASAPI 和 PresentSink;但当前播放器 probe 的 A/V drift P95 约 2.8 秒(门槛 50 ms),L2/GBV 有大量 descriptor-uninitialized 错误,Phase 6 gate/Reviewer/checkpoint 均未通过。
-- 还没有可发布的共享 EngineController、播放器 UI、字幕、采集卡输入、DAV2 depth provider、图片导出、D3D12 NVENC 视频导出、设置/恢复/日志导出或安装交付闭环。
-- 当前工作树包含一组未提交的 Phase 6 改动。新 Agent 必须先审计和保存它们,禁止 reset、checkout 或从旧 checkpoint 覆盖。
-- 旧路线中“采集卡、Depth Anything 和导出不属于 V1”的决定已于 2026-09-03 被用户撤销;不要再按旧边界施工。
-- 旧路线中“只做 1080p 薄闭环、离线导出允许 raw pipe”的决定也已于 2026-09-03 被用户撤销;首发 gate 必须覆盖 4K SDR、原生硬件编码和产品级恢复/诊断。
-- 当前工作从“Phase 5 产品级修复”继续。唯一施工顺序见 `VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md` 的“2026-09-06 接管恢复计划”和 `loop/BACKLOG.md`;Phase 7 联合 gate 全通过才算功能 release candidate。
+- 播放/采集默认 **Live 1080**:4K 解码、1080 内部 NR/FG、按显示窗口缩放。状态显示真实输入/处理尺寸,不称原生 4K NR。
+- 原生 4K 与 SR 4K 可选;本机 RTX 5070 实测原生 4K NR 约 22–23ms/帧,无法承诺 4K60 实时。实时档的短测另行记录。
+- 视频导出不采用实时档降分辨率:4K 输入原生 4K NR,可选 FG2X,D3D12 NVENC H.264/HEVC MP4,兼容音轨保留;PNG/JPEG 图片增强保存。
+- DirectShow 实卡功能已接入,硬件测试状态始终为 `awaiting_user_capture_test`,不能冒充测试通过。
+- Depth provider 未实现,明确 Motion Only;HDR / 3X4X / AV1ProRes / 私有采集SDK不在本次承诺。
+- 仅本机研发交付,专有 DLL 分发未授权:`distribution_blocked`,不制作安装包或上传二进制。
-## 开工顺序
+## 文档唯一入口
-必须依次完整阅读:
+1. `AGENTS.md`:安全、许可、实现纪律。
+2. `docs/ACTIVE_DELIVERY_PLAN.md`:当前 F0–F6 推进与用户授权的短测合同,覆盖旧长测/严格串行施工规则。
+3. `VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md` / `VEYRA_PRODUCT_SPEC_V1.md`:技术参数与原始规格;旧状态文字仅作历史,最新状态看 DELIVERY_STATUS/STATE。
+4. `docs/COMPETITOR_AUDIT_2026-09-03.md`:竞品与许可事实。
+5. `docs/WORKLOG.md`、`loop/STATE.json`、`loop/EVIDENCE.md`、`loop/JOURNAL.md`:实际证据与恢复点。
-1. `AGENTS.md`
-2. `VEYRA_PRODUCT_SPEC_V1.md`
-3. `VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md`
-4. `docs/COMPETITOR_AUDIT_2026-09-03.md`
-5. `docs/WORKLOG.md`
-6. Goal 模式再读 `loop/LOOP_ENGINE.md`、`loop/STATE.json`、`loop/BACKLOG.md`、`loop/INBOX.md`
-
-然后运行:
+## 构建与短测
```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\build.ps1 -Root . -Preset x64-release
powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate preflight
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\gates\delivery.ps1 -Root .
```
-## 二进制边界
-
-- `nvngx_dlssnr.dll`:用户提供、NVIDIA 签名的本地实验 runtime。只能复制到已忽略的 `runtime_local/nvidia/`,不得修改、提交、上传或随安装包分发。
-- `renodx-dlss5-1.addon64`:未签名的 ReShade/RenoDX add-on,不是配置文件。只用于隔离对照;Veyra 主程序不得加载、注入、链接或分发它。
-- Veyra 直接调用 NGX,不以 Magpie/ReShade 为运行依赖。
-
-Magpie 已证明窗口/视频路径能调用这些能力,但没有替 Veyra 验证参数、资源状态、颜色、时序、延迟或画质。每一个“更好”结论仍需同源 A/B 证据。
-
-## 当前接管原则
+应用:`out/build/x64-release/veyra.exe`。依赖现有 `runtime_local/nvidia`、`third_party_local/nvidia` 与本机 FFmpeg;不把 SDK/runtime 提交 Git。NGX DLL 使用固定身份和绝对路径。Video Codec API 头文件来源/许可证见 `THIRD_PARTY_NOTICES.md`。
-- 不重写已验证的 NGX/NVOF/FG backend;先把它们从 `tools/player_probe/main.cpp` 迁入真正共享的库。
-- 不先做漂亮 UI。先让共享 engine 在 1080p 与 native 4K 上通过正确性、GBV、GPU timing、A/V drift 和 teardown 门槛。
-- 不接受“probe 能跑”等于“产品完成”。Capture、Player、Export 必须由同一可执行程序调用同一 graph。
-- 泄露 runtime 只能是外置、可关闭、固定 hash 的实验依赖;功能完成但分发权未解决时状态只能是 `distribution_blocked`。
+历史 Phase 0–4 仅证明当时基础 harness。旧 Phase 5 的错误输入、假指标和未接 Guidance 结论已撤回并修复;本次独立 review 前不宣称新的阶段放行。不得再跑旧 30 分钟 gate 作为本次默认任务,也不得把短测写成耐久证明。
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
new file mode 100644
index 00000000..5e966f66
--- /dev/null
+++ b/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Local development dependencies
+
+NVIDIA DLSS/Optical Flow SDKs and experimental DLSSNR runtime: external local assets, not committed or redistributed. Existing SDK agreements remain applicable. ReShade/RenoDX addon is never loaded by the product.
+
+## NVENC API declarations
+
+Source: https://github.com/FFmpeg/nv-codec-headers ; checkout `eddcea9e27f6b772057c9b3f87de2cc1737faffc` (SDK 13.1.15 declarations), stored only under ignored `third_party_local/nvidia/nv-codec-headers`.
+
+The nvEncodeAPI.h header itself has NVIDIA's permissive MIT-style notice (Copyright 2010–2026 NVIDIA Corporation). Its full notice is retained unmodified in that header. This permits using the declarations without retrieving the full developer-portal sample package; it does not grant rights to distribute NVIDIA driver/runtime binaries. Veyra uses the system NVENC library, never copies it into a package. Implementation is independently authored against these declarations; no competitor/sample implementation copied.
+
+FFmpeg build: external `C:/veyra-deps/installed/x64-windows`; public distribution requires review of actual configuration and linked components. No license-complete installer has been produced.
diff --git a/VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md b/VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md
index 610d80c8..b4512c22 100644
--- a/VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md
+++ b/VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md
@@ -1,5 +1,7 @@
# Veyra Launch V1 施工手册
+> 2026-09-06 用户授权接管修订:当前推进、五分钟短测与用户实卡验收以 `docs/ACTIVE_DELIVERY_PLAN.md` 为准,取代下文旧的严格串行施工/30分钟测试/未接设备阻塞全部交付规则。历史记录不是当前通过证明。
+
版本:1.2(强 Agent 接管恢复版)
日期:2026-09-06
diff --git a/VEYRA_PRODUCT_SPEC_V1.md b/VEYRA_PRODUCT_SPEC_V1.md
index 6a55f630..9e603864 100644
--- a/VEYRA_PRODUCT_SPEC_V1.md
+++ b/VEYRA_PRODUCT_SPEC_V1.md
@@ -1,5 +1,7 @@
# Veyra V1 产品与技术规格
+> 2026-09-06 用户授权接管修订:当前推进、五分钟短测与用户实卡验收以 `docs/ACTIVE_DELIVERY_PLAN.md` 为准,取代下文旧的严格串行施工/30分钟测试/未接设备阻塞全部交付规则。历史记录不是当前通过证明。
+
版本:Launch V1.3(2026-09-06 接管重基线)
日期:2026-09-06
diff --git a/Veyra.cmd b/Veyra.cmd
new file mode 100644
index 00000000..93d4bd6c
--- /dev/null
+++ b/Veyra.cmd
@@ -0,0 +1,2 @@
+@echo off
+powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "%~dp0scripts\start-veyra.ps1"
diff --git a/apps/veyra/main.cpp b/apps/veyra/main.cpp
new file mode 100644
index 00000000..ddd583a0
--- /dev/null
+++ b/apps/veyra/main.cpp
@@ -0,0 +1,88 @@
+#include <windows.h>
+#include <objbase.h>
+#include <commctrl.h>
+#include <commdlg.h>
+#include <shellapi.h>
+#include <filesystem>
+#include <format>
+#include <string>
+#include <chrono>
+#include "veyra/engine/EngineController.h"
+#include "veyra/engine/VideoExportJob.h"
+#include "veyra/source/CaptureCardSource.h"
+#include "veyra/Log.h"
+#include "veyra/engine/Subtitles.h"
+namespace {
+enum {Open=101,Play,Stop,Save,Nr,Sr,Fg,Seek,Info,Capture,Export,Realtime,Recent};
+veyra::engine::EngineController engine;
+HWND mainWindow=nullptr,video=nullptr,statusBar=nullptr,seekBar=nullptr;
+std::wstring currentFile,autoInput;bool paused=false,dragging=false;int smokeSeconds=0;ULONGLONG startTick=0;int resultCode=0;
+std::wstring exportOutput;unsigned exportFrames=0;unsigned cancelAfterMs=0;bool exportHevc=false;veyra::engine::PlayerOptions initialOptions;
+std::vector<veyra::engine::SubtitleCue> subtitles;HWND subtitleLabel=nullptr;
+HFONT font=nullptr;bool smokeControls=false;int smokeStep=0;std::wstring smokeSave;
+HWND captureWindow=nullptr,captureDevice=nullptr,captureFormat=nullptr,captureAudio=nullptr;
+std::vector<veyra::source::CaptureFormat> captureFormats;
+void openFile(const std::wstring&);
+void refreshFormats(){SendMessageW(captureFormat,CB_RESETCONTENT,0,0);int i=int(SendMessageW(captureDevice,CB_GETCURSEL,0,0));captureFormats=i>=0?veyra::source::CaptureCardSource::formats(i):std::vector<veyra::source::CaptureFormat>{};for(auto& f:captureFormats)SendMessageW(captureFormat,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(f.label.c_str()));if(!captureFormats.empty())SendMessageW(captureFormat,CB_SETCURSEL,0,0);}
+LRESULT CALLBACK captureProc(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp){if(msg==WM_CREATE){auto add=[&](const wchar_t* cls,const wchar_t* text,int id,DWORD style,int y){return CreateWindowExW(0,cls,text,WS_CHILD|WS_VISIBLE|style,12,y,510,200,hwnd,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);};
+captureDevice=add(L"COMBOBOX",L"",1,CBS_DROPDOWNLIST|WS_VSCROLL,15);captureFormat=add(L"COMBOBOX",L"",2,CBS_DROPDOWNLIST|WS_VSCROLL,55);captureAudio=add(L"COMBOBOX",L"",3,CBS_DROPDOWNLIST|WS_VSCROLL,95);
+auto devices=veyra::source::CaptureCardSource::devices();for(auto& name:devices)SendMessageW(captureDevice,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name.c_str()));if(!devices.empty())SendMessageW(captureDevice,CB_SETCURSEL,0,0);else SendMessageW(captureDevice,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(L"No capture device found — connect card and reopen"));
+SendMessageW(captureAudio,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(L"No audio (select HDMI input below to monitor audio)"));for(auto& name:veyra::source::CaptureCardSource::devices(true))SendMessageW(captureAudio,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name.c_str()));SendMessageW(captureAudio,CB_SETCURSEL,0,0);refreshFormats();
+CreateWindowExW(0,L"STATIC",L"Device / actual format / HDMI audio. NR, SR and FG use the main window settings. Hardware acceptance is pending your test. FG needs one arriving source frame of lookahead.",WS_CHILD|WS_VISIBLE,12,140,510,64,hwnd,nullptr,GetModuleHandleW(nullptr),nullptr);
+CreateWindowExW(0,L"BUTTON",L"Start capture",WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON,12,211,180,32,hwnd,reinterpret_cast<HMENU>(4),GetModuleHandleW(nullptr),nullptr);return 0;}
+if(msg==WM_COMMAND){if(LOWORD(wp)==1&&HIWORD(wp)==CBN_SELCHANGE)refreshFormats();if(LOWORD(wp)==4){int d=int(SendMessageW(captureDevice,CB_GETCURSEL,0,0)),f=int(SendMessageW(captureFormat,CB_GETCURSEL,0,0)),a=int(SendMessageW(captureAudio,CB_GETCURSEL,0,0))-1;if(d>=0&&f>=0&&size_t(f)<captureFormats.size()){openFile(std::format(L"capture:{}:{}:{}",d,captureFormats[f].index,a));DestroyWindow(hwnd);}else MessageBoxW(hwnd,L"No supported 1080p/4K 30/60 format selected.",L"Capture",MB_OK);}return 0;}if(msg==WM_DESTROY){captureWindow=nullptr;return 0;}return DefWindowProcW(hwnd,msg,wp,lp);}
+void showCapture(){if(captureWindow){SetForegroundWindow(captureWindow);return;}WNDCLASSW wc{};wc.lpfnWndProc=captureProc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraCaptureSetup";wc.hbrBackground=reinterpret_cast<HBRUSH>(COLOR_BTNFACE+1);wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&wc);captureWindow=CreateWindowExW(WS_EX_TOOLWINDOW,wc.lpszClassName,L"Capture card setup",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,550,295,mainWindow,nullptr,wc.hInstance,nullptr);}
+veyra::engine::PlayerOptions options(){return {IsDlgButtonChecked(mainWindow,Nr)==BST_CHECKED,IsDlgButtonChecked(mainWindow,Sr)==BST_CHECKED,IsDlgButtonChecked(mainWindow,Fg)==BST_CHECKED,IsDlgButtonChecked(mainWindow,Realtime)==BST_CHECKED};}
+std::wstring fileDialog(bool save){wchar_t name[32768]{};OPENFILENAMEW ofn{};ofn.lStructSize=sizeof(ofn);ofn.hwndOwner=mainWindow;ofn.lpstrFile=name;ofn.nMaxFile=32768;
+ofn.lpstrFilter=save?L"PNG image\0*.png\0JPEG image\0*.jpg\0":L"Video / image\0*.mp4;*.mkv;*.mov;*.avi;*.ts;*.png;*.jpg;*.jpeg\0All files\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:L"";}
+void openFile(const std::wstring& file){if(file.empty())return;currentFile=file;subtitles=veyra::engine::loadSrt(std::filesystem::path(file).replace_extension(L".srt").wstring());paused=false;SetWindowTextW(GetDlgItem(mainWindow,Play),L"Pause");engine.open(video,file,options());SetWindowTextW(mainWindow,(L"Veyra — "+std::filesystem::path(file).filename().wstring()).c_str());WritePrivateProfileStringW(L"Player",L"Recent",file.c_str(),(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/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|style,x,y,w,h,mainWindow,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(hwnd,WM_SETFONT,reinterpret_cast<WPARAM>(font),TRUE);return hwnd;}
+void layout(){RECT r{};GetClientRect(mainWindow,&r);MoveWindow(video,8,52,std::max(1L,r.right-16),std::max(1L,r.bottom-160),TRUE);if(subtitleLabel)MoveWindow(subtitleLabel,8,std::max(56L,r.bottom-104),std::max(1L,r.right-16),32,TRUE);MoveWindow(seekBar,8,std::max(56L,r.bottom-71),std::max(1L,r.right-16),24,TRUE);MoveWindow(statusBar,12,std::max(80L,r.bottom-42),std::max(1L,r.right-24),36,TRUE);}
+LRESULT CALLBACK proc(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp){switch(msg){
+case WM_CREATE:{mainWindow=hwnd;font=CreateFontW(-16,0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Segoe UI");
+control(L"BUTTON",L"Open video / image",Open,BS_PUSHBUTTON,10,10,150,30);control(L"BUTTON",L"Play",Play,BS_PUSHBUTTON,168,10,68,30);control(L"BUTTON",L"Stop",Stop,BS_PUSHBUTTON,244,10,62,30);control(L"BUTTON",L"Save image",Save,BS_PUSHBUTTON,314,10,95,30);
+control(L"BUTTON",L"DLSS NR",Nr,BS_AUTOCHECKBOX,425,10,85,30);control(L"BUTTON",L"SR 4K",Sr,BS_AUTOCHECKBOX,518,10,78,30);control(L"BUTTON",L"FG 2X",Fg,BS_AUTOCHECKBOX,600,10,78,30);CheckDlgButton(hwnd,Nr,BST_CHECKED);
+control(L"BUTTON",L"Capture",Capture,BS_PUSHBUTTON,690,10,75,30);control(L"BUTTON",L"Export video",Export,BS_PUSHBUTTON,773,10,103,30);control(L"BUTTON",L"Logs",Info,BS_PUSHBUTTON,884,10,60,30);
+control(L"BUTTON",L"Live 1080",Realtime,BS_AUTOCHECKBOX,952,10,112,30);
+control(L"BUTTON",L"Recent",Recent,BS_PUSHBUTTON,1072,10,75,30);
+subtitleLabel=control(L"STATIC",L"",0,SS_CENTER,8,640,1100,32);
+video=control(L"STATIC",L"",0,SS_BLACKRECT,8,52,1100,610);seekBar=control(TRACKBAR_CLASSW,L"",Seek,TBS_HORZ,8,675,1100,24);SendMessageW(seekBar,TBM_SETRANGE,TRUE,MAKELPARAM(0,10000));statusBar=control(L"STATIC",L"Open a local video or PNG/JPEG. Experimental local runtime; not an official NVIDIA product.",0,SS_LEFT,12,708,1080,36);
+DragAcceptFiles(hwnd,TRUE);SetTimer(hwnd,1,200,nullptr);layout();return 0;}
+case WM_SIZE:layout();return 0;
+case WM_DROPFILES:{wchar_t file[32768]{};DragQueryFileW(reinterpret_cast<HDROP>(wp),0,file,32768);DragFinish(reinterpret_cast<HDROP>(wp));openFile(file);return 0;}
+case WM_COMMAND:switch(LOWORD(wp)){
+case Open:openFile(fileDialog(false));break;
+case Recent:{wchar_t recent[32768]{};GetPrivateProfileStringW(L"Player",L"Recent",L"",recent,32768,(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/veyra.ini").wstring().c_str());openFile(recent);break;}
+case Play:{auto s=engine.snapshot();if(!currentFile.empty()&&(!s.running||(s.duration>0&&s.position>=s.duration-0.1))){openFile(currentFile);break;}paused=!paused;engine.pause(paused);SetWindowTextW(GetDlgItem(hwnd,Play),paused?L"Play":L"Pause");break;}
+case Stop:engine.stop();break;
+case Save:{auto name=fileDialog(true);if(!name.empty())engine.saveFrame(name);break;}
+case Realtime:case Nr:case Sr:case Fg:{auto opts=options();auto ini=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/veyra.ini").wstring();WritePrivateProfileStringW(L"Player",L"NR",opts.nr?L"1":L"0",ini.c_str());WritePrivateProfileStringW(L"Player",L"SR",opts.sr?L"1":L"0",ini.c_str());WritePrivateProfileStringW(L"Player",L"FG",opts.fg?L"1":L"0",ini.c_str());WritePrivateProfileStringW(L"Player",L"Realtime",opts.realtime?L"1":L"0",ini.c_str());if(!currentFile.empty())openFile(currentFile);break;}
+case Capture:showCapture();break;
+case Export:{if(currentFile.empty())break;wchar_t name[32768]{};OPENFILENAMEW d{};d.lStructSize=sizeof(d);d.hwndOwner=hwnd;d.lpstrFile=name;d.nMaxFile=32768;d.lpstrFilter=L"MP4 video\0*.mp4\0";d.lpstrDefExt=L"mp4";d.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST|OFN_OVERWRITEPROMPT;if(GetSaveFileNameW(&d)){int codec=MessageBoxW(hwnd,L"Use HEVC? Yes = HEVC, No = H.264. Current NR / SR / FG options apply. Existing files are never overwritten.",L"Video export",MB_YESNOCANCEL);if(codec!=IDCANCEL)engine.startExport(currentFile,name,options(),codec==IDYES);}break;}
+case Info:ShellExecuteW(hwnd,L"open",(std::filesystem::path(VEYRA_PROJECT_ROOT)/"logs").wstring().c_str(),nullptr,nullptr,SW_SHOW);break;
+}return 0;
+case WM_HSCROLL:if(reinterpret_cast<HWND>(lp)==seekBar){dragging=LOWORD(wp)==TB_THUMBTRACK;auto s=engine.snapshot();if(!dragging&&s.duration>0)engine.seek(s.duration*SendMessageW(seekBar,TBM_GETPOS,0,0)/10000.0);}return 0;
+case WM_KEYDOWN:if(wp==VK_SPACE){SendMessageW(hwnd,WM_COMMAND,Play,0);return 0;}if(wp==VK_F11){static WINDOWPLACEMENT old{sizeof(old)};static bool full=false;full=!full;if(full){GetWindowPlacement(hwnd,&old);SetWindowLongPtrW(hwnd,GWL_STYLE,WS_POPUP|WS_VISIBLE);MONITORINFO mi{sizeof(mi)};GetMonitorInfoW(MonitorFromWindow(hwnd,MONITOR_DEFAULTTONEAREST),&mi);SetWindowPos(hwnd,HWND_TOP,mi.rcMonitor.left,mi.rcMonitor.top,mi.rcMonitor.right-mi.rcMonitor.left,mi.rcMonitor.bottom-mi.rcMonitor.top,SWP_FRAMECHANGED);}else{SetWindowLongPtrW(hwnd,GWL_STYLE,WS_OVERLAPPEDWINDOW|WS_VISIBLE);SetWindowPlacement(hwnd,&old);SetWindowPos(hwnd,nullptr,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);}return 0;}break;
+case WM_TIMER:{if(!autoInput.empty()){auto file=autoInput;autoInput.clear();openFile(file);startTick=GetTickCount64();}if(smokeControls&&startTick){const auto elapsed=GetTickCount64()-startTick;
+if(smokeStep==0&&elapsed>2200){engine.pause(true);smokeStep=1;}
+if(smokeStep==1&&elapsed>2600){engine.seek(1.0);smokeStep=2;}
+if(smokeStep==2&&elapsed>3200){engine.pause(false);smokeStep=3;}
+if(smokeStep==3&&elapsed>4100&&!smokeSave.empty()){engine.saveFrame(smokeSave);smokeStep=4;}
+}auto s=engine.snapshot();SetWindowTextW(subtitleLabel,veyra::engine::subtitleAt(subtitles,s.position).c_str());auto text=std::format(L"{}\r\n{:.1f} / {:.1f}s {:.1f} processed fps lateness {:+.1f}ms source {} / generated {}",s.status,s.position,s.duration,s.fps,s.lateMs,s.frames,s.generated);SetWindowTextW(statusBar,text.c_str());if(!dragging&&s.duration>0)SendMessageW(seekBar,TBM_SETPOS,TRUE,LPARAM(s.position/s.duration*10000));
+if(smokeSeconds>0&&startTick&&GetTickCount64()-startTick>ULONGLONG(smokeSeconds)*1000){veyra::log::info("app",std::format("smoke frames={} generated={} failed={} latenessMs={:.2f} absLatenessP95Ms={:.2f} controlsStep={}",s.frames,s.generated,s.failed,s.lateMs,s.lateP95Ms,smokeStep));resultCode=s.frames>0&&!s.failed?0:1;PostMessageW(hwnd,WM_CLOSE,0,0);}return 0;}
+case WM_CLOSE:KillTimer(hwnd,1);engine.stop();DestroyWindow(hwnd);return 0;
+case WM_DESTROY:DeleteObject(font);PostQuitMessage(resultCode);return 0;
+}return DefWindowProcW(hwnd,msg,wp,lp);}
+}
+int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,LPWSTR,int show){
+SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);INITCOMMONCONTROLSEX controls{sizeof(controls),ICC_BAR_CLASSES};InitCommonControlsEx(&controls);
+CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED);
+std::filesystem::create_directories(std::filesystem::path(VEYRA_PROJECT_ROOT)/"logs");veyra::Logger::instance().openFile((std::filesystem::path(VEYRA_PROJECT_ROOT)/"logs/veyra-app.log").wstring());
+auto ini=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/veyra.ini").wstring();initialOptions.nr=GetPrivateProfileIntW(L"Player",L"NR",1,ini.c_str())!=0;initialOptions.sr=GetPrivateProfileIntW(L"Player",L"SR",0,ini.c_str())!=0;initialOptions.fg=GetPrivateProfileIntW(L"Player",L"FG",0,ini.c_str())!=0;initialOptions.realtime=GetPrivateProfileIntW(L"Player",L"Realtime",1,ini.c_str())!=0;
+int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);for(int i=1;i<argc;++i){const std::wstring arg=argv[i];if(arg==L"--smoke-seconds"&&i+1<argc)smokeSeconds=std::clamp(_wtoi(argv[++i]),1,240);else if(arg==L"--export-out"&&i+1<argc)exportOutput=argv[++i];else if(arg==L"--max-frames"&&i+1<argc)exportFrames=std::max(1,_wtoi(argv[++i]));else if(arg==L"--cancel-after-ms"&&i+1<argc)cancelAfterMs=std::clamp(_wtoi(argv[++i]),1,240000);else if(arg==L"--hevc")exportHevc=true;else if(arg==L"--smoke-controls")smokeControls=true;else if(arg==L"--smoke-save"&&i+1<argc)smokeSave=argv[++i];else if(arg==L"--native")initialOptions.realtime=false;else if(arg==L"--realtime")initialOptions.realtime=true;else if(arg==L"--fg")initialOptions.fg=true;else if(arg==L"--sr")initialOptions.sr=true;else if(arg==L"--no-nr")initialOptions.nr=false;else autoInput=arg;}LocalFree(argv);
+if(!exportOutput.empty()){std::atomic<bool> cancel{false},finished{false};std::thread cancelTimer;if(cancelAfterMs)cancelTimer=std::thread([&]{const auto start=GetTickCount64();while(!finished&&GetTickCount64()-start<cancelAfterMs)std::this_thread::sleep_for(std::chrono::milliseconds(5));if(!finished)cancel=true;});bool ok=veyra::engine::exportVideo(autoInput,exportOutput,initialOptions,exportHevc,cancel,[](double,const std::wstring& s){OutputDebugStringW(s.c_str());},exportFrames);finished=true;if(cancelTimer.joinable())cancelTimer.join();veyra::log::info("app",std::format("export result={}",ok));CoUninitialize();return ok?0:cancel?3:1;}
+WNDCLASSEXW wc{sizeof(wc)};wc.hInstance=instance;wc.lpfnWndProc=proc;wc.lpszClassName=L"VeyraApp";wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);wc.hbrBackground=reinterpret_cast<HBRUSH>(COLOR_BTNFACE+1);RegisterClassExW(&wc);
+auto hwnd=CreateWindowExW(0,wc.lpszClassName,L"Veyra — Local Experimental",WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,1200,800,nullptr,nullptr,instance,nullptr);if(!hwnd)return 1;CheckDlgButton(hwnd,Nr,initialOptions.nr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Sr,initialOptions.sr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Fg,initialOptions.fg?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Realtime,initialOptions.realtime?BST_CHECKED:BST_UNCHECKED);ShowWindow(hwnd,show);MSG msg{};while(GetMessageW(&msg,nullptr,0,0)>0){TranslateMessage(&msg);DispatchMessageW(&msg);}CoUninitialize();return int(msg.wParam);
+}
diff --git a/docs/ACTIVE_DELIVERY_PLAN.md b/docs/ACTIVE_DELIVERY_PLAN.md
new file mode 100644
index 00000000..2d774f97
--- /dev/null
+++ b/docs/ACTIVE_DELIVERY_PLAN.md
@@ -0,0 +1,60 @@
+# 2026-09-06 用户直接接管执行计划(当前唯一推进顺序)
+
+授权原话:直接接手,先整理文档并制定详细计划,完成软件;测试最多五分钟;当前采集卡未接入,由用户亲自实卡测试;开启目标模式。
+
+本修订替代旧 R0–R12 的严格串行施工顺序、30 分钟耐久和无人值守实卡验收要求;不撤销代码正确性、诚实证据、固定二进制身份或许可证要求。仅本次用户授权重建控制面 hash,此后恢复锁定。旧长测保留为历史,不重跑,也不冒充当前通过。
+
+## 交付与验收
+
+2026-09-07 补充用户决定:实测原生 4K NR GPU 约 22–23ms/帧、颜色还原约 0.28ms,用户明确回答“接受,默认实时档,原生 4K 可选”。因此播放器/采集默认采用明确标注的 1080 working 实时档(仍解码 4K 输入,最终显示缩放);保留原生 4K 及 SR 4K 可选。视频导出保留原生 4K。禁止把实时档的 60fps 冒充原生 4K NR 60fps。本条与交付文档同步属于新的用户授权修订,控制面记录新 hash 后再次锁定。
+
+- 交付一个本机可运行 Win32 程序:播放器、DirectShow 采集卡入口、图片/视频增强导出。三入口共用产品 EnhanceGraph,不能用三份 probe 拼壳。
+- 保留 Windows x64/C++20/D3D12、4K SDR、实验 NR、可选 SR 与 FG 2X、NVOF 和明确的质量降级。Depth 是可选 provider,不可把常量深度称为 AI 深度,也不可把 Auto fallback 称为已实现 provider。
+- 自动测试每次完整调用上限 300 秒(超时杀本次子进程并报告失败);优先 10–60 秒窄测。最终联合视频测试也在 300 秒内;不以缩短测试声称证明长期稳定。不得循环重跑长测消耗用户时间。
+- 采集功能要实现枚举、格式选择、启动/停止、音视频接入和断连处理;硬件未连接标 `awaiting_user_capture_test`,不阻止交付给用户测试,但绝不写实卡通过。
+- 本机交付与公开发布分开。未解决分发许可仍 `distribution_blocked`;不做安装包、不上传 runtime。目标完成指约定本机软件交付,不代表授权公开首发。
+- 阶段状态表示验收,不禁止开发有独立价值的下一产品模块。允许 UI/controller 与底层缺陷迭代集成;不允许未通过底层被标成上层成功。新上下文只读 Reviewer 检查最终差异及短测,无需再重跑小时级耐久。
+
+## 已核对的真实起点
+
+HEAD 6f0ebaa;工作树只有用户测试片删除,保留。已有共享 `src/pipeline/EnhanceGraph.cpp`,不再说 GPU 链仅在 probe。旧 `src/core/EnhanceGraph.cpp` 是单元测试用计数实现,必须移除产品证明中的歧义。尚无可用产品 UI/capture/export。
+
+当前优先缺陷:软件 NV12 upload 读取未初始化描述符、shader 把字节位型当浮点、chroma 宽度错误;NR 仍绑 Zero motion,NVOF 放在 NR 后;reset 不拒绝旧 NVOF;quality JSON 的 native extent/CPU 当 GPU 时间/硬编码 queue 和 fence/析构后 VRAM 都不能证明真实指标。旧结论“串行 runner 是唯一瓶颈”未经正确计时证明,撤回。
+
+## 执行清单与顺序
+
+### F0 文档与证据修复
+
+更新 README/规则/Goal/State/Backlog,保留历史日志原文并追加纠错;建立本计划为唯一顺序,重建控制 hash,preflight。将无观测值改成 null/未实现,不能默认为 0。不把历史 30 分钟计数作为当前正确画面证据。
+
+### F1 首先修真实画面输入
+
+修 `src/pipeline/EnhanceGraph.cpp` 的 software NV12 ingestion:使用明确 rowPitch/plane footprint CopyTextureRegion 或完整有效的 raw SRV;每平面正确尺寸,YUV metadata 显式传递,upload buffer 用 fence 管所有权。修 `shaders/Nv12Upload.hlsl` 的字节对齐/归一化(若退出主路径仍不能留坏备用)。去除未经证明的“注入/驱动”归因。短视频 no-feature/NR 与 GBV 窄测,诊断抓帧验证非黑且随输入变化;诊断 readback 不进入正常路径。
+
+### F2 共享质量与生命周期
+
+post-SR 原始 working color -> NVOF A/B -> densify/confidence -> NR parity encode/evaluate/decode -> FG -> sink。canonical flow 为 current→previous working pixels,FG 单独适配;first/reset 禁止旧 flow,scene/seek/resize/source-switch 全历史 reset。复用 NvOfSession 和既有已证明 raw/32 契约。统一资源池/command slots,先消灭错误再优化同步。用 query heap+queue frequency 得到真实 GPU 时间,CPU enqueue 时间单列。临时缺失 depth 显示 Motion Only,provider 资产许可/shape核验后再接可选推理,不写假成功。
+
+### F3 产品播放器先落地
+
+新增共享 engine/controller(不把 main.cpp 复制一份),worker 拥有 D3D12/NGX;UI 通过有界命令队列 open/pause/seek/stop/resize/toggle。Win32 窗口有打开文件、播放/暂停、进度拖动、NR/SR/FG/quality、全屏、状态/错误和最近文件;字幕/OSD 在 FG 后。复用 MediaFileSource、PresentSink、WasapiAudioSink。audio clock 做主时钟,不截断 lateness 来伪同步;性能不足明确显示,不隐性丢播放器源帧。打开 native4K和1080p→4K视频做短测。
+
+### F4 图片与视频导出
+
+图片用 Windows WIC 解码/方向/sRGB,接同一 graph;WIC PNG/JPEG 写临时文件、解码回验后原子改名,默认不覆盖。视频用系统 nvEncodeAPI64.dll 的 D3D12 NVENC,input texture/fence 与输出 bitstream slot 有界;FFmpeg 仅封装码流与保留/转换音频。需要 Video Codec SDK 的官方 header,先检查本地依赖,再核对官方可取的 SDK/header 与许可证;禁止从未知 DLL 猜 ABI。没有 SDK 只阻对应项,不耽误 UI/图片/capture。不得把 CPU raw pipe当合格视频导出。进度/取消/错误/partial恢复实际接通。
+
+### F5 采集入口
+
+使用 FFmpeg avdevice dshow(若依赖未构建 avdevice,则 Windows DirectShow 接入),真实 friendly-name/media-type/音频枚举;选择设备实际提供的1080p/2160p30/60。latest mailbox容量1,丢帧触发统一reset;无FG为0额外lookahead,FG为A/B一帧,质量模式最多A/B/C;不得宣称采集缓冲提供免费未来帧。无设备明确显示“未发现采集卡”,不造虚拟PASS。用户实卡清单覆盖选择格式、预览/音频、NR/FG、停止重开、断连、延迟与画质。
+
+### F6 收尾与交付
+
+首次依赖检查/设置/运行日志导出(排除媒体SDK和runtime);短测覆盖视频播放与seek、开关、4K输入输出、PNG/JPEG、H264/HEVC导出解码回验。独立只读复核,不做并行写入。记录 exe/runtime/input/config身份、真实调用/退出码、输出位置、已知限制。交付可执行文件路径与最短操作说明,采集硬件验收单独留给用户。阶段门禁仍诚实报告未过项,不凭 UI 出现宣布完成。
+
+## 依赖位置与构建
+
+- runtime 固定 `runtime_local/nvidia/nvngx_dlssnr.dll`,SHA256 `E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E`;启动绝对路径/身份检查,不联网换版。ReShade addon永不加载。
+- NGX SDK:`third_party_local/nvidia/DLSS_SDK_310.7.0`;NVOF:`third_party_local/nvidia/Optical_Flow_SDK_5.0.7`;FFmpeg:`C:/veyra-deps/installed/x64-windows`(用 CMake cache 核对实际路径)。
+- 构建:`powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\build.ps1 -Root . -Preset x64-release`。
+- gate:`powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate preflight`;phase gate重写为本次短测合同,缺项明确失败。
+- 每轮改动前 JOURNAL 写任务/窄测,完成后 STATE/EVIDENCE/WORKLOG 写实际结果。失败三种不同假设仍无法推进时只阻塞该独立项,不重跑旧矩阵空转。不得无授权改驱动、关远程软件、删除 STOP、放宽画面正确性。
diff --git a/docs/DELIVERY_STATUS.md b/docs/DELIVERY_STATUS.md
new file mode 100644
index 00000000..cfa9812b
--- /dev/null
+++ b/docs/DELIVERY_STATUS.md
@@ -0,0 +1,38 @@
+# 本机交付状态 — 2026-09-07
+
+状态:本机软件联合短测与独立只读复核均已通过,可交给用户使用和实卡验收。不是公开发行许可;实卡未接入。最终复验与范围见 REVIEW_F6.md。
+
+最终构建EXE:`70DD23C44337004FC734FBAE8BB6139E185C52370AE97CCE6C3432A3C6F30DE1`;独立联合短测run `9be0614da5d642e394a35c71d80f6207`,40.31秒通过,包含新增4K图片保存与真实NVENC中途取消。下方31.59秒是初测历史,不是最终二进制身份。
+
+## 已有实际软件
+
+- `Veyra.cmd` → `out/build/x64-release/veyra.exe`,Win32 UI + 同一共享增强引擎。
+- 本地 H.264/HEVC 播放,音频主时钟,暂停/定位/全屏/开关/最近文件,外部同名 SRT。
+- WIC PNG/JPEG 图片输入和保存;D3D12 NVENC 原生 4K H.264/HEVC MP4 + 兼容音轨,FG 2X、取消/partial。
+- DirectShow 视频设备/实际格式/HDMI 音频选择、容量1实时邮箱;没有实卡运行证据。
+
+## 本轮实测
+
+构建:`scripts/build.ps1 -Root . -Preset x64-release` exit0。
+
+联合门禁:`scripts/gates/delivery.ps1 -Root .`,run `d28879b01b5c44dd86cad33d6f386d90`,31.59秒、16项通过。原始 JSON:`logs/delivery/d28879b01b5c44dd86cad33d6f386d90/result.json`。
+
+- Native 1080:60 NR,真实 NVOF/非零 motion 接入,GBV 0错误,诊断 PNG 可见非黑测试图。
+- Native 4K:12 NR,actual source/working/output =3840×2160。
+- 4K输入实时档 FG2X:264源帧、263生成帧,短测 absolute lateness P95=14.88ms;不是端到端光子延迟。
+- 暂停中 seek → resume → JPEG 保存,exit0。
+- PNG 经过实际应用打开/增强/显示,exit0。
+- H264 与 HEVC 各12源帧→23输出帧,原生4K;ffprobe `-count_frames`逐帧解码、均保留音轨。
+- 本次 EXE SHA256:`900DD752D749036EC482B3B9557AD23D12C60D58A58E37B44C1C960D5DC1B747`。
+
+## 重要修复与否定结论
+
+修了 NV12 错误上传、chroma 尺寸、uint根常量按float传递、motion统计步长;将 NVOF 放到 NR 之前并实际绑定;加入场景切换清历史、命令时间戳、正确退出;修音频环与暂停定位,明确48k双声道浮点格式由WASAPI转换到设备格式。
+
+原生4K GPU分段实测 `logs/f6-profile-split.*`:NR-only约22–23ms、parity decode/output约0.28ms。以前“decode shader24ms”根因结论错误。用户已接受默认实时档/原生4K可选;原生4K60不能凭改队列保证,导出不受实时预算限制。
+
+## 未被证明 / 明确限制
+
+实卡视频音频与按键体感延迟、长时稳定、全面seek/resize/device-loss压力、多音轨/音频转码、内嵌字幕、depth provider、VFR原样时间线、HDR、安装包及专有分发权均未证明或不提供。部分完整产品体验仍是显式错误后手动重开,不宣称无缝恢复。使用范围与操作见 USER_GUIDE。
+
+下一步唯一任务:用户接实卡按USER_GUIDE验收并反馈。软件本机交付停止自动扩展,不重跑历史30分钟矩阵,不自动发布。
diff --git a/docs/REVIEW_F6.md b/docs/REVIEW_F6.md
new file mode 100644
index 00000000..c28b7e20
--- /dev/null
+++ b/docs/REVIEW_F6.md
@@ -0,0 +1,16 @@
+# F6 独立只读复核 — 2026-09-07
+
+Reviewer:新上下文 `final_readonly_review`。接管基线6f0ebaa,主体为当前用户授权的本机软件交付合同,非原始规格所有项/公开发布许可。
+
+初审 preflight/phase5=0/0,但 VERDICT FAIL:默认实时档误缩小4K图片;取消时编码回调捕获对象先析构;第二次音轨源读取失败静默降为无声。Maker修复后再次构建。
+
+最终 GATE_EXIT=0/0,WORKTREE_MUTATED_BY_REVIEWER=no,VERDICT=PASS,未发现新的P0/P1。当前EXE SHA256=70DD23C44337004FC734FBAE8BB6139E185C52370AE97CCE6C3432A3C6F30DE1。
+
+独立复验 `logs/delivery/9be0614da5d642e394a35c71d80f6207/result.json`,40.31秒。
+
+- 所有联合短测通过,含真实NR/NVOF、GBV、4K输入实时FG播放、暂停定位、WIC、H264/HEVC原生4K音视频导出和解码。
+- Live1080开启时,4K静态图保存仍3840×2160。
+- 取消前实际提交43次NVENC EncodePicture,随后排空释放,预期exit3,仅保留.partial,没有成功MP4。
+- tracked diff与四个修复文件SHA256在Reviewer运行前后不变。
+
+证据边界:实卡、长时稳定、完整device-loss压力未证明;音轨检查失败分支完成代码复核,未故障注入。短测与本机交付PASS不等于公开分发许可、原始完整规格全部验收或与竞品画质等价。
diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md
new file mode 100644
index 00000000..d8decf77
--- /dev/null
+++ b/docs/USER_GUIDE.md
@@ -0,0 +1,39 @@
+# Veyra 本机使用
+
+双击项目根目录 `Veyra.cmd`。实际程序在 `out/build/x64-release/veyra.exe`;暂时不要移动项目目录,编译时绑定了本机 runtime / shader 路径。这不是含专有 DLL 的安装包。
+
+## 播放器
+
+1. 点 **Open video / image**,或拖入 MP4/MKV/H.264/HEVC 视频。
+2. **DLSS NR** 是实验 Feature 18;**FG 2X** 是补帧;**SR 4K** 是在 NR 前超分到 4K。
+3. **Live 1080** 是用户同意的默认实时档:4K 视频仍按 4K 解码,内部处理到 1080p,最终按窗口/全屏尺寸显示。状态行写真实 input / processing,绝不是原生 4K NR。
+4. 取消 **Live 1080** 使用原生分辨率。RTX 5070 本机实测原生 4K NR 单次约 22–23ms,因此它不能保证 4K60 实时;不要在这种负载下期待仅靠补帧修复音画落后。SR 4K 也走 4K NR 高成本路径。
+5. 拖进度条可 seek;暂停时也可定位。Space 暂停、F11 全屏。更改增强开关会重新打开源文件;不是无缝动态切换。
+6. **Recent** 打开最近文件。NR/SR/FG/Live 设置保存在 `runtime_local/veyra.ini`。
+7. 同名 UTF-8 / UTF-16LE `.srt` 自动加载,显示在画面下方独立字幕区域,不进入 NR/FG。当前不解码内嵌字幕,也不烧录字幕到导出文件。
+
+## 图片 / 视频导出
+
+- 打开 PNG/JPEG 后点 **Save image**,保存增强后的 PNG 或 JPG。播放视频时也可保存当前源帧增强截图。WIC 处理 JPEG EXIF 方向。
+- **Export video** 选择新 MP4 文件名,Yes 选择 HEVC、No 选择 H.264。使用当前 NR/SR/FG;**Live 1080 不影响视频导出**,4K 输入仍按原生 4K 处理。
+- 视频使用真正 D3D12 NVENC:GPU 纹理/fence 直接给编码器;CPU 只接压缩码流,不走 raw 像素 pipe。
+- 默认保留第一条可封装到 MP4 的音轨;不兼容的音频编码会报错拒绝导出,不偷偷丢音轨。多音轨选择、音频转码尚未提供。
+- Stop 取消导出;`.partial` 保留以便诊断,未完成文件不会改名成成功 MP4。没有断点续编;重新导出请选择新文件名。
+- 不覆盖已有文件。若上次有同名 `.partial`,换名字或自行确认删除它后再试。
+- V1 输出为 CFR,FG 2X。场景切换不跨镜头插帧,空出的时间格使用明确记录的源帧 hold,而非声称它是生成帧。
+
+## 采集卡:等待你实机测试
+
+1. 接采集卡,点 **Capture**。依次选择真实视频设备、实际支持的 1080p/2160p 30/60 格式、HDMI 音频输入。
+2. 音频不是自动猜选;不选就无音频。点 Start capture。
+3. 先默认 Live 1080、NR 开、FG 关确认视频声音;再开 FG 2X。内部实时入口只保留最新一帧,丢帧会清除历史。
+4. 分别检查 1080p60、4K30/60(以设备实际提供为准)、停止重开、拔线后的错误提示、重接后重新打开 Capture、音画差和按键体感延迟。
+5. 补帧必须等待后一源帧到达,不是利用采集卡获得免费未来帧。HDMI 音频目前由 DirectShow 实时监听,尚未经过实卡端到端延迟校准。
+
+## 真实边界
+
+仅本机 Windows x64 / RTX / SDR,最高 3840×2160、偶数尺寸;HDR 会拒绝。Depth Anything provider 当前不可用,实际是 NVOF motion + cost 门控,不是游戏原生深度/运动向量。
+
+短测不证明长时间稳定,也不证明画质优于 Magpie/ReShade。设备丢失会停止并报错,重新打开源来重建引擎;不是无缝恢复。公开分发权尚未解决,勿打包/上传实验 runtime 或 ReShade add-on。
+
+错误先点 **Logs** 查看 `logs/veyra-app.log`。提交反馈只需日志与操作步骤,不要发送 runtime、SDK 或私人媒体。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index f5971443..49da17da 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,11 @@
# Veyra Worklog
+## 2026-09-07 direct implementation delivery
+
+See docs/DELIVERY_STATUS.md for current software, tests and limits. Actual app/controller/presenter, DirectShow source, WIC and D3D12 NVENC export now exist; earlier “no UI/export” entries are historical. Fixed NV12/uint shader inputs, real guidance-before-NR, scene resets, audio format/paused seek, GPU timestamp semantics. CMake x64-release exit0; consolidated gate run d28879b01b5c44dd86cad33d6f386d90 exit0 in31.59s. No 30-minute retests. User accepted realtime internal-resolution option after GPU measurement. Independent review next; do not claim phase checkpoint yet.
+
+> 2026-09-06 用户授权接管修订:当前推进、五分钟短测与用户实卡验收以 `../docs/ACTIVE_DELIVERY_PLAN.md` 为准,取代下文旧的严格串行施工/30分钟测试/未接设备阻塞全部交付规则。历史记录不是当前通过证明。
+
## 2026-09-02 Phase 2 — RenoDX-equivalent parity codec (gate 35/35 + reviewer PASS)
Goal:
diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.h
new file mode 100644
index 00000000..6bfd7c2c
--- /dev/null
+++ b/include/veyra/engine/EngineController.h
@@ -0,0 +1,35 @@
+#pragma once
+#include <windows.h>
+#include <atomic>
+#include <mutex>
+#include <string>
+#include <thread>
+namespace veyra::engine {
+struct PlayerOptions { bool nr=true,sr=false,fg=false,realtime=true; };
+struct PlayerSnapshot {
+ std::wstring status=L"Open a video or image";
+ double position=0,duration=0,fps=0,lateMs=0,lateP95Ms=0;
+ uint64_t frames=0,generated=0;
+ bool running=false,failed=false,image=false;
+};
+class EngineController {
+public:
+ ~EngineController(){stop();}
+ void open(HWND video,const std::wstring& path,PlayerOptions options);
+ void stop();
+ void pause(bool p){paused_.store(p);}
+ void seek(double seconds){seekSeconds_.store(seconds);}
+ void saveFrame(const std::wstring& path);
+ void startExport(const std::wstring& input,const std::wstring& output,PlayerOptions,bool hevc);
+ PlayerSnapshot snapshot()const;
+private:
+ void run(HWND,std::wstring,PlayerOptions);
+ void status(const std::wstring&,bool failed=false);
+ mutable std::mutex mutex_;
+ PlayerSnapshot snapshot_;
+ std::wstring savePath_;
+ std::thread worker_;
+ std::atomic<bool> stop_{false},paused_{false};
+ std::atomic<double> seekSeconds_{-1};
+};
+}
diff --git a/include/veyra/engine/Subtitles.h b/include/veyra/engine/Subtitles.h
new file mode 100644
index 00000000..e403cb70
--- /dev/null
+++ b/include/veyra/engine/Subtitles.h
@@ -0,0 +1,8 @@
+#pragma once
+#include <string>
+#include <vector>
+namespace veyra::engine {
+struct SubtitleCue {double begin=0,end=0;std::wstring text;};
+std::vector<SubtitleCue> loadSrt(const std::wstring& path);
+std::wstring subtitleAt(const std::vector<SubtitleCue>&,double seconds);
+}
diff --git a/include/veyra/engine/VideoExportJob.h b/include/veyra/engine/VideoExportJob.h
new file mode 100644
index 00000000..b2bc6a9b
--- /dev/null
+++ b/include/veyra/engine/VideoExportJob.h
@@ -0,0 +1,8 @@
+#pragma once
+#include "veyra/engine/EngineController.h"
+#include <functional>
+namespace veyra::engine {
+bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptions,bool hevc,
+ std::atomic<bool>& cancel,const std::function<void(double,const std::wstring&)>& progress,
+ unsigned maxFrames=0);
+}
diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.h
new file mode 100644
index 00000000..06fa2111
--- /dev/null
+++ b/include/veyra/engine/VideoPresenter.h
@@ -0,0 +1,20 @@
+#pragma once
+#include "veyra/gfx/PresentSink.h"
+#include "veyra/pipeline/GpuPassUtils.h"
+namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }
+namespace veyra::pipeline { class EnhanceGraph; }
+namespace veyra::engine {
+class VideoPresenter {
+public:
+ bool open(gfx::D3D12DeviceContext&, HWND, pipeline::EnhanceGraph&);
+ bool present(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,pipeline::EnhanceGraph&,unsigned slot,bool generated);
+ void close();
+private:
+ gfx::PresentSink sink_;
+ pipeline::GraphicsPass pass_;
+ Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> rtvs_;
+ unsigned inc_=0;
+ HWND window_=nullptr;
+ void refresh(ID3D12Device*);
+};
+}
diff --git a/include/veyra/gfx/CommandSlotRing.h b/include/veyra/gfx/CommandSlotRing.h
index e9e230c7..16e410f0 100644
--- a/include/veyra/gfx/CommandSlotRing.h
+++ b/include/veyra/gfx/CommandSlotRing.h
@@ -5,6 +5,7 @@
#include <cstdint>
#include <vector>
+#include <string>
#include "veyra/Result.h"
@@ -48,6 +49,7 @@ public:
// Closes, submits and signals the slot; advances the fence timeline.
bool submitAndSignal(uint32_t slot);
+ void tag(uint32_t slot,const char* label){slots_.at(slot).label=label;}
// The fence value most recently signaled by this ring. Callers that need
// a GPU-side dependency on the just-submitted work (e.g. NVOF input
@@ -72,12 +74,16 @@ public:
// Query heap for D3D12_QUERY_TYPE_TIMESTAMP entries (two per slot).
ID3D12QueryHeap* timestampHeap() const { return timestampHeap_.Get(); }
+ uint64_t cpuWaitCount() const { return cpuWaitCount_; }
+ const std::vector<double>& gpuCommandTimesMs() const { return gpuCommandTimesMs_; }
private:
struct Slot {
ComPtr<ID3D12CommandAllocator> allocator;
ComPtr<ID3D12GraphicsCommandList> list;
uint64_t fenceValue = 0; // 0 means "never submitted"
+ bool timed = false;
+ std::string label;
};
bool initialized_ = false;
@@ -89,6 +95,9 @@ private:
uint64_t nextFenceValue_ = 1;
ComPtr<ID3D12QueryHeap> timestampHeap_;
std::vector<Slot> slots_;
+ ComPtr<ID3D12Resource> timingReadback_;
+ uint64_t timestampFrequency_ = 0, cpuWaitCount_ = 0;
+ std::vector<double> gpuCommandTimesMs_;
};
} // namespace veyra::gfx
diff --git a/include/veyra/gfx/PresentSink.h b/include/veyra/gfx/PresentSink.h
index a888e281..14582218 100644
--- a/include/veyra/gfx/PresentSink.h
+++ b/include/veyra/gfx/PresentSink.h
@@ -35,6 +35,7 @@ public:
bool vsync = true;
// Probe runs create their own window class name per process.
std::wstring title = L"Veyra";
+ HWND targetWindow = nullptr; // borrowed UI-owned child HWND; never destroyed by sink
};
// Creates a Win32 window (not shown as foreground; background probe
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index c35d7ee4..db6342c3 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -23,6 +23,7 @@
#include <d3d12.h>
#include "veyra/pipeline/GpuPassUtils.h"
+#include "veyra/core/SceneCadenceAnalyzer.h"
struct AVFrame;
struct SwsContext;
@@ -105,6 +106,7 @@ public:
uint64_t nvofExecuteCount = 0;
uint64_t nvofFrameFailures = 0;
uint64_t fgGeneratedFrames = 0;
+ uint64_t nrMotionFrames = 0, sceneCutCount = 0, resetCount = 0;
};
const Metrics& metrics() const { return metrics_; }
const std::string& mvecSource() const { return mvecSource_; }
@@ -211,6 +213,10 @@ private:
// Per-run state.
uint64_t realFrameIndex_ = 0;
+ uint32_t nextListSlot_ = 0;
+ uint64_t uploadFences_[2] = {};
+ core::SceneCadenceAnalyzer scene_;
+ std::vector<uint8_t> previousLuma_;
double prevPtsMs_ = -1.0;
bool prevValid_ = false;
Metrics metrics_{};
diff --git a/include/veyra/sink/ImageExportSink.h b/include/veyra/sink/ImageExportSink.h
new file mode 100644
index 00000000..3f3a4c88
--- /dev/null
+++ b/include/veyra/sink/ImageExportSink.h
@@ -0,0 +1,13 @@
+#pragma once
+#include <cstdint>
+#include <string>
+#include <vector>
+#include <d3d12.h>
+namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }
+namespace veyra::sink {
+struct RgbaImage { uint32_t width=0, height=0; std::vector<uint8_t> pixels; };
+// Image export / explicit diagnostics only. Never used by playback or video export.
+bool readRgba8(gfx::D3D12DeviceContext&, gfx::CommandSlotRing&, ID3D12Resource*, RgbaImage&);
+bool saveImage(const std::wstring& path, const RgbaImage&, bool jpeg=false);
+bool loadImage(const std::wstring& path, RgbaImage&);
+}
diff --git a/include/veyra/sink/NvencD3D12Encoder.h b/include/veyra/sink/NvencD3D12Encoder.h
new file mode 100644
index 00000000..8f18830a
--- /dev/null
+++ b/include/veyra/sink/NvencD3D12Encoder.h
@@ -0,0 +1,21 @@
+#pragma once
+#include <d3d12.h>
+#include <functional>
+#include <memory>
+#include <vector>
+namespace veyra::gfx {class D3D12DeviceContext;class CommandSlotRing;}
+namespace veyra::pipeline {class EnhanceGraph;}
+namespace veyra::sink {
+class NvencD3D12Encoder {
+public:
+ using PacketWriter=std::function<bool(const uint8_t*,size_t,int64_t,bool)>;
+ NvencD3D12Encoder();~NvencD3D12Encoder();
+ bool open(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,pipeline::EnhanceGraph&,bool hevc,unsigned fpsNum,unsigned fpsDen,PacketWriter);
+ bool encode(unsigned frameSlot,bool generated,int64_t pts);
+ bool finish();
+ void close();
+ std::vector<uint8_t> headers() const;
+private:
+ struct Impl;std::unique_ptr<Impl> p_;
+};
+}
diff --git a/include/veyra/sink/WasapiAudioSink.h b/include/veyra/sink/WasapiAudioSink.h
index e8c619ab..fd92ed92 100644
--- a/include/veyra/sink/WasapiAudioSink.h
+++ b/include/veyra/sink/WasapiAudioSink.h
@@ -66,6 +66,7 @@ public:
size_t pull(float* dst, size_t maxFrames, double* firstPtsMs);
void stopThread();
+ void setPaused(bool value) { paused_.store(value); }
// Seek protocol (engine thread calls; audio thread executes). Blocks
// until the audio thread finished the atomic re-sequence and prefilled.
@@ -108,6 +109,7 @@ private:
std::condition_variable wake_;
std::condition_variable seekDoneCv_;
std::atomic<bool> stopFlag_{false};
+ std::atomic<bool> paused_{false};
bool seekRequested_ = false;
bool seekDone_ = true;
double seekTargetMs_ = 0.0;
@@ -129,6 +131,7 @@ public:
// Called by the audio thread after prefill: begins playback anchored at
// the PTS of the sample that will be written first.
bool startAnchored(double firstBufferPtsMs);
+ void setPaused(bool value);
// Event-driven pump for ONE event cycle. Writes real data when the ring
// has it, silence otherwise (underrun counted). Returns false on hard
@@ -158,9 +161,9 @@ private:
UINT32 bufferFrames_ = 0;
uint32_t sampleRate_ = kAudioRate;
UINT64 clockFrequency_ = 0;
- UINT64 anchorPos_ = 0;
+ std::atomic<UINT64> anchorPos_{0};
std::atomic<double> anchorPtsMs_{0.0};
- bool started_ = false;
+ std::atomic<bool> started_{false};
bool running_ = false;
bool comInited_ = false;
std::atomic<uint64_t> underruns_{0};
diff --git a/include/veyra/source/CaptureCardSource.h b/include/veyra/source/CaptureCardSource.h
new file mode 100644
index 00000000..bbf18243
--- /dev/null
+++ b/include/veyra/source/CaptureCardSource.h
@@ -0,0 +1,19 @@
+#pragma once
+#include "veyra/source/IFrameSource.h"
+#include <memory>
+#include <vector>
+namespace veyra::source {
+struct CaptureFormat {int index=0;unsigned width=0,height=0;double fps=0;std::wstring label;};
+class CaptureCardSource final:public IFrameSource {
+public:
+ CaptureCardSource();~CaptureCardSource()override;
+ static std::vector<std::wstring> devices(bool audio=false);
+ static std::vector<CaptureFormat> formats(unsigned device);
+ 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;
+private:struct Impl;std::unique_ptr<Impl> p_;
+};
+}
diff --git a/include/veyra/source/IFrameSource.h b/include/veyra/source/IFrameSource.h
index 39dd2027..54a89b49 100644
--- a/include/veyra/source/IFrameSource.h
+++ b/include/veyra/source/IFrameSource.h
@@ -37,6 +37,7 @@ enum class SourceReadStatus : uint8_t {
Frame = 0, // packet metadata + decoded frame valid
Eos, // source fully drained
Error,
+ Waiting, // live capture has no new sample yet; poll cancellation then retry
};
class IFrameSource {
diff --git a/loop/BACKLOG.md b/loop/BACKLOG.md
index 1c509125..f0f03fc7 100644
--- a/loop/BACKLOG.md
+++ b/loop/BACKLOG.md
@@ -1,5 +1,17 @@
# Veyra Launch V1 Backlog
+## 当前唯一队列(F6,2026-09-07)
+
+- [x] 真实共享输入/NR guidance/资源修复,Win32播放器、WIC图片、D3D12 NVENC视频、DirectShow输入实现。
+- [x] 用户确认默认实时内部处理档,保留原生4K可选/原生4K导出。
+- [x] 联合软件短测31.59秒通过,证据见DELIVERY_STATUS。
+- [x] 新上下文只读Reviewer:3个P1修复复验后PASS,见REVIEW_F6。
+- [x] 本机交付Veyra.cmd与文档;实卡交给用户,不等硬件接入、不假报实测。
+
+以下原阶段队列保留为历史规格,不得绕过上述用户授权新顺序重跑长测。
+
+> 2026-09-06 用户授权接管修订:当前推进、五分钟短测与用户实卡验收以 `../docs/ACTIVE_DELIVERY_PLAN.md` 为准,取代下文旧的严格串行施工/30分钟测试/未接设备阻塞全部交付规则。历史记录不是当前通过证明。
+
状态:`TODO / DOING / BLOCKED / GATE_PASS / REVIEW_PASS / DONE`。Maker 每个 cycle 只处理当前 Phase 第一个前置满足的 TODO。若某项因外部许可/硬件明确标为 BLOCKED,可继续同一 Phase 后面与它独立的 TODO;该 Phase 最终 gate 仍不得通过。
## Phase 0–4 — 已验证基础
diff --git a/loop/CONTROL_HASHES.json b/loop/CONTROL_HASHES.json
index 6e7c53e9..0c8340ef 100644
--- a/loop/CONTROL_HASHES.json
+++ b/loop/CONTROL_HASHES.json
@@ -1,6 +1,6 @@
{
"schemaVersion": 1,
- "purpose": "Fail-closed hash manifest for the user-authorized Launch V1.3 strong-agent recovery rebaseline on 2026-09-06.",
+ "purpose": "2026-09-07 subsequent explicit user approval: realtime default, optional native4K; local delivery docs/short acceptance consolidated. Relocked; no further self-rebaseline.",
"files": [
{
"path": ".gitignore",
@@ -8,19 +8,19 @@
},
{
"path": "AGENTS.md",
- "sha256": "533C51B4D462A3060A001BE4425C58515135068C8C2585C27973712FC84C648C"
+ "sha256": "F52DC67AC0B3575B18CB4AD1692B8E6AB222C798CB0B2259FF81679269A3C61A"
},
{
"path": "README.md",
- "sha256": "FD2EB1E4630060D0C1DFED18D5D6D4217E08E22F81F8A1FC2D29142B8073CBDA"
+ "sha256": "781FAFD857A82A19FCC09FDEDB2E00EE2465099E32B5A0857127D648316336E0"
},
{
"path": "VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md",
- "sha256": "A8AC38DEA358D057D2EBE0B4595A31DFB11B75C28A3A8847F6C4169624E0524D"
+ "sha256": "44120B363B831A9EE45B43424AB64D8A222B6D3748969C89BA576A6062896C9B"
},
{
"path": "VEYRA_PRODUCT_SPEC_V1.md",
- "sha256": "54D77ACEB7C4CC8B87ED23C4BC8B0698F8230970F3E759B5B6BC90460BB05159"
+ "sha256": "619CF628CA41766BE84D8491A6353485E34FB848DEB9F86F610E66A80A6769FD"
},
{
"path": "docs/COMPETITOR_AUDIT_2026-09-03.md",
@@ -28,19 +28,23 @@
},
{
"path": "loop/GOAL_PROMPT.md",
- "sha256": "4ECBC2750DE2D89188EFE3C0AB2E6405C059A172ED48119DDE049EA22966AD74"
+ "sha256": "CCCF90513A0CE66943CADC4C36B83D19FFD337F550E81EEA115AB59BC25748FF"
},
{
"path": "loop/LOOP_ENGINE.md",
- "sha256": "3D935FEDF7B43F0FDC307A3F4F979A46AC1DE65C175A867B0F1E79E170A23BF2"
+ "sha256": "FF576DB39B94748948B9EEC547FC33A145F8DEB64529E2A843F3123F2A85433A"
},
{
"path": "loop/REVIEW_PROMPT.md",
- "sha256": "C3465962300442B0EC13C6B8C3ABB2B27DBCAA0BF6E56E499017FE87350C59FA"
+ "sha256": "4846CA2BACCA6645937AF44C481B0EC874BFC7407FD3DB1F4D411A849AEDBD2D"
},
{
"path": "scripts/gates/README.md",
- "sha256": "D41934206612C68F66BF018287907B636C508EE4CE42472AB02AE0B9EA913F27"
+ "sha256": "4A729467922F332734B8E68E271A712A4D6174C1666B3B2DCDB7D109F4FB18F0"
+ },
+ {
+ "path": "docs/ACTIVE_DELIVERY_PLAN.md",
+ "sha256": "CFDB1C41DF3890014852BF9600089C4D7B8E4CB90CA77A36EE2841EEF685E220"
}
]
}
diff --git a/loop/EVIDENCE.md b/loop/EVIDENCE.md
index 0ca68dca..a4308cb1 100644
--- a/loop/EVIDENCE.md
+++ b/loop/EVIDENCE.md
@@ -1,5 +1,17 @@
# Veyra Gate Evidence
+## FINAL current binary / independent PASS — 2026-09-07
+
+Current EXE SHA256 70DD23C44337004FC734FBAE8BB6139E185C52370AE97CCE6C3432A3C6F30DE1. New-context Reviewer preflight/phase5 (consolidated delivery) exit0/0, PASS, no reviewer source mutations. logs/delivery/9be0614da5d642e394a35c71d80f6207/result.json,40.31s. Initial3 P1 fixed and independently reproduced correction: image4K dimensions, cancel callback lifetime43encodes exit3/partial only, audio fail-closed code review. Review persisted docs/REVIEW_F6.md. Local contract only; awaiting_user_capture_test and distribution_blocked remain.
+
+## F6 consolidated local delivery — 2026-09-07
+
+Build x64-release exit0. `scripts/gates/delivery.ps1 -Root .` exit0, run d28879b01b5c44dd86cad33d6f386d90, 31.59s, 16 checks. Full current evidence in logs/delivery/{run}/result.json and per-command stdout/stderr/JSON/media. Actual 1080 NR60 + NVOF motion + GBV0, native4K NR12, 4K-input realtime FG source264/generated263/absolute-latenessP95 14.88ms, paused seek/resume/JPEG, PNG application run, native4K H264 and HEVC23 frames each + audio fully decoded by ffprobe. EXE900DD752D749036EC482B3B9557AD23D12C60D58A58E37B44C1C960D5DC1B747. New read-only reviewer pending. No capture hardware or endurance PASS.
+
+Raw GPU segmentation logs/f6-profile-split.* proves NR22–23ms versus decode/output0.28ms. User explicitly accepted default realtime processing profile with optional native4K. New controls/doc hash rebaseline records this subsequent user authorization, not a hidden lowering of native4K quality/output correctness.
+
+> 2026-09-06 用户授权接管修订:当前推进、五分钟短测与用户实卡验收以 `../docs/ACTIVE_DELIVERY_PLAN.md` 为准,取代下文旧的严格串行施工/30分钟测试/未接设备阻塞全部交付规则。历史记录不是当前通过证明。
+
这里只登记真实存在的门禁证据。格式固定:
## Phase 3 / phase3 / 2026-09-03T01:20:00+08:00
diff --git a/loop/GOAL_PROMPT.md b/loop/GOAL_PROMPT.md
index 5fc4a17b..be35623c 100644
--- a/loop/GOAL_PROMPT.md
+++ b/loop/GOAL_PROMPT.md
@@ -1,90 +1,7 @@
-# 可直接交给 Goal 模式的任务
+# Veyra 当前 Goal 入口
-将下面整段作为另一个 Agent 的目标。推荐把 Goal 最大循环数设为 120;如果产品另有硬上限,以更小的硬上限为准,达到上限时必须留档,不能伪报完成。
+按 `docs/ACTIVE_DELIVERY_PLAN.md` F0→F6 接管完成本机软件。先读 AGENTS/README/Playbook/ProductSpec/竞品审查与当前 WORKLOG/STATE,再 preflight。保留固定 runtime 和用户未提交改动。已有真实共享 pipeline,修输入/证据/Guidance,接共享 controller、Win32 Player、WIC 图片、D3D12 NVENC 视频和 DirectShow Capture。
-~~~text
-目标:接管当前 Veyra DLSS Video Player 工作区,严格按 AGENTS.md、
-loop/LOOP_ENGINE.md、VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md 和
-VEYRA_PRODUCT_SPEC_V1.md,从 2026-09-06 的真实恢复基线继续,完成
-Launch V1。V1 不是 MVP:物理采集卡实时增强、可交互播放器、图片导出、
-视频导出和 native 4K SDR 必须同时交付,并共同使用一套
-FrameSource -> EnhanceGraph -> FrameSink。
+用户授权每次完整自动测试 <=300 秒,优先短测;不再跑旧30分钟矩阵。当前采集卡未连接,由用户亲自实卡验收,标 awaiting_user_capture_test;实现与视频验证继续,不假报硬件通过。允许跨旧阶段开展独立产品实现,验收状态不冒进。
-重要纠错:不要信任旧“Phase 5 passed”。Phase 0–4 证据有效;Phase 5
-已因 gate 与实现不符重开。旧 gate 接受 manifest-only depth、把第二次
-1080p endurance 放进 4K 检查位置;src/core/EnhanceGraph.cpp 只计数,
-真正 GPU 链仍在 harness;tools/player_probe/main.cpp 约 3600 行。Phase 6
-已有值得保留的未提交代码和真实 FG/NVOF/WASAPI/Present 证据,但最新
-player run 的 drift P95 约 2.8 秒且 L2/GBV 有 descriptor-uninitialized,
-所以 Phase 6/7 必须保持 locked,禁止从 UI 或 Capture 开始。
-
-用户已决定继续使用当前固定 hash 的实验 nvngx_dlssnr.dll/Feature 18 做
-本机研发。不要等待公开 DLSS 5 SDK,也不要重新争论市场可行性;同时
-不得声称它与官方游戏/Magpie 画质等价。不得寻找其他泄露版本、从游戏
-或驱动缓存抽 DLL、patch/重签/提交/打包/上传 runtime。分发权未解决时
-最终只能 distribution_blocked。
-
-你是唯一写入 Maker。启动后完整阅读上述四份文件以及 README、
-docs/COMPETITOR_AUDIT_2026-09-03.md、loop/STATE.json、BACKLOG、INBOX、
-EVIDENCE、JOURNAL 和 WORKLOG 最新记录。若 loop/STOP 存在立即停机。
-首轮按 Playbook R0 执行,首条项目命令必须是:
-
-powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate preflight
-
-随后运行 git status --porcelain=v1、git diff --stat、git diff --check、
-git log -10、Release build,并对当前 git diff --binary 计算接管指纹。
-当前工作树在控制面重基线后约有 44 个未提交 status entry;禁止 reset、clean、checkout、
-覆盖或整树格式化。先把每个未提交文件归类为 keep/repair/obsolete,保留
-其他 Agent 的真实成果。validation/fixed_clips 下的 tracked MP4 删除先
-不处理,等新 gate 改用确定性生成 corpus 后单独报告。
-
-施工严格执行 Playbook 0.3 的 R0→R12 和 BACKLOG 第一个可执行原子项:
-R0 保存接管基线;R1 重写 phase5 gate 并先证明失败;R2 补全 packet/
-window/guidance/reset 契约;R3 把真实 GPU graph 从 player_probe 提取到
-共享库;R4 完成 NVOF confidence、DAV2/Auto、scene/reset;R5 重新通过
-Phase 5 gate+Reviewer;R6 修 GBV、GPU timing、性能、A/V drift 并通过
-Phase 6;R7 Player app;R8 Capture;R9 Image Export;R10 D3D12 NVENC
-Video Export;R11 UI/设置/恢复;R12 Phase 7 联合 gate+Reviewer。
-
-每个 cycle 只能做一个可证伪原子任务。改代码前先在 JOURNAL 写假设、
-预计文件、窄测试和新增证据;改后先跑窄测试,再跑当前 phase gate。
-所有成功必须来自本次 run-id、exe/input/config/runtime hash、exit code、
-真实 Create/Evaluate、counter、GPU timestamp 或 capture。以下一律是假完成:
-stub、只增加 counter、仅编译、manifest 代替 provider、harness-only 链路、
-1080p 重跑冒充 native 4K、Zero motion 冒充 NVOF、blend/duplicate 冒充 FG、
-raw pipe 冒充 D3D12 NVENC、窗口捕获冒充物理采集卡。
-
-R3 必须删除双实现:把已验证代码从 player_probe 移入 veyra_pipeline/
-veyra_guidance/veyra_sources/veyra_sinks;probe 最终只做组装和写证据。
-Player、Capture、Export 不得复制 NGX、颜色、Guidance、reset 或资源生命周期。
-逐帧路径禁止全帧 GPU->CPU readback、每 pass CPU fence wait、无界队列。
-
-Phase 5 新 gate 必须在真实共享 library 上验证 1080p60 和 native 4K60
-各 30 分钟、NVOF 非零 motion/confidence、DAV2 或明确且可测的 Auto fallback、
-reset/scene、真实 extent、GPU timing、VRAM/queue/memory。依赖 manifest
-不能单独过 provider gate。Phase 6 必须先修 GBV id=938,加入 query-heap
-GPU timing,把 1080p/4K player drift P95 降到 <=50ms,L0/L1/L2 均自然
-return、0 ERROR/CORRUPTION,再跑 4K30/60 30 分钟。不得关掉验证层或删
-错误来过关。
-
-Video Codec SDK 13.1 和真实 4K60 采集设备是外部阻塞,只阻塞对应原子项;
-可继续同 Phase 内独立工作。NVOF SDK 5.0.7 已存在,不得继续写成缺失。
-同一 failure fingerprint 最多 3 个真正不同且增加证据的方案;连续 5 个
-cycle 无新证据或总计 120 cycle 就留档停止,禁止空转。
-
-每个 Phase gate 首次通过后,必须把 loop/REVIEW_PROMPT.md 交给一个新
-上下文只读 Reviewer。Reviewer 独立重跑 gate,不能修改工作区。修完全部
-P0/P1、gate 与 Reviewer 再通过后才能本地 checkpoint、更新 STATE 并解锁
-下一 Phase。禁止并行写同一 checkout,禁止 push、PR、发布、上传、签名、
-制作安装包、安装/降级驱动或替用户接受 EULA。
-
-Goal 启动后所有控制面只读,不得重写计划、gate contract 或 hash manifest
-来自我放行。只有 Phase 0–7 全部有当前规格的 gate+Reviewer、无 P0/P1、
-三入口和 4K 证据完整、专有文件未入 Git,才可标功能 release_candidate;
-分发 blocker 清零前绝不能标 complete 或公开首发。
-
-现在立即从 BOOT/RECONCILE 与 R0 开始。不要先写 UI,不要再问文档已经
-回答的问题,也不要用旧摘要代替重新运行命令。
-~~~
-
-说明:这是本项目唯一的无人值守执行入口。非 Goal 模式只能完成当前 Phase 后停下报告。
+Maker 唯一写入;每轮 JOURNAL 先记假设和窄测,改后记录真实退出/输出到 STATE/EVIDENCE/WORKLOG。最终只读独立 Reviewer 检查。禁止修改固定 runtime、下载其他泄露版本、关远程/更新驱动、上传/打包/发布。公网分发权未解决保持 distribution_blocked。Goal 完成指本次约定的本机软件交付,不表示公开授权。检测 STOP 立即停机;代码缺陷继续修,不把历史假统计当完成。
diff --git a/loop/INBOX.md b/loop/INBOX.md
index 856cc7f1..2a742243 100644
--- a/loop/INBOX.md
+++ b/loop/INBOX.md
@@ -1,5 +1,7 @@
# Veyra Human Inbox
+> 2026-09-06 用户授权接管修订:当前推进、五分钟短测与用户实卡验收以 `../docs/ACTIVE_DELIVERY_PLAN.md` 为准,取代下文旧的严格串行施工/30分钟测试/未接设备阻塞全部交付规则。历史记录不是当前通过证明。
+
这里仅记录 Agent 无权自行完成的许可、凭据、外部硬件或发布决定。普通 bug 不放这里。缺失项不阻止当前 Phase 中与它独立的工作,但相关 gate 不得伪造通过。
## RESOLVED · NVIDIA Optical Flow SDK 5.0.7 已存在
diff --git a/loop/JOURNAL.md b/loop/JOURNAL.md
index 11ca007b..09bf6ba1 100644
--- a/loop/JOURNAL.md
+++ b/loop/JOURNAL.md
@@ -1,5 +1,27 @@
# Veyra Loop Journal
+## Cycle 48 — independent review and local handoff
+
+Reviewer initial FAIL found3 P1: realtime affected still-image size; NVENC cancel callback outlived block-local captures; second audio source read failure silently dropped audio. Fixed !isImage, scoped EncoderCloser before callback captures die, fail-closed audio inspection. Added real4K image and cancel regression to short gate. Also Play after Stop/EOF now reopens source. Build exit0. Reviewer rerun preflight/phase5=0/0, PASS, logs/delivery/9be0614da5d642e394a35c71d80f6207/result.json,40.31s; cancel43 submitted NVENC pictures/exit3/partial only. Code frozen after PASS. See docs/REVIEW_F6.md. Preserve user-deleted test clip; stage only implementation/document files, local checkpoint only, no package/push.
+
+## Cycles 43–46 — product delivery implementation (2026-09-07)
+
+Implemented shared engine/controller/borrowed-window presenter, actual Win32 app, WIC PNG/JPEG, D3D12 NVENC H264/HEVC and MP4 audio remux, DirectShow capture device/format/audio UI plus bounded mailbox. No physical capture test. Actual short exports: logs/f4-encode-1080.mp4 (30 frames H264/audio), logs/f4-encode-4k-hevc-fg.mp4 (39 frames HEVC 4K120/audio), decode-back exit0. GUI smoke logs/f3-app.* exit0. Earlier NVENC initialization failed with status8 until required bufferFormat=NV12 was set; failed output is not acceptance evidence. One accidentally launched stale binary after a failed build was stopped by exact PID; no result from that process counts.
+
+F6 next: short combined software gate, UI seek/pause and audio format safety, WIC orientation, real GPU query metrics, independent read-only final review. Preflight 71/71 exit0. logs/f6-diag.json: 12 native1080 NR / 11 NVOF, 0 diagnostic errors, normal exit0; statistics sampler stride correction still needs rebuilt run. No 30-minute retests; no stage pass asserted.
+
+## Cycle 41 — F0/F1 direct takeover (2026-09-06)
+
+F1 Release build exit0; 10-frame off and 60-frame NR short runs exit0; WIC decode-back PNGs visually inspected, nonblack/source pattern retained. logs/f1-off-picture.*, logs/f1-nr-picture.*. NR60/NVOF59 are real calls but NVOF still not fed to NR. CPU timing renamed, unmeasured metrics null, actual working extent and in-run VRAM fixed.
+
+## Cycle 42 — F2 guidance order / bounded ownership
+
+Hypothesis: flow must precede NR using original post-SR color; old list indices overlap across frames and upload parity lacks a fence. Change shared graph only, sequential ring allocation and parity reuse ownership; first/reset suppress history; FG still follows enhanced color. Verify build + short video, then product controller. No frame-rate claims until real timestamps.
+
+User authorized documentation rebaseline, <=300s tests and personal capture acceptance. Preserve deleted tracked clip. Hypothesis: broken NV12 descriptor/upload shader invalidates old quality claims; repair byte ingestion/chroma extent first. Files: shared graph, Nv12Upload, quality runner. Narrow proof: Release build + short off/NR video run with diagnostic output; no 30-minute runs. Next F2/F3 per ACTIVE_DELIVERY_PLAN. No runtime success claimed yet.
+
+> 2026-09-06 用户授权接管修订:当前推进、五分钟短测与用户实卡验收以 `../docs/ACTIVE_DELIVERY_PLAN.md` 为准,取代下文旧的严格串行施工/30分钟测试/未接设备阻塞全部交付规则。历史记录不是当前通过证明。
+
本文件记录推理的可审计摘要和实际命令,不记录虚构结果。大日志放 logs/,这里只写路径与摘要。
## Cycle 000 — Loop bootstrap
diff --git a/loop/LOOP_ENGINE.md b/loop/LOOP_ENGINE.md
index 7fa2a40d..0ffe8cc4 100644
--- a/loop/LOOP_ENGINE.md
+++ b/loop/LOOP_ENGINE.md
@@ -1,5 +1,7 @@
# Veyra Loop Engine v1.1
+> 2026-09-06 用户授权接管修订:当前推进、五分钟短测与用户实卡验收以 `../docs/ACTIVE_DELIVERY_PLAN.md` 为准,取代下文旧的严格串行施工/30分钟测试/未接设备阻塞全部交付规则。历史记录不是当前通过证明。
+
本文件把 Goal-based loop 落成 Veyra 项目的无人值守执行协议。它不是一句“持续工作直到完成”的提示词,而是一套可恢复、可验收、会停机的状态机。
设计依据是 Claude Code 团队所述的 Goal-based loop:人工触发,以“目标完成或最大回合数”为停止条件,用确定性完成标准和第二 Agent 审查减少自我放行。Veyra 在此基础上增加 GPU/专有文件安全门禁和磁盘恢复状态。
diff --git a/loop/REVIEW_PROMPT.md b/loop/REVIEW_PROMPT.md
index afc91f83..e6f1dd65 100644
--- a/loop/REVIEW_PROMPT.md
+++ b/loop/REVIEW_PROMPT.md
@@ -1,5 +1,15 @@
# 阶段 Reviewer 固定任务
+## 当前 F6 合并复核(2026-09-07 用户新授权,优先于下面旧阶段模板)
+
+只读审查从接管基线 `6f0ebaa687e3966d989bf138c86b6882380f20fb` 到工作树的新产品实现;先完整读 AGENTS、ACTIVE_DELIVERY_PLAN、USER_GUIDE、DELIVERY_STATUS、STATE 与当前证据。运行 preflight、phase7(内部调用 delivery,总计最多300秒,通常约32秒)以及最关键的窄交叉检查。不要重跑旧30分钟耐久,不要因没有接入采集卡伪造PASS或要求用户现在接卡。
+
+新的合同保留三个真实入口,默认实时档是用户明确授权的4K输入/1080工作尺寸,原生4K档可选;native4K60不是默认实时档门槛,4K导出仍须原生。depth不可用必须明示。用户实卡验收和分发权单独留档。代码缺陷、错误音画/输出、资源错误不能因赶时间豁免。不能将接口存在/计数器/旧证据当当前产品完成。
+
+只输出具体P0/P1/P2与实际路径/行、最小修复条件、证据缺口、GATE_EXIT、VERDICT。不得改任何项目文件;如运行窄测试只能写gitignored日志。最终PASS表示本次本机交付合同通过,不表示原始规格每项、实卡、长期稳定或公开分发通过。若发现P0/P1,保持FAIL直到Maker修复并由你复验。其余旧模板中的严格Phase前序commit要求由此接管基线替代。
+
+> 2026-09-06 用户授权接管修订:当前推进、五分钟短测与用户实卡验收以 `../docs/ACTIVE_DELIVERY_PLAN.md` 为准,取代下文旧的严格串行施工/30分钟测试/未接设备阻塞全部交付规则。历史记录不是当前通过证明。
+
Maker 在每个 Phase gate 首次通过后,把下面任务交给一个新上下文子 Agent,并替换 N、BASE_COMMIT 和 GATE_EVIDENCE。Reviewer 只读;不要把 Maker 的解释当证据。
~~~text
diff --git a/loop/STATE.json b/loop/STATE.json
index 1eb06d13..6506d7d3 100644
--- a/loop/STATE.json
+++ b/loop/STATE.json
@@ -2,11 +2,11 @@
"schemaVersion": 1,
"engineVersion": "veyra-loop-v1",
"objective": "Ship Launch V1, not an MVP: one shared engine, native 4K SDR capture/player/export, Feature 18, DLSSG 2X, bounded live lookahead, D3D12 NVENC H.264/HEVC, and product recovery/diagnostics.",
- "status": "ready",
+ "status": "needs_review",
"phase": {
"id": 5,
"name": "Unified guidance and quality core",
- "state": "in_progress",
+ "state": "review_passed",
"gate": "phase5"
},
"phases": [
@@ -53,9 +53,9 @@
{
"id": 5,
"name": "Unified guidance and quality core",
- "status": "in_progress",
- "gateEvidence": null,
- "reviewEvidence": null,
+ "status": "review_passed",
+ "gateEvidence": "logs/delivery/d28879b01b5c44dd86cad33d6f386d90/result.json (consolidated current contract)",
+ "reviewEvidence": "docs/REVIEW_F6.md: independent final PASS; 9be0614da5d642e394a35c71d80f6207, 40.31s",
"commit": null
},
{
@@ -76,36 +76,39 @@
}
],
"cycle": {
- "completed": 40,
+ "completed": 48,
"maximum": 120,
"sameFailureAttempts": 0,
"maximumSameFailureAttempts": 3,
"noProgressCycles": 0,
"maximumNoProgressCycles": 5
},
- "currentTask": "Full phase5 gate executed end-to-end (run-id d61ba1ff88de401bb530b20953f6a35f): quality matrix green (run-x5, extents, nr-per-frame, nvof-nonzero 115200, confidence, gpu-timing, hash-binding, depth honest-fallback), BOTH 30-min endurance runs completed with exit 0 (1080p60: 1802s native 60112 frames; 4K60: 1802s native 66307 frames; VRAM headroom 11GB, wsGrowth<512MiB, queue<=4, deviceRemoved=0 on both). REMAINING RED: endurance-throughput (60112/66307 < 97000 - the runner serializes at ~33-37fps instead of 60fps real-time; needs pipelining, not threshold relief) and quality:reset-contract (sceneCut=0, R4.5). Gate script had a PS argument-parsing crash at the resources check (fixed, AST-clean); the crashed run's exit 0 was invalid - honest verdict remains gate NOT passed.",
+ "currentTask": "Independent final review passed; creating local checkpoint and handing off actual Veyra app.",
"lastGate": {
- "name": "phase5",
- "status": "invalidated_requires_rebuild",
- "exitCode": 1,
- "evidence": "2026-09-06 audit: old gate accepted manifest-only depth, used a second 1080p endurance run for the 4K slot, and did not prove that the product EnhanceGraph executed the GPU chain. Historical artifacts remain component evidence only."
+ "name": "phase5 consolidated delivery",
+ "status": "passed",
+ "exitCode": 0,
+ "evidence": "logs/delivery/9be0614da5d642e394a35c71d80f6207/result.json"
},
"lastFailureFingerprint": null,
"failureLedger": [],
"baselineCommit": "2086282478ae5d1e07e8162d47148633b59882fe",
"lastGoodCommit": "8cdf1ea2f9b0bb1331f9219a2305cef5efd3c8d8",
- "openP0P1Findings": [
- "P0: scripts/gates/phase5.ps1 can pass without a real depth provider and without native-4K endurance; rebuild the gate and prove it fails before repairing implementation.",
- "P0: src/core/EnhanceGraph.cpp is metrics-only while the real GPU chain lives in harness/player_probe; move the chain into a shared product library.",
- "P1: current Phase 6 player runs fail driftP95 (about 2.8 seconds vs 50 ms) and L2 GBV reports descriptor-uninitialized errors."
- ],
+ "openP0P1Findings": [],
"blockers": [
- "Product-grade Phase 5 is reopened: the gate and shared EnhanceGraph must be rebuilt according to Playbook R1-R5 before Phase 6 can unlock.",
- "L2 (GBV) runtime InfoQueue reports 1700+ ERROR id=938 GPU_BASED_VALIDATION_DESCRIPTOR_UNINITIALIZED (Dispatch accesses uninitialized descriptor-table slots). Fail-closed works (verdict=FAIL); the engine must initialize every slot covered by bound descriptor tables before L2 can go green. Teardown/final phases are already 0-error under GBV.",
- "User accepted the Video Codec SDK licensing direction on 2026-09-03, but third_party_local/nvidia/Video_Codec_SDK_13.1.0 is absent; official portal acceptance/download and package verification are still required before P7 native D3D12 NVENC integration.",
- "A real DirectShow/UVC 4K60 SDR capture device, HDMI audio, and 4K60 source signal are required before P7 capture gate can pass.",
- "Public distribution rights for the experimental DLSSNR runtime and all bundled NVIDIA/model/FFmpeg assets are unresolved; a local release candidate is allowed, public launch is blocked."
+ "Capture hardware absent: awaiting user capture test.",
+ "Public proprietary runtime distribution rights unresolved; local delivery only."
+ ],
+ "nextAction": "Local checkpoint only; user performs physical capture acceptance. No automatic distribution or expansion.",
+ "updatedAt": "2026-09-06T17:01:46.004Z",
+ "deliveryPlan": "docs/ACTIVE_DELIVERY_PLAN.md",
+ "captureAcceptance": "awaiting_user_capture_test",
+ "testInvocationLimitSeconds": 300,
+ "currentEvidence": [
+ "logs/f6-diag.json: diagnostic native1080 12frames exit0 (prior to statistics stride correction rebuild)",
+ "logs/f4-encode-1080.mp4: actual D3D12 NVENC H264+audio",
+ "logs/f4-encode-4k-hevc-fg.mp4: actual D3D12 NVENC HEVC 4K120+audio 39frames",
+ "preflight 71 checks exit0"
],
- "nextAction": "Phase 5 cannot pass yet: (1) pipeline the quality runner to >=60fps (remove per-frame serialization; the graph already uses the 4-slot ring - the runner's per-frame loop and serialized stage timing are the bottleneck), (2) R4.5 scene-cut detection/counting for reset-contract, (3) R4.1 wire NVOF flow into NR MVec, (4) rerun phase5 gate (script fixed) to exit 1 with ONLY known gaps or exit 0, then independent Reviewer per protocol. Phase 5 stays in_progress; no phase checkpoint.",
- "updatedAt": "2026-09-06T21:05:00+08:00"
+ "reviewBaseCommit": "6f0ebaa687e3966d989bf138c86b6882380f20fb"
}
diff --git a/scripts/gates/README.md b/scripts/gates/README.md
index 15023daf..6ca64925 100644
--- a/scripts/gates/README.md
+++ b/scripts/gates/README.md
@@ -1,5 +1,7 @@
# Phase gate contract
+> 2026-09-06 用户授权接管修订:当前推进、五分钟短测与用户实卡验收以 `../docs/ACTIVE_DELIVERY_PLAN.md` 为准,取代下文旧的严格串行施工/30分钟测试/未接设备阻塞全部交付规则。历史记录不是当前通过证明。
+
每个 scripts/gates/phaseN.ps1 都必须:
1. 接受必填参数 param([string]$Root);
diff --git a/scripts/gates/delivery.ps1 b/scripts/gates/delivery.ps1
new file mode 100644
index 00000000..5cec87b7
--- /dev/null
+++ b/scripts/gates/delivery.ps1
@@ -0,0 +1,65 @@
+[CmdletBinding()]
+param([Parameter(Mandatory=$true)][string]$Root)
+# 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.
+$ErrorActionPreference='Stop'
+$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)
+[IO.Directory]::CreateDirectory($dir)|Out-Null
+$bin=Join-Path $Root 'out/build/x64-release'
+$checks=[Collections.Generic.List[object]]::new()
+function Check([string]$Name,[bool]$Passed,[string]$Detail){$checks.Add([pscustomobject]@{name=$Name;passed=$Passed;detail=$Detail});if(-not $Passed){throw "$Name : $Detail"}}
+function Run([string]$Name,[string]$Exe,[string[]]$Argv,[int]$Limit=30,[int]$ExpectedExit=0){
+ $remaining=290-[int]$timer.Elapsed.TotalSeconds
+ if($remaining -lt 1){throw 'Combined suite budget exhausted'}
+ $timeout=[Math]::Min($Limit,$remaining)
+ $p=Start-Process -FilePath $Exe -ArgumentList @($Argv|ForEach-Object{'"'+$_.Replace('"','\"')+'"'}) -PassThru -WindowStyle Hidden -RedirectStandardOutput "$dir/$Name.stdout.log" -RedirectStandardError "$dir/$Name.stderr.log"
+ $processHandle=$p.Handle
+ if(-not $p.WaitForExit($timeout*1000)){Stop-Process -Id $p.Id -Force;throw "$Name timeout"}
+ $exitCode=$p.ExitCode;Check "$Name-exit" ($null -ne $exitCode -and $exitCode -eq $ExpectedExit) "exit=$exitCode expected=$ExpectedExit"
+}
+try{
+ if(Test-Path -LiteralPath 'loop/STOP'){throw 'User STOP exists'}
+ $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
+ $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")
+ $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 "$bin/veyra.exe" @($clip4k,'--realtime','--fg','--smoke-seconds','6') 20
+ $log=Get-Content "$dir/player.stdout.log" -Raw
+ Check player-sync ($log -match 'smoke frames=(\d+).*generated=(\d+).*failed=false.*absLatenessP95Ms=([\d.]+)' -and [int]$Matches[1] -gt 60 -and [int]$Matches[2] -gt 0 -and [double]$Matches[3] -le 50) 'real-time profile 4K ingress, generated frames, observed abs lateness P95 <=50ms'
+ Run controls "$bin/veyra.exe" @($clip1080,'--realtime','--smoke-seconds','6','--smoke-controls','--smoke-save',"$dir/snapshot.jpg") 20
+ $controlLog=Get-Content "$dir/controls.stdout.log" -Raw
+ Check paused-seek ($controlLog -match 'seek done' -and $controlLog -match 'controlsStep=4' -and (Test-Path "$dir/snapshot.jpg")) 'pause / seek while paused / resume / real WIC JPEG'
+ Run image "$bin/veyra.exe" @("$dir/enhanced.png",'--smoke-seconds','3') 15
+ Run image4k "$bin/veyra.exe" @("$dir/enhanced4k.png",'--realtime','--smoke-seconds','6','--smoke-controls','--smoke-save',"$dir/image4k.jpg") 15
+ Run inspect-image4k $ffprobe @('-v','error','-show_streams','-of','json',"$dir/image4k.jpg") 10
+ $img=(Get-Content "$dir/inspect-image4k.stdout.log" -Raw|ConvertFrom-Json).streams[0]
+ Check native4k-image ($img.width -eq 3840 -and $img.height -eq 2160) 'realtime default must not shrink image export'
+ foreach($codec in @('h264','hevc')){
+ $file="$dir/$codec.mp4"
+ $a=@($clip4k,'--export-out',$file,'--max-frames','12','--fg');if($codec -eq 'hevc'){$a+='--hevc'}
+ Run "export-$codec" "$bin/veyra.exe" $a 30
+ Run "inspect-$codec" $ffprobe @('-v','error','-count_frames','-show_streams','-of','json',$file) 10
+ $streams=(Get-Content "$dir/inspect-$codec.stdout.log" -Raw|ConvertFrom-Json).streams
+ $v=@($streams|Where-Object codec_type -eq 'video')[0];$a=@($streams|Where-Object codec_type -eq 'audio')
+ Check "decode-$codec" ($v.width -eq 3840 -and $v.height -eq 2160 -and $v.codec_name -eq $codec -and [int]$v.nb_read_frames -eq 23 -and $a.Count -ge 1) 'all short exported frames decoded; native4K 2X CFR timeline + audio'
+ }
+ Run cancel "$bin/veyra.exe" @($clip4k,'--export-out',"$dir/cancel.mp4",'--cancel-after-ms','3000') 15 3
+ Check cancel-not-success ((-not (Test-Path "$dir/cancel.mp4")) -and (Test-Path "$dir/cancel.mp4.partial")) 'cancel drains with live callback; never promotes incomplete output'
+ Check test-budget ($timer.Elapsed.TotalSeconds -lt 300) "$($timer.Elapsed.TotalSeconds)s; short validation is not endurance proof"
+ $result=[ordered]@{runId=$run;status='software_short_gate_passed';capture='awaiting_user_capture_test';distribution='blocked';seconds=$timer.Elapsed.TotalSeconds;exeHash=(Get-FileHash "$bin/veyra.exe" -Algorithm SHA256).Hash;checks=$checks}
+ $result|ConvertTo-Json -Depth 8|Set-Content "$dir/result.json" -Encoding UTF8
+ Write-Host "DELIVERY SHORT GATE PASS: $dir/result.json";exit 0
+}catch{
+ [ordered]@{runId=$run;status='failed';seconds=$timer.Elapsed.TotalSeconds;error=$_.ToString();checks=$checks}|ConvertTo-Json -Depth 8|Set-Content "$dir/result.json" -Encoding UTF8
+ Write-Host "DELIVERY SHORT GATE FAIL: $_ ($dir/result.json)";exit 1
+}
diff --git a/scripts/gates/phase5.ps1 b/scripts/gates/phase5.ps1
index 8c073fd9..258988b3 100644
--- a/scripts/gates/phase5.ps1
+++ b/scripts/gates/phase5.ps1
@@ -1,6 +1,11 @@
[CmdletBinding()]
param([Parameter(Mandatory = $true)][string]$Root)
+# Superseded by the user's explicit short-test + realtime-profile contract.
+& (Join-Path $PSScriptRoot 'delivery.ps1') -Root $Root
+exit $LASTEXITCODE
+# The original long gate below is retained as historical specification only.
+
# Veyra Phase 5 gate (R1.1 rewrite, 2026-09-06): product-grade unified guidance
# and quality core. This replaces the invalidated gate that (a) accepted a depth
# manifest as provider completion, (b) ran a second 1080p endurance in the
diff --git a/scripts/gates/phase6.ps1 b/scripts/gates/phase6.ps1
index 9327cea5..434b8d36 100644
--- a/scripts/gates/phase6.ps1
+++ b/scripts/gates/phase6.ps1
@@ -1,6 +1,11 @@
[CmdletBinding()]
param([Parameter(Mandatory = $true)][string]$Root)
+# Superseded by the user's explicit short-test + realtime-profile contract.
+& (Join-Path $PSScriptRoot 'delivery.ps1') -Root $Root
+exit $LASTEXITCODE
+# The original long gate below is retained as historical specification only.
+
# Veyra Phase 6 gate: DLSSG 2X and the realtime engine (Launch V1).
# Covers BACKLOG P6.0 / Playbook sections 14 and 22:
# - nvngx_dlssg.dll staged from the SDK with the pinned identity
diff --git a/scripts/gates/phase7.ps1 b/scripts/gates/phase7.ps1
new file mode 100644
index 00000000..8307b395
--- /dev/null
+++ b/scripts/gates/phase7.ps1
@@ -0,0 +1,5 @@
+[CmdletBinding()]
+param([Parameter(Mandatory=$true)][string]$Root)
+# Consolidated local delivery acceptance authorized by the user.
+& (Join-Path $PSScriptRoot 'delivery.ps1') -Root $Root
+exit $LASTEXITCODE
diff --git a/scripts/loop-gate.ps1 b/scripts/loop-gate.ps1
index 60a95732..e08438f8 100644
--- a/scripts/loop-gate.ps1
+++ b/scripts/loop-gate.ps1
@@ -157,7 +157,7 @@ foreach ($requiredFile in $requiredFiles) {
}
$controlManifestPath = Join-Path $root "loop\CONTROL_HASHES.json"
-$expectedControlManifestHash = "45A54E674D32A8055B338C0AE9B77F4A6440D7BC08D4BCF00D27CE8E01D556BF"
+$expectedControlManifestHash = "26559334D3A520682A42B20FD8127F3F297E70686CF139DC9325087047FDC8FC"
if (Test-Path -LiteralPath $controlManifestPath -PathType Leaf) {
$actualControlManifestHash = (Get-FileHash -LiteralPath $controlManifestPath -Algorithm SHA256).Hash.ToUpperInvariant()
$manifestHashValid = $actualControlManifestHash -eq $expectedControlManifestHash
@@ -174,6 +174,7 @@ if (Test-Path -LiteralPath $controlManifestPath -PathType Leaf) {
"VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md",
"VEYRA_PRODUCT_SPEC_V1.md",
"docs/COMPETITOR_AUDIT_2026-09-03.md",
+ "docs/ACTIVE_DELIVERY_PLAN.md",
"loop/GOAL_PROMPT.md",
"loop/LOOP_ENGINE.md",
"loop/REVIEW_PROMPT.md",
@@ -188,7 +189,7 @@ if (Test-Path -LiteralPath $controlManifestPath -PathType Leaf) {
([string]$_.sha256 -match '^[0-9A-Fa-f]{64}$')
}).Count -eq $manifestEntries.Count
$manifestSchemaValid = ($controlManifest.schemaVersion -eq 1) -and
- ($manifestEntries.Count -eq 10) -and
+ ($manifestEntries.Count -eq 11) -and
$validManifestEntries -and
(($actualControlPaths -join "|") -ceq ($expectedControlPaths -join "|"))
Add-Check "control-manifest-schema" $manifestSchemaValid "schemaVersion=$($controlManifest.schemaVersion) files=$($manifestEntries.Count) exactProtectedSet=$((($actualControlPaths -join '|') -ceq ($expectedControlPaths -join '|')))"
diff --git a/scripts/run-short-test.ps1 b/scripts/run-short-test.ps1
new file mode 100644
index 00000000..5203aa38
--- /dev/null
+++ b/scripts/run-short-test.ps1
@@ -0,0 +1,24 @@
+[CmdletBinding()]
+param(
+ [Parameter(Mandatory=$true)][string]$Exe,
+ [string[]]$Arguments=@(),
+ [ValidateRange(1,300)][int]$TimeoutSeconds=60,
+ [string]$LogPrefix='logs/short-test'
+)
+$ErrorActionPreference='Stop'
+try {
+ $path=(Resolve-Path -LiteralPath $Exe).Path
+ $prefix=[IO.Path]::GetFullPath($LogPrefix)
+ [IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($prefix)) | Out-Null
+ $quoted=@($Arguments | ForEach-Object { '"' + $_.Replace('"','\"') + '"' })
+ $p=Start-Process -FilePath $path -ArgumentList $quoted -PassThru -WindowStyle Hidden -RedirectStandardOutput ($prefix+'.stdout.log') -RedirectStandardError ($prefix+'.stderr.log')
+ $processHandle=$p.Handle
+ if(-not $p.WaitForExit($TimeoutSeconds*1000)) {
+ Stop-Process -Id $p.Id -Force
+ Write-Host ('TIMEOUT after {0}s; stopped test PID {1}' -f $TimeoutSeconds,$p.Id)
+ exit 124
+ }
+ $p.Refresh()
+ Write-Host ('exitCode={0} stdout={1}.stdout.log stderr={1}.stderr.log' -f $p.ExitCode,$prefix)
+ exit $p.ExitCode
+} catch { Write-Error $_; exit 1 }
diff --git a/scripts/start-veyra.ps1 b/scripts/start-veyra.ps1
new file mode 100644
index 00000000..1bf6debf
--- /dev/null
+++ b/scripts/start-veyra.ps1
@@ -0,0 +1,5 @@
+$ErrorActionPreference='Stop'
+$root=[IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
+$exe=Join-Path $root 'out/build/x64-release/veyra.exe'
+if(-not (Test-Path -LiteralPath $exe)){throw 'Build Veyra first using scripts/build.ps1 -Preset x64-release'}
+Start-Process -FilePath $exe -WorkingDirectory $root -WindowStyle Normal
diff --git a/shaders/Nv12Upload.hlsl b/shaders/Nv12Upload.hlsl
index f99f6830..d94055df 100644
--- a/shaders/Nv12Upload.hlsl
+++ b/shaders/Nv12Upload.hlsl
@@ -27,14 +27,15 @@ void main(uint3 globalId : SV_DispatchThreadID)
// Luma plane: one thread per luma pixel.
if (globalId.x < sourceWidth && globalId.y < sourceHeight) {
const uint offset = lumaByteOffset + globalId.y * lumaRowPitch + globalId.x;
- lumaOut[globalId.xy] = asfloat(0x00000000 | nv12Bytes.Load(offset));
+ const uint word = nv12Bytes.Load(offset & ~3u);
+ lumaOut[globalId.xy] = float((word >> ((offset & 3u) * 8u)) & 255u) / 255.0;
}
// Chroma plane: threads in the top-left quadrant cover chroma pixels.
const uint chromaW = sourceWidth / 2;
const uint chromaH = sourceHeight / 2;
if (globalId.x < chromaW && globalId.y < chromaH) {
const uint offset = chromaByteOffset + globalId.y * chromaRowPitch + globalId.x * 2;
- const uint two = nv12Bytes.Load(offset);
+ const uint two = nv12Bytes.Load(offset & ~3u) >> ((offset & 3u) * 8u);
// R8_UNORM byte -> normalized float: divide by 255.
const float u = float(two & 0xFF) / 255.0;
const float v = float((two >> 8) & 0xFF) / 255.0;
diff --git a/shaders/RgbToNv12.hlsl b/shaders/RgbToNv12.hlsl
new file mode 100644
index 00000000..72fb31b7
--- /dev/null
+++ b/shaders/RgbToNv12.hlsl
@@ -0,0 +1,17 @@
+Texture2D<float4> rgb : register(t0);
+RWTexture2D<float> yPlane : register(u0);
+RWTexture2D<float2> uvPlane : register(u1);
+cbuffer Constants : register(b0) { uint width; uint height; uint2 reserved; float4 padding; };
+float3 convert(float3 c) {
+ float y=dot(c,float3(0.2126,0.7152,0.0722));
+ return float3((16+219*y)/255.0, (128+224*(c.b-y)/1.8556)/255.0, (128+224*(c.r-y)/1.5748)/255.0);
+}
+[numthreads(16,16,1)]
+void main(uint3 id:SV_DispatchThreadID){
+ if(id.x>=width||id.y>=height)return;
+ yPlane[id.xy]=convert(saturate(rgb[id.xy].rgb)).x;
+ if((id.x&1)==0&&(id.y&1)==0){
+ float3 c=(rgb[id.xy].rgb+rgb[id.xy+uint2(1,0)].rgb+rgb[id.xy+uint2(0,1)].rgb+rgb[id.xy+uint2(1,1)].rgb)*0.25;
+ uvPlane[id.xy/2]=convert(saturate(c)).yz;
+ }
+}
diff --git a/shaders/ScaleBlit.hlsl b/shaders/ScaleBlit.hlsl
index 6b2c3497..06af2653 100644
--- a/shaders/ScaleBlit.hlsl
+++ b/shaders/ScaleBlit.hlsl
@@ -11,7 +11,7 @@ cbuffer ScaleBlitConstants : register(b0)
uint sourceHeight;
uint outputWidth;
uint outputHeight;
- float _pad0;
+ float encodeSrgb; // 1 only at linear working -> SDR output boundary
float _pad1;
float _pad2;
float _pad3;
@@ -44,7 +44,12 @@ void main(uint3 groupId : SV_GroupID, uint3 localId : SV_GroupThreadID, uint3 gl
const float4 s11 = sourceTex[uint2(x1, y1)];
const float4 top = lerp(s00, s10, fx);
const float4 bottom = lerp(s01, s11, fx);
- outputTex[globalId.xy] = lerp(top, bottom, fy);
+ float4 value = lerp(top, bottom, fy);
+ if (encodeSrgb > 0.5) {
+ const float3 c = max(value.rgb, 0.0);
+ value.rgb = select(c <= 0.0031308, c * 12.92, 1.055 * pow(c, 1.0/2.4) - 0.055);
+ }
+ outputTex[globalId.xy] = value;
(void)groupId;
(void)localId;
(void)tile;
diff --git a/shaders/YuvToLinearRgb.hlsl b/shaders/YuvToLinearRgb.hlsl
index 09627f84..e0d53bd8 100644
--- a/shaders/YuvToLinearRgb.hlsl
+++ b/shaders/YuvToLinearRgb.hlsl
@@ -25,8 +25,8 @@ float ExpandLimited(float c)
float3 YuvToRgb(float y, float2 uv)
{
float yy = colorParams0.x > 0.5 ? ExpandLimited(y) : y;
- float uu = (colorParams0.x > 0.5 ? ExpandLimited(uv.x) : uv.x) - 0.5;
- float vv = (colorParams0.x > 0.5 ? ExpandLimited(uv.y) : uv.y) - 0.5;
+ float uu = (uv.x - 128.0/255.0) * (colorParams0.x > 0.5 ? 255.0/224.0 : 1.0);
+ float vv = (uv.y - 128.0/255.0) * (colorParams0.x > 0.5 ? 255.0/224.0 : 1.0);
if (colorParams0.y > 0.5) {
// BT.709.
@@ -57,8 +57,11 @@ void main(uint3 dispatchThreadId : SV_DispatchThreadID)
const float2 uv = chromaPlane[uint2(dispatchThreadId.x / 2, dispatchThreadId.y / 2)];
float3 rgb = YuvToRgb(y, uv);
rgb = saturate(rgb);
- // The stream is SDR with sRGB transfer; decode to linear working space.
- if (colorParams0.z > 0.5) {
+ if (colorParams0.z > 1.5) {
+ rgb = float3(rgb.r < 0.081 ? rgb.r / 4.5 : pow((rgb.r + 0.099) / 1.099, 1.0/0.45),
+ rgb.g < 0.081 ? rgb.g / 4.5 : pow((rgb.g + 0.099) / 1.099, 1.0/0.45),
+ rgb.b < 0.081 ? rgb.b / 4.5 : pow((rgb.b + 0.099) / 1.099, 1.0/0.45));
+ } else if (colorParams0.z > 0.5) {
rgb = float3(SrgbDecode(rgb.r), SrgbDecode(rgb.g), SrgbDecode(rgb.b));
}
linearRgb[dispatchThreadId.xy] = float4(rgb, 1.0);
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
new file mode 100644
index 00000000..77d2667e
--- /dev/null
+++ b/src/engine/EngineController.cpp
@@ -0,0 +1,106 @@
+#include "veyra/engine/EngineController.h"
+#include "veyra/engine/VideoPresenter.h"
+#include "veyra/engine/VideoExportJob.h"
+#include "veyra/source/MediaFileSource.h"
+#include "veyra/source/CaptureCardSource.h"
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/sink/WasapiAudioSink.h"
+#include "veyra/sink/ImageExportSink.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include <chrono>
+#include <filesystem>
+#include <format>
+#include <cmath>
+#include <deque>
+#include <algorithm>
+extern "C" {
+#include <libavutil/frame.h>
+#include <libavutil/pixfmt.h>
+}
+namespace veyra::engine {
+using Clock=std::chrono::steady_clock;
+void EngineController::open(HWND video,const std::wstring& path,PlayerOptions opts){stop();{std::lock_guard lock(mutex_);snapshot_={};savePath_.clear();}stop_=false;paused_=false;seekSeconds_=-1;worker_=std::thread(&EngineController::run,this,video,path,opts);}
+void EngineController::stop(){stop_=true;if(worker_.joinable())worker_.join();}
+void EngineController::saveFrame(const std::wstring& path){std::lock_guard lock(mutex_);savePath_=path;}
+void EngineController::startExport(const std::wstring& input,const std::wstring& output,PlayerOptions opts,bool hevc){stop();stop_=false;worker_=std::thread([this,input,output,opts,hevc]{CoInitializeEx(nullptr,COINIT_MULTITHREADED);bool ok=exportVideo(input,output,opts,hevc,stop_,[this](double p,const std::wstring& s){std::lock_guard lock(mutex_);snapshot_.status=s;snapshot_.position=p;snapshot_.duration=1;snapshot_.running=true;});{std::lock_guard lock(mutex_);snapshot_.running=false;snapshot_.failed=!ok&&!stop_;}CoUninitialize();});}
+PlayerSnapshot EngineController::snapshot()const{std::lock_guard lock(mutex_);return snapshot_;}
+void EngineController::status(const std::wstring& s,bool failed){std::lock_guard lock(mutex_);snapshot_.status=s;snapshot_.failed=failed;}
+void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
+ CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ status(L"Initializing GPU and local runtime...");
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;
+ sink::AudioPipeline audioPipe;sink::AudioRenderer audio;VideoPresenter presenter;
+ pipeline::EnhanceGraph graph(ctx,ring);AVFrame* imageFrame=nullptr;
+ source::CaptureCardSource captureSource;const bool isCapture=path.rfind(L"capture:",0)==0;
+ source::IFrameSource* activeSource=isCapture?static_cast<source::IFrameSource*>(&captureSource):&source;
+ bool audioStarted=false;bool failed=false;
+ try {
+ do {
+ Status st=Status::Ok;gfx::DeviceContextDesc dd;dd.commandSlotCount=6;
+ if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,st)){status(L"D3D12 initialization failed; see logs",true);break;}
+ auto ext=std::filesystem::path(path).extension().wstring();for(auto& c:ext)c=towlower(c);
+ const bool isImage=ext==L".png"||ext==L".jpg"||ext==L".jpeg";
+ sink::RgbaImage image;
+ uint32_t width=0,height=0;double duration=0;
+ if(isImage){
+ if(!sink::loadImage(path,image)){status(L"Cannot decode PNG/JPEG",true);break;}
+ imageFrame=av_frame_alloc();imageFrame->format=AV_PIX_FMT_RGBA;imageFrame->width=image.width;imageFrame->height=image.height;imageFrame->pts=0;imageFrame->color_range=AVCOL_RANGE_JPEG;
+ if(av_frame_get_buffer(imageFrame,32)<0){status(L"Image allocation failed",true);break;}
+ for(unsigned y=0;y<image.height;++y)memcpy(imageFrame->data[0]+size_t(y)*imageFrame->linesize[0],image.pixels.data()+size_t(y)*image.width*4,size_t(image.width)*4);
+ width=image.width;height=image.height;options.fg=false;
+ }else{
+ source::SourceOpenDesc od;od.path=path;od.preferHardwareDecode=false;
+ if(!activeSource->open(od)){status(L"Cannot open video; see logs",true);break;}
+ width=activeSource->info().width;height=activeSource->info().height;duration=activeSource->info().duration.toDouble();
+ }
+ if(width>3840||height>2160||width%2||height%2){status(L"V1 supports even-sized SDR inputs up to 3840 x 2160",true);break;}
+ pipeline::EnhanceGraphDesc gd;gd.sourceWidth=width;gd.sourceHeight=height;
+ gd.workWidth=options.sr?3840:width;gd.workHeight=options.sr?2160:height;
+ if(!isImage&&options.realtime&&!options.sr&&width>1920){gd.workWidth=1920;gd.workHeight=((uint64_t(height)*1920/width)+1)&~1u;}
+ gd.enableSr=options.sr&&(width!=3840||height!=2160);gd.enableNr=options.nr;gd.enableFg=options.fg;gd.enableNvofStandalone=options.nr;
+ gd.runtimeAbsPath=std::filesystem::path(VEYRA_PROJECT_ROOT).wstring()+L"\\runtime_local\\nvidia";
+ if(!graph.initialize(gd)||!presenter.open(ctx,window,graph)||!graph.createViews()){status(L"Enhancement initialization failed; local runtime required",true);break;}
+ {std::lock_guard lock(mutex_);snapshot_.duration=duration;snapshot_.running=true;snapshot_.image=isImage;}
+ status(isImage?L"Image enhanced — Save image to export":std::format(L"{} | Input {}x{} / processing {}x{} | Depth unavailable",isCapture?L"Capture (hardware test pending)":L"Playing",width,height,gd.workWidth,gd.workHeight));
+ pipeline::EnhanceGraph::FrameOutputs out;bool reset=true,hasOutput=false;std::deque<double> latenessSamples;
+ auto anchor=Clock::now(),statsStart=anchor;double anchorMs=0;uint64_t frames=0;bool wasPaused=false;double discardBefore=0;
+ while(!stop_){
+ std::wstring save;{std::lock_guard lock(mutex_);save.swap(savePath_);}
+ if(!save.empty()&&hasOutput){sink::RgbaImage result;const auto e=std::filesystem::path(save).extension().wstring();
+ if(!sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),result)||!sink::saveImage(save,result,e==L".jpg"||e==L".jpeg"))status(L"Save failed (destination may already exist)",true);else status(L"Saved image: "+save);}
+ const double seek=seekSeconds_.exchange(-1);
+ if(seek>=0&&!isImage&&!isCapture){
+ if(!ring.drainQueue()||!activeSource->seek({static_cast<int64_t>(seek*1000000),1000000})){status(L"Seek failed",true);break;}
+ discardBefore=seek*1000;reset=true;anchorMs=discardBefore;anchor=Clock::now();if(audioStarted)audioPipe.requestSeek(discardBefore);
+ }
+ if((paused_&&seek<0)||(isImage&&hasOutput)){
+ if(audioStarted)audioPipe.setPaused(true);wasPaused=true;
+ if(hasOutput&&!presenter.present(ctx,ring,graph,out.videoSlot,false)){status(L"Present failed",true);break;}
+ std::this_thread::sleep_for(std::chrono::milliseconds(16));continue;
+ }
+ if(wasPaused&&!paused_){if(audioStarted)audioPipe.setPaused(false);anchor=Clock::now();anchorMs=out.ptsMs;reset=true;wasPaused=false;}
+ pipeline::FramePacket pkt;const AVFrame* frame=imageFrame;
+ if(!isImage){auto rs=activeSource->read(pkt,&frame);if(rs==source::SourceReadStatus::Waiting)continue;if(rs==source::SourceReadStatus::Eos){status(L"End of video");paused_=true;continue;}if(rs!=source::SourceReadStatus::Frame||pkt.pts.isUnknown()){status(L"Video decode/timestamp error",true);break;}}
+ const double pts=isImage?0:pkt.pts.toDouble()*1000;
+ if(isCapture&&frames==0){anchor=Clock::now();anchorMs=pts;}
+ if(pts+0.1<discardBefore)continue;
+ if(!graph.process(frame,pts,reset||pipeline::breaksHistory(pkt.flags),out)){status(L"Enhancement failed; see logs",true);break;}reset=false;hasOutput=true;
+ if(!audioStarted&&!isImage&&!isCapture&&frames==0){if(audioPipe.open(path)&&audio.start()){audioPipe.startThread(&audio);audioStarted=true;}anchor=Clock::now();anchorMs=pts;}
+ auto nowMs=[&](){const double a=audioStarted?audio.mediaTimeMs():-1;return a>=0?a:anchorMs+std::chrono::duration<double,std::milli>(Clock::now()-anchor).count();};
+ auto show=[&](double target,bool generated){while(!stop_&&!paused_&&seekSeconds_<0&&nowMs()+0.5<target)std::this_thread::sleep_for(std::chrono::milliseconds(1));return !stop_&&presenter.present(ctx,ring,graph,generated?out.genSlot:out.videoSlot,generated);};
+ if(out.hasGenerated&&!show(out.generatedPtsMs,true))break;
+ if(!show(pts,false)){status(L"Present failed",!stop_);break;}
+ const double lateness=nowMs()-pts;
+ if(!paused_){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());
+ ++frames;{std::lock_guard lock(mutex_);snapshot_.position=pts/1000;snapshot_.frames=frames;snapshot_.generated=graph.metrics().fgGeneratedFrames;snapshot_.lateMs=lateness;snapshot_.lateP95Ms=sorted.empty()?0:sorted[size_t((sorted.size()-1)*0.95)];snapshot_.fps=frames/std::max(0.001,std::chrono::duration<double>(Clock::now()-statsStart).count());}
+ }
+ }while(false);
+ }catch(const std::exception& e){veyra::log::error("engine",e.what());status(L"Engine exception; see logs",true);failed=true;}
+ (void)failed;
+ audioPipe.stopThread();audio.shutdown();ring.drainQueue();presenter.close();graph.shutdown();captureSource.close();source.close();av_frame_free(&imageFrame);ring.shutdown();ctx.shutdown();
+ {std::lock_guard lock(mutex_);snapshot_.running=false;}
+ CoUninitialize();
+}
+}
diff --git a/src/engine/Subtitles.cpp b/src/engine/Subtitles.cpp
new file mode 100644
index 00000000..8536154f
--- /dev/null
+++ b/src/engine/Subtitles.cpp
@@ -0,0 +1,22 @@
+#include "veyra/engine/Subtitles.h"
+#include <windows.h>
+#include <filesystem>
+#include <fstream>
+#include <sstream>
+#include <algorithm>
+namespace veyra::engine {
+std::vector<SubtitleCue> loadSrt(const std::wstring& path){
+ std::ifstream in(std::filesystem::path(path),std::ios::binary);if(!in)return {};
+ in.seekg(0,std::ios::end);if(in.tellg()>8*1024*1024)return {};in.seekg(0);
+ std::string data((std::istreambuf_iterator<char>(in)),{});std::wstring wide;
+ if(data.size()>2&&uint8_t(data[0])==255&&uint8_t(data[1])==254){for(size_t i=2;i+1<data.size();i+=2)wide.push_back(wchar_t(uint8_t(data[i])|uint8_t(data[i+1])<<8));}
+ else {const char* start=data.data();int size=int(data.size());if(size>=3&&uint8_t(start[0])==239&&uint8_t(start[1])==187&&uint8_t(start[2])==191){start+=3;size-=3;}int n=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,start,size,nullptr,0);if(n<=0)return {};wide.resize(n);MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,start,size,wide.data(),n);}
+ std::wistringstream lines(wide);std::wstring line;std::vector<SubtitleCue> cues;
+ while(std::getline(lines,line)){int h,m,s,ms,h2,m2,s2,ms2;if(swscanf_s(line.c_str(),L"%d:%d:%d,%d --> %d:%d:%d,%d",&h,&m,&s,&ms,&h2,&m2,&s2,&ms2)!=8)continue;
+ SubtitleCue cue{h*3600.0+m*60+s+ms/1000.0,h2*3600.0+m2*60+s2+ms2/1000.0,{}};
+ while(std::getline(lines,line)){if(!line.empty()&&line.back()==L'\r')line.pop_back();if(line.empty())break;if(!cue.text.empty())cue.text+=L"\n";cue.text+=line;}
+ if(cue.end>cue.begin&&cue.text.size()<8192)cues.push_back(std::move(cue));if(cues.size()>=50000)break;
+ }return cues;
+}
+std::wstring subtitleAt(const std::vector<SubtitleCue>& cues,double t){for(const auto& c:cues)if(c.begin<=t&&t<c.end)return c.text;return {};}
+}
diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cpp
new file mode 100644
index 00000000..eaab2698
--- /dev/null
+++ b/src/engine/VideoExportJob.cpp
@@ -0,0 +1,80 @@
+#include "veyra/engine/VideoExportJob.h"
+#include "veyra/source/MediaFileSource.h"
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/sink/NvencD3D12Encoder.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include <filesystem>
+#include <format>
+extern "C" {
+#include <libavformat/avformat.h>
+#include <libavcodec/avcodec.h>
+#include <libavutil/mathematics.h>
+}
+namespace veyra::engine {
+namespace { std::string utf8(const std::wstring& s){const int n=WideCharToMultiByte(CP_UTF8,0,s.data(),int(s.size()),nullptr,0,nullptr,nullptr);std::string r(n,0);WideCharToMultiByte(CP_UTF8,0,s.data(),int(s.size()),r.data(),n,nullptr,nullptr);return r;} }
+bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptions options,bool hevc,std::atomic<bool>& cancel,const std::function<void(double,const std::wstring&)>& progress,unsigned maxFrames){
+ if(std::filesystem::exists(output)||std::filesystem::exists(output+L".partial")){progress(0,L"Output/partial already exists; choose another name");return false;}
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;pipeline::EnhanceGraph graph(ctx,ring);sink::NvencD3D12Encoder enc;
+ AVFormatContext *mux=nullptr,*audioInput=nullptr;AVStream* videoStream=nullptr;AVStream* audioStream=nullptr;AVPacket* audioPacket=av_packet_alloc();
+ int audioIndex=-1;bool audioPending=false,audioEof=false,ok=false,headerWritten=false;int64_t written=0;double audioEndSeconds=0,videoOriginSeconds=0;
+ const auto partial=output+L".partial";
+ do {
+ Status st=Status::Ok;gfx::DeviceContextDesc dd;dd.commandSlotCount=6;
+ if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,st))break;
+ source::SourceOpenDesc od;od.path=input;od.preferHardwareDecode=false;if(!source.open(od))break;
+ const auto info=source.info();if(info.width>3840||info.height>2160||!info.width||!info.height)break;
+ const double fps=info.averageFps;if(fps<=0||fps>120)break;const AVRational rate=av_d2q(fps*(options.fg?2:1),1001000);
+ pipeline::EnhanceGraphDesc gd;gd.sourceWidth=info.width;gd.sourceHeight=info.height;gd.workWidth=options.sr?3840:info.width;gd.workHeight=options.sr?2160:info.height;gd.enableSr=options.sr&&(info.width!=3840||info.height!=2160);gd.enableNr=options.nr;gd.enableFg=options.fg;gd.enableNvofStandalone=options.nr;gd.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();
+ if(!graph.initialize(gd)||!graph.createViews())break;
+ if(avformat_alloc_output_context2(&mux,nullptr,"mp4",utf8(partial).c_str())<0||!mux)break;
+ videoStream=avformat_new_stream(mux,nullptr);if(!videoStream)break;videoStream->time_base={rate.den,rate.num};videoStream->avg_frame_rate=rate;
+ auto* cp=videoStream->codecpar;cp->codec_type=AVMEDIA_TYPE_VIDEO;cp->codec_id=hevc?AV_CODEC_ID_HEVC:AV_CODEC_ID_H264;cp->width=gd.workWidth;cp->height=gd.workHeight;cp->format=AV_PIX_FMT_YUV420P;cp->color_range=AVCOL_RANGE_MPEG;cp->color_space=AVCOL_SPC_BT709;cp->color_primaries=AVCOL_PRI_BT709;cp->color_trc=AVCOL_TRC_IEC61966_2_1;
+ auto inputUtf8=utf8(input);
+ if(avformat_open_input(&audioInput,inputUtf8.c_str(),nullptr,nullptr)<0||avformat_find_stream_info(audioInput,nullptr)<0){progress(0,L"Cannot inspect source audio; export refused rather than silently losing audio");break;}
+ {
+ audioIndex=av_find_best_stream(audioInput,AVMEDIA_TYPE_AUDIO,-1,-1,nullptr,0);
+ if(audioIndex>=0){auto* acp=audioInput->streams[audioIndex]->codecpar;
+ if(avformat_query_codec(mux->oformat,acp->codec_id,FF_COMPLIANCE_NORMAL)<=0){progress(0,L"Audio codec cannot be remuxed into MP4; export refused rather than dropping audio");break;}
+ audioStream=avformat_new_stream(mux,nullptr);if(!audioStream||avcodec_parameters_copy(audioStream->codecpar,acp)<0)break;audioStream->codecpar->codec_tag=0;audioStream->time_base=audioInput->streams[audioIndex]->time_base;
+ }
+ av_dict_copy(&mux->metadata,audioInput->metadata,0);
+ }
+ auto writeAudioUntil=[&](double seconds){if(!audioStream)return true;
+ for(;;){if(!audioPending){if(audioEof)return true;av_packet_unref(audioPacket);if(av_read_frame(audioInput,audioPacket)<0){audioEof=true;return true;}if(audioPacket->stream_index!=audioIndex)continue;audioPending=true;}
+ const auto tb=audioInput->streams[audioIndex]->time_base;const int64_t ts=audioPacket->pts!=AV_NOPTS_VALUE?audioPacket->pts:audioPacket->dts;const double time=ts==AV_NOPTS_VALUE?0:ts*av_q2d(tb)-videoOriginSeconds;if(time>seconds)return true;
+ const int64_t origin=av_rescale_q(static_cast<int64_t>(videoOriginSeconds*1000000),{1,1000000},tb);
+ if(audioPacket->pts!=AV_NOPTS_VALUE)audioPacket->pts-=origin;if(audioPacket->dts!=AV_NOPTS_VALUE)audioPacket->dts-=origin;
+ av_packet_rescale_ts(audioPacket,tb,audioStream->time_base);audioPacket->stream_index=audioStream->index;audioPacket->pos=-1;audioPending=false;if(av_interleaved_write_frame(mux,audioPacket)<0)return false;
+ }};
+ auto writer=[&](const uint8_t* bytes,size_t size,int64_t pts,bool key){if(!headerWritten)return false;
+ AVPacket* pkt=av_packet_alloc();if(!pkt)return false;if(av_new_packet(pkt,int(size))<0){av_packet_free(&pkt);return false;}memcpy(pkt->data,bytes,size);pkt->stream_index=videoStream->index;pkt->pts=pkt->dts=pts;pkt->duration=1;if(key)pkt->flags|=AV_PKT_FLAG_KEY;
+ av_packet_rescale_ts(pkt,{rate.den,rate.num},videoStream->time_base);const bool good=av_interleaved_write_frame(mux,pkt)>=0;av_packet_free(&pkt);++written;audioEndSeconds=(pts+1)*double(rate.den)/rate.num;return good&&writeAudioUntil(audioEndSeconds);};
+ // Must drain before rate/writeAudioUntil/writer leave scope, including cancel/error.
+ struct EncoderCloser {sink::NvencD3D12Encoder& encoder;~EncoderCloser(){encoder.close();}} closer{enc};
+ if(!enc.open(ctx,ring,graph,hevc,rate.num,rate.den,writer))break;
+ auto headers=enc.headers();cp->extradata=static_cast<uint8_t*>(av_mallocz(headers.size()+AV_INPUT_BUFFER_PADDING_SIZE));if(!cp->extradata)break;memcpy(cp->extradata,headers.data(),headers.size());cp->extradata_size=int(headers.size());
+ if(avio_open(&mux->pb,utf8(partial).c_str(),AVIO_FLAG_WRITE)<0||avformat_write_header(mux,nullptr)<0)break;headerWritten=true;
+ uint64_t sourceCount=0;int64_t outputIndex=0;bool error=false;
+ while(!cancel){pipeline::FramePacket packet;const AVFrame* frame=nullptr;auto rs=source.read(packet,&frame);if(rs==source::SourceReadStatus::Eos)break;if(rs!=source::SourceReadStatus::Frame||packet.pts.isUnknown()){error=true;break;}
+ if(sourceCount==0)videoOriginSeconds=packet.pts.toDouble();
+ pipeline::EnhanceGraph::FrameOutputs out;if(!graph.process(frame,packet.pts.toDouble()*1000,sourceCount==0||pipeline::breaksHistory(packet.flags),out)){error=true;break;}
+ if(out.hasGenerated&&!enc.encode(out.genSlot,true,outputIndex++)){error=true;break;}
+ if(options.fg&&sourceCount>0&&!out.hasGenerated){
+ veyra::log::info("export","history reset: hold current source for missing interpolation interval (not a generated frame)");
+ if(!enc.encode(out.videoSlot,false,outputIndex++)){error=true;break;}
+ }
+ if(!enc.encode(out.videoSlot,false,outputIndex++)){error=true;break;}
+ ++sourceCount;progress(info.duration.toDouble()>0?packet.pts.toDouble()/info.duration.toDouble():0,std::format(L"Exporting {} source frames / {} encoded frames (D3D12 NVENC)",sourceCount,outputIndex));
+ if(maxFrames&&sourceCount>=maxFrames)break;
+ }
+ if(error||cancel)break;
+ if(!enc.finish()||!writeAudioUntil(audioEndSeconds)||av_write_trailer(mux)<0)break;
+ ok=written>0;
+ }while(false);
+ enc.close();if(mux){if(mux->pb)avio_closep(&mux->pb);avformat_free_context(mux);}if(audioInput)avformat_close_input(&audioInput);av_packet_free(&audioPacket);
+ ring.drainQueue();graph.shutdown();source.close();ring.shutdown();ctx.shutdown();
+ if(ok){source::MediaFileSource check;source::SourceOpenDesc od;od.path=partial;od.preferHardwareDecode=false;pipeline::FramePacket pkt;const AVFrame* frame=nullptr;ok=check.open(od)&&check.read(pkt,&frame)==source::SourceReadStatus::Frame;check.close();if(ok)ok=MoveFileExW(partial.c_str(),output.c_str(),MOVEFILE_WRITE_THROUGH)!=FALSE;}
+ progress(ok?1:0,ok?L"Video exported and decoded back successfully":cancel?L"Export cancelled; partial retained":L"Video export failed; partial retained, see logs");return ok;
+}
+}
diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cpp
new file mode 100644
index 00000000..e2a47a22
--- /dev/null
+++ b/src/engine/VideoPresenter.cpp
@@ -0,0 +1,42 @@
+#include "veyra/engine/VideoPresenter.h"
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+namespace veyra::engine {
+bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::EnhanceGraph& graph) {
+ window_=window;RECT rc{};GetClientRect(window,&rc);
+ gfx::PresentSink::Desc d;d.targetWindow=window;d.width=std::max(1L,rc.right);d.height=std::max(1L,rc.bottom);d.vsync=false;
+ Status st=Status::Ok;if(!sink_.initialize(ctx.device(),ctx.directQueue(),d,st))return false;
+ std::vector<uint8_t> vs,ps;
+ if(!pipeline::loadShaderBytes("PresentBlit_vs.dxil",vs)||!pipeline::loadShaderBytes("PresentBlit_ps.dxil",ps)||!pass_.create(ctx.device(),vs,ps,4))return false;
+ D3D12_DESCRIPTOR_HEAP_DESC hd{};hd.Type=D3D12_DESCRIPTOR_HEAP_TYPE_RTV;hd.NumDescriptors=3;
+ if(FAILED(ctx.device()->CreateDescriptorHeap(&hd,IID_PPV_ARGS(&rtvs_))))return false;
+ inc_=ctx.device()->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);refresh(ctx.device());
+ for(unsigned i=0;i<4;++i)pipeline::makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),DXGI_FORMAT_R8G8B8A8_UNORM,{pass_.heap->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i)*pass_.increment});
+ return true;
+}
+void VideoPresenter::refresh(ID3D12Device* device){for(unsigned i=0;i<3;++i){Microsoft::WRL::ComPtr<ID3D12Resource> bb;if(SUCCEEDED(sink_.swapChain()->GetBuffer(i,IID_PPV_ARGS(&bb))))device->CreateRenderTargetView(bb.Get(),nullptr,{rtvs_->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i)*inc_});}}
+bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,pipeline::EnhanceGraph& graph,unsigned slot,bool generated) {
+ RECT rc{};GetClientRect(window_,&rc);if(rc.right<1||rc.bottom<1)return true;
+ if(unsigned(rc.right)!=sink_.width()||unsigned(rc.bottom)!=sink_.height()) {if(!ring.drainQueue())return false;sink_.resize(rc.right,rc.bottom);refresh(ctx.device());}
+ Status st=Status::Ok;const auto commandSlot=ring.slotCount()-1;auto* list=ring.acquire(commandSlot,st);if(!list)return false;
+ auto* source=generated?graph.generatedFrameResource(slot):graph.videoFrameResource(slot);auto* bb=sink_.currentBackBuffer();if(!bb)return false;
+ D3D12_RESOURCE_BARRIER barriers[2]{};
+ for(auto& b:barriers){b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;b.Transition.StateBefore=D3D12_RESOURCE_STATE_COMMON;b.Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;}
+ barriers[0].Transition.pResource=source;barriers[0].Transition.StateAfter=D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
+ barriers[1].Transition.pResource=bb;barriers[1].Transition.StateAfter=D3D12_RESOURCE_STATE_RENDER_TARGET;list->ResourceBarrier(2,barriers);
+ D3D12_CPU_DESCRIPTOR_HANDLE rtv{rtvs_->GetCPUDescriptorHandleForHeapStart().ptr+size_t(sink_.swapChain()->GetCurrentBackBufferIndex())*inc_};
+ const float black[4]={0,0,0,1};list->ClearRenderTargetView(rtv,black,0,nullptr);list->OMSetRenderTargets(1,&rtv,FALSE,nullptr);
+ const float scale=std::min(float(sink_.bufferWidth())/graph.workWidth(),float(sink_.bufferHeight())/graph.workHeight());
+ const float w=graph.workWidth()*scale,h=graph.workHeight()*scale;
+ D3D12_VIEWPORT viewport{(sink_.bufferWidth()-w)*0.5f,(sink_.bufferHeight()-h)*0.5f,w,h,0,1};
+ D3D12_RECT rect{0,0,LONG(sink_.bufferWidth()),LONG(sink_.bufferHeight())};list->RSSetViewports(1,&viewport);list->RSSetScissorRects(1,&rect);
+ ID3D12DescriptorHeap* heaps[]={pass_.heap.Get()};list->SetDescriptorHeaps(1,heaps);list->SetGraphicsRootSignature(pass_.rootSig.Get());list->SetPipelineState(pass_.pso.Get());
+ float dims[8]={float(graph.workWidth()),float(graph.workHeight()),0,0,float(sink_.bufferWidth()),float(sink_.bufferHeight()),0,0};list->SetGraphicsRoot32BitConstants(0,8,dims,0);
+ list->SetGraphicsRootDescriptorTable(1,{pass_.heap->GetGPUDescriptorHandleForHeapStart().ptr+size_t(slot+(generated?2:0))*pass_.increment});
+ list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);list->DrawInstanced(3,1,0,0);
+ for(auto& b:barriers)std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(2,barriers);
+ return ring.submitAndSignal(commandSlot)&&sink_.present(st);
+}
+void VideoPresenter::close(){rtvs_.Reset();pass_={};sink_.shutdown();}
+}
diff --git a/src/gfx/CommandSlotRing.cpp b/src/gfx/CommandSlotRing.cpp
index afdd1363..8362cf04 100644
--- a/src/gfx/CommandSlotRing.cpp
+++ b/src/gfx/CommandSlotRing.cpp
@@ -46,6 +46,11 @@ bool CommandSlotRing::initialize(ID3D12Device* device,
}
UINT64 frequency = 0;
const HRESULT freqResult = queue_->GetTimestampFrequency(&frequency);
+ if(FAILED(freqResult)||frequency==0)return false;
+ timestampFrequency_=frequency;
+ D3D12_HEAP_PROPERTIES rh{};rh.Type=D3D12_HEAP_TYPE_READBACK;
+ D3D12_RESOURCE_DESC rb{};rb.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;rb.Width=slotCount_*2*sizeof(uint64_t);rb.Height=1;rb.DepthOrArraySize=1;rb.MipLevels=1;rb.SampleDesc.Count=1;rb.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ if(FAILED(device_->CreateCommittedResource(&rh,D3D12_HEAP_FLAG_NONE,&rb,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&timingReadback_))))return false;
veyra::log::info("gfx", std::format("slot-ring: timestamp heap created slots={} pairs={} frequencyHz={} freqQuery={}",
slotCount_, timestampHeapDesc.Count, frequency, veyra::hresultString(freqResult)));
@@ -87,6 +92,7 @@ void CommandSlotRing::shutdown()
(void)waitIdle();
slots_.clear();
timestampHeap_.Reset();
+ timingReadback_.Reset();
initialized_ = false;
veyra::log::info("gfx", "slot-ring: shutdown complete");
}
@@ -109,6 +115,7 @@ ID3D12GraphicsCommandList* CommandSlotRing::acquire(uint32_t slot, Status& statu
veyra::log::error("gfx", std::format("slot-ring: SetEventOnCompletion slot={} failed hr={}", slot, veyra::hresultString(waitResult)));
return nullptr;
}
+ ++cpuWaitCount_;
const DWORD wait = WaitForSingleObject(fenceEvent_, 10000);
if (wait != WAIT_OBJECT_0) {
status = Status::DeviceFailure;
@@ -118,6 +125,14 @@ ID3D12GraphicsCommandList* CommandSlotRing::acquire(uint32_t slot, Status& statu
}
}
+ if(target.timed && timingReadback_) {
+ uint64_t* data=nullptr;D3D12_RANGE range{slot*2*sizeof(uint64_t),(slot*2+2)*sizeof(uint64_t)};
+ if(SUCCEEDED(timingReadback_->Map(0,&range,reinterpret_cast<void**>(&data)))) {
+ const uint64_t begin=data[slot*2],end=data[slot*2+1];
+ if(end>=begin&&gpuCommandTimesMs_.size()<16384){const double ms=double(end-begin)*1000.0/timestampFrequency_;gpuCommandTimesMs_.push_back(ms);if(!target.label.empty())veyra::log::info("gpu-profile",std::format("{} {:.4f} ms",target.label,ms));}
+ D3D12_RANGE empty{0,0};timingReadback_->Unmap(0,&empty);
+ }target.timed=false;target.label.clear();
+ }
HRESULT result = target.allocator->Reset();
if (FAILED(result)) {
status = Status::DeviceFailure;
@@ -130,6 +145,7 @@ ID3D12GraphicsCommandList* CommandSlotRing::acquire(uint32_t slot, Status& statu
veyra::log::error("gfx", std::format("slot-ring: list reset slot={} failed hr={}", slot, veyra::hresultString(result)));
return nullptr;
}
+ target.list->EndQuery(timestampHeap_.Get(),D3D12_QUERY_TYPE_TIMESTAMP,slot*2);
return target.list.Get();
}
@@ -141,6 +157,9 @@ bool CommandSlotRing::submitAndSignal(uint32_t slot)
}
Slot& target = slots_[slot];
+ target.list->EndQuery(timestampHeap_.Get(),D3D12_QUERY_TYPE_TIMESTAMP,slot*2+1);
+ target.list->ResolveQueryData(timestampHeap_.Get(),D3D12_QUERY_TYPE_TIMESTAMP,slot*2,2,timingReadback_.Get(),slot*2*sizeof(uint64_t));
+ target.timed=true;
const HRESULT closeResult = target.list->Close();
if (FAILED(closeResult)) {
veyra::log::error("gfx", std::format("slot-ring: close slot={} failed hr={}", slot, veyra::hresultString(closeResult)));
diff --git a/src/gfx/PresentSink.cpp b/src/gfx/PresentSink.cpp
index 076fc368..7fd229f0 100644
--- a/src/gfx/PresentSink.cpp
+++ b/src/gfx/PresentSink.cpp
@@ -39,6 +39,7 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,
const Desc& desc, Status& status)
{
device_ = device;
+ shutdownCalled_ = false;
desc_ = desc;
width_ = desc.width;
height_ = desc.height;
@@ -65,7 +66,7 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,
const DWORD style = WS_OVERLAPPEDWINDOW;
RECT rect{0, 0, static_cast<LONG>(width_), static_cast<LONG>(height_)};
AdjustWindowRect(&rect, style, FALSE);
- hwnd_ = CreateWindowExW(WS_EX_OVERLAPPEDWINDOW, kWindowClassName, desc_.title.c_str(),
+ hwnd_ = desc.targetWindow ? desc.targetWindow : CreateWindowExW(WS_EX_OVERLAPPEDWINDOW, kWindowClassName, desc_.title.c_str(),
style, CW_USEDEFAULT, CW_USEDEFAULT,
rect.right - rect.left, rect.bottom - rect.top,
nullptr, nullptr, instance, nullptr);
@@ -74,7 +75,7 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,
status = Status::WindowFailure;
return false;
}
- ShowWindow(hwnd_, SW_SHOWNOACTIVATE); // background probe: never steal focus
+ if (!desc.targetWindow) ShowWindow(hwnd_, SW_SHOWNOACTIVATE);
UpdateWindow(hwnd_);
// Factory with tearing awareness.
@@ -287,7 +288,7 @@ void PresentSink::shutdown()
}
swapChain_.Reset();
log::info("present", "sink-shutdown: sub-step window-destroy-last");
- if (hwnd_ != nullptr) {
+ if (hwnd_ != nullptr && !desc_.targetWindow) {
DestroyWindow(hwnd_);
hwnd_ = nullptr;
MSG msg{};
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index e20b542c..c3e26a03 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -7,6 +7,7 @@
#include "veyra/pipeline/EnhanceGraph.h"
#include <algorithm>
+#include <bit>
#include <chrono>
#include <cmath>
#include <cstring>
@@ -36,6 +37,7 @@ namespace veyra::pipeline {
namespace {
constexpr int64_t usPerSecond = 1000000;
+float uintBits(uint32_t v) { return std::bit_cast<float>(v); }
} // namespace
@@ -47,8 +49,7 @@ EnhanceGraph::EnhanceGraph(gfx::D3D12DeviceContext& context, gfx::CommandSlotRin
EnhanceGraph::~EnhanceGraph()
{
- // shutdown() must have run (features/NVOF/NGX need ordered teardown while
- // the device is alive); ComPtr releases afterwards are then no-ops.
+ shutdown();
}
// ---------------------------------------------------------------------------
@@ -105,7 +106,7 @@ bool EnhanceGraph::createResources()
upZeroDepth_ = makeUploadBuffer(context_.device(), dPitch_ * workH_);
upZeroMotion_ = makeUploadBuffer(context_.device(), dPitch_ * workH_);
lumaTex_ = makeTexture(context_.device(), srcW_, srcH_, DXGI_FORMAT_R8_UNORM, true);
- chromaTex_ = makeTexture(context_.device(), srcW_, srcH_ / 2, DXGI_FORMAT_R8G8_UNORM, true);
+ chromaTex_ = makeTexture(context_.device(), srcW_ / 2, srcH_ / 2, DXGI_FORMAT_R8G8_UNORM, true);
srcRgba_ = makeTexture(context_.device(), srcW_, srcH_, DXGI_FORMAT_R16G16B16A16_FLOAT, true);
workRgba_ = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R16G16B16A16_FLOAT, true);
proxyTex_ = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R8G8B8A8_UNORM, true);
@@ -417,10 +418,10 @@ bool EnhanceGraph::initNgxFeatures()
bool EnhanceGraph::createComputePasses()
{
std::vector<uint8_t> cs;
- if (!yuvPass_.loadShader("YuvToLinearRgb.dxil", cs) || !yuvPass_.create(context_.device(), cs, 8)) return false;
- if (!encPass_.loadShader("ParityEncode.dxil", cs) || !encPass_.create(context_.device(), cs, 8)) return false;
+ if (!yuvPass_.loadShader("YuvToLinearRgb.dxil", cs) || !yuvPass_.create(context_.device(), cs, 8, 2, 1)) return false;
+ if (!encPass_.loadShader("ParityEncode.dxil", cs) || !encPass_.create(context_.device(), cs, 8, 1, 1)) return false;
if (!decPass_.loadShader("ParityDecode.dxil", cs) || !decPass_.create(context_.device(), cs, 8)) return false;
- if (!blitPass_.loadShader("ScaleBlit.dxil", cs) || !blitPass_.create(context_.device(), cs, 16)) return false;
+ if (!blitPass_.loadShader("ScaleBlit.dxil", cs) || !blitPass_.create(context_.device(), cs, 16, 1, 1)) return false;
// Nv12Upload stays: frame-time CopyTextureRegion is poisoned by the
// injected layer (SEH in NGX evaluate, r33-final3 evidence); the compute
// upload is the proven frame-path ingestion on this system.
@@ -468,7 +469,8 @@ bool EnhanceGraph::createViews()
stager_.stageSrv(resource, &srv, pass.heap.Get(), slot);
};
- // STATIC DESCRIPTOR VIEWS (LAST: system constraint).
+ stagedSrv(workRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, blitPass_, 15);
+ // Immutable per-resource views.
if (viewsTex) stagedSrv(lumaTex_.Get(), DXGI_FORMAT_R8_UNORM, yuvPass_, 0);
if (viewsTex) stagedSrv(chromaTex_.Get(), DXGI_FORMAT_R8G8_UNORM, yuvPass_, 1);
if (viewsUav) makeUav(context_.device(), srcRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, cpu(yuvPass_, 2));
@@ -480,11 +482,7 @@ bool EnhanceGraph::createViews()
if (viewsUav) makeUav(context_.device(), finalRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, cpu(decPass_, 3));
if (viewsUav) makeUav(context_.device(), lumaTex_.Get(), DXGI_FORMAT_R8_UNORM, cpu(uploadPass_, 2));
if (viewsUav) makeUav(context_.device(), chromaTex_.Get(), DXGI_FORMAT_R8G8_UNORM, cpu(uploadPass_, 3));
- // NOTE: uploadPass RAW buffer SRV slots 0/1 remain uninitialized BY
- // DESIGN on this system: creating them trips the injected layer (device
- // removal + blocked NVOF, r33b-views evidence). The dispatch consumes
- // them anyway (driver-tolerated); GBV flags them as id=938 - the R6.1
- // residual with a narrower known fix (pre-NGX creation, untested).
+ // Software NV12 ingestion uses plane copies; no raw-SRV dispatch.
// Blit pass layout (all static; per-use offsets chosen at bind time):
// 0: srcRgba SRV 1: workRgba UAV (SR bypass / NR-off blit)
// 2: finalRgba SRV 3/4: videoFrame UAV (section 5)
@@ -494,7 +492,7 @@ bool EnhanceGraph::createViews()
// 13/14: genTex SRV (slot 2)
if (viewsTex) stagedSrv(srcRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, blitPass_, 0);
if (viewsUav) makeUav(context_.device(), workRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, cpu(blitPass_, 1));
- if (viewsTex) stagedSrv(finalRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, blitPass_, 2);
+ if (viewsTex) stagedSrv(nrEnabled_ ? finalRgba_.Get() : workRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, blitPass_, 2);
if (viewsUav) makeUav(context_.device(), videoFrame_[0].Get(), DXGI_FORMAT_R8G8B8A8_UNORM, cpu(blitPass_, 3));
if (viewsUav) makeUav(context_.device(), videoFrame_[1].Get(), DXGI_FORMAT_R8G8B8A8_UNORM, cpu(blitPass_, 4));
if (viewsTex) stagedSrv(nvofInB_.Get(), DXGI_FORMAT_B8G8R8A8_UNORM, blitPass_, 5);
@@ -548,9 +546,11 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
out = FrameOutputs{};
out.ptsMs = ptsMs;
static const bool graphOff = GetEnvironmentVariableW(L"VEYRA_GRAPH_OFF", nullptr, 0) != 0;
- if (frame->pts == AV_NOPTS_VALUE || frame->pts < 0) {
- return true; // no timestamp: skip this frame entirely
+ if (!frame || !initialized_ || !std::isfinite(ptsMs)) return false;
+ if (frame->color_trc == AVCOL_TRC_SMPTE2084 || frame->color_trc == AVCOL_TRC_ARIB_STD_B67) {
+ veyra::log::error("graph", "HDR input is unsupported by the V1 SDR pipeline"); return false;
}
+ if (reset) { prevValid_ = false; scene_.reset(); previousLuma_.clear(); }
const uint32_t parity = static_cast<uint32_t>(realFrameIndex_ % 2);
if (graphOff) {
@@ -562,7 +562,8 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
out.passthrough = true;
return true;
}
- const uint32_t slot = static_cast<uint32_t>(realFrameIndex_ % 4);
+ uint32_t slot = nextListSlot_++ % ring_.slotCount();
+ if (uploadFences_[parity] && !context_.waitForFenceValue(uploadFences_[parity])) return false;
Status st = Status::Ok;
// 1. Source NV12: D3D12VA texture directly (GPU) or CPU upload.
@@ -633,25 +634,38 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
frame->width, frame->height, AV_PIX_FMT_NV12, SWS_POINT,
nullptr, nullptr, nullptr);
if (nv12Ctx_ == nullptr) { veyra::log::error("graph", "sws"); return false; }
+ const int colorSpace=(frame->colorspace==AVCOL_SPC_BT470BG||frame->colorspace==AVCOL_SPC_SMPTE170M)?SWS_CS_ITU601:SWS_CS_ITU709;
+ const int* coefficients=sws_getCoefficients(colorSpace);
+ const int full=frame->color_range==AVCOL_RANGE_JPEG?1:0;
+ if(sws_setColorspaceDetails(nv12Ctx_,coefficients,full,coefficients,full,0,1<<16,1<<16)<0)return false;
uint8_t* planes[2] = { nv12Buf_.data(), nv12Buf_.data() + lumaSize_ };
const int strides[2] = { static_cast<int>(lumaPitch_), static_cast<int>(chromaPitch_) };
sws_scale(nv12Ctx_, frame->data, frame->linesize, 0, frame->height, planes, strides);
+ std::vector<uint8_t> sample;sample.reserve(64*36);std::vector<double> hist(256,0);double sad=0;
+ for(unsigned y=0;y<36;++y)for(unsigned x=0;x<64;++x){const uint8_t v=planes[0][size_t(y*srcH_/36)*lumaPitch_+x*srcW_/64];hist[v]+=1.0/(64*36);sample.push_back(v);}
+ if(previousLuma_.size()==sample.size())for(size_t i=0;i<sample.size();++i)sad+=std::abs(int(sample[i])-int(previousLuma_[i]))/(255.0*sample.size());
+ const auto analysis=scene_.analyze(realFrameIndex_,hist,sad,static_cast<uint64_t>(std::max(0.0,ptsMs)*1000));
+ if(analysis.isSceneCut||analysis.isCadenceBreak){reset=true;prevValid_=false;if(analysis.isSceneCut)++metrics_.sceneCutCount;}
+ previousLuma_=std::move(sample);
for (uint32_t y = 0; y < srcH_; ++y)
std::memcpy(mappedLuma_[parity] + y * lumaPitch_, planes[0] + y * lumaPitch_, srcW_);
for (uint32_t y = 0; y < srcH_ / 2; ++y)
std::memcpy(mappedChroma_[parity] + y * chromaPitch_, planes[1] + y * chromaPitch_, srcW_);
- tracker_.transition(list, lumaTex_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
- tracker_.transition(list, chromaTex_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
- tracker_.transition(list, upLuma_[parity].Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
- const float constants[8] = {
- static_cast<float>(srcW_), static_cast<float>(srcH_),
- static_cast<float>(lumaPitch_), static_cast<float>(chromaPitch_), 0, 0, 0, 0 };
- uploadPass_.bind(list, constants,
- gpuHandleOf(uploadPass_, parity).ptr, gpuHandleOf(uploadPass_, 2).ptr);
- list->Dispatch((srcW_ + 31) / 32 * 2, (srcH_ + 31) / 32 * 2, 1);
- tracker_.uavBarrier(list, lumaTex_.Get());
- tracker_.uavBarrier(list, chromaTex_.Get());
- tracker_.transition(list, upLuma_[parity].Get(), D3D12_RESOURCE_STATE_GENERIC_READ);
+ auto copyPlane = [&](ID3D12Resource* texture, ID3D12Resource* upload,
+ DXGI_FORMAT format, UINT width, UINT height, UINT pitch) {
+ tracker_.transition(list, texture, D3D12_RESOURCE_STATE_COPY_DEST);
+ D3D12_TEXTURE_COPY_LOCATION dst{}, src{};
+ dst.pResource = texture;
+ dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ src.pResource = upload;
+ src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
+ src.PlacedFootprint.Footprint = {format, width, height, 1, pitch};
+ list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
+ };
+ copyPlane(lumaTex_.Get(), upLuma_[parity].Get(), DXGI_FORMAT_R8_UNORM,
+ srcW_, srcH_, static_cast<UINT>(lumaPitch_));
+ copyPlane(chromaTex_.Get(), upChroma_[parity].Get(), DXGI_FORMAT_R8G8_UNORM,
+ srcW_/2, srcH_/2, static_cast<UINT>(chromaPitch_));
tracker_.transition(list, lumaTex_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
tracker_.transition(list, chromaTex_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
}
@@ -660,8 +674,10 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
// 2. YUV -> RGBA16F.
tracker_.transition(list, srcRgba_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
{
- const float constants[8] = { 1.0f, 1.0f, 1.0f, 0.0f,
- static_cast<float>(srcW_), static_cast<float>(srcH_), 0.0f, 0.0f };
+ const float constants[8] = { frame->color_range == AVCOL_RANGE_JPEG ? 0.0f : 1.0f,
+ (frame->colorspace == AVCOL_SPC_BT470BG || frame->colorspace == AVCOL_SPC_SMPTE170M) ? 0.0f : 1.0f,
+ (frame->color_trc == AVCOL_TRC_BT709 || frame->color_trc == AVCOL_TRC_SMPTE170M) ? 2.0f : 1.0f, 0.0f,
+ uintBits(srcW_), uintBits(srcH_), 0.0f, 0.0f };
yuvPass_.bind(list, constants, gpuHandleOf(yuvPass_, 0).ptr, gpuHandleOf(yuvPass_, 2).ptr);
list->Dispatch((srcW_ + 15) / 16, (srcH_ + 15) / 16, 1);
}
@@ -673,6 +689,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
if (desc_.stageMark) desc_.stageMark("yuv");
// 3. SR into workRgba (or 1:1 blit bypass).
+ if(reset)++metrics_.resetCount;
if (srEnabled_ && srBackend_ && srBackend_->created()) {
tracker_.transition(list, workRgba_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
ngx::DlssSrBackend::EvalDesc ed{};
@@ -691,8 +708,8 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
} else {
tracker_.transition(list, workRgba_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
const float constants[8] = {
- static_cast<float>(srcW_), static_cast<float>(srcH_),
- static_cast<float>(workW_), static_cast<float>(workH_), 0, 0, 0, 0 };
+ uintBits(srcW_), uintBits(srcH_),
+ uintBits(workW_), uintBits(workH_), 0, 0, 0, 0 };
blitPass_.bind(list, constants, gpuHandleOf(blitPass_, 0).ptr, gpuHandleOf(blitPass_, 1).ptr);
list->Dispatch((workW_ + 15) / 16, (workH_ + 15) / 16, 1);
tracker_.uavBarrier(list, workRgba_.Get());
@@ -700,11 +717,58 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
}
if (desc_.stageMark) desc_.stageMark("sr");
+
+ // Guidance from original post-SR color BEFORE NR. Queue waits are GPU-side.
+ bool haveFlow = false;
+ const bool runMotion = nvofStandalone_ || fgEnabled_;
+ if (runMotion && nvof_ && nvof_->initialized()) {
+ const float dims[8] = {uintBits(workW_),uintBits(workH_),uintBits(workW_),uintBits(workH_),0,0,0,0};
+ if (prevValid_) {
+ tracker_.transition(list,nvofInB_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ tracker_.transition(list,nvofInA_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ blitPass_.bind(list,dims,gpuHandleOf(blitPass_,5).ptr,gpuHandleOf(blitPass_,6).ptr);
+ list->Dispatch((workW_+15)/16,(workH_+15)/16,1);
+ tracker_.uavBarrier(list,nvofInA_.Get());
+ tracker_.transition(list,nvofInA_.Get(),D3D12_RESOURCE_STATE_COMMON);
+ }
+ tracker_.transition(list,nvofInB_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ const float encodedDims[8] = {uintBits(workW_),uintBits(workH_),uintBits(workW_),uintBits(workH_),1,0,0,0};
+ blitPass_.bind(list,encodedDims,gpuHandleOf(blitPass_,15).ptr,gpuHandleOf(blitPass_,9).ptr);
+ list->Dispatch((workW_+15)/16,(workH_+15)/16,1);
+ tracker_.uavBarrier(list,nvofInB_.Get());
+ tracker_.transition(list,nvofInB_.Get(),D3D12_RESOURCE_STATE_COMMON);
+ if (prevValid_) {
+ if(!ring_.submitAndSignal(slot))return false;
+ haveFlow=nvof_->execute(ring_.lastSignaledValue(),st);
+ if(!haveFlow) { ++metrics_.nvofFrameFailures; mvecSource_="zero-motion-fallback (NVOF execute failed)"; }
+ else {
+ ++metrics_.nvofExecuteCount;
+ if(FAILED(context_.directQueue()->Wait(nvofOutFence_.Get(),nvof_->nextOutValue()-1)))return false;
+ }
+ slot=nextListSlot_++%ring_.slotCount(); list=ring_.acquire(slot,st);if(!list)return false;
+ if(haveFlow) {
+ tracker_.transition(list,nvofRawTex_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ tracker_.transition(list,nvofCostTex_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ tracker_.transition(list,flowTex_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ tracker_.transition(list,confTex_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ const float dc[8]={uintBits(rawW_),uintBits(rawH_),uintBits(workW_),uintBits(workH_),
+ uintBits(selectedGrid_),uintBits(0),uintBits(32),0};
+ densifyPass_.bind(list,dc,gpuHandleOf(densifyPass_,0).ptr,gpuHandleOf(densifyPass_,2).ptr);
+ list->Dispatch((workW_+15)/16,(workH_+15)/16,1);
+ tracker_.uavBarrier(list,flowTex_.Get());tracker_.uavBarrier(list,confTex_.Get());
+ tracker_.transition(list,nvofRawTex_.Get(),D3D12_RESOURCE_STATE_COMMON);
+ tracker_.transition(list,nvofCostTex_.Get(),D3D12_RESOURCE_STATE_COMMON);
+ tracker_.transition(list,flowTex_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ tracker_.transition(list,confTex_.Get(),D3D12_RESOURCE_STATE_COMMON);
+ }
+ }
+ }
+
// 4a. Parity encode.
if (nrEnabled_ && nrHandle_ != nullptr) {
tracker_.transition(list, proxyTex_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
const float constants[8] = { 1.0f, 1.0f, 1.0f, 0.0f,
- static_cast<float>(workW_), static_cast<float>(workH_), 0.0f, 0.0f };
+ uintBits(workW_), uintBits(workH_), 0.0f, 0.0f };
encPass_.bind(list, constants, gpuHandleOf(encPass_, 0).ptr, gpuHandleOf(encPass_, 1).ptr);
list->Dispatch((workW_ + 15) / 16, (workH_ + 15) / 16, 1);
tracker_.uavBarrier(list, proxyTex_.Get());
@@ -713,14 +777,15 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
// 4b. NR evaluate on a FRESH list (snippet constraint).
if (!ring_.submitAndSignal(slot)) { veyra::log::error("graph", "submit before nr"); return false; }
- ID3D12GraphicsCommandList* nlist = ring_.acquire((slot + 1) % 4, st);
+ slot = nextListSlot_++ % ring_.slotCount();
+ ID3D12GraphicsCommandList* nlist = ring_.acquire(slot, st);
if (nlist == nullptr) { veyra::log::error("graph", "acquire nr list"); return false; }
{
namespace p = ngx::dlssnr;
ngx::ParameterBlock pb(ngxParams_);
pb.setD3D12Resource(p::kColor, proxyTex_.Get());
pb.setD3D12Resource(p::kOutput, neuralTex_.Get());
- pb.setD3D12Resource(p::kMVec, nrZeroMotion_.Get());
+ pb.setD3D12Resource(p::kMVec, haveFlow ? flowTex_.Get() : nrZeroMotion_.Get());
pb.setD3D12Resource(p::kDepth, nrZeroDepth_.Get());
pb.setU32(p::kColorSubrectWidth, workW_); pb.setU32(p::kColorSubrectHeight, workH_);
pb.setU32(p::kOutputSubrectWidth, workW_); pb.setU32(p::kOutputSubrectHeight, workH_);
@@ -746,13 +811,21 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
return false;
}
++metrics_.nrEvaluateCount;
+ if(haveFlow)++metrics_.nrMotionFrames;
tracker_.uavBarrier(nlist, neuralTex_.Get());
tracker_.transition(nlist, neuralTex_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ wchar_t profileFlag[2]{};
+ if(GetEnvironmentVariableW(L"VEYRA_PROFILE_SPLIT",profileFlag,2)&&profileFlag[0]==L'1'){
+ ring_.tag(slot,"nr-only");
+ if(!ring_.submitAndSignal(slot))return false;
+ slot=nextListSlot_++%ring_.slotCount();nlist=ring_.acquire(slot,st);if(!nlist)return false;
+ ring_.tag(slot,"decode-output-fg");
+ }
// 4c. Parity decode.
tracker_.transition(nlist, finalRgba_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
const float constants[8] = { 1.0f, 1.0f, 1.0f, 0.0f,
- static_cast<float>(workW_), static_cast<float>(workH_), 0.0f, 0.0f };
+ uintBits(workW_), uintBits(workH_), 0.0f, 0.0f };
decPass_.bind(nlist, constants, gpuHandleOf(decPass_, 0).ptr, gpuHandleOf(decPass_, 3).ptr);
nlist->Dispatch((workW_ + 15) / 16, (workH_ + 15) / 16, 1);
tracker_.uavBarrier(nlist, finalRgba_.Get());
@@ -770,132 +843,45 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
tracker_.transition(list, videoFrame_[parity].Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
const float constants[8] = {
- static_cast<float>(workW_), static_cast<float>(workH_),
- static_cast<float>(workW_), static_cast<float>(workH_), 0, 0, 0, 0 };
+ uintBits(workW_), uintBits(workH_),
+ uintBits(workW_), uintBits(workH_), 1, 0, 0, 0 };
blitPass_.bind(list, constants, gpuHandleOf(blitPass_, srcSlot).ptr, gpuHandleOf(blitPass_, uavSlot).ptr);
list->Dispatch((workW_ + 15) / 16, (workH_ + 15) / 16, 1);
tracker_.uavBarrier(list, videoFrame_[parity].Get());
tracker_.transition(list, videoFrame_[parity].Get(), D3D12_RESOURCE_STATE_COMMON);
- // NVOF chain via blits: A := B, then B := this frame.
- tracker_.transition(list, nvofInA_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
- blitPass_.bind(list, constants, gpuHandleOf(blitPass_, 5).ptr, gpuHandleOf(blitPass_, 6).ptr);
- list->Dispatch((workW_ + 15) / 16, (workH_ + 15) / 16, 1);
- tracker_.uavBarrier(list, nvofInA_.Get());
- tracker_.transition(list, nvofInA_.Get(), D3D12_RESOURCE_STATE_COMMON);
- tracker_.transition(list, nvofInB_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
- const float nvofConstants[8] = {
- static_cast<float>(workW_), static_cast<float>(workH_),
- static_cast<float>(nvofW_), static_cast<float>(nvofH_), 0, 0, 0, 0 };
- blitPass_.bind(list, nvofConstants,
- gpuHandleOf(blitPass_, 7 + parity).ptr, gpuHandleOf(blitPass_, 9).ptr);
- list->Dispatch((nvofW_ + 15) / 16, (nvofH_ + 15) / 16, 1);
- tracker_.uavBarrier(list, nvofInB_.Get());
- tracker_.transition(list, nvofInB_.Get(), D3D12_RESOURCE_STATE_COMMON);
- }
-
- if (!ring_.submitAndSignal((nrEnabled_ && nrHandle_ != nullptr) ? (slot + 1) % 4 : slot)) {
- veyra::log::error("graph", "submit after color work");
- return false;
}
+ if (!ring_.submitAndSignal(slot)) return false;
out.videoFenceValue = ring_.lastSignaledValue();
- // 6. NVOF (+ optional FG), queue-ordered after the color work. The
- // quality core runs NVOF+densify standalone (no FG) for motion stats.
- const bool wantMotion = (nvofStandalone_ || (fgEnabled_ && fgBackend_ && fgBackend_->created())) && prevValid_;
- if (wantMotion) {
- const auto nvofT0 = std::chrono::steady_clock::now();
- bool haveFlow = nvof_ && nvof_->initialized() ? nvof_->execute(out.videoFenceValue, st) : false;
- if (desc_.stageMark) {
- const double nvofMs = std::chrono::duration<double, std::milli>(
- std::chrono::steady_clock::now() - nvofT0).count();
- (void)nvofMs; // caller-side timing aggregation uses stageMark
- }
- if (haveFlow) {
- ++metrics_.nvofExecuteCount;
- if (FAILED(context_.directQueue()->Wait(nvofOutFence_.Get(), nvof_->nextOutValue() - 1))) {
- veyra::log::error("graph", "queue wait on nvof out fence");
- return false;
- }
- } else {
- // The injected D3D12 layer on this system blocks NVOF frame-time
- // executes once descriptor views exist. Fall back to zero-guidance:
- // DLSSG's internal optical flow still performs the interpolation.
- // Reported honestly as mvecSource.
- if (mvecSource_ == "nvof") {
- mvecSource_ = "zero-motion-fallback (NVOF blocked by injected layer post-views; "
- "real NVOF proven in P5 probe and FG truth in P6.2)";
- veyra::log::warn("graph", "NVOF frame execute blocked by injected layer; "
- "FG falls back to zero-guidance mvec");
- }
- ++metrics_.nvofFrameFailures;
- }
- if (!haveFlow && !(fgEnabled_ && fgBackend_ && fgBackend_->created())) {
- // No flow and no FG: nothing to record on the third list.
- } else {
- ID3D12GraphicsCommandList* flist = ring_.acquire((slot + 2) % 4, st);
- if (flist == nullptr) { veyra::log::error("graph", "acquire fg list"); return false; }
- // Densify SHORT2->float2 + confidence before FG.
- if (haveFlow) {
- tracker_.transition(flist, nvofRawTex_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
- tracker_.transition(flist, nvofCostTex_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
- tracker_.transition(flist, flowTex_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
- tracker_.transition(flist, confTex_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
- const float dc[8] = {
- static_cast<float>(rawW_), static_cast<float>(rawH_),
- static_cast<float>(nvofW_), static_cast<float>(nvofH_),
- static_cast<float>(selectedGrid_),
- 1.0f, // negate: single explicit direction flip (proven by displacement tests)
- 32.0f, // costThreshold (cells below -> zero motion)
- 0.0f };
- densifyPass_.bind(flist, dc,
- gpuHandleOf(densifyPass_, 0).ptr, gpuHandleOf(densifyPass_, 2).ptr);
- flist->Dispatch((nvofW_ + 15) / 16, (nvofH_ + 15) / 16, 1);
- tracker_.uavBarrier(flist, flowTex_.Get());
- tracker_.uavBarrier(flist, confTex_.Get());
- tracker_.transition(flist, nvofRawTex_.Get(), D3D12_RESOURCE_STATE_COMMON);
- tracker_.transition(flist, nvofCostTex_.Get(), D3D12_RESOURCE_STATE_COMMON);
- tracker_.transition(flist, flowTex_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
- tracker_.transition(flist, confTex_.Get(), D3D12_RESOURCE_STATE_COMMON);
- }
- if (desc_.stageMark) desc_.stageMark("decode_blit");
- if (!(fgEnabled_ && fgBackend_ && fgBackend_->created())) {
- // Standalone motion mode: densify already recorded; submit and done.
- if (!ring_.submitAndSignal((slot + 2) % 4)) { veyra::log::error("graph", "motion submit"); return false; }
- } else {
- ID3D12Resource* mvecResource = haveFlow ? flowTex_.Get() : nrZeroMotion_.Get();
- tracker_.transition(flist, nvofInB_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
- tracker_.transition(flist, depthTex_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
- const uint32_t genSlot = static_cast<uint32_t>(realFrameIndex_ % 2);
- tracker_.transition(flist, genFrame_[genSlot].Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ // FG reads enhanced SDR color, not the pre-NR guidance input.
+ if (fgEnabled_ && fgBackend_ && fgBackend_->created()) {
+ slot=nextListSlot_++%ring_.slotCount();
+ auto* flist=ring_.acquire(slot,st); if(!flist)return false;
+ auto* motion=haveFlow?flowTex_.Get():nrZeroMotion_.Get();
+ tracker_.transition(flist,videoFrame_[parity].Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ tracker_.transition(flist,motion,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ tracker_.transition(flist,depthTex_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ tracker_.transition(flist,genFrame_[parity].Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
ngx::DlssFgBackend::EvalDesc fe{};
- fe.backbuffer = nvofInB_.Get();
- fe.depth = depthTex_.Get();
- fe.mvecs = mvecResource;
- fe.outputInterpolated = genFrame_[genSlot].Get();
- fe.reset = reset;
- fe.frameId = realFrameIndex_;
- fe.mvecScaleX = haveFlow ? (1.0f / static_cast<float>(workW_)) : 1.0f;
- fe.mvecScaleY = haveFlow ? (1.0f / static_cast<float>(workH_)) : 1.0f;
- if (!fgBackend_->evaluate(flist, ngxParams_, fe, st)) {
- veyra::log::error("graph", "fg evaluate failed");
- return false;
- }
- tracker_.uavBarrier(flist, genFrame_[genSlot].Get());
- tracker_.transition(flist, genFrame_[genSlot].Get(), D3D12_RESOURCE_STATE_COMMON);
- tracker_.transition(flist, nvofInB_.Get(), D3D12_RESOURCE_STATE_COMMON);
- tracker_.transition(flist, mvecResource, D3D12_RESOURCE_STATE_COMMON);
- tracker_.transition(flist, depthTex_.Get(), D3D12_RESOURCE_STATE_COMMON);
- if (!ring_.submitAndSignal((slot + 2) % 4)) { veyra::log::error("graph", "fg submit"); return false; }
- if (desc_.stageMark) desc_.stageMark("fg");
- ++metrics_.fgGeneratedFrames;
- out.hasGenerated = true;
- out.genSlot = genSlot;
- out.genFenceValue = ring_.lastSignaledValue();
- out.generatedPtsMs = (prevPtsMs_ + ptsMs) * 0.5;
- }
- } // fg-enabled motion close
- }
+ fe.backbuffer=videoFrame_[parity].Get(); fe.depth=depthTex_.Get(); fe.mvecs=motion;
+ fe.outputInterpolated=genFrame_[parity].Get(); fe.reset=reset||!prevValid_;
+ fe.frameId=realFrameIndex_;
+ // FG consumer adapter: current->previous pixel flow -> normalized reverse flow.
+ fe.mvecScaleX=haveFlow?-1.0f/static_cast<float>(workW_):1.0f;
+ fe.mvecScaleY=haveFlow?-1.0f/static_cast<float>(workH_):1.0f;
+ if(!fgBackend_->evaluate(flist,ngxParams_,fe,st))return false;
+ tracker_.uavBarrier(flist,genFrame_[parity].Get());
+ tracker_.transition(flist,videoFrame_[parity].Get(),D3D12_RESOURCE_STATE_COMMON);
+ tracker_.transition(flist,genFrame_[parity].Get(),D3D12_RESOURCE_STATE_COMMON);
+ tracker_.transition(flist,depthTex_.Get(),D3D12_RESOURCE_STATE_COMMON);
+ if(!ring_.submitAndSignal(slot))return false;
+ out.hasGenerated=prevValid_&&!reset;
+ out.genSlot=parity; out.genFenceValue=ring_.lastSignaledValue();
+ out.generatedPtsMs=(prevPtsMs_+ptsMs)*0.5;
+ if(out.hasGenerated)++metrics_.fgGeneratedFrames;
+ }
+ uploadFences_[parity]=ring_.lastSignaledValue();
prevPtsMs_ = ptsMs;
prevValid_ = true;
@@ -952,6 +938,8 @@ ID3D12Resource* EnhanceGraph::generatedFrameResource(uint32_t slot) const
// ---------------------------------------------------------------------------
void EnhanceGraph::shutdown()
{
+ if (!initialized_ && !nrAdapter_ && !nvof_ && !srcRgba_) return;
+ (void)ring_.drainQueue();
Status st = Status::Ok;
if (nv12Ctx_ != nullptr) { sws_freeContext(nv12Ctx_); nv12Ctx_ = nullptr; }
diff --git a/src/sink/ImageExportSink.cpp b/src/sink/ImageExportSink.cpp
new file mode 100644
index 00000000..cd73201e
--- /dev/null
+++ b/src/sink/ImageExportSink.cpp
@@ -0,0 +1,78 @@
+#include "veyra/sink/ImageExportSink.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/Log.h"
+#include <wincodec.h>
+#include <wrl/client.h>
+#include <cstring>
+#include <filesystem>
+namespace veyra::sink {
+using Microsoft::WRL::ComPtr;
+bool readRgba8(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,ID3D12Resource* tex,RgbaImage& img) {
+ if(!tex) return false;
+ auto d=tex->GetDesc();
+ if(d.Format!=DXGI_FORMAT_R8G8B8A8_UNORM) return false;
+ D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{}; UINT rows=0; UINT64 rowBytes=0,total=0;
+ ctx.device()->GetCopyableFootprints(&d,0,1,0,&fp,&rows,&rowBytes,&total);
+ D3D12_HEAP_PROPERTIES hp{}; hp.Type=D3D12_HEAP_TYPE_READBACK;
+ D3D12_RESOURCE_DESC bd{}; bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER; bd.Width=total;
+ bd.Height=1; bd.DepthOrArraySize=1; bd.MipLevels=1; bd.SampleDesc.Count=1; bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ ComPtr<ID3D12Resource> rb;
+ if(FAILED(ctx.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&rb)))) return false;
+ Status st=Status::Ok; const auto slot=ring.slotCount()-1; auto* list=ring.acquire(slot,st); if(!list)return false;
+ D3D12_RESOURCE_BARRIER b{}; b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
+ b.Transition={tex,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_SOURCE};
+ list->ResourceBarrier(1,&b);
+ D3D12_TEXTURE_COPY_LOCATION src{},dst{};src.pResource=tex;src.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ dst.pResource=rb.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;dst.PlacedFootprint=fp;
+ list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);
+ std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(1,&b);
+ if(!ring.submitAndSignal(slot)||!ring.waitIdle())return false;
+ uint8_t* data=nullptr; D3D12_RANGE range{0,static_cast<SIZE_T>(total)};
+ if(FAILED(rb->Map(0,&range,reinterpret_cast<void**>(&data))))return false;
+ img.width=static_cast<uint32_t>(d.Width);img.height=d.Height;img.pixels.resize(size_t(img.width)*img.height*4);
+ for(UINT y=0;y<img.height;++y)std::memcpy(img.pixels.data()+size_t(y)*img.width*4,data+fp.Offset+size_t(y)*fp.Footprint.RowPitch,size_t(img.width)*4);
+ D3D12_RANGE empty{0,0};rb->Unmap(0,&empty);return true;
+}
+bool loadImage(const std::wstring& path,RgbaImage& img) {
+ ComPtr<IWICImagingFactory> fac;ComPtr<IWICBitmapDecoder> dec;ComPtr<IWICBitmapFrameDecode> frame;ComPtr<IWICFormatConverter> conv;
+ if(FAILED(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&fac)))||
+ FAILED(fac->CreateDecoderFromFilename(path.c_str(),nullptr,GENERIC_READ,WICDecodeMetadataCacheOnLoad,&dec))||
+ FAILED(dec->GetFrame(0,&frame))||FAILED(fac->CreateFormatConverter(&conv))||
+ FAILED(conv->Initialize(frame.Get(),GUID_WICPixelFormat32bppRGBA,WICBitmapDitherTypeNone,nullptr,0,WICBitmapPaletteTypeCustom))||
+ FAILED(conv->GetSize(&img.width,&img.height))||img.width==0||img.height==0||img.width>8192||img.height>8192) return false;
+ ComPtr<IWICMetadataQueryReader> metadata;
+ UINT orientation=1;
+ if(SUCCEEDED(frame->GetMetadataQueryReader(&metadata))){PROPVARIANT value{};
+ if(SUCCEEDED(metadata->GetMetadataByName(L"/app1/ifd/{ushort=274}",&value))&&value.vt==VT_UI2)orientation=value.uiVal;
+ PropVariantClear(&value);
+ }
+ const WICBitmapTransformOptions transforms[9]={WICBitmapTransformRotate0,WICBitmapTransformRotate0,WICBitmapTransformFlipHorizontal,WICBitmapTransformRotate180,WICBitmapTransformFlipVertical,
+ static_cast<WICBitmapTransformOptions>(WICBitmapTransformRotate90|WICBitmapTransformFlipHorizontal),WICBitmapTransformRotate90,
+ static_cast<WICBitmapTransformOptions>(WICBitmapTransformRotate270|WICBitmapTransformFlipHorizontal),WICBitmapTransformRotate270};
+ ComPtr<IWICBitmapFlipRotator> oriented;
+ if(FAILED(fac->CreateBitmapFlipRotator(&oriented))||FAILED(oriented->Initialize(conv.Get(),transforms[orientation<=8?orientation:1]))||FAILED(oriented->GetSize(&img.width,&img.height)))return false;
+ img.pixels.resize(size_t(img.width)*img.height*4);
+ return SUCCEEDED(oriented->CopyPixels(nullptr,img.width*4,static_cast<UINT>(img.pixels.size()),img.pixels.data()));
+}
+bool saveImage(const std::wstring& path,const RgbaImage& img,bool jpeg) {
+ if(img.pixels.size()!=size_t(img.width)*img.height*4||std::filesystem::exists(path))return false;
+ const auto temp=path+L".partial";
+ if(std::filesystem::exists(temp))return false;
+ ComPtr<IWICImagingFactory> fac;ComPtr<IWICStream> stream;ComPtr<IWICBitmapEncoder> enc;ComPtr<IWICBitmapFrameEncode> frame;ComPtr<IPropertyBag2> opts;
+ if(FAILED(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&fac)))||
+ FAILED(fac->CreateStream(&stream))||FAILED(stream->InitializeFromFilename(temp.c_str(),GENERIC_WRITE))||
+ FAILED(fac->CreateEncoder(jpeg?GUID_ContainerFormatJpeg:GUID_ContainerFormatPng,nullptr,&enc))||
+ FAILED(enc->Initialize(stream.Get(),WICBitmapEncoderNoCache))||FAILED(enc->CreateNewFrame(&frame,&opts))||
+ FAILED(frame->Initialize(opts.Get()))||FAILED(frame->SetSize(img.width,img.height)))return false;
+ auto format=jpeg?GUID_WICPixelFormat24bppBGR:GUID_WICPixelFormat32bppRGBA;
+ if(FAILED(frame->SetPixelFormat(&format)))return false;
+ std::vector<uint8_t> bgr;
+ const uint8_t* pixels=img.pixels.data();UINT stride=img.width*4;
+ if(jpeg){bgr.resize(size_t(img.width)*img.height*3);for(size_t i=0;i<img.pixels.size()/4;++i){bgr[i*3]=pixels[i*4+2];bgr[i*3+1]=pixels[i*4+1];bgr[i*3+2]=pixels[i*4];}pixels=bgr.data();stride=img.width*3;}
+ if(FAILED(frame->WritePixels(img.height,stride,stride*img.height,const_cast<BYTE*>(pixels)))||FAILED(frame->Commit())||FAILED(enc->Commit()))return false;
+ frame.Reset();enc.Reset();stream.Reset();RgbaImage check;
+ if(!loadImage(temp,check)||check.width!=img.width||check.height!=img.height)return false;
+ return MoveFileExW(temp.c_str(),path.c_str(),MOVEFILE_WRITE_THROUGH)!=FALSE;
+}
+}
diff --git a/src/sink/NvencD3D12Encoder.cpp b/src/sink/NvencD3D12Encoder.cpp
new file mode 100644
index 00000000..869f4ec4
--- /dev/null
+++ b/src/sink/NvencD3D12Encoder.cpp
@@ -0,0 +1,85 @@
+#include "veyra/sink/NvencD3D12Encoder.h"
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include <ffnvcodec/nvEncodeAPI.h>
+#include <array>
+#include <bit>
+#include <format>
+#include <algorithm>
+namespace veyra::sink {
+using namespace veyra::pipeline;
+struct NvencD3D12Encoder::Impl {
+ HMODULE dll=nullptr;void* encoder=nullptr;NV_ENCODE_API_FUNCTION_LIST api{};
+ gfx::D3D12DeviceContext* ctx=nullptr;gfx::CommandSlotRing* ring=nullptr;EnhanceGraph* graph=nullptr;
+ unsigned w=0,h=0;uint64_t submitted=0,completed=0;
+ ComPtr<ID3D12Fence> fence;HANDLE event=nullptr;
+ ComputePass convert;StateTracker states;ComPtr<ID3D12Resource> y,uv;
+ PacketWriter writer;std::vector<uint8_t> sequence;
+ struct Slot {ComPtr<ID3D12Resource> input,output;NV_ENC_REGISTERED_PTR registeredIn=nullptr,registeredOut=nullptr;NV_ENC_INPUT_PTR mappedIn=nullptr,mappedOut=nullptr;NV_ENC_INPUT_RESOURCE_D3D12 in{};NV_ENC_OUTPUT_RESOURCE_D3D12 out{};uint64_t value=0;bool pending=false;};
+ std::array<Slot,4> slots;
+ bool check(NVENCSTATUS code,const char* op){veyra::log::info("nvenc",std::format("{} status={} detail={}",op,int(code),code!=NV_ENC_SUCCESS&&encoder&&api.nvEncGetLastErrorString?api.nvEncGetLastErrorString(encoder):""));return code==NV_ENC_SUCCESS;}
+ bool drain(Slot& s){
+ if(!s.pending)return true;
+ if(fence->GetCompletedValue()<s.value){if(FAILED(fence->SetEventOnCompletion(s.value,event))||WaitForSingleObject(event,10000)!=WAIT_OBJECT_0)return false;}
+ NV_ENC_LOCK_BITSTREAM lock{};lock.version=NV_ENC_LOCK_BITSTREAM_VER;lock.outputBitstream=&s.out;lock.doNotWait=0;
+ if(!check(api.nvEncLockBitstream(encoder,&lock),"LockBitstream"))return false;
+ const bool ok=writer(static_cast<uint8_t*>(lock.bitstreamBufferPtr),lock.bitstreamSizeInBytes,static_cast<int64_t>(lock.outputTimeStamp),lock.pictureType==NV_ENC_PIC_TYPE_IDR);
+ const bool unlock=check(api.nvEncUnlockBitstream(encoder,&s.out),"UnlockBitstream");
+ s.pending=false;++completed;return ok&&unlock;
+ }
+};
+NvencD3D12Encoder::NvencD3D12Encoder():p_(std::make_unique<Impl>()){}
+NvencD3D12Encoder::~NvencD3D12Encoder(){close();}
+std::vector<uint8_t> NvencD3D12Encoder::headers()const{return p_->sequence;}
+bool NvencD3D12Encoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,EnhanceGraph& graph,bool hevc,unsigned fpsNum,unsigned fpsDen,PacketWriter writer){
+ auto& p=*p_;p.ctx=&ctx;p.ring=&ring;p.graph=&graph;p.w=graph.workWidth();p.h=graph.workHeight();p.writer=std::move(writer);
+ wchar_t dir[MAX_PATH]{};GetSystemDirectoryW(dir,MAX_PATH);const auto dllPath=std::wstring(dir)+L"\\nvEncodeAPI64.dll";
+ p.dll=LoadLibraryExW(dllPath.c_str(),nullptr,LOAD_LIBRARY_SEARCH_SYSTEM32);if(!p.dll)return false;
+ using Create=NVENCSTATUS(NVENCAPI*)(NV_ENCODE_API_FUNCTION_LIST*);auto create=reinterpret_cast<Create>(GetProcAddress(p.dll,"NvEncodeAPICreateInstance"));
+ p.api.version=NV_ENCODE_API_FUNCTION_LIST_VER;if(!create||!p.check(create(&p.api),"CreateInstance"))return false;
+ NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS open{};open.version=NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;open.apiVersion=NVENCAPI_VERSION;open.device=ctx.device();open.deviceType=NV_ENC_DEVICE_TYPE_DIRECTX;
+ if(!p.check(p.api.nvEncOpenEncodeSessionEx(&open,&p.encoder),"OpenD3D12Session"))return false;
+ const GUID codec=hevc?NV_ENC_CODEC_HEVC_GUID:NV_ENC_CODEC_H264_GUID;
+ NV_ENC_PRESET_CONFIG preset{};preset.version=NV_ENC_PRESET_CONFIG_VER;preset.presetCfg.version=NV_ENC_CONFIG_VER;
+ if(!p.check(p.api.nvEncGetEncodePresetConfigEx(p.encoder,codec,NV_ENC_PRESET_P4_GUID,NV_ENC_TUNING_INFO_LOW_LATENCY,&preset),"GetPreset"))return false;
+ preset.presetCfg.frameIntervalP=1;preset.presetCfg.gopLength=120;preset.presetCfg.rcParams.rateControlMode=NV_ENC_PARAMS_RC_CONSTQP;
+ preset.presetCfg.rcParams.constQP={20,22,22};preset.presetCfg.rcParams.enableLookahead=0;
+ NV_ENC_INITIALIZE_PARAMS init{};init.version=NV_ENC_INITIALIZE_PARAMS_VER;init.encodeGUID=codec;init.presetGUID=NV_ENC_PRESET_P4_GUID;init.tuningInfo=NV_ENC_TUNING_INFO_LOW_LATENCY;
+ init.encodeWidth=p.w;init.encodeHeight=p.h;init.darWidth=p.w;init.darHeight=p.h;init.frameRateNum=fpsNum;init.frameRateDen=fpsDen;init.enablePTD=1;init.encodeConfig=&preset.presetCfg;init.maxEncodeWidth=p.w;init.maxEncodeHeight=p.h;
+ init.bufferFormat=NV_ENC_BUFFER_FORMAT_NV12;
+ if(!p.check(p.api.nvEncInitializeEncoder(p.encoder,&init),"InitializeEncoder"))return false;
+ p.sequence.resize(4096);uint32_t size=0;NV_ENC_SEQUENCE_PARAM_PAYLOAD seq{};seq.version=NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;seq.inBufferSize=4096;seq.spsppsBuffer=p.sequence.data();seq.outSPSPPSPayloadSize=&size;
+ if(!p.check(p.api.nvEncGetSequenceParams(p.encoder,&seq),"GetSequenceParams"))return false;p.sequence.resize(size);
+ if(FAILED(ctx.device()->CreateFence(0,D3D12_FENCE_FLAG_NONE,IID_PPV_ARGS(&p.fence))))return false;p.event=CreateEventW(nullptr,FALSE,FALSE,nullptr);if(!p.event)return false;
+ p.y=makeTexture(ctx.device(),p.w,p.h,DXGI_FORMAT_R8_UNORM,true);p.uv=makeTexture(ctx.device(),p.w/2,p.h/2,DXGI_FORMAT_R8G8_UNORM,true);if(!p.y||!p.uv)return false;
+ std::vector<uint8_t> cs;if(!p.convert.loadShader("RgbToNv12.dxil",cs)||!p.convert.create(ctx.device(),cs,6,1,2))return false;
+ for(unsigned i=0;i<4;++i)makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),DXGI_FORMAT_R8G8B8A8_UNORM,cpuHandleOf(p.convert,i));
+ makeUav(ctx.device(),p.y.Get(),DXGI_FORMAT_R8_UNORM,cpuHandleOf(p.convert,4));makeUav(ctx.device(),p.uv.Get(),DXGI_FORMAT_R8G8_UNORM,cpuHandleOf(p.convert,5));
+ for(auto& s:p.slots){
+ s.input=makeTexture(ctx.device(),p.w,p.h,DXGI_FORMAT_NV12,false);if(!s.input)return false;
+ D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=(uint64_t(p.w)*p.h*4+4095)&~4095ull;bd.Height=1;bd.DepthOrArraySize=1;bd.MipLevels=1;bd.SampleDesc.Count=1;bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ if(FAILED(ctx.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&s.output))))return false;
+ auto reg=[&](ID3D12Resource* resource,bool output,NV_ENC_REGISTERED_PTR& registered,NV_ENC_INPUT_PTR& mapped){NV_ENC_REGISTER_RESOURCE r{};r.version=NV_ENC_REGISTER_RESOURCE_VER;r.resourceType=NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;r.resourceToRegister=resource;r.width=output?static_cast<uint32_t>(bd.Width):p.w;r.height=output?1:p.h;r.bufferFormat=output?NV_ENC_BUFFER_FORMAT_U8:NV_ENC_BUFFER_FORMAT_NV12;r.bufferUsage=output?NV_ENC_OUTPUT_BITSTREAM:NV_ENC_INPUT_IMAGE;
+ if(!p.check(p.api.nvEncRegisterResource(p.encoder,&r),output?"RegisterOutput":"RegisterNV12"))return false;registered=r.registeredResource;
+ NV_ENC_MAP_INPUT_RESOURCE m{};m.version=NV_ENC_MAP_INPUT_RESOURCE_VER;m.registeredResource=registered;if(!p.check(p.api.nvEncMapInputResource(p.encoder,&m),"MapResource"))return false;mapped=m.mappedResource;return true;};
+ if(!reg(s.input.Get(),false,s.registeredIn,s.mappedIn)||!reg(s.output.Get(),true,s.registeredOut,s.mappedOut))return false;
+ s.in.version=NV_ENC_INPUT_RESOURCE_D3D12_VER;s.in.pInputBuffer=s.mappedIn;s.in.inputFencePoint.version=NV_ENC_FENCE_POINT_D3D12_VER;s.in.inputFencePoint.pFence=ctx.fence();s.in.inputFencePoint.bWait=1;
+ s.out.version=NV_ENC_OUTPUT_RESOURCE_D3D12_VER;s.out.pOutputBuffer=s.mappedOut;s.out.outputFencePoint.version=NV_ENC_FENCE_POINT_D3D12_VER;s.out.outputFencePoint.pFence=p.fence.Get();s.out.outputFencePoint.bSignal=1;
+ }return true;
+}
+bool NvencD3D12Encoder::encode(unsigned frameSlot,bool generated,int64_t pts){auto& p=*p_;auto& s=p.slots[p.submitted%4];if(!p.drain(s))return false;
+ Status st=Status::Ok;const auto slot=p.ring->slotCount()-1;auto* list=p.ring->acquire(slot,st);if(!list)return false;
+ auto* color=generated?p.graph->generatedFrameResource(frameSlot):p.graph->videoFrameResource(frameSlot);
+ p.states.transition(list,color,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);p.states.transition(list,p.y.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);p.states.transition(list,p.uv.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ const float dims[8]={std::bit_cast<float>(p.w),std::bit_cast<float>(p.h),0,0,0,0,0,0};p.convert.bind(list,dims,gpuHandleOf(p.convert,frameSlot+(generated?2:0)).ptr,gpuHandleOf(p.convert,4).ptr);list->Dispatch((p.w+15)/16,(p.h+15)/16,1);
+ p.states.uavBarrier(list,p.y.Get());p.states.uavBarrier(list,p.uv.Get());p.states.transition(list,p.y.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);p.states.transition(list,p.uv.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);p.states.transition(list,s.input.Get(),D3D12_RESOURCE_STATE_COPY_DEST);
+ for(unsigned plane=0;plane<2;++plane){D3D12_TEXTURE_COPY_LOCATION a{},b{};a.pResource=plane?p.uv.Get():p.y.Get();a.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;b.pResource=s.input.Get();b.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;b.SubresourceIndex=plane;list->CopyTextureRegion(&b,0,0,0,&a,nullptr);}
+ p.states.transition(list,s.input.Get(),D3D12_RESOURCE_STATE_COMMON);p.states.transition(list,color,D3D12_RESOURCE_STATE_COMMON);if(!p.ring->submitAndSignal(slot))return false;
+ s.in.inputFencePoint.waitValue=p.ring->lastSignaledValue();s.value=p.submitted+1;s.out.outputFencePoint.signalValue=s.value;
+ NV_ENC_PIC_PARAMS pic{};pic.version=NV_ENC_PIC_PARAMS_VER;pic.inputWidth=p.w;pic.inputHeight=p.h;pic.inputBuffer=&s.in;pic.outputBitstream=&s.out;pic.bufferFmt=NV_ENC_BUFFER_FORMAT_NV12;pic.pictureStruct=NV_ENC_PIC_STRUCT_FRAME;pic.inputTimeStamp=pts;pic.inputDuration=1;
+ if(!p.check(p.api.nvEncEncodePicture(p.encoder,&pic),"EncodePicture"))return false;s.pending=true;++p.submitted;return true;
+}
+bool NvencD3D12Encoder::finish(){auto& p=*p_;while(p.completed<p.submitted){if(!p.drain(p.slots[p.completed%4]))return false;}return true;}
+void NvencD3D12Encoder::close(){if(!p_)return;auto& p=*p_;if(p.encoder){finish();for(auto& s:p.slots){if(s.mappedOut)p.api.nvEncUnmapInputResource(p.encoder,s.mappedOut);if(s.mappedIn)p.api.nvEncUnmapInputResource(p.encoder,s.mappedIn);if(s.registeredOut)p.api.nvEncUnregisterResource(p.encoder,s.registeredOut);if(s.registeredIn)p.api.nvEncUnregisterResource(p.encoder,s.registeredIn);}p.api.nvEncDestroyEncoder(p.encoder);p.encoder=nullptr;}if(p.event){CloseHandle(p.event);p.event=nullptr;}if(p.dll){FreeLibrary(p.dll);p.dll=nullptr;}}
+}
diff --git a/src/sink/WasapiAudioSink.cpp b/src/sink/WasapiAudioSink.cpp
index d6c6db16..f2fb4806 100644
--- a/src/sink/WasapiAudioSink.cpp
+++ b/src/sink/WasapiAudioSink.cpp
@@ -24,14 +24,15 @@ AudioPipeline::AudioPipeline()
AudioPipeline::~AudioPipeline()
{
- closeAll();
stopThread();
+ closeAll();
}
bool AudioPipeline::open(const std::wstring& path)
{
- std::string narrow;
- narrow.assign(path.begin(), path.end());
+ const int length=WideCharToMultiByte(CP_UTF8,0,path.data(),static_cast<int>(path.size()),nullptr,0,nullptr,nullptr);
+ std::string narrow(length,'\0');
+ WideCharToMultiByte(CP_UTF8,0,path.data(),static_cast<int>(path.size()),narrow.data(),length,nullptr,nullptr);
if (avformat_open_input(&fmt_, narrow.c_str(), nullptr, nullptr) != 0) return false;
if (avformat_find_stream_info(fmt_, nullptr) < 0) return false;
const AVCodec* codec = nullptr;
@@ -226,13 +227,18 @@ bool AudioRenderer::start()
hr = device_->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr,
reinterpret_cast<void**>(&client_));
if (FAILED(hr)) return false;
- WAVEFORMATEX* mix = nullptr;
- if (FAILED(client_->GetMixFormat(&mix))) return false;
- sampleRate_ = mix->nSamplesPerSec;
- hr = client_->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
- 10 * 10000, 0, mix, nullptr);
+ WAVEFORMATEX mix{};
+ mix.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
+ mix.nChannels = 2;
+ mix.nSamplesPerSec = kAudioRate;
+ mix.wBitsPerSample = 32;
+ mix.nBlockAlign = 8;
+ mix.nAvgBytesPerSec = mix.nSamplesPerSec * mix.nBlockAlign;
+ sampleRate_ = kAudioRate;
+ hr = client_->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK |
+ AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY,
+ 10 * 10000, 0, &mix, nullptr);
const bool initOk = SUCCEEDED(hr);
- CoTaskMemFree(mix);
if (!initOk) return false;
if (FAILED(client_->GetBufferSize(&bufferFrames_))) return false;
event_ = CreateEventW(nullptr, FALSE, FALSE, nullptr);
@@ -307,9 +313,7 @@ double AudioRenderer::mediaTimeMs() const
void AudioRenderer::stopAndReset()
{
- if (!running_) return;
- (void)client_->Stop();
- (void)client_->Reset();
+ if (client_) { (void)client_->Stop(); (void)client_->Reset(); }
started_ = false;
framesWritten_ = 0;
}
@@ -320,15 +324,21 @@ uint64_t AudioRenderer::framesWritten() const { return framesWritten_; }
void AudioRenderer::shutdown()
{
- if (!running_) return;
- (void)client_->Stop();
- (void)client_->Reset();
+ if (client_) { (void)client_->Stop(); (void)client_->Reset(); }
#define REL(x) if (x) { x->Release(); x = nullptr; }
REL(clock_); REL(render_); REL(client_); REL(device_); REL(enum_);
#undef REL
if (event_ != nullptr) { CloseHandle(event_); event_ = nullptr; }
running_ = false;
- if (comInited_) CoUninitialize();
+ started_ = false;
+ if (comInited_) { CoUninitialize(); comInited_ = false; }
+}
+
+void AudioRenderer::setPaused(bool value)
+{
+ if (!client_ || !started_) return;
+ const HRESULT hr = value ? client_->Stop() : client_->Start();
+ if (FAILED(hr)) veyra::log::error("audio", std::format("pause/resume failed hr=0x{:X}", static_cast<unsigned>(hr)));
}
void AudioPipeline::runOnAudioThread(AudioRenderer* renderer)
@@ -356,7 +366,11 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer)
veyra::log::info("audio", std::format("startup prefill done in {:.0f}ms firstPtsMs={:.1f} bufferedMs={:.0f}",
lastPrefillMs_.load(), firstPts, bufferedMs()));
+ bool pauseApplied = false;
while (!stopFlag_.load()) {
+ const bool pauseNow = paused_.load();
+ if (pauseNow != pauseApplied && renderer) renderer->setPaused(pauseNow);
+ pauseApplied = pauseNow;
// Seek request? Atomic re-sequence.
{
std::unique_lock<std::mutex> lock(mutex_);
@@ -383,7 +397,7 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer)
double startPts = headPtsMs();
if (startPts < 0.0) startPts = target;
firstPtsAfterSeek_.store(startPts);
- if (renderer != nullptr) renderer->startAnchored(startPts);
+ if (renderer != nullptr) { renderer->startAnchored(startPts); if (pauseNow) renderer->setPaused(true); }
{
std::lock_guard<std::mutex> l2(mutex_);
discardUntilPtsMs_ = -1.0;
@@ -395,6 +409,7 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer)
continue;
}
}
+ if (pauseNow) { std::this_thread::sleep_for(std::chrono::milliseconds(5)); continue; }
// Regular cycle: pump the endpoint, then top up below high watermark.
if (renderer != nullptr) {
double firstPts = -1.0;
diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cpp
new file mode 100644
index 00000000..c4551176
--- /dev/null
+++ b/src/source/CaptureCardSource.cpp
@@ -0,0 +1,68 @@
+#include "veyra/source/CaptureCardSource.h"
+#include "veyra/Log.h"
+#include <windows.h>
+#include <dshow.h>
+#include <dvdmedia.h>
+#include <wrl/client.h>
+#include <mutex>
+#include <condition_variable>
+#include <atomic>
+#include <format>
+#include <chrono>
+extern "C" {
+#include <libavutil/frame.h>
+#include <libavutil/pixfmt.h>
+}
+namespace veyra::source {
+using Microsoft::WRL::ComPtr;
+namespace {
+// Legacy qedit interfaces are intentionally declared without obsolete qedit.h,
+// which conflicts with modern D3D headers. ABI follows Microsoft DirectShow.
+struct __declspec(uuid("0579154A-2B53-4994-B0D0-E773148EFF85")) ISampleGrabberCB: IUnknown {virtual HRESULT STDMETHODCALLTYPE SampleCB(double,IMediaSample*)=0;virtual HRESULT STDMETHODCALLTYPE BufferCB(double,BYTE*,long)=0;};
+struct __declspec(uuid("6B652FFF-11FE-4FCE-92AD-0266B5D7C78F")) ISampleGrabber:IUnknown {virtual HRESULT STDMETHODCALLTYPE SetOneShot(BOOL)=0;virtual HRESULT STDMETHODCALLTYPE SetMediaType(const AM_MEDIA_TYPE*)=0;virtual HRESULT STDMETHODCALLTYPE GetConnectedMediaType(AM_MEDIA_TYPE*)=0;virtual HRESULT STDMETHODCALLTYPE SetBufferSamples(BOOL)=0;virtual HRESULT STDMETHODCALLTYPE GetCurrentBuffer(long*,long*)=0;virtual HRESULT STDMETHODCALLTYPE GetCurrentSample(IMediaSample**)=0;virtual HRESULT STDMETHODCALLTYPE SetCallback(ISampleGrabberCB*,long)=0;};
+const CLSID SampleGrabberClass={0xc1f400a0,0x3f08,0x11d3,{0x9f,0x0b,0x00,0x60,0x08,0x03,0x9e,0x37}};
+const CLSID NullRendererClass={0xc1f400a4,0x3f08,0x11d3,{0x9f,0x0b,0x00,0x60,0x08,0x03,0x9e,0x37}};
+void freeType(AM_MEDIA_TYPE* t,bool pointer=true){if(!t)return;CoTaskMemFree(t->pbFormat);if(t->pUnk)t->pUnk->Release();if(pointer)CoTaskMemFree(t);}
+std::vector<ComPtr<IMoniker>> monikers(bool audio){std::vector<ComPtr<IMoniker>> out;ComPtr<ICreateDevEnum> de;ComPtr<IEnumMoniker> en;if(FAILED(CoCreateInstance(CLSID_SystemDeviceEnum,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&de)))||de->CreateClassEnumerator(audio?CLSID_AudioInputDeviceCategory:CLSID_VideoInputDeviceCategory,&en,0)!=S_OK)return out;for(;;){ComPtr<IMoniker> m;if(en->Next(1,&m,nullptr)!=S_OK)break;out.push_back(m);}return out;}
+bool bind(unsigned index,bool audio,ComPtr<IBaseFilter>& filter){auto list=monikers(audio);return index<list.size()&&SUCCEEDED(list[index]->BindToObject(nullptr,nullptr,IID_PPV_ARGS(&filter)));}
+bool configuration(unsigned device,ComPtr<IGraphBuilder>& g,ComPtr<ICaptureGraphBuilder2>& b,ComPtr<IBaseFilter>& f,ComPtr<IAMStreamConfig>& c){return SUCCEEDED(CoCreateInstance(CLSID_FilterGraph,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&g)))&&SUCCEEDED(CoCreateInstance(CLSID_CaptureGraphBuilder2,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&b)))&&SUCCEEDED(b->SetFiltergraph(g.Get()))&&bind(device,false,f)&&SUCCEEDED(g->AddFilter(f.Get(),L"Capture card"))&&SUCCEEDED(b->FindInterface(&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,f.Get(),IID_PPV_ARGS(&c)));}
+}
+struct CaptureCardSource::Impl:ISampleGrabberCB {
+ std::atomic<ULONG> refs{1};std::mutex mutex;std::condition_variable wake;ComPtr<IMediaSample> pending;double pendingTime=0;uint64_t dropped=0,lastDrop=0,sequence=0;
+ ComPtr<IGraphBuilder> graph;ComPtr<ICaptureGraphBuilder2> builder;ComPtr<IBaseFilter> device,grabFilter,nullFilter,audioFilter;ComPtr<IAMStreamConfig> config;ComPtr<ISampleGrabber> grab;ComPtr<IMediaControl> control;ComPtr<IMediaEvent> events;
+ SourceInfo info;AVFrame* frame=nullptr;bool bottomUp=true;unsigned stride=0;std::chrono::steady_clock::time_point lastFrame;
+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** pp)override{if(!pp)return E_POINTER;*pp=nullptr;if(id==IID_IUnknown||id==__uuidof(ISampleGrabberCB)){*pp=static_cast<ISampleGrabberCB*>(this);AddRef();return S_OK;}return E_NOINTERFACE;}
+ ULONG STDMETHODCALLTYPE AddRef()override{return ++refs;}ULONG STDMETHODCALLTYPE Release()override{return --refs;}
+ HRESULT STDMETHODCALLTYPE SampleCB(double time,IMediaSample* sample)override{{std::lock_guard lock(mutex);if(pending)++dropped;pending=sample;pendingTime=time;}wake.notify_one();return S_OK;}
+ HRESULT STDMETHODCALLTYPE BufferCB(double,BYTE*,long)override{return E_NOTIMPL;}
+};
+CaptureCardSource::CaptureCardSource():p_(std::make_unique<Impl>()){}
+CaptureCardSource::~CaptureCardSource(){close();}
+std::vector<std::wstring> CaptureCardSource::devices(bool audio){std::vector<std::wstring> result;for(auto& m:monikers(audio)){ComPtr<IPropertyBag> bag;VARIANT v;VariantInit(&v);std::wstring name=L"Unknown capture device";if(SUCCEEDED(m->BindToStorage(nullptr,nullptr,IID_PPV_ARGS(&bag)))&&SUCCEEDED(bag->Read(L"FriendlyName",&v,nullptr))&&v.vt==VT_BSTR)name=v.bstrVal;VariantClear(&v);result.push_back(name);}return result;}
+std::vector<CaptureFormat> CaptureCardSource::formats(unsigned device){ComPtr<IGraphBuilder> g;ComPtr<ICaptureGraphBuilder2>b;ComPtr<IBaseFilter>f;ComPtr<IAMStreamConfig>c;std::vector<CaptureFormat> out;if(!configuration(device,g,b,f,c))return out;int count=0,size=0;if(FAILED(c->GetNumberOfCapabilities(&count,&size))||size<1||size>65536)return out;std::vector<BYTE> caps(size);for(int i=0;i<count;++i){AM_MEDIA_TYPE* t=nullptr;if(FAILED(c->GetStreamCaps(i,&t,caps.data())))continue;BITMAPINFOHEADER* bm=nullptr;REFERENCE_TIME duration=0;if(t->formattype==FORMAT_VideoInfo&&t->cbFormat>=sizeof(VIDEOINFOHEADER)){auto* vi=reinterpret_cast<VIDEOINFOHEADER*>(t->pbFormat);bm=&vi->bmiHeader;duration=vi->AvgTimePerFrame;}else if(t->formattype==FORMAT_VideoInfo2&&t->cbFormat>=sizeof(VIDEOINFOHEADER2)){auto* vi=reinterpret_cast<VIDEOINFOHEADER2*>(t->pbFormat);bm=&vi->bmiHeader;duration=vi->AvgTimePerFrame;}
+ if(bm&&bm->biWidth>0&&bm->biWidth<=3840&&abs(bm->biHeight)<=2160&&duration>0){unsigned w=bm->biWidth,h=abs(bm->biHeight);double fps=1e7/duration;if((w==1920&&h==1080||w==3840&&h==2160)&&fps>=29&&fps<=61)out.push_back({i,w,h,fps,std::format(L"{} x {} @ {:.2f} fps [format {}]",w,h,fps,i)});}freeType(t);}return out;}
+const SourceInfo& CaptureCardSource::info()const{return p_->info;}
+bool CaptureCardSource::open(const SourceOpenDesc& desc){close();auto& p=*p_;unsigned index=0;int format=0,audio=-1;if(swscanf_s(desc.path.c_str(),L"capture:%u:%d:%d",&index,&format,&audio)!=3)return false;
+ if(!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;HRESULT hr=p.config->SetFormat(native);freeType(native);if(FAILED(hr))return false;
+ if(FAILED(CoCreateInstance(SampleGrabberClass,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&p.grabFilter)))||FAILED(p.grabFilter.As(&p.grab))||FAILED(p.graph->AddFilter(p.grabFilter.Get(),L"Latest frame mailbox")))return false;
+ AM_MEDIA_TYPE want{};want.majortype=MEDIATYPE_Video;want.subtype=MEDIASUBTYPE_RGB32;want.formattype=FORMAT_VideoInfo;
+ if(FAILED(p.grab->SetMediaType(&want))||FAILED(CoCreateInstance(NullRendererClass,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&p.nullFilter)))||FAILED(p.graph->AddFilter(p.nullFilter.Get(),L"Video sink"))||FAILED(p.builder->RenderStream(&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,p.device.Get(),p.grabFilter.Get(),p.nullFilter.Get())))return false;
+ AM_MEDIA_TYPE connected{};if(FAILED(p.grab->GetConnectedMediaType(&connected)))return false;
+ if(connected.formattype!=FORMAT_VideoInfo||connected.cbFormat<sizeof(VIDEOINFOHEADER)){freeType(&connected,false);return false;}auto vi=*reinterpret_cast<VIDEOINFOHEADER*>(connected.pbFormat);freeType(&connected,false);
+ if(vi.bmiHeader.biWidth<=0||vi.bmiHeader.biWidth>3840||abs(vi.bmiHeader.biHeight)>2160||vi.bmiHeader.biBitCount!=32)return false;
+ p.info={};p.info.kind=pipeline::SourceKind::CaptureCard;p.info.width=vi.bmiHeader.biWidth;p.info.height=abs(vi.bmiHeader.biHeight);p.info.averageFps=vi.AvgTimePerFrame>0?1e7/vi.AvgTimePerFrame:0;p.info.duration=pipeline::Rational::unknown();p.bottomUp=vi.bmiHeader.biHeight>0;p.stride=p.info.width*4;
+ if(audio>=0){if(!bind(unsigned(audio),true,p.audioFilter)||FAILED(p.graph->AddFilter(p.audioFilter.Get(),L"Capture audio"))||FAILED(p.builder->RenderStream(&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Audio,p.audioFilter.Get(),nullptr,nullptr)))return false;}
+ if(FAILED(p.graph.As(&p.control))||FAILED(p.graph.As(&p.events))||FAILED(p.grab->SetBufferSamples(FALSE))||FAILED(p.grab->SetCallback(&p,0)))return false;
+ p.frame=av_frame_alloc();p.frame->format=AV_PIX_FMT_BGRA;p.frame->width=p.info.width;p.frame->height=p.info.height;p.frame->color_range=AVCOL_RANGE_JPEG;if(av_frame_get_buffer(p.frame,32)<0)return false;
+ p.lastFrame=std::chrono::steady_clock::now();hr=p.control->Run();veyra::log::info("capture",std::format("Run hr=0x{:X} actual={}x{} fps={:.3f} mailbox=1 audioDevice={}",unsigned(hr),p.info.width,p.info.height,p.info.averageFps,audio));p.info.opened=SUCCEEDED(hr);return p.info.opened;
+}
+SourceReadStatus CaptureCardSource::read(pipeline::FramePacket& packet,const AVFrame** frame){auto& p=*p_;*frame=nullptr;if(!p.info.opened)return SourceReadStatus::Error;
+ long code=0;LONG_PTR a=0,b=0;while(p.events&&p.events->GetEvent(&code,&a,&b,0)==S_OK){p.events->FreeEventParams(code,a,b);if(code==EC_DEVICE_LOST||code==EC_ERRORABORT)return SourceReadStatus::Error;}
+ ComPtr<IMediaSample> sample;double time=0;bool drop=false;{std::unique_lock lock(p.mutex);p.wake.wait_for(lock,std::chrono::milliseconds(30),[&]{return p.pending!=nullptr;});if(!p.pending)return std::chrono::steady_clock::now()-p.lastFrame>std::chrono::seconds(3)?SourceReadStatus::Error:SourceReadStatus::Waiting;sample.Swap(p.pending);time=p.pendingTime;drop=p.dropped!=p.lastDrop;p.lastDrop=p.dropped;}
+ BYTE* data=nullptr;if(FAILED(sample->GetPointer(&data))||sample->GetActualDataLength()<LONG(p.stride*p.info.height))return SourceReadStatus::Error;
+ for(unsigned y=0;y<p.info.height;++y)memcpy(p.frame->data[0]+size_t(y)*p.frame->linesize[0],data+size_t(p.bottomUp?p.info.height-1-y:y)*p.stride,p.stride);
+ p.frame->pts=static_cast<int64_t>(time*10000000);packet={};packet.pts={p.frame->pts,10000000};packet.sourceKind=pipeline::SourceKind::CaptureCard;packet.sequence=++p.sequence;packet.flags=drop?static_cast<uint32_t>(pipeline::FrameFlagBits::Drop):0;packet.sourceEpoch=1;*frame=p.frame;p.lastFrame=std::chrono::steady_clock::now();return SourceReadStatus::Frame;
+}
+void CaptureCardSource::close()noexcept{auto& p=*p_;if(p.control)p.control->Stop();if(p.grab)p.grab->SetCallback(nullptr,0);{std::lock_guard lock(p.mutex);p.pending.Reset();}p.events.Reset();p.control.Reset();p.grab.Reset();p.nullFilter.Reset();p.grabFilter.Reset();p.audioFilter.Reset();p.config.Reset();p.device.Reset();p.builder.Reset();p.graph.Reset();av_frame_free(&p.frame);p.info={};p.sequence=p.dropped=p.lastDrop=0;}
+}
diff --git a/tools/quality_probe/main.cpp b/tools/quality_probe/main.cpp
index ada5635b..c08e81b9 100644
--- a/tools/quality_probe/main.cpp
+++ b/tools/quality_probe/main.cpp
@@ -7,6 +7,7 @@
// readback on sampled frames - the normal playback path never reads back.
#include <windows.h>
#include <psapi.h>
+#include <d3d12sdklayers.h>
#include <algorithm>
#include <chrono>
@@ -27,6 +28,7 @@
#include "veyra/gfx/D3D12DeviceContext.h"
#include "veyra/pipeline/EnhanceGraph.h"
#include "veyra/source/MediaFileSource.h"
+#include "veyra/sink/ImageExportSink.h"
#include "../nr_harness/harness_util.h"
@@ -64,8 +66,8 @@ bool sampleGuidanceStats(veyra::gfx::D3D12DeviceContext& ctx,
const uint32_t stepX = width / kCols, stepY = height / kRows;
// Full-width row copies: flow needs width*8 bytes, confidence width*1.
- const uint64_t flowPitch = (static_cast<uint64_t>(width) * 8 + 255) & ~255ull;
- const uint64_t confPitch = (static_cast<uint64_t>(width) + 255) & ~255ull;
+ const uint64_t flowPitch = (static_cast<uint64_t>(width) * 4 + 511) & ~511ull;
+ const uint64_t confPitch = (static_cast<uint64_t>(width) + 511) & ~511ull;
const uint64_t size = (flowPitch + confPitch) * kRows;
D3D12_HEAP_PROPERTIES rp{};
@@ -142,8 +144,8 @@ bool sampleGuidanceStats(veyra::gfx::D3D12DeviceContext& ctx,
for (uint32_t c = 0; c < kCols; ++c) {
const uint32_t x = c * stepX;
if (x >= width) continue;
- const uint16_t m0 = *reinterpret_cast<const uint16_t*>(flowRowBytes + x * 8);
- const uint16_t m1 = *reinterpret_cast<const uint16_t*>(flowRowBytes + x * 8 + 2);
+ const uint16_t m0 = *reinterpret_cast<const uint16_t*>(flowRowBytes + x * 4);
+ const uint16_t m1 = *reinterpret_cast<const uint16_t*>(flowRowBytes + x * 4 + 2);
++stats.sampledTexels;
if (m0 != 0 || m1 != 0) ++stats.nonZeroMotion;
stats.confidences.push_back(confRowBytes[x] / 255.0);
@@ -155,7 +157,7 @@ bool sampleGuidanceStats(veyra::gfx::D3D12DeviceContext& ctx,
std::string line = "sample-dump flow[0..7]:";
const uint8_t* f0 = mapped;
for (int i = 0; i < 8; ++i) {
- line += std::format(" {:04X}", *reinterpret_cast<const uint16_t*>(f0 + i * 8));
+ line += std::format(" {:04X}", *reinterpret_cast<const uint16_t*>(f0 + i * 4));
}
line += std::format(" | conf[0..7]:");
const uint8_t* c0 = mapped + flowPitch * kRows;
@@ -204,10 +206,18 @@ int main(int argc, char** argv)
{
std::string corpusManifest, guidanceMode = "motion", runId = "quality-probe", jsonPath, logPath, inputPath;
int durationSeconds = 0;
+ int maxFrames = 60;
+ bool native = false, diag = false;
+ std::string dumpPath;
+ CoInitializeEx(nullptr, COINIT_MULTITHREADED);
for (int i = 1; i < argc; ++i) {
const std::string arg = argv[i];
auto value = [&]() -> std::string { return (i + 1 < argc) ? std::string(argv[++i]) : std::string(); };
- if (arg == "--corpus") corpusManifest = value();
+ if (arg == "--diag") diag = true;
+ else if (arg == "--native") native = true;
+ else if (arg == "--frames") maxFrames = std::atoi(value().c_str());
+ else if (arg == "--dump") dumpPath = value();
+ else if (arg == "--corpus") corpusManifest = value();
else if (arg == "--input") inputPath = value();
else if (arg == "--guidance") guidanceMode = value();
else if (arg == "--duration-seconds") durationSeconds = std::atoi(value().c_str());
@@ -216,6 +226,7 @@ int main(int argc, char** argv)
else if (arg == "--json-file") jsonPath = value();
else { std::fprintf(stderr, "unknown arg %s\n", arg.c_str()); return 2; }
}
+ if (durationSeconds < 0 || durationSeconds > 240 || maxFrames <= 0) return 2;
if (corpusManifest.empty() && inputPath.empty()) {
std::fprintf(stderr, "--corpus or --input required\n");
return 2;
@@ -260,6 +271,9 @@ int main(int argc, char** argv)
veyra::gfx::D3D12DeviceContext ctx;
veyra::gfx::DeviceContextDesc ddesc;
ddesc.commandSlotCount = 4;
+ if(diag){ComPtr<ID3D12Debug> debug;ComPtr<ID3D12Debug1> gbv;
+ if(FAILED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug)))||FAILED(debug.As(&gbv)))return 1;
+ debug->EnableDebugLayer();gbv->SetEnableGPUBasedValidation(TRUE);ddesc.enableDebugLayer=true;}
Status st = Status::Ok;
if (!ctx.initialize(ddesc, st)) { noteFail("device init failed"); return 1; }
veyra::gfx::CommandSlotRing ring;
@@ -270,7 +284,7 @@ int main(int argc, char** argv)
// Config string -> configHash (mode + extents + feature switches).
const std::string configText = "guidance=" + guidanceMode
- + ";workExtent=3840x2160;nrPerFrame=1;fg=0;nvofStandalone="
+ + (native ? ";workExtent=native;nrPerFrame=1;fg=0;nvofStandalone=" : ";workExtent=3840x2160;nrPerFrame=1;fg=0;nvofStandalone=")
+ (guidanceMode == "motion" || guidanceMode == "motion-depth" || guidanceMode == "auto" ? "1" : "0")
+ ";";
const std::string configHash = veyra::sha256Hex(
@@ -290,13 +304,15 @@ int main(int argc, char** argv)
// Aggregates for the JSON contract.
uint64_t sourceFrames = 0, processedFrames = 0;
uint64_t resetSeek = 0;
- uint64_t aggNr = 0, aggSr = 0, aggNvof = 0, aggFg = 0;
+ uint64_t aggNr = 0, aggSr = 0, aggNvof = 0, aggFg = 0, aggNrMotion = 0, aggCuts = 0;
uint32_t firstSourceW = 0, firstSourceH = 0;
std::string guidanceProvenance = guidanceMode == "off" ? "off" : "zero";
GuidanceStats stats;
std::vector<double> gpuPassMs;
uint64_t normalPathReadbackCount = 0; // diagnostic stats copies are not the normal path
SIZE_T wsPeak = pmcStart.WorkingSetSize;
+ uint64_t vramHeadroom = UINT64_MAX;
+ uint32_t actualWorkW=0, actualWorkH=0;
const bool nrOn = guidanceMode != "off";
const bool nvofOn = guidanceMode == "motion" || guidanceMode == "motion-depth" || guidanceMode == "auto";
@@ -313,8 +329,9 @@ int main(int argc, char** argv)
veyra::pipeline::EnhanceGraphDesc gd{};
gd.sourceWidth = srcW;
gd.sourceHeight = srcH;
- gd.workWidth = 3840; gd.workHeight = 2160;
- gd.enableSr = (srcW != 3840 || srcH != 2160);
+ gd.workWidth = native ? srcW : 3840; gd.workHeight = native ? srcH : 2160;
+ gd.enableSr = nrOn && (srcW != gd.workWidth || srcH != gd.workHeight);
+ actualWorkW = gd.workWidth; actualWorkH = gd.workHeight;
gd.enableNr = nrOn;
gd.enableFg = false;
gd.enableNvofStandalone = nvofOn;
@@ -328,6 +345,7 @@ int main(int argc, char** argv)
uint64_t framesThisClip = 0;
const auto clipStart = std::chrono::steady_clock::now();
bool resetNext = true;
+ veyra::pipeline::EnhanceGraph::FrameOutputs lastOut;
for (;;) {
if (durationSeconds > 0) {
const double elapsed = std::chrono::duration<double>(
@@ -360,19 +378,30 @@ int main(int argc, char** argv)
}
gpuPassMs.push_back(std::chrono::duration<double, std::milli>(
std::chrono::steady_clock::now() - mark0).count());
+ lastOut = out;
resetNext = false;
+ PROCESS_MEMORY_COUNTERS pmc{};
+ if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc))) wsPeak = std::max(wsPeak, pmc.WorkingSetSize);
+ vramHeadroom = std::min(vramHeadroom, queryVramBudgetHeadroomMiB(ctx));
++processedFrames;
++framesThisClip;
// Sample guidance statistics every 60th frame.
if (nvofOn && framesThisClip % 60 == 0) {
- if (!sampleGuidanceStats(ctx, ring, graph, 3840, 2160, stats)) {
+ if (!sampleGuidanceStats(ctx, ring, graph, gd.workWidth, gd.workHeight, stats)) {
veyra::log::warn("quality", "guidance stats sample failed");
}
}
- if (durationSeconds == 0 && framesThisClip >= 6000) break; // safety
+ if (durationSeconds == 0 && framesThisClip >= static_cast<uint64_t>(maxFrames)) break; // safety
+ }
+ if (!dumpPath.empty() && framesThisClip > 0) {
+ veyra::sink::RgbaImage image;
+ if (!veyra::sink::readRgba8(ctx, ring, graph.videoFrameResource(lastOut.videoSlot), image) ||
+ !veyra::sink::saveImage(std::wstring(dumpPath.begin(),dumpPath.end()), image)) noteFail("diagnostic image write failed");
}
aggNr += graph.metrics().nrEvaluateCount;
+ aggNrMotion += graph.metrics().nrMotionFrames;
+ aggCuts += graph.metrics().sceneCutCount;
aggSr += graph.metrics().srEvaluateCount;
aggNvof += graph.metrics().nvofExecuteCount;
aggFg += graph.metrics().fgGeneratedFrames;
@@ -383,12 +412,17 @@ int main(int argc, char** argv)
graph.shutdown();
}
+ uint64_t diagErrors=0;
+ if(diag){ComPtr<ID3D12InfoQueue> iq;if(FAILED(ctx.device()->QueryInterface(IID_PPV_ARGS(&iq))))noteFail("InfoQueue missing");
+ else for(UINT64 i=0;i<iq->GetNumStoredMessages();++i){SIZE_T size=0;iq->GetMessage(i,nullptr,&size);std::vector<uint8_t> bytes(size);auto* msg=reinterpret_cast<D3D12_MESSAGE*>(bytes.data());if(FAILED(iq->GetMessage(i,msg,&size))){noteFail("InfoQueue retrieval failed");break;}if(msg->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++diagErrors;veyra::log::error("d3d",msg->pDescription);}}
+ if(diagErrors)noteFail("D3D12 validation errors");
+ }
PROCESS_MEMORY_COUNTERS pmcEnd{};
GetProcessMemoryInfo(GetCurrentProcess(), &pmcEnd, sizeof(pmcEnd));
const double durationS = std::chrono::duration<double>(std::chrono::steady_clock::now() - tStart).count();
uint32_t removedReason = 0;
const bool deviceAlive = ctx.checkDeviceAlive(removedReason);
- const uint64_t vramHeadroom = queryVramBudgetHeadroomMiB(ctx);
+ if (vramHeadroom == UINT64_MAX) vramHeadroom = 0;
if (wsPeak < pmcEnd.WorkingSetSize) wsPeak = pmcEnd.WorkingSetSize;
const uint64_t nrEvaluateCount = aggNr;
@@ -405,8 +439,8 @@ int main(int argc, char** argv)
j += std::format(" \"configHash\": \"{}\",\n", configHash);
j += std::format(" \"runtimeHash\": \"{}\",\n", runtimeHash.empty() ? "unavailable" : runtimeHash);
j += std::format(" \"sourceExtent\": {{\"width\": {}, \"height\": {}}},\n", firstSourceW, firstSourceH);
- const uint32_t workJsonW = durationSeconds > 0 ? firstSourceW : 3840;
- const uint32_t workJsonH = durationSeconds > 0 ? firstSourceH : 2160;
+ const uint32_t workJsonW = actualWorkW;
+ const uint32_t workJsonH = actualWorkH;
j += std::format(" \"workingExtent\": {{\"width\": {}, \"height\": {}}},\n", workJsonW, workJsonH);
j += std::format(" \"outputExtent\": {{\"width\": {}, \"height\": {}}},\n", workJsonW, workJsonH);
j += std::format(" \"sourceFrames\": {},\n", sourceFrames);
@@ -424,14 +458,20 @@ int main(int argc, char** argv)
"DAV2 provider not implemented (R4.4 pending); motion-only/zero path");
j += " \"depthAgeP95\": 0.0,\n";
j += std::format(" \"resetCountsByReason\": {{\"Open\": {}, \"Seek\": {}}},\n", clips.size(), resetSeek);
- j += " \"sceneCutCount\": 0,\n";
- j += " \"crossCutHistoryCount\": 0,\n";
- j += std::format(" \"gpuPassP50Ms\": {:.3f},\n", percentile(gpuPassMs, 0.50));
- j += std::format(" \"gpuPassP95Ms\": {:.3f},\n", percentile(gpuPassMs, 0.95));
+ j += std::format(" \"sceneCutCount\": {},\n",aggCuts);
+ j += std::format(" \"nrMotionFrames\": {},\n",aggNrMotion);
+ j += std::format(" \"d3dDiagErrors\": {},\n",diagErrors);
+ j += std::format(" \"diagnosticsEnabled\": {},\n",diag);
+ j += " \"crossCutHistoryCount\": null,\n";
+ j += std::format(" \"cpuProcessP50Ms\": {:.3f},\n", percentile(gpuPassMs, 0.50));
+ j += std::format(" \"cpuProcessP95Ms\": {:.3f},\n", percentile(gpuPassMs, 0.95));
j += std::format(" \"normalPathReadbackCount\": {},\n", normalPathReadbackCount);
- j += " \"cpuFenceWaitPerFrame\": 0,\n";
- j += " \"queueHighWater\": 4,\n";
- j += " \"resourcePoolPeakMiB\": 0,\n";
+ j += " \"gpuPassP50Ms\": null,\n \"gpuPassP95Ms\": null,\n";
+ j += std::format(" \"cpuFenceWaitCount\": {},\n",ring.cpuWaitCount());
+ j += std::format(" \"gpuCommandListP50Ms\": {:.4f},\n",percentile(ring.gpuCommandTimesMs(),0.5));
+ j += std::format(" \"gpuCommandListP95Ms\": {:.4f},\n",percentile(ring.gpuCommandTimesMs(),0.95));
+ j += " \"queueHighWater\": null,\n";
+ j += " \"resourcePoolPeakMiB\": null,\n";
j += std::format(" \"vramBudgetHeadroomMiB\": {},\n", vramHeadroom);
j += std::format(" \"workingSetStartMiB\": {:.1f},\n", pmcStart.WorkingSetSize / 1048576.0);
j += std::format(" \"workingSetPeakMiB\": {:.1f},\n", wsPeak / 1048576.0);