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

fix: repair RTX30/40 MFG, sustained scheduling, playback and exports

Veyra Goal Agent89f4f7f5caf1
diff --git a/CMakeLists.txt b/CMakeLists.txt
index cbb085d9..3b4c5566 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -129,10 +129,13 @@ add_library(veyra_ngx STATIC
src/ngx/DlssSrBackend.cpp
src/ngx/VideoSrBackend.cpp
src/ngx/DlssFgBackend.cpp
+ src/ngx/FgCompatibilitySession.cpp
+ src/ngx/compat/hde/hde64.c
src/ngx/AdaMfgUnlock.cpp
src/ngx/AmpereMfgUnlock.cpp
src/ngx/NvapiArchSpoof.cpp
)
+ set_source_files_properties(src/ngx/compat/hde/hde64.c PROPERTIES LANGUAGE CXX)
veyra_apply_warnings(veyra_ngx)
target_compile_features(veyra_ngx PUBLIC cxx_std_20)
target_link_libraries(veyra_ngx PUBLIC veyra_base veyra_gfx d3d11)
@@ -465,7 +468,11 @@ 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_include_directories(veyra_sinks PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/third_party_local/nvidia/nv-codec-headers/include")
+ set(VEYRA_NVENC_HEADERS_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/third_party_local/nvidia/nv-codec-headers-13.0" CACHE PATH "NVENC 13.0 ABI headers (nv-codec-headers n13.0.19.0)")
+ if(NOT EXISTS "${VEYRA_NVENC_HEADERS_ROOT}/include/ffnvcodec/nvEncodeAPI.h")
+ message(FATAL_ERROR "Stage nv-codec-headers n13.0.19.0 at VEYRA_NVENC_HEADERS_ROOT; see THIRD_PARTY_NOTICES.md")
+ endif()
+ target_include_directories(veyra_sinks PRIVATE "${VEYRA_NVENC_HEADERS_ROOT}/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 mfplat mfuuid mf)
@@ -533,6 +540,9 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_include_directories(veyra_live_timing_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
add_executable(veyra_repair_contract_tests tests/unit/RepairContractTests.cpp)
+ add_executable(veyra_subtitle_loading_tests tests/integration/SubtitleLoadingTests.cpp)
+ target_link_libraries(veyra_subtitle_loading_tests PRIVATE veyra_engine)
+ target_compile_features(veyra_subtitle_loading_tests PRIVATE cxx_std_20)
# veyra_engine is linked for the subtitle engine (SRT/ASS/VTT parsing +
# indexed cue lookup); FFmpeg import libraries come from its public surface.
target_link_libraries(veyra_repair_contract_tests PRIVATE veyra_base veyra_engine ${FFMPEG_LIBRARIES})
@@ -640,6 +650,36 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_compile_definitions(veyra_repair_parameter_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")
target_link_libraries(veyra_repair_parameter_tests PRIVATE veyra_pipeline veyra_sinks veyra_nvof)
add_executable(veyra_repair_fg_tests tests/integration/RepairFgTests.cpp)
+ add_executable(veyra_export_frame_pool_tests tests/integration/ExportFramePoolTests.cpp)
+ add_executable(veyra_export_worker_failure_tests tests/integration/ExportWorkerFailureTests.cpp)
+ target_compile_features(veyra_export_worker_failure_tests PRIVATE cxx_std_20)
+ target_link_libraries(veyra_export_worker_failure_tests PRIVATE veyra_engine)
+ add_executable(veyra_fg_lifecycle_tests tests/integration/FgLifecycleTests.cpp)
+ add_executable(veyra_fg_settings_tests tests/integration/FgSettingsTests.cpp)
+ add_executable(veyra_fg_sustained_tests tests/integration/FgSustainedTests.cpp)
+ target_compile_features(veyra_fg_sustained_tests PRIVATE cxx_std_20)
+ target_link_libraries(veyra_fg_sustained_tests PRIVATE veyra_engine)
+ add_executable(veyra_fg_presentation_tests tests/integration/FgPresentationTests.cpp)
+ target_compile_features(veyra_fg_presentation_tests PRIVATE cxx_std_20)
+ target_compile_definitions(veyra_fg_presentation_tests PRIVATE VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")
+ target_link_libraries(veyra_fg_presentation_tests PRIVATE veyra_engine)
+ add_executable(veyra_player_tracks_tests tests/integration/PlayerTracksTests.cpp)
+ add_executable(veyra_scheduling_chain_tests tests/integration/SchedulingChainTests.cpp)
+ target_compile_features(veyra_scheduling_chain_tests PRIVATE cxx_std_20)
+ target_link_libraries(veyra_scheduling_chain_tests PRIVATE veyra_engine)
+ target_compile_features(veyra_player_tracks_tests PRIVATE cxx_std_20)
+ target_link_libraries(veyra_player_tracks_tests PRIVATE veyra_engine)
+ add_executable(veyra_audio_track_output_tests tests/integration/AudioTrackOutputTests.cpp)
+ target_compile_features(veyra_audio_track_output_tests PRIVATE cxx_std_20)
+ target_link_libraries(veyra_audio_track_output_tests PRIVATE veyra_engine)
+ target_compile_features(veyra_fg_settings_tests PRIVATE cxx_std_20)
+ target_link_libraries(veyra_fg_settings_tests PRIVATE veyra_engine)
+ target_compile_features(veyra_fg_lifecycle_tests PRIVATE cxx_std_20)
+ target_compile_definitions(veyra_fg_lifecycle_tests PRIVATE VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")
+ target_link_libraries(veyra_fg_lifecycle_tests PRIVATE veyra_engine)
+ target_compile_features(veyra_export_frame_pool_tests PRIVATE cxx_std_20)
+ target_compile_definitions(veyra_export_frame_pool_tests PRIVATE VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")
+ target_link_libraries(veyra_export_frame_pool_tests PRIVATE veyra_engine)
add_executable(veyra_motion_validation_tests tests/integration/MotionValidationTests.cpp)
add_executable(veyra_depth_response_tests tests/integration/DepthResponseTests.cpp)
add_executable(veyra_srfg_depth_tests tests/integration/SrFgDepthResponseTests.cpp)
@@ -673,7 +713,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_link_libraries(veyra_repair_fg_tests PRIVATE veyra_pipeline veyra_sinks veyra_nvof)
# Headless quality-core runner (Playbook R3.3): the phase5 gate's quality
- add_library(veyra_engine STATIC src/engine/EngineController.cpp src/engine/EngineControllerImage.cpp src/engine/TiledImageProcessor.cpp src/engine/PresetStore.cpp src/engine/VideoPresenter.cpp src/engine/VideoExportJob.cpp src/engine/ExportJobManager.cpp src/engine/Subtitles.cpp)
+ add_library(veyra_engine STATIC src/engine/EngineController.cpp src/engine/EngineControllerImage.cpp src/engine/TiledImageProcessor.cpp src/engine/PresetStore.cpp src/engine/VideoPresenter.cpp src/engine/VideoExportJob.cpp src/engine/ExportJobManager.cpp src/engine/Subtitles.cpp src/engine/FgCompatibilityProbe.cpp)
target_sources(veyra_pipeline PRIVATE src/guidance/AmdOpticalFlow.cpp
src/guidance/GpuDisOpticalFlow.cpp third_party/gpu-dis/src/gpu/native_strict_dis_provider.cpp)
target_include_directories(veyra_pipeline PRIVATE third_party/gpu-dis/src/gpu)
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 7662dac3..a3d634fa 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -4,9 +4,9 @@ NVIDIA SDKs and runtimes are excluded from source control. The publisher-authori
## 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`.
+Source: https://github.com/FFmpeg/nv-codec-headers ; encoder ABI baseline `e844e5b26f46bb77479f063029595293aa8f812d` (tag `n13.0.19.0`, SDK 13.0 declarations), stored only under ignored `third_party_local/nvidia/nv-codec-headers-13.0`. Stage with `git clone --depth 1 --branch n13.0.19.0 https://github.com/FFmpeg/nv-codec-headers.git third_party_local/nvidia/nv-codec-headers-13.0`. CMake accepts `VEYRA_NVENC_HEADERS_ROOT`; compilation checks major/minor 13.0. The previous 13.1 checkout `eddcea9e27f6b772057c9b3f87de2cc1737faffc` remains unmodified for other local tools. Veyra now queries the driver's maximum API before creating the 13.0 function table/session and uses the same ABI for every structure, without pretending that a version-number-only downgrade changes structure layouts. No header or runtime is copied into source control.
-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.
+The nvEncodeAPI.h header itself has NVIDIA's permissive MIT-style notice (Copyright 2010–2024 NVIDIA Corporation in the pinned 13.0 header). 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: dynamically linked 9.0.1#1 vcpkg build. The portable package carries five FFmpeg DLLs, the complete copyright/license notices and SPDX provenance. Corresponding upstream source and the vcpkg patch/build recipe are listed in `docs/BUILD.md`. No FFmpeg command-line executable or test-media toolchain is shipped.
@@ -216,33 +216,75 @@ Same upstream (MIT, commit `33b41835dc39c5d8ab1ef93efb2449be31139c09`),
(sm_86 adapter contract), ported into
`include/veyra/ngx/AmpereMfgUnlock.h` / `src/ngx/AmpereMfgUnlock.cpp`.
-The provider ships zero sm_86 targets; every DLSS-G fatbin only carries sm_89
-PTX and sm_120 PTX/cubin. Veyra rebuilds all 69 fatbins of the audited 310.7
-runtime as single-entry sm_86 PTX programs — 25 registration-table programs
-(8 runs x 25 slots, 200 pointer fields), 38 `.rdata` neural-network programs
-and 6 `.data` auxiliary programs (font/capture/clear) referenced through 44
-RIP-relative `lea` sites — and republishes every reference plus the two
-architecture compares (`0x1b0` -> `0x170`). The temporal program additionally
-receives the same midpoint correction as the Ada path. Ada/Blackwell-only PTX
-constructs (`.e4m3`, `.e5m2`, `wgmma.`, `tcgen05.`, `mmma.sp::ordered_metadata`,
-`sm_90`, `sm_120`) are refused, matching the upstream refusal list.
-
-Veyra additions: module identity is verified against the audited 310.7 build;
-the rebuilt set must load through a private CUDA context (`cuModuleLoadDataEx`)
-before any pointer is published; the allocation window is chosen so every
-RIP-relative displacement stays encodable; every write is recorded and fully
-restored on release; the on-disk DLL is never touched. The upstream native
-cache (cubin) path is not used — dashdogy does not publish those kernels, and
-the published PTX path is sufficient (verified 69/69 through the driver JIT).
-Upstream explicitly labels its RTX 30 support "very early and experimental";
-the same caveat applies here until real Ampere hardware validation.
-
-Local evidence (RTX 5070, structure and mechanics only):
+2026-09-18 correction: the current port rebuilds only the 25 registered DLFG
+programs and the hash-identified auxiliary font, matching upstream's scope.
+It preserves the 38 network and other five auxiliary fatbins. The previous
+all-69 rewrite and global Blackwell architecture spoof are superseded.
+Real NVAPI architecture is preserved for provider hardware selection; scoped
+capability policies and two ceiling comparisons are adapted separately.
+Both registration pointer and supplied length are published. The temporal
+program retains the upstream midpoint correction and unsupported PTX checks.
+
+Additional source from the same MIT commit: `ampere_font_program.inl`
+(`PrepareFont`, `FontPageProtectionMatches`, `RestoreFontPage`, `WriteFont`)
+and `ampere_cuda_program.cpp` (adapter LUID matching and function preflight).
+Veyra adapts these into `src/ngx/AmpereMfgUnlock.cpp`: rebuild font PTX from
+the mapped provider, preserve its address, save/restore page bytes and actual
+protection, accept privatized WRITECOPY pages only with working-set proof.
+No upstream native font payload is embedded. The 26 rebuilt programs must
+pass `cuModuleLoadData`, `cuModuleGetFunction` and available `cuFuncLoad` on
+the D3D12 adapter's CUDA device, with the caller's context restored.
+`src/pipeline/EnhanceGraph.cpp` passes that LUID and defaults to no spoof.
+All modifications are in process memory; the provider DLL on disk is untouched.
+
+Current evidence: `out/logs/3060-r4-real-arch-lifecycle-final.stdout.log`
+passes 2X through 6X and repeated patch restoration on RTX5070, with 26/26
+preflight and actual NGX Evaluate. RTX3060 execution remains unverified;
+CUDA preflight on RTX5070 is not proof of target hardware support.
+
+Historical evidence for the superseded all-69 implementation (RTX5070 only):
`veyra_dlssg_ampere_probe` — scan (runs=8, 200 slots, 25+38+6 fatbins, 44 lea,
2 gates, temporal unique), apply (applied=1, preflight=69/69, readBack=1,
restored=1), delivery gate
`logs/delivery/548a606d92484286806f272d4744d2a7/result.json`.
+## NGX compatibility session port (2026-09-17)
+
+Source: dashdogy/RTX40MFG-Unlock, fixed commit
+`33b41835dc39c5d8ab1ef93efb2449be31139c09`, MIT, copyright 2026 Michael Robles.
+Full permission notice: `src/ngx/compat/RTX40MFG_LICENSE.txt`.
+
+- `source/native/ampere_backend.cpp` discovery and scoped startup/Create logic:
+ adapted into `src/ngx/compat/NgxDiscovery.h`, `src/ngx/FgCompatibilitySession.cpp`
+ and `include/veyra/ngx/FgCompatibilitySession.h`. Veyra substitutes its direct
+ NGX calls and owned D3D12 resources for upstream wrapper/swapchain hooks;
+ adds an exclusive session lease, absolute-path/module ownership, adapter
+ and texture identity, and restoration before releasing module references.
+ Follow-up on 2026-09-18: extend the verified Ampere metadata scope to the
+ direct NGX Init call in `src/pipeline/EnhanceGraph.cpp`, matching upstream's
+ startup coverage before capability results can be cached. Restore on both
+ successful and failed Init; reject capabilities before successful Init.
+- `source/native/ampere_patterns.h`: metadata/Create patterns only, extracted
+ into `src/ngx/compat/NgxPatterns.h`; Streamline patterns omitted.
+- `source/native/protected_pointer.h`: retained implementation in
+ `src/ngx/compat/protected_pointer.h`, attribution comment added.
+- `src/ngx/compat/RestoreMemory.h`: Veyra helper using the above page-query
+ and restoration routines; accepts Windows image-page copy-on-write protection,
+ verifies writes/cache flush/protection and retains a process failure latch.
+ Ada/Ampere program publications now retain rollback records before each
+ checked write. Unproven rollback blocks later NGX sessions.
+- Upstream MinHook HDE64 decoder: `src/ngx/compat/hde/{hde64.c,hde64.h,table64.h,pstdint.h}`.
+ BSD copyright/terms retained in `src/ngx/compat/HDE_LICENSE.txt` and source
+ headers. Compiled as C++; local `c` initialized to zero for MSVC /WX.
+
+The session is used only for the requested Ada/Ampere compatibility path.
+Native RTX50 does not install these patches. Forced-path RTX5070 diagnostics
+are not evidence of RTX30/40 hardware compatibility.
+`src/engine/FgCompatibilityProbe.cpp` is Veyra's own bounded child-process
+Create/Evaluate preflight, with inherited mapping, process job, exact adapter
+selection and cancellation; it is not upstream wrapper code or a quality gate.
+
+
## Media Foundation encoder(系统硬件编码路径,移植自 FFmpeg mfenc.c)
Source: FFmpeg n9.0.1 `libavcodec/mfenc.c` 与 `libavcodec/mf_utils.c`
diff --git a/apps/veyra/main.cpp b/apps/veyra/main.cpp
index 395df30f..f98d64cf 100644
--- a/apps/veyra/main.cpp
+++ b/apps/veyra/main.cpp
@@ -1,8 +1,18 @@
#include <windows.h>
#include "veyra/Log.h"
#include "veyra/RuntimePaths.h"
+#include "veyra/engine/FgCompatibilityProbe.h"
+#include <shellapi.h>
int runVeyraApp(HINSTANCE,int);
int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,LPWSTR,int show){
+ int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);
+ if(argv&&argc==3&&std::wstring_view(argv[1])==L"--fg-compat-probe"){
+ const auto mapping=reinterpret_cast<HANDLE>(_wcstoui64(argv[2],nullptr,10));LocalFree(argv);
+ return veyra::engine::runFgCompatibilityProbe(mapping);
+ }
+ if(argv)LocalFree(argv);
+ wchar_t executable[32768]{};
+ if(GetModuleFileNameW(nullptr,executable,32768))veyra::engine::setFgCompatibilityProbeExecutable(executable);
wchar_t logOverride[32768]{};
const auto length=GetEnvironmentVariableW(L"VEYRA_LOG_FILE",logOverride,32768);
auto logPath=length>0&&length<32768?std::filesystem::path(logOverride):veyra::runtime::logsDirectory()/L"veyra-app.log";
diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cpp
index 88d8f3de..b8cb8b49 100644
--- a/apps/veyra/ui/AppShell.cpp
+++ b/apps/veyra/ui/AppShell.cpp
@@ -9,6 +9,7 @@
#include "WorkspaceTransition.h"
#include "UiSessionState.h"
#include "UiPreferenceStore.h"
+#include "PlaybackPowerGuard.h"
#include "CapturePanel.h"
#ifdef VEYRA_ENABLE_REMOTEPLAY
#include "RemotePlayPanel.h"
@@ -61,8 +62,9 @@ bool remoteViewOnly=false;
veyra::engine::ExportJobManager exportJob;
veyra::ui::UiSessionState uiState;
veyra::ui::UiPreferenceStore preferences(veyra::runtime::localDataDirectory());veyra::ui::UiPreferences uiPreferences;
+veyra::ui::PlaybackPowerGuard playbackPower;
HWND inspector=nullptr,metricLabel=nullptr,tooltips=nullptr,diagnosticPanel=nullptr,liveStatusPanel=nullptr;bool showDiagnostics=false,inspectorResizing=false;int proposedInspectorWidth=320;bool preferWatching=true,jobPaused=false;int subtitlePixels=22;
-veyra::engine::EnhancementSettings lastSuccessful,jobExpected;bool haveSuccessful=false;uint64_t masterPendingRevision=0,masterPendingSession=0;bool masterPreviousEnabled=true;
+veyra::engine::EnhancementSettings jobExpected;uint64_t masterPendingRevision=0,masterPendingSession=0;bool masterPreviousEnabled=true;
std::wstring smokeView;bool smokeViewApplied=false;
std::wstring smokeDualOutput;bool smokeEmpty=false;DWORD modeGdiStart=0,modeHandlesStart=0;SIZE_T modePrivateStart=0;
bool smokeDual=false,smokeDualPause=false,smokeMaster=false,smokeMasterReject=false,smokeAudio=false,smokeJob=false,smokeJobCancel=false,smokeJobExit=false,smokeColor=false;int dualStep=0,masterStep=0,audioStep=0,jobStep=0,colorStep=0;double pausedPosition=-1,jobPosition=0;uint64_t pausedFrames=0;ULONGLONG jobPauseTick=0;HANDLE workerMapping=nullptr;
@@ -100,7 +102,11 @@ std::wstring exportOutput;unsigned exportFrames=0;unsigned cancelAfterMs=0;bool
// embedded container tracks. Offsets live per track; the viewer's look settings
// live in uiState so they can be persisted.
std::vector<veyra::engine::SubtitleTrack> subtitleTracks;
+std::unique_ptr<veyra::engine::SubtitleLoader> subtitleLoader;
+uint64_t subtitleGeneration=0;
+size_t subtitleLoadedTracks=0;
int subtitlePrimary=-1,subtitleSecondary=-1;
+bool subtitlePrimaryChosen=false,subtitleSecondaryChosen=false;
HWND subtitleLabel=nullptr;
std::wstring subtitleStatus;
int subtitleRequestPrimary=INT_MIN,subtitleRequestSecondary=INT_MIN,subtitleRequestOffsetMs=0;
@@ -124,34 +130,38 @@ bool subtitleIsChinese(const veyra::engine::SubtitleTrack& track){
}
void refreshSubtitleTracks(const std::wstring& media){
subtitleTracks.clear();subtitlePrimary=-1;subtitleSecondary=-1;subtitleStatus.clear();
- if(media.empty()||media.starts_with(L"capture:")||media.starts_with(L"capture2:")||media.starts_with(L"remoteplay:"))return;
- const std::filesystem::path mediaPath(media);
- for(const wchar_t* extension:{L".srt",L".ass",L".ssa",L".vtt"}){
- auto candidate=mediaPath;candidate.replace_extension(extension);
- std::error_code ec;
- if(!std::filesystem::exists(candidate,ec))continue;
- auto track=veyra::engine::loadSubtitleFile(candidate.wstring());
- if(!track.usable())continue;
- track.rebuildIndex();
- track.name=std::format(L"外挂 · {}",candidate.filename().wstring());
- subtitleTracks.push_back(std::move(track));
- break;
- }
- auto embedded=veyra::engine::loadEmbeddedSubtitleTracks(media);
- for(auto& track:embedded)subtitleTracks.push_back(std::move(track));
+ subtitlePrimaryChosen=subtitleSecondaryChosen=false;
+ subtitleLoadedTracks=0;
+ if(!subtitleLoader)subtitleLoader=std::make_unique<veyra::engine::SubtitleLoader>();
+ subtitleGeneration=subtitleLoader->request(media);
+}
+void pollSubtitleTracks(){
+ if(!subtitleLoader||menuOpen)return;
+ auto result=subtitleLoader->poll();if(!result||result->generation!=subtitleGeneration)return;
+ const auto count=result->tracks.size();
+ // Replace the loader-owned prefix; preserve manually loaded tracks and
+ // offsets/choices made while embedded text was still being read.
+ for(size_t i=0;i<std::min(subtitleLoadedTracks,count);++i)result->tracks[i].offsetMs=subtitleTracks[i].offsetMs;
+ const int added=int(count)-int(subtitleLoadedTracks);
+ if(subtitlePrimary>=int(subtitleLoadedTracks))subtitlePrimary+=added;
+ if(subtitleSecondary>=int(subtitleLoadedTracks))subtitleSecondary+=added;
+ subtitleTracks.erase(subtitleTracks.begin(),subtitleTracks.begin()+subtitleLoadedTracks);
+ subtitleTracks.insert(subtitleTracks.begin(),std::make_move_iterator(result->tracks.begin()),std::make_move_iterator(result->tracks.end()));
+ subtitleLoadedTracks=count;
int firstUsable=-1,firstChinese=-1;
for(size_t index=0;index<subtitleTracks.size();++index){
if(!subtitleTracks[index].usable())continue;
if(firstUsable<0)firstUsable=int(index);
if(firstChinese<0&&subtitleIsChinese(subtitleTracks[index]))firstChinese=int(index);
}
- subtitlePrimary=firstChinese>=0?firstChinese:firstUsable;
- if(subtitleRequestPrimary!=INT_MIN&&subtitleRequestPrimary<int(subtitleTracks.size()))subtitlePrimary=subtitleRequestPrimary;
- if(subtitleRequestSecondary!=INT_MIN)subtitleSecondary=(subtitleRequestSecondary<int(subtitleTracks.size()))?subtitleRequestSecondary:-1;
- if(subtitleRequestOffsetMs!=0&&subtitlePrimary>=0&&size_t(subtitlePrimary)<subtitleTracks.size())subtitleTracks[size_t(subtitlePrimary)].offsetMs=subtitleRequestOffsetMs;
- for(const auto& track:subtitleTracks)veyra::log::info("subtitle",std::format("track name={} codec={} language={} embedded={} cues={} usable={} note={}",narrow(track.name),narrow(track.codec),narrow(track.language),track.embedded?1:0,track.cues.size(),track.usable()?1:0,narrow(track.note)));
- veyra::log::info("subtitle",std::format("tracks={} primary={} secondary={}",subtitleTracks.size(),subtitlePrimary,subtitleSecondary));
- if(uiState.subtitleSecondLanguage){
+ if(!subtitlePrimaryChosen){
+ subtitlePrimary=firstChinese>=0?firstChinese:firstUsable;
+ if(subtitleRequestPrimary!=INT_MIN&&subtitleRequestPrimary<int(subtitleTracks.size()))subtitlePrimary=subtitleRequestPrimary;
+ if(subtitleRequestOffsetMs!=0&&subtitlePrimary>=0&&size_t(subtitlePrimary)<subtitleTracks.size())subtitleTracks[size_t(subtitlePrimary)].offsetMs=subtitleRequestOffsetMs;
+ }
+ if(!subtitleSecondaryChosen&&subtitleRequestSecondary!=INT_MIN)subtitleSecondary=(subtitleRequestSecondary<int(subtitleTracks.size()))?subtitleRequestSecondary:-1;
+ if(result->complete)for(const auto& track:subtitleTracks)veyra::log::info("subtitle",std::format("track name={} codec={} language={} embedded={} cues={} usable={} note={}",narrow(track.name),narrow(track.codec),narrow(track.language),track.embedded?1:0,track.cues.size(),track.usable()?1:0,narrow(track.note)));
+ if(!subtitleSecondaryChosen&&subtitleRequestSecondary==INT_MIN&&uiState.subtitleSecondLanguage){
int candidate=-1;
for(size_t index=0;index<subtitleTracks.size();++index){
if(!subtitleTracks[index].usable()||int(index)==subtitlePrimary)continue;
@@ -159,6 +169,7 @@ void refreshSubtitleTracks(const std::wstring& media){
}
subtitleSecondary=candidate;
}
+ veyra::log::info("subtitle",std::format("tracks={} primary={} secondary={}",subtitleTracks.size(),subtitlePrimary,subtitleSecondary));
}
void setSubtitleOffset(int deltaMs){
if(subtitlePrimary<0||size_t(subtitlePrimary)>=subtitleTracks.size())return;
@@ -169,6 +180,7 @@ void setSubtitleOffset(int deltaMs){
}
void cycleSubtitleTrack(bool secondary){
if(subtitleTracks.empty())return;
+ (secondary?subtitleSecondaryChosen:subtitlePrimaryChosen)=true;
int& slot=secondary?subtitleSecondary:subtitlePrimary;
slot=(slot+2>int(subtitleTracks.size()))?-1:slot+1; // -1 -> 0 -> 1 ... -> -1
if(slot<0){
@@ -191,6 +203,8 @@ std::atomic<bool> subtitleAlignRunning{false},subtitleAlignReady{false};
std::atomic<int> subtitleAlignOffsetMs{0};
std::mutex subtitleAlignMutex;
std::wstring subtitleAlignDetail;
+uint64_t subtitleAlignGeneration=0;
+int subtitleAlignTrack=-1;
void startSubtitleAutoAlign(){
if(subtitleAlignRunning.load()){
subtitleStatus=L"字幕自动对齐:已经有一个分析在进行";
@@ -202,6 +216,7 @@ void startSubtitleAutoAlign(){
}
const std::wstring media=currentFile;
const auto track=subtitleTracks[size_t(subtitlePrimary)];
+ subtitleAlignGeneration=subtitleGeneration;subtitleAlignTrack=subtitlePrimary;
subtitleAlignRunning=true;subtitleAlignReady=false;
subtitleStatus=L"字幕自动对齐:正在分析音轨(最多取前 30 分钟)…";
subtitleAlignWorker=std::jthread([media,track]{
@@ -218,9 +233,10 @@ void startSubtitleAutoAlign(){
void pollSubtitleAutoAlign(){
if(subtitleAlignRunning.load()&&subtitleStatus.empty())subtitleStatus=L"字幕自动对齐:正在分析音轨…";
if(!subtitleAlignReady.exchange(false))return;
+ if(subtitleAlignGeneration!=subtitleGeneration||subtitleAlignTrack<0||size_t(subtitleAlignTrack)>=subtitleTracks.size())return;
std::wstring detail;
{std::lock_guard lock(subtitleAlignMutex);detail=subtitleAlignDetail;}
- if(subtitlePrimary>=0&&size_t(subtitlePrimary)<subtitleTracks.size())subtitleTracks[size_t(subtitlePrimary)].offsetMs=subtitleAlignOffsetMs.load();
+ subtitleTracks[size_t(subtitleAlignTrack)].offsetMs=subtitleAlignOffsetMs.load();
subtitleStatus=std::format(L"字幕自动对齐:{}(按 Z/X 可微调)",detail);
veyra::log::info("subtitle",std::format("auto align applied offsetMs={}",subtitleAlignOffsetMs.load()));
}
@@ -374,10 +390,45 @@ for(int id:std::initializer_list<int>{Open,Capture,Recent,Master,Save,Sr,Play,St
if(smokeDual)veyra::log::info("ui-layout-timing",std::format("frameMs={:.3f} animation={}",std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-layoutBegin).count(),transition.running));
}
+void subtitleTrackMenu(bool secondary){
+ using namespace veyra::ui;
+ std::vector<PopupOption> choices{{-1,L"关闭",Icon::Subtitle,(secondary?subtitleSecondary:subtitlePrimary)<0}};
+ for(size_t i=0;i<subtitleTracks.size();++i){
+ const auto& t=subtitleTracks[i];
+ choices.push_back({int(i),std::format(L"{} · {} [{}]{}",i+1,t.name,t.language,t.note.empty()?L"":L" · "+t.note),Icon::Subtitle,(secondary?subtitleSecondary:subtitlePrimary)==int(i)});
+ }
+ menuOpen=true;
+ const int selected=popupSelector(GetDlgItem(mainWindow,Subtitle),choices,(secondary?subtitleSecondary:subtitlePrimary)+1,true,secondary?L"副字幕":L"主字幕");
+ menuOpen=false;
+ if(selected<0||size_t(selected)>=choices.size())return;
+ const int track=choices[selected].command;
+ (secondary?subtitleSecondaryChosen:subtitlePrimaryChosen)=true;
+ (secondary?subtitleSecondary:subtitlePrimary)=track;
+ if(secondary)uiState.subtitleSecondLanguage=track>=0;
+ if(track>=0){uiState.subtitles=true;subtitleStatus=std::format(L"{}:{}",secondary?L"副字幕":L"主字幕",subtitleTracks[track].name);}
+ veyra::log::info("subtitle",std::format("selected secondary={} track={} stream={} enabled={}",secondary,track,track>=0?subtitleTracks[track].streamIndex:-1,uiState.subtitles));
+ layout();
+}
+void audioTrackMenu(){
+ using namespace veyra::ui;
+ const auto state=engine.snapshot();
+ auto wide=[](const std::string& text){const int n=MultiByteToWideChar(CP_UTF8,0,text.data(),int(text.size()),nullptr,0);std::wstring result(n,0);if(n)MultiByteToWideChar(CP_UTF8,0,text.data(),int(text.size()),result.data(),n);return result;};
+ std::vector<PopupOption> choices;int current=0;
+ for(const auto& t:state.audioTracks){
+ if(t.streamIndex==state.selectedAudioTrack)current=int(choices.size());
+ choices.push_back({t.streamIndex,std::format(L"{} · {} · {} · {} 声道{}",choices.size()+1,wide(t.language.empty()?"und":t.language),wide(t.codec),t.channels,t.title.empty()?L"":L" · "+wide(t.title)),Icon::None,t.streamIndex==state.selectedAudioTrack});
+ }
+ if(choices.empty())return;
+ menuOpen=true;const int selected=popupSelector(GetDlgItem(mainWindow,Subtitle),choices,current,true,L"音轨");menuOpen=false;
+ if(selected>=0&&size_t(selected)<choices.size())engine.selectAudioTrack(state.sessionId,choices[selected].command);
+}
void subtitleMenu(){
using namespace veyra::ui;
std::vector<PopupOption> options;std::vector<std::function<void()>> actions;
auto add=[&](int command,std::wstring label,Icon icon,bool checked,std::function<void()> action){options.push_back({command,std::move(label),icon,checked});actions.push_back(std::move(action));};
+ add(Subtitle,L"音轨…",Icon::None,false,[]{audioTrackMenu();});
+ add(Subtitle,L"主字幕…",Icon::Subtitle,subtitlePrimary>=0,[]{subtitleTrackMenu(false);});
+ add(Subtitle,L"副字幕…",Icon::Subtitle,subtitleSecondary>=0,[]{subtitleTrackMenu(true);});
add(Subtitle,uiState.subtitles?L"字幕 · 已开启 (B)":L"字幕 · 已关闭 (B)",Icon::Subtitle,uiState.subtitles,[&]{uiState.subtitles=!uiState.subtitles;layout();});
add(SubtitleLoad,L"载入外部字幕(SRT/ASS/SSA/VTT)…",Icon::Load,false,[&]{
std::vector<wchar_t> name(32768);OPENFILENAMEW d{sizeof(d)};d.hwndOwner=mainWindow;d.lpstrFile=name.data();d.nMaxFile=32768;
@@ -390,20 +441,10 @@ void subtitleMenu(){
track.name=std::format(L"外挂 · {}",std::filesystem::path(name.data()).filename().wstring());
subtitleTracks.push_back(std::move(track));
subtitlePrimary=int(subtitleTracks.size())-1;
+ subtitlePrimaryChosen=true;
uiState.subtitles=true;subtitleStatus=std::format(L"已载入 {}",subtitleTracks.back().name);layout();
});
add(SubtitleLoad,L"重新扫描内嵌字幕轨",Icon::Load,false,[&]{refreshSubtitleTracks(currentFile);layout();});
- add(0,L"── 主字幕 ──",Icon::None,false,[]{});
- for(size_t index=0;index<subtitleTracks.size();++index){
- const auto& track=subtitleTracks[index];
- std::wstring label=std::format(L"主字幕 · {} [{}]{}",track.name,track.codec,track.usable()?L"":std::format(L" · {}",track.note));
- add(Subtitle,label,Icon::Subtitle,subtitlePrimary==int(index),[&,index]{subtitlePrimary=int(index);subtitleStatus=std::format(L"主字幕:{}",subtitleTracks[index].name);});
- }
- add(0,L"── 副字幕(双语)──",Icon::None,false,[]{});
- add(Subtitle,L"副字幕 · 关闭",Icon::Subtitle,subtitleSecondary<0,[&]{subtitleSecondary=-1;uiState.subtitleSecondLanguage=false;});
- for(size_t index=0;index<subtitleTracks.size();++index){
- add(Subtitle,std::format(L"副字幕 · {}",subtitleTracks[index].name),Icon::Subtitle,subtitleSecondary==int(index),[&,index]{subtitleSecondary=int(index);uiState.subtitleSecondLanguage=true;subtitleStatus=std::format(L"副字幕:{}",subtitleTracks[index].name);});
- }
add(0,L"── 时间(作用于主字幕)──",Icon::None,false,[]{});
add(SubtitleSize,L"延时 -1 秒",Icon::Type,false,[&]{setSubtitleOffset(-1000);});
add(SubtitleSize,L"延时 -50 毫秒",Icon::Type,false,[&]{setSubtitleOffset(-50);});
@@ -419,7 +460,7 @@ void subtitleMenu(){
add(SubtitleSize,L"位置上移",Icon::Type,false,[&]{uiState.subtitleMargin=std::clamp(uiState.subtitleMargin+4,0,240);});
add(SubtitleSize,L"位置下移",Icon::Type,false,[&]{uiState.subtitleMargin=std::clamp(uiState.subtitleMargin-4,0,240);});
add(SubtitleSize,std::format(L"字体:{}",subtitleFontName()),Icon::Type,false,[&]{uiState.subtitleFont=(uiState.subtitleFont+1)%kSubtitleFontCount;subtitleStatus=std::format(L"字幕字体:{}",subtitleFontName());});
- menuOpen=true;const int selected=popupSelector(GetDlgItem(mainWindow,Subtitle),options,0,true,L"字幕设置");menuOpen=false;
+ menuOpen=true;const int selected=popupSelector(GetDlgItem(mainWindow,Subtitle),options,0,true,L"字幕与音轨");menuOpen=false;
if(selected>=0&&size_t(selected)<actions.size()&&actions[size_t(selected)])actions[size_t(selected)]();
pointerActivity();
}
@@ -443,11 +484,9 @@ void startVideoExport(bool hevc){
const auto s=engine.snapshot();
const wchar_t* reason=nullptr;
if(currentFile.empty()||s.capture||s.image)reason=L"请先打开一个本地视频。";
- else if(!s.frames||s.applying)reason=L"视频或效果正在初始化,请稍后重试。";
else if(exportJob.poll().active())reason=L"已有导出任务,请先完成或取消当前任务。";
if(reason){veyra::log::warn("export-dialog","request rejected by source/settings/job state");MessageBoxW(mainWindow,reason,L"暂时无法导出",MB_OK|MB_ICONINFORMATION);return;}
- // Export owns a separate worker. A failed preview must not leave an
- // enabled export button that silently ignores clicks; use applied settings.
+ // The worker initializes its own graph from the current requested settings.
std::vector<wchar_t> name(32768);
const auto suggested=std::filesystem::path(currentFile).stem().wstring()+L"-Veyra.mp4";
wcsncpy_s(name.data(),name.size(),suggested.c_str(),_TRUNCATE);
@@ -461,7 +500,7 @@ void startVideoExport(bool hevc){
if(std::filesystem::exists(name.data())||std::filesystem::exists(std::wstring(name.data())+L".partial")){
MessageBoxW(mainWindow,L"这个名称的文件或 partial 已存在。为保留原文件,请使用新名称。",L"请选择新名称",MB_OK|MB_ICONINFORMATION);return;
}
- exportJob.start(currentFile,name.data(),s.applied,hevc);jobPaused=false;layout();
+ exportJob.start(currentFile,name.data(),uiState.effective(),hevc,0,s.selectedAudioTrack);jobPaused=false;layout();
}else if(const auto error=CommDlgExtendedError()){
veyra::log::error("export-dialog",std::format("GetSaveFileNameW failed code=0x{:08X}",error));
MessageBoxW(mainWindow,std::format(L"无法打开保存位置窗口,错误 0x{:08X}。详见诊断日志。",error).c_str(),L"导出窗口错误",MB_OK|MB_ICONERROR);
@@ -472,7 +511,13 @@ void startVideoExport(bool hevc){
#include "TransportChecks.h"
#include "FgOnlyChecks.h"
LRESULT CALLBACK proc(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp){switch(msg){
-case WM_CREATE:{mainWindow=hwnd;backdrop.attach(hwnd);font=veyra::ui::makeFont(hwnd);veyra::ui::titleTheme(hwnd);uiState.configured=initialOptions.snapshot();uiState.enhanced=initialOptions.nr||initialOptions.sr||initialOptions.fg;
+case WM_SYSCOMMAND:
+ if((wp&0xfff0)==SC_SCREENSAVE||(wp&0xfff0)==SC_MONITORPOWER){
+ const auto s=engine.snapshot();
+ if(s.running&&!s.failed&&!s.image&&s.transport==veyra::engine::TransportState::Playing)return 0;
+ }break;
+case WM_CREATE:{mainWindow=hwnd;backdrop.attach(hwnd);font=veyra::ui::makeFont(hwnd);veyra::ui::titleTheme(hwnd);uiState.configured=initialOptions.snapshot();uiState.enhanced=uiPreferences.enhancementEnabled<0?(initialOptions.nr||initialOptions.sr||initialOptions.fg):uiPreferences.enhancementEnabled!=0;
+engine.requestSettings(uiState.effective());
#ifdef VEYRA_ENABLE_REMOTEPLAY
control(L"BUTTON",L"PS5",RemotePlay,BS_PUSHBUTTON,0,0,56,28);veyra::ui::ghost(GetDlgItem(hwnd,RemotePlay));SetPropW(GetDlgItem(hwnd,RemotePlay),L"veyra.tip",HANDLE(L"PS5 串流 · 配对与连接"));
#endif
@@ -566,7 +611,7 @@ case JobProgress:if(uiState.mode==veyra::ui::Mode::Daily)switchMode();uiState.dr
case Details:uiState.diagnostics=!uiState.diagnostics;SetWindowTextW(GetDlgItem(hwnd,Details),uiState.diagnostics?L"性能 ▴":L"性能 ▾");layout();break;
case Mute:{auto s=engine.snapshot();engine.setVolume(s.volume,!s.muted);break;}
case Subtitle:if(lp)subtitleMenu();else{uiState.subtitles=!uiState.subtitles;layout();}break;
-case SubtitleLoad:{std::vector<wchar_t> name(32768);OPENFILENAMEW d{sizeof(d)};d.hwndOwner=hwnd;d.lpstrFile=name.data();d.nMaxFile=32768;d.lpstrFilter=L"字幕文件\0*.srt;*.ass;*.ssa;*.vtt\0所有文件\0*.*\0";d.Flags=OFN_FILEMUSTEXIST|OFN_NOCHANGEDIR;if(GetOpenFileNameW(&d)){auto track=veyra::engine::loadSubtitleFile(name.data());if(track.usable()){track.rebuildIndex();track.name=std::format(L"外挂 · {}",std::filesystem::path(name.data()).filename().wstring());subtitleTracks.push_back(std::move(track));subtitlePrimary=int(subtitleTracks.size())-1;uiState.subtitles=true;}else subtitleStatus=L"这个字幕文件读不出任何字幕";layout();}break;}
+case SubtitleLoad:{std::vector<wchar_t> name(32768);OPENFILENAMEW d{sizeof(d)};d.hwndOwner=hwnd;d.lpstrFile=name.data();d.nMaxFile=32768;d.lpstrFilter=L"字幕文件\0*.srt;*.ass;*.ssa;*.vtt\0所有文件\0*.*\0";d.Flags=OFN_FILEMUSTEXIST|OFN_NOCHANGEDIR;if(GetOpenFileNameW(&d)){auto track=veyra::engine::loadSubtitleFile(name.data());if(track.usable()){track.rebuildIndex();track.name=std::format(L"外挂 · {}",std::filesystem::path(name.data()).filename().wstring());subtitleTracks.push_back(std::move(track));subtitlePrimary=int(subtitleTracks.size())-1;subtitlePrimaryChosen=true;uiState.subtitles=true;}else subtitleStatus=L"这个字幕文件读不出任何字幕";layout();}break;}
case SubtitleSize:subtitlePixels=subtitlePixels==22?28:subtitlePixels==28?34:22;break;
case Recent:{std::vector<wchar_t> recent(32768);GetPrivateProfileStringW(L"Player",L"最近打开",L"",recent.data(),32768,(veyra::runtime::localDataDirectory()/"veyra.ini").wstring().c_str());openFile(recent.data());break;}
case Play:{auto s=engine.snapshot();if(s.capture||s.image||s.transport==veyra::engine::TransportState::Opening||s.transport==veyra::engine::TransportState::Stopping)break;if(!currentFile.empty()&&(!s.running||s.transport==veyra::engine::TransportState::Ended)){openFile(currentFile);break;}if(seekPreview.active){seekPreview.resume=!seekPreview.resume;paused=!seekPreview.resume;break;}paused=s.transport==veyra::engine::TransportState::Playing;engine.pause(paused);SetWindowTextW(GetDlgItem(hwnd,Play),paused?L"播放":L"暂停");break;}
@@ -588,7 +633,7 @@ case Split:compareMode=compareMode==2?0:2;updateComparison();break;
case Reference:referenceBase=SendDlgItemMessageW(hwnd,Reference,CB_GETCURSEL,0,0)==1;updateComparison();break;
case Settings:if(uiState.mode==veyra::ui::Mode::Daily)switchMode();selectInspector(0);break;
#ifdef VEYRA_ENABLE_REMOTEPLAY
-case RemotePlay:veyra::ui::showRemotePlayPanel(hwnd,[](veyra::source::RemotePlayConnectDesc desc){cancelProtection();remoteViewOnly=desc.request.viewOnly;if(!desc.request.viewOnly){if(!remoteController.start())veyra::log::warn("remoteplay-input","SDL gamepad initialization failed");startShellTimer(mainWindow,ControllerTimer,8);}else{KillTimer(mainWindow,ControllerTimer);remoteController.stop();}currentFile=L"remoteplay:";subtitleTracks.clear();subtitlePrimary=-1;subtitleSecondary=-1;paused=false;engine.previewView({});engine.openRemotePlay(video,std::move(desc),options());SetWindowTextW(mainWindow,L"Veyra — PS5 Remote Play");layout();},[](std::string pin){engine.remotePlayLoginPin(std::move(pin));},[]{auto s=engine.snapshot();veyra::ui::RemotePlayPanelStatus result;
+case RemotePlay:veyra::ui::showRemotePlayPanel(hwnd,[](veyra::source::RemotePlayConnectDesc desc){cancelProtection();remoteViewOnly=desc.request.viewOnly;if(!desc.request.viewOnly){if(!remoteController.start())veyra::log::warn("remoteplay-input","SDL gamepad initialization failed");startShellTimer(mainWindow,ControllerTimer,8);}else{KillTimer(mainWindow,ControllerTimer);remoteController.stop();}currentFile=L"remoteplay:";refreshSubtitleTracks(currentFile);paused=false;engine.previewView({});engine.openRemotePlay(video,std::move(desc),options());SetWindowTextW(mainWindow,L"Veyra — PS5 Remote Play");layout();},[](std::string pin){engine.remotePlayLoginPin(std::move(pin));},[]{auto s=engine.snapshot();veyra::ui::RemotePlayPanelStatus result;
result.active=s.remotePlay&&(s.running||s.transport==veyra::engine::TransportState::Opening||s.transport==veyra::engine::TransportState::Stopping);
result.message=s.failed?s.status:s.remoteRecovering?s.remoteRecoveryMessage:s.remotePlay&&s.running?L"PS5 画面已进入播放;关闭此面板不停止串流。":result.active?s.status:L"PS5 串流已停止,可以重新连接。";
if(s.remotePlay&&s.running){
@@ -632,13 +677,13 @@ if(wp==ControllerTimer){const auto state=engine.snapshot();if(state.remotePlay&&
#endif
{if(wp==TransitionTimer){transition.sample(GetTickCount64());if(!transition.running){endTransition();veyra::log::info("ui-transition","completed; final layout and swapchain resize released");}layout();return 0;}
if(full&&fullControls&&!menuOpen&&!veyra::ui::popupSelectorOpen()&&!GetCapture()&&GetTickCount64()-pointerTick>1600){POINT p{};GetCursorPos(&p);ScreenToClient(hwnd,&p);RECT r{};GetClientRect(hwnd,&r);if(p.y<r.bottom-veyra::ui::dip(hwnd,98)||p.x<0||p.x>=r.right||p.y>=r.bottom){fullControls=false;layout();if(GetForegroundWindow()==hwnd)SetCursor(nullptr);veyra::log::info("ui-fullscreen","controls hidden; video and subtitles only");}}
-if(closing){if(engine.idle()&&!exportJob.poll().active()){KillTimer(hwnd,TelemetryTimer);DestroyWindow(hwnd);}return 0;}if(!autoInput.empty()){auto file=autoInput;autoInput.clear();openFile(file);startTick=GetTickCount64();if(subtitleRequestAutoAlign){subtitleRequestAutoAlign=false;startSubtitleAutoAlign();}if(openColourPageOnStart){openColourPageOnStart=false;if(uiState.mode==veyra::ui::Mode::Daily)switchMode();selectInspector(2);layout();}}if(smokeControls&&startTick){const auto elapsed=GetTickCount64()-startTick;
+if(closing){if(engine.idle()&&!exportJob.poll().active()){KillTimer(hwnd,TelemetryTimer);DestroyWindow(hwnd);}return 0;}if(!autoInput.empty()){auto file=autoInput;autoInput.clear();openFile(file);startTick=GetTickCount64();if(openColourPageOnStart){openColourPageOnStart=false;if(uiState.mode==veyra::ui::Mode::Daily)switchMode();selectInspector(2);layout();}}if(smokeControls&&startTick){const auto elapsed=GetTickCount64()-startTick;
if(smokeStep==0&&elapsed>2200){engine.pause(true);smokeStep=1;}
if(smokeStep==1&&elapsed>2600){engine.seek(1.0);smokeStep=2;}
if(smokeStep==2&&elapsed>3200){engine.pause(false);smokeStep=3;}
if(smokeStep==3&&elapsed>4100&&!smokeSave.empty()){engine.saveFrame(smokeSave);smokeStep=4;}
if(smokeStep==4&&elapsed>5200&&GetEnvironmentVariableW(L"VEYRA_TEST_LARGE_IMAGE_SAVE_THROW",nullptr,0)){const auto retained=engine.snapshot();if(!retained.failed&&retained.running&&retained.frames>0){engine.saveFrame(smokeSave);smokeStep=5;veyra::log::info("image-save-test","retry after injected allocation failure; result/session retained");}}
-}auto s=engine.snapshot();pollSubtitleAutoAlign();
+}auto s=engine.snapshot();playbackPower.update(!closing&&s.running&&!s.failed&&!s.image&&s.transport==veyra::engine::TransportState::Playing);pollSubtitleTracks();if(subtitleRequestAutoAlign&&subtitlePrimary>=0){subtitleRequestAutoAlign=false;startSubtitleAutoAlign();}pollSubtitleAutoAlign();
{
std::vector<veyra::ui::SubtitleLine> draw;
const bool showSubtitles=uiState.subtitles&&!subtitleTracks.empty()&&!(showDiagnostics&&uiState.mode==veyra::ui::Mode::Professional&&!full);
@@ -697,7 +742,6 @@ if(compareMode||holdOriginal)text+=L"\r\n真实帧对比:两侧同一源帧;
const auto problem=veyra::Logger::instance().latestProblem();if(!problem.empty()){int n=MultiByteToWideChar(CP_UTF8,0,problem.data(),int(problem.size()),nullptr,0);std::wstring detail(n,0);MultiByteToWideChar(CP_UTF8,0,problem.data(),int(problem.size()),detail.data(),n);text+=L"\r\n最近问题:"+detail.substr(0,100)+L"(详见诊断)";}
veyra::ui::setText(statusBar,text);
using namespace veyra::ui;
-if(uiState.enhanced&&s.frames>0&&!s.applying&&!s.failed){lastSuccessful=s.applied;haveSuccessful=true;}
if(masterPendingRevision&&!s.applying){if(s.sessionId==masterPendingSession&&s.rejectedRevision==masterPendingRevision&&s.desired.revision<masterPendingRevision){uiState.enhanced=masterPreviousEnabled;settingsEnabled(uiState.enhanced,uiState.configured);veyra::log::warn("ui-master","transaction rolled back; UI restored to actual enabled state");}masterPendingRevision=0;}
if(smokeScreenshot&&screenshotStep==0&&s.frames>20){SendMessageW(hwnd,WM_COMMAND,Save,0);screenshotStep=1;}
if(screenshotPending){
@@ -724,7 +768,7 @@ auto stamp=[](double v){int seconds=std::max(0,int(v));return std::format(L"{:02
setText(GetDlgItem(hwnd,TimeLabel),s.remotePlay?(s.remoteRatesReady?std::format(L"接收 {:.1f} · 解码 {:.1f} fps",s.remoteReceivedFps,s.remoteDecodedFps):std::wstring(L"PS5 帧率采样中")):s.capture?std::format(L"输入 {:.1f} fps{}",s.captureFps,s.captureHalfRate?L" · 60→30":s.applied.content==veyra::engine::ContentRate::Capture60To30?L" · 不适用":L""):s.image?L"静态图片":stamp(s.seekPresented<s.seekRequested&&!s.failed?s.seekTarget:s.position)+L" / "+stamp(s.duration)+(s.seekPresented<s.seekRequested&&!s.failed?L" · 跳转中…":L"")+(s.transport==veyra::engine::TransportState::Opening?L" · 正在打开…":s.failed?L" · 发生错误,详见专业诊断":L""));
std::wstring metric=std::format(L"源帧处理 {:.1f} fps · 显示提交 {:.1f} fps · 有效生成 {}\n提交迟到 p95 {:.1f} ms · GPU / CPU 时间分别统计\n{}\n实际扫描率与光子延迟:未测",s.fps,submittedFps,s.generated,s.lateP95Ms,s.status);setText(metricLabel,metric);
if(uiState.mode==Mode::Professional&&!full&&!transition.running&&GetTickCount64()-dashboardTick>=250){dashboardTick=GetTickCount64();RECT client{};GetClientRect(hwnd,&client);RECT dashboard{0,client.bottom-dip(hwnd,232),client.right,client.bottom};InvalidateRect(hwnd,&dashboard,FALSE);}
-exportJob.watching(preferWatching&&s.running&&s.transport==veyra::engine::TransportState::Playing);auto job=exportJob.poll();exportPanelStatus(job,!currentFile.empty()&&!s.capture&&!s.image&&s.frames>0&&!s.applying,s.running&&s.frames>0);setText(GetDlgItem(hwnd,JobProgress),job.message+std::format(L" {}% · 查看",int(job.progress*100)));ShowWindow(GetDlgItem(hwnd,JobProgress),job.state==veyra::engine::ExportState::Idle||full?SW_HIDE:SW_SHOW);
+exportJob.watching(preferWatching&&s.running&&s.transport==veyra::engine::TransportState::Playing);auto job=exportJob.poll();exportPanelStatus(job,!currentFile.empty()&&!s.capture&&!s.image,s.running&&s.frames>0);setText(GetDlgItem(hwnd,JobProgress),job.message+std::format(L" {}% · 查看",int(job.progress*100)));ShowWindow(GetDlgItem(hwnd,JobProgress),job.state==veyra::engine::ExportState::Idle||full?SW_HIDE:SW_SHOW);
setText(GetDlgItem(hwnd,EmptyTitle),s.failed?L"播放已停止":L"开始观看");setText(GetDlgItem(hwnd,EmptyHint),s.failed?s.status:L"打开本地视频,或连接采集卡\n精细调整与原生导出在专业模式中");ShowWindow(GetDlgItem(hwnd,EmptyTitle),SW_HIDE);ShowWindow(GetDlgItem(hwnd,EmptyHint),SW_HIDE);
if(dragging&&GetCapture()!=seekBar){dragging=false;seekPreview.released=true;}
seekPreview.tick();
@@ -733,7 +777,7 @@ if(!smokeViewApplied&&!smokeView.empty()&&(s.frames>0||smokeEmpty)){smokeViewApp
if(smokeDualPause&&pausedPosition<0&&s.frames>20){engine.pause(true);pausedPosition=s.position;pausedFrames=s.frames;}
if(smokeDual&&startTick&&s.frames>10&&dualStep<40&&GetTickCount64()-startTick>ULONGLONG(1500+dualStep*200)){if(dualStep==4){modeGdiStart=GetGuiResources(GetCurrentProcess(),GR_GDIOBJECTS);GetProcessHandleCount(GetCurrentProcess(),&modeHandlesStart);PROCESS_MEMORY_COUNTERS_EX pm{};pm.cb=sizeof(pm);GetProcessMemoryInfo(GetCurrentProcess(),reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pm),sizeof(pm));modePrivateStart=pm.PrivateUsage;}switchMode();
if(smokeDualPause&&pausedPosition>=0&&s.transport==veyra::engine::TransportState::Paused){auto after=engine.snapshot();if(after.position!=s.position||after.frames!=s.frames)dualStep=-100;}++dualStep;if(dualStep==40){DWORD handles=0;GetProcessHandleCount(GetCurrentProcess(),&handles);PROCESS_MEMORY_COUNTERS_EX pm{};pm.cb=sizeof(pm);GetProcessMemoryInfo(GetCurrentProcess(),reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pm),sizeof(pm));veyra::log::info("ui-resources",std::format("gdiStart={} gdiEnd={} handlesStart={} handlesEnd={} privateStart={} privateEnd={}",modeGdiStart,GetGuiResources(GetCurrentProcess(),GR_GDIOBJECTS),modeHandlesStart,handles,modePrivateStart,pm.PrivateUsage));}}
-if((smokeDual||smokeJobCancel||smokeJobExit)&&!smokeDualOutput.empty()&&s.frames>20){jobExpected=s.applied;jobExpected.nrPolicy=veyra::pipeline::NrSizePolicy::Native;exportJob.start(currentFile,smokeDualOutput,s.applied,false,(smokeJob||smokeJobCancel||smokeJobExit)?120:24);smokeDualOutput.clear();jobStep=1;jobPosition=s.position;}
+if((smokeDual||smokeJob||smokeJobCancel||smokeJobExit)&&!smokeDualOutput.empty()&&s.frames>20){jobExpected=s.applied;jobExpected.nrPolicy=veyra::pipeline::NrSizePolicy::Native;exportJob.start(currentFile,smokeDualOutput,s.applied,false,(smokeJob||smokeJobCancel||smokeJobExit)?120:24);smokeDualOutput.clear();jobStep=1;jobPosition=s.position;}
if((smokeJobCancel||smokeJobExit)&&jobStep==1&&job.state==veyra::engine::ExportState::Running&&job.sourceFrames>=10){if(smokeJobExit){veyra::log::info("ui-job-test","parent close with active worker; cooperative cancellation requested");resultCode=0;PostMessageW(hwnd,WM_CLOSE,0,0);}else exportJob.cancel();jobStep=2;}
if(smokeJobCancel&&jobStep==2&&job.state==veyra::engine::ExportState::Cancelled){jobStep=4;veyra::log::info("ui-job-test",std::format("cancelled=true foregroundContinues={} source={} encoded={}",s.running,job.sourceFrames,job.encoded));}
if(smokeJob&&jobStep==1&&job.state==veyra::engine::ExportState::Running){exportJob.pause(true);jobStep=2;jobPauseTick=GetTickCount64();auto changed=s.desired;changed.model.intensity=.65f;engine.requestSettings(changed);}
@@ -1030,8 +1074,10 @@ if(smokeProtection&&startTick&&GetTickCount64()-startTick>1500){
}
if(smokeSeconds>0&&startTick&&GetTickCount64()-startTick>ULONGLONG(smokeSeconds)*1000){veyra::log::info("app",std::format("smoke frames={} generated={} failed={} latenessMs={:.2f} absLatenessP95Ms={:.2f} controlsStep={} capture={} processedFps={:.2f} callbackFps={:.2f} captureDropped={} callbackToPresentReturnP95Ms={:.3f} schedulingWaitP95Ms={:.3f} processCpuP95Ms={:.3f} presentCpuP95Ms={:.3f} nrEvaluated={} nvofExecuted={}",s.frames,s.generated,s.failed,s.lateMs,s.lateP95Ms,smokeStep,s.capture,s.fps,s.captureFps,s.captureDropped,s.captureAgeP95Ms,s.schedulingWaitP95Ms,s.processCpuP95Ms,s.presentCpuP95Ms,s.nrEvaluated,s.nvofExecuted));resultCode=(s.frames>0||smokeEmpty)&&!s.failed&&(!smokeZoom||zoomStep==3)&&(!smokeProtection||protectionStep==4)&&(!smokeRepair||repairStep==10)&&(!smokeTransport||transportStep==10)&&(!smokeFgOnly||fgOnlyStep==4)&&(!smokeSettings||settingsStep==5)&&(!smokeColor||colorStep==8)&&(!smokeRollback||settingsStep==3)&&(!smokeUi||uiStep==8)&&(!smokeDual||dualStep==40)&&(!smokeMaster||masterStep==3)&&(!smokeAudio||audioStep==4)&&(!(smokeJob||smokeJobCancel)||jobStep==4)&&(!smokeScreenshot||screenshotStep==2)?0:1;PostMessageW(hwnd,WM_CLOSE,0,0);}return 0;}
-case WM_CLOSE:endTransition();if(!closing&&smokeSeconds<=0&&exportJob.poll().active()&&MessageBoxW(hwnd,L"导出尚未完成。取消导出并退出?\n选择“否”返回播放器继续导出。",L"退出 Veyra",MB_YESNO|MB_DEFBUTTON2|MB_ICONQUESTION)!=IDYES)return 0;if(!closing&&smokeSeconds<=0){auto snapshot=engine.snapshot();WINDOWPLACEMENT placement{sizeof(placement)};if(full)placement=windowPlacement;else GetWindowPlacement(hwnd,&placement);auto r=placement.rcNormalPosition;uiPreferences.width=MulDiv(r.right-r.left,96,veyra::ui::layoutDpi(hwnd));uiPreferences.height=MulDiv(r.bottom-r.top,96,veyra::ui::layoutDpi(hwnd));uiPreferences.x=r.left;uiPreferences.y=r.top;uiPreferences.positioned=true;uiPreferences.volume=snapshot.volume;uiPreferences.muted=snapshot.muted;uiPreferences.subtitles=uiState.subtitles;uiPreferences.subtitleSize=subtitlePixels;uiPreferences.subtitleOutline=uiState.subtitleOutline;uiPreferences.subtitleBackground=uiState.subtitleBackground;uiPreferences.subtitleSecondLanguage=uiState.subtitleSecondLanguage;uiPreferences.subtitleMargin=uiState.subtitleMargin;uiPreferences.subtitleFont=uiState.subtitleFont;uiPreferences.inspector=uiState.inspector;uiPreferences.colourFoldMask=preferences.load().colourFoldMask;veyra::log::warn("ui-preferences","preferences not saved; corrupt original preserved");}exportJob.cancel();closing=true;engine.stop();SetWindowTextW(statusBar,L"正在释放当前任务资源…");return 0;
+case WM_CLOSE:endTransition();if(!closing&&smokeSeconds<=0&&exportJob.poll().active()&&MessageBoxW(hwnd,L"导出尚未完成。取消导出并退出?\n选择“否”返回播放器继续导出。",L"退出 Veyra",MB_YESNO|MB_DEFBUTTON2|MB_ICONQUESTION)!=IDYES)return 0;if(!closing&&smokeSeconds<=0){auto snapshot=engine.snapshot();WINDOWPLACEMENT placement{sizeof(placement)};if(full)placement=windowPlacement;else GetWindowPlacement(hwnd,&placement);auto r=placement.rcNormalPosition;uiPreferences.width=MulDiv(r.right-r.left,96,veyra::ui::layoutDpi(hwnd));uiPreferences.height=MulDiv(r.bottom-r.top,96,veyra::ui::layoutDpi(hwnd));uiPreferences.x=r.left;uiPreferences.y=r.top;uiPreferences.positioned=true;uiPreferences.volume=snapshot.volume;uiPreferences.muted=snapshot.muted;uiPreferences.subtitles=uiState.subtitles;uiPreferences.subtitleSize=subtitlePixels;uiPreferences.subtitleOutline=uiState.subtitleOutline;uiPreferences.subtitleBackground=uiState.subtitleBackground;uiPreferences.subtitleSecondLanguage=uiState.subtitleSecondLanguage;uiPreferences.subtitleMargin=uiState.subtitleMargin;uiPreferences.subtitleFont=uiState.subtitleFont;uiPreferences.inspector=uiState.inspector;uiPreferences.colourFoldMask=preferences.load().colourFoldMask;uiPreferences.enhancementEnabled=uiState.enhanced?1:0;auto saved=uiState.enhanced&&snapshot.running&&snapshot.frames>0&&!snapshot.applying&&!snapshot.failed?snapshot.applied:uiState.configured;if(!preferences.save(uiPreferences,&saved))veyra::log::warn("ui-preferences","preferences save failed; existing corrupt original preserved");else veyra::log::info("ui-preferences","UI and enhancement preferences saved");}playbackPower.update(false);exportJob.cancel();closing=true;engine.stop();SetWindowTextW(statusBar,L"正在释放当前任务资源…");return 0;
case WM_DESTROY:
+playbackPower.update(false);
+subtitleLoader.reset();
#ifdef VEYRA_ENABLE_REMOTEPLAY
remoteController.stop();KillTimer(hwnd,ControllerTimer);
#endif
@@ -1044,7 +1090,7 @@ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);INITCO
CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED);
initialOptions=veyra::engine::PlayerOptions::from(veyra::ui::defaultSettings());
-int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);for(int i=1;i<argc;++i){const std::wstring arg=argv[i];if(arg==L"--export-worker"&&i+1<argc)workerMapping=reinterpret_cast<HANDLE>(_wcstoui64(argv[++i],nullptr,10));else if(arg==L"--smoke-view"&&i+1<argc)smokeView=argv[++i];else if(arg==L"--smoke-fg-only")smokeFgOnly=true;else if(arg==L"--smoke-transport")smokeTransport=true;else if(arg==L"--smoke-repair-ui")smokeRepair=true;else if(arg==L"--smoke-repair-ui-reject")smokeRepair=smokeRepairReject=true;else if(arg==L"--smoke-hover")smokeZoom=smokeHover=true;else if(arg==L"--smoke-protection")smokeProtection=true;else if(arg==L"--smoke-zoom")smokeZoom=true;else if(arg==L"--smoke-empty")smokeEmpty=true;else if(arg==L"--smoke-dual")smokeDual=true;else if(arg==L"--smoke-dual-pause"){smokeDual=smokeDualPause=true;}else if(arg==L"--smoke-master-reject")smokeMaster=smokeMasterReject=true;else if(arg==L"--smoke-master")smokeMaster=true;else if(arg==L"--smoke-audio")smokeAudio=true;else if(arg==L"--smoke-job-cancel")smokeJobCancel=true;else if(arg==L"--smoke-job-exit")smokeJobExit=true;else if(arg==L"--smoke-job")smokeJob=true;else if(arg==L"--smoke-dual-export"&&i+1<argc)smokeDualOutput=argv[++i];else 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"--bitrate-mbps"&&i+1<argc)initialOptions.settings.exportBitrateMbps=uint32_t(std::clamp(_wtoi(argv[++i]),0,300));else if(arg==L"--subtitle-primary"&&i+1<argc)subtitleRequestPrimary=std::clamp(_wtoi(argv[++i]),-1,64);else if(arg==L"--subtitle-secondary"&&i+1<argc)subtitleRequestSecondary=std::clamp(_wtoi(argv[++i]),-1,64);else if(arg==L"--subtitle-offset-ms"&&i+1<argc)subtitleRequestOffsetMs=std::clamp(_wtoi(argv[++i]),-30000,30000);else if(arg==L"--subtitle-font-size"&&i+1<argc)subtitlePixels=std::clamp(_wtoi(argv[++i]),16,56);else if(arg==L"--subtitle-no-outline")uiState.subtitleOutline=false;else if(arg==L"--subtitle-background")uiState.subtitleBackground=true;else if(arg==L"--subtitle-auto-align")subtitleRequestAutoAlign=true;else if(arg==L"--smoke-rollback-flow"){smokeRollback=true;smokeRollbackFlow=true;}else if(arg==L"--smoke-rollback")smokeRollback=true;else if(arg==L"--smoke-ui")smokeUi=true;else if(arg==L"--no-fg")initialOptions.fg=false;else if(arg==L"--smoke-settings")smokeSettings=true;else if(arg==L"--smoke-color")smokeColor=true;else if(arg==L"--smoke-screenshot")smokeScreenshot=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"--fg-multiplier"&&i+1<argc){initialOptions.fgMultiplier=std::clamp(_wtoi(argv[++i]),2,4);initialOptions.fg=true;}else if(arg==L"--capture-audio"&&i+1<argc)initialOptions.settings.captureAudio=static_cast<veyra::engine::CaptureAudioIngress>(std::clamp(_wtoi(argv[++i]),0,2));else if(arg==L"--flow-amd")initialOptions.settings.opticalFlowBackend=veyra::engine::OpticalFlowBackend::AmdFidelityFx;else if(arg==L"--flow-gpudis")initialOptions.settings.opticalFlowBackend=veyra::engine::OpticalFlowBackend::GpuDis;else if(arg==L"--video-sr"&&i+1<argc){initialOptions.settings.videoSrQuality=std::clamp(_wtoi(argv[++i]),1,5);initialOptions.sr=true;}else if(arg==L"--nr-ampere")initialOptions.settings.nrRuntime=veyra::engine::NrRuntime::Ampere;else if(arg==L"--nr-community")initialOptions.settings.nrRuntime=veyra::engine::NrRuntime::Community;else if(arg==L"--nr-original")initialOptions.settings.nrRuntime=veyra::engine::NrRuntime::Original;else if(arg==L"--sr")initialOptions.sr=true;else if(arg==L"--no-nr")initialOptions.nr=false;else if(arg==L"--nr")initialOptions.nr=true;else if(arg==L"--no-sr")initialOptions.sr=false;else autoInput=arg;}LocalFree(argv);
+int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);for(int i=1;i<argc;++i){const std::wstring arg=argv[i];if(arg==L"--export-worker"&&i+1<argc)workerMapping=reinterpret_cast<HANDLE>(_wcstoui64(argv[++i],nullptr,10));else if(arg==L"--smoke-view"&&i+1<argc)smokeView=argv[++i];else if(arg==L"--smoke-fg-only")smokeFgOnly=true;else if(arg==L"--smoke-transport")smokeTransport=true;else if(arg==L"--smoke-repair-ui")smokeRepair=true;else if(arg==L"--smoke-repair-ui-reject")smokeRepair=smokeRepairReject=true;else if(arg==L"--smoke-hover")smokeZoom=smokeHover=true;else if(arg==L"--smoke-protection")smokeProtection=true;else if(arg==L"--smoke-zoom")smokeZoom=true;else if(arg==L"--smoke-empty")smokeEmpty=true;else if(arg==L"--smoke-dual")smokeDual=true;else if(arg==L"--smoke-dual-pause"){smokeDual=smokeDualPause=true;}else if(arg==L"--smoke-master-reject")smokeMaster=smokeMasterReject=true;else if(arg==L"--smoke-master")smokeMaster=true;else if(arg==L"--smoke-audio")smokeAudio=true;else if(arg==L"--smoke-job-cancel")smokeJobCancel=true;else if(arg==L"--smoke-job-exit")smokeJobExit=true;else if(arg==L"--smoke-job")smokeJob=true;else if(arg==L"--smoke-dual-export"&&i+1<argc)smokeDualOutput=argv[++i];else 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"--bitrate-mbps"&&i+1<argc)initialOptions.settings.exportBitrateMbps=uint32_t(std::clamp(_wtoi(argv[++i]),0,300));else if(arg==L"--subtitle-primary"&&i+1<argc)subtitleRequestPrimary=std::clamp(_wtoi(argv[++i]),-1,64);else if(arg==L"--subtitle-secondary"&&i+1<argc)subtitleRequestSecondary=std::clamp(_wtoi(argv[++i]),-1,64);else if(arg==L"--subtitle-offset-ms"&&i+1<argc)subtitleRequestOffsetMs=std::clamp(_wtoi(argv[++i]),-30000,30000);else if(arg==L"--subtitle-font-size"&&i+1<argc)subtitlePixels=std::clamp(_wtoi(argv[++i]),16,56);else if(arg==L"--subtitle-no-outline")uiState.subtitleOutline=false;else if(arg==L"--subtitle-background")uiState.subtitleBackground=true;else if(arg==L"--subtitle-auto-align")subtitleRequestAutoAlign=true;else if(arg==L"--smoke-rollback-flow"){smokeRollback=true;smokeRollbackFlow=true;}else if(arg==L"--smoke-rollback")smokeRollback=true;else if(arg==L"--smoke-ui")smokeUi=true;else if(arg==L"--no-fg")initialOptions.fg=false;else if(arg==L"--smoke-settings")smokeSettings=true;else if(arg==L"--smoke-color")smokeColor=true;else if(arg==L"--smoke-screenshot")smokeScreenshot=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"--fg-multiplier"&&i+1<argc){initialOptions.fgMultiplier=std::clamp(_wtoi(argv[++i]),2,6);initialOptions.fg=true;}else if(arg==L"--capture-audio"&&i+1<argc)initialOptions.settings.captureAudio=static_cast<veyra::engine::CaptureAudioIngress>(std::clamp(_wtoi(argv[++i]),0,2));else if(arg==L"--flow-amd")initialOptions.settings.opticalFlowBackend=veyra::engine::OpticalFlowBackend::AmdFidelityFx;else if(arg==L"--flow-gpudis")initialOptions.settings.opticalFlowBackend=veyra::engine::OpticalFlowBackend::GpuDis;else if(arg==L"--video-sr"&&i+1<argc){initialOptions.settings.videoSrQuality=std::clamp(_wtoi(argv[++i]),1,5);initialOptions.sr=true;}else if(arg==L"--nr-ampere")initialOptions.settings.nrRuntime=veyra::engine::NrRuntime::Ampere;else if(arg==L"--nr-community")initialOptions.settings.nrRuntime=veyra::engine::NrRuntime::Community;else if(arg==L"--nr-original")initialOptions.settings.nrRuntime=veyra::engine::NrRuntime::Original;else if(arg==L"--sr")initialOptions.sr=true;else if(arg==L"--no-nr")initialOptions.nr=false;else if(arg==L"--nr")initialOptions.nr=true;else if(arg==L"--no-sr")initialOptions.sr=false;else autoInput=arg;}LocalFree(argv);
// Diagnostic: force the colour grade on with a fixed exposure (EV). The grade is
// fused into the ingest dispatch, so this flag is how the graded cost is measured
// against the grade-off baseline on the same clip.
diff --git a/apps/veyra/ui/PlaybackPowerGuard.h b/apps/veyra/ui/PlaybackPowerGuard.h
new file mode 100644
index 00000000..5b605a9c
--- /dev/null
+++ b/apps/veyra/ui/PlaybackPowerGuard.h
@@ -0,0 +1,23 @@
+#pragma once
+#include <windows.h>
+#include <format>
+#include "veyra/Log.h"
+
+namespace veyra::ui {
+// SetThreadExecutionState must be acquired and cleared on the same UI thread.
+class PlaybackPowerGuard {
+ bool active_=false;
+public:
+ ~PlaybackPowerGuard(){update(false);}
+ bool active()const{return active_;}
+ void update(bool playing){
+ if(playing==active_)return;
+ const auto flags=ES_CONTINUOUS|(playing?(ES_DISPLAY_REQUIRED|ES_SYSTEM_REQUIRED):0);
+ if(!SetThreadExecutionState(flags)){
+ log::error("playback-power",std::format("SetThreadExecutionState failed win32={}",GetLastError()));return;
+ }
+ active_=playing;
+ log::info("playback-power",playing?"playback display/system request acquired":"playback display/system request released");
+ }
+};
+}
diff --git a/apps/veyra/ui/SeekPreview.h b/apps/veyra/ui/SeekPreview.h
index 9569682c..2eaa7564 100644
--- a/apps/veyra/ui/SeekPreview.h
+++ b/apps/veyra/ui/SeekPreview.h
@@ -15,7 +15,7 @@ struct SeekPreview {
target=seconds;released=release;
// Mouse release supersedes even an outstanding preview: the final
// exact target must never be dropped behind a busy preview.
- if(release){engine.seek(target);submitted=target;}
+ if(release&&target!=submitted){engine.seek(target);submitted=target;}
else tick();
}
void tick() {
diff --git a/apps/veyra/ui/UiPreferenceStore.h b/apps/veyra/ui/UiPreferenceStore.h
index 1edd2918..051854ef 100644
--- a/apps/veyra/ui/UiPreferenceStore.h
+++ b/apps/veyra/ui/UiPreferenceStore.h
@@ -18,6 +18,8 @@ struct UiPreferences {
int subtitleMargin=0,subtitleFont=0;
// v4: colour-page accordion fold mask (one bit per section).
uint32_t colourFoldMask=0;
+ // -1 migrates v1-v4 by deriving the master switch from the saved effects.
+ int enhancementEnabled=-1;
};
class UiPreferenceStore {
std::filesystem::path folder_;
@@ -29,7 +31,7 @@ public:
// inspector index 4 is the audio page (selectInspector(4)), so the valid
// range is 0..4. A narrower bound here silently discarded every saved
// window size, volume and subtitle style for users who last sat on it.
- if(!(file>>magic>>version>>read.volume>>mute>>sub>>read.width>>read.height>>read.x>>read.y>>pos>>read.inspector>>read.subtitleSize)||magic!="VEYRA_UI"||(version<1||version>4)||!std::isfinite(read.volume)||read.volume<0||read.volume>1||mute<0||mute>1||sub<0||sub>1||pos<0||pos>1||read.width<720||read.width>10000||read.height<540||read.height>10000||abs(int64_t(read.x))>100000||abs(int64_t(read.y))>100000||read.inspector<0||read.inspector>4||read.subtitleSize<16||read.subtitleSize>56){corrupt_=true;return result;}
+ if(!(file>>magic>>version>>read.volume>>mute>>sub>>read.width>>read.height>>read.x>>read.y>>pos>>read.inspector>>read.subtitleSize)||magic!="VEYRA_UI"||(version<1||version>5)||!std::isfinite(read.volume)||read.volume<0||read.volume>1||mute<0||mute>1||sub<0||sub>1||pos<0||pos>1||read.width<720||read.width>10000||read.height<540||read.height>10000||abs(int64_t(read.x))>100000||abs(int64_t(read.y))>100000||read.inspector<0||read.inspector>4||read.subtitleSize<16||read.subtitleSize>56){corrupt_=true;return result;}
if(version==2&&(!(file>>read.inspectorWidth)||read.inspectorWidth<296||read.inspectorWidth>420)){corrupt_=true;return result;}
if(version>=3){
int outline=0,background=0,second=0;
@@ -42,12 +44,13 @@ public:
// v4 appends the colour-page fold mask *after* the v3 subtitle block, so
// it must be read here - reading it earlier shifted every following field.
if(version>=4&&!(file>>read.colourFoldMask)){corrupt_=true;return result;}
+ if(version>=5&&(!(file>>read.enhancementEnabled)||read.enhancementEnabled< -1||read.enhancementEnabled>1)){corrupt_=true;return result;}
file>>std::ws;if(!file.eof()){corrupt_=true;return result;}read.muted=mute;read.subtitles=sub;read.positioned=pos;return read;
}
engine::EnhancementSettings startup(engine::EnhancementSettings fallback){engine::PresetStore last(folder_/"last-applied.v1");if(!last.load()||last.entries().empty())return fallback;return last.entries().front().settings;}
bool save(const UiPreferences& p,const engine::EnhancementSettings* applied){
bool ok=true;std::filesystem::create_directories(folder_);if(applied){engine::PresetStore last(folder_/"last-applied.v1");ok=last.load()&&last.put(L"Last applied",*applied,true);}
- if(corrupt_)return false;std::ostringstream out;out<<"VEYRA_UI 4\n"<<p.volume<<' '<<p.muted<<' '<<p.subtitles<<' '<<p.width<<' '<<p.height<<' '<<p.x<<' '<<p.y<<' '<<p.positioned<<' '<<p.inspector<<' '<<p.subtitleSize<<' '<<p.inspectorWidth<<' '<<p.subtitleOutline<<' '<<p.subtitleBackground<<' '<<p.subtitleSecondLanguage<<' '<<p.subtitleMargin<<' '<<p.subtitleFont<<' '<<p.colourFoldMask<<'\n';
+ if(corrupt_)return false;std::ostringstream out;out<<"VEYRA_UI 5\n"<<p.volume<<' '<<p.muted<<' '<<p.subtitles<<' '<<p.width<<' '<<p.height<<' '<<p.x<<' '<<p.y<<' '<<p.positioned<<' '<<p.inspector<<' '<<p.subtitleSize<<' '<<p.inspectorWidth<<' '<<p.subtitleOutline<<' '<<p.subtitleBackground<<' '<<p.subtitleSecondLanguage<<' '<<p.subtitleMargin<<' '<<p.subtitleFont<<' '<<p.colourFoldMask<<' '<<p.enhancementEnabled<<'\n';
auto target=folder_/"ui-preferences.v1",tmp=folder_/(L"ui-preferences.tmp-"+std::to_wstring(GetCurrentProcessId()));auto data=out.str();HANDLE file=CreateFileW(tmp.c_str(),GENERIC_WRITE,0,nullptr,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,nullptr);if(file==INVALID_HANDLE_VALUE)return false;DWORD written=0;bool saved=WriteFile(file,data.data(),DWORD(data.size()),&written,nullptr)&&written==data.size()&&FlushFileBuffers(file);CloseHandle(file);if(saved)saved=MoveFileExW(tmp.c_str(),target.c_str(),MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH)!=FALSE;return ok&&saved;
}
};
diff --git a/docs/DLSS_SUSTAINED_REPAIR_2026-09-18.md b/docs/DLSS_SUSTAINED_REPAIR_2026-09-18.md
new file mode 100644
index 00000000..9e5299bd
--- /dev/null
+++ b/docs/DLSS_SUSTAINED_REPAIR_2026-09-18.md
@@ -0,0 +1,155 @@
+# Sustained DLSS 4X / 6X repair, 2026-09-18
+
+Branch: `codex/post140-field-repair-20260917`. No merge, push or release.
+Local hardware: RTX 5070 / driver 616.56 / physical USB3 capture, 1080p60 YUY2.
+User reports both 4X and 6X becoming limited without full total GPU usage.
+The physical RTX 30/40/5090 acceptance limits in the other repair documents remain.
+
+## Findings and implementation
+
+- Preserved application log: `out/logs/dlss-sustained-user-20260918.log`, SHA256
+ `65A775AECEC8C73BC96B8AC5FDB838EF2B0C05A7ED9689A7DB628C59C198D641`.
+ Its capture configuration includes SR to 4K, realtime NR at 1080p, FG at 4K
+ and a 2191x1187 window. Many evaluated generated frames expire before Present.
+- `FrameMetrics.h` omitted Fg4/Fg5. 6X therefore overwrote FgBatch and Blit
+ timestamps. Added separate stages, static assertions and regression checks.
+- Shared presentation/enhancement allocators caused approximately 6ms waits in
+ Present although DXGI service was approximately 0.1-0.2ms. Admission counted
+ this GPU waiting again as presentation service. DLSS now uses a dedicated
+ DIRECT presentation queue, fence and three command slots. The enhancement
+ ring stays at six slots. XeSS/FSR keep their existing provider queues.
+- Producer/consumer GPU fence handoffs protect each output parity. A real
+ texture waits for the full FG batch because FG still reads it. A generated
+ texture waits its own ready fence. Reuse and teardown wait for consumer
+ completion. Test-only readback drains the correct queue.
+- Live capture accepts at most one pending enhancement batch while continuing
+ to service its bounded presentation queue. It reads the latest mailbox frame
+ after capacity is available, avoiding accumulating stale enhanced batches.
+- Live interpolation deadlines now include measured base processing after B
+ arrives, capped at one source interval and sampled before processing. PTS
+ stay unchanged. This adds bounded live latency; it is not free lookahead.
+- Admission never discounts future FG by CPU elapsed time. CPU progress is
+ capped at measured base cost. Transient rejection no longer imposes a fixed
+ 250ms cooldown, which otherwise loses 15 healthy 60Hz pairs; every pair still
+ checks its real deadline, and recovery requires consecutive admissions.
+- Presentation service samples expire after one second. Soft history resets
+ retain revision-scoped observations instead of starving completion metrics.
+
+## Experiments and failures
+
+All rates below are submission rates, not physical scanout FPS. Each test is
+bounded below 300 seconds. Admission-off runs are diagnostic controls only.
+Product settings do not enable that override.
+
+| Capture configuration / experiment | Post-recovery mean submissions/s |
+| --- | ---: |
+| Original 6X NR+SR | about 60 / target 360 |
+| Enum fix only, 4X NR+SR | 69.615 / target 240 |
+| Deadline allowance, 4X / 6X NR+SR | 90.290 / 90.261 |
+| 6X effects off | 359.923 / target 360 |
+| Dedicated queue, 4X NR+SR | 96.913 |
+| Dedicated queue + 12 enhancement slots, 4X NR+SR | 93.615 |
+| Dedicated queue + one pending GPU batch, old cooldown, 4X NR+SR | 131.615 |
+| Same, admission off, 4X NR+SR | 179.000; still expires frames |
+| Dedicated queue + backpressure, old cooldown, NR-only 6X, 60 seconds | 359.868 |
+
+The 12-slot experiment was removed; it did not reliably improve throughput.
+Full NR+SR local GPU work was about 17-18ms per source at 4X and 20ms at 6X,
+above the 16.67ms budget of 60Hz. Low total utilization cannot prove that this
+serial processing path fits its deadline. No claim of full 4K 360fps is made.
+
+Build6 failed on `.at()` used with a C array; corrected to bounds-checked
+indexing. Builds7-10 passed. Logs: `out/logs/fg-sustained-buildN-20260918.log`.
+First presentation regression passed exact pixels for 4X (18 generated) and
+6X (30 generated), with zero D3D12 errors. Its repeated 4X cycle failed because
+the test attempted to save the same PNG twice; fixed with cycle-specific names.
+Original result: `out/logs/fg-presentation-final-result-20260918.log`.
+Pixel equality checks presentation against actual DLSS output, not interpolation
+quality. The earlier content-dependent synthetic motion failures remain open.
+
+## Final local validation
+
+Build directory: `out/build/post140-hdr-preflight-20260918`.
+`veyra_presentation_worker_tests.exe`: passed, including deadline recovery and
+expiry tests; log `out/logs/fg-scheduler-final-20260918.log`.
+`veyra_repair_contract_tests.exe`: 205 checks, zero failures.
+
+Build11 passed (44 targets): `out/logs/fg-sustained-build11-20260918.log`.
+Final executable: `out/build/post140-hdr-preflight-20260918/veyra.exe`.
+SHA256: `9F63750E652C8FBE2CE6185D3D21CFBD7E7CAA19BB7A66E2DDFB297D875B7251`.
+
+| Final configuration | Duration | Recovery mean submissions/s | Result |
+| --- | ---: | ---: | --- |
+| 1080p60 capture, NR, DLSS 4X | 180 s | 239.981 / 240 | PASS |
+| 1080p60 capture, NR, DLSS 6X | 180 s | 359.943 / 360 | PASS |
+| 1080p60 capture, NR + SR to 4K, DLSS 4X at 4K | 45 s | 177.609 / 240 | FAIL throughput; lifecycle PASS |
+| 1080p60 capture, NR + SR to 4K, DLSS 6X at 4K | 45 s | 191.130 / 360 | FAIL throughput; lifecycle PASS |
+
+Each run injected 55 ms CPU work per source frame from t=15 to t=17 seconds.
+The recovery mean starts at t=22. Both 180-second runs have 158 recovery
+samples with zero limited samples: 4X ranges 239-241 submissions/s, 6X 359-361.
+Expired frames remain at 3 and 7 respectively throughout recovery. Total
+generated frames are 32049 and 53410. The 6X runtime log records Create and
+Release `0x1` and 53440 Evaluate calls. These are actual local runtime calls,
+not RTX30/40 acceptance or display scanout measurements.
+Results: `out/logs/fg-final-{nr4,nr6,full4,full6}-result-20260918.log`;
+runtime logs: corresponding `out/logs/fg-final-*-20260918/engine.log`.
+The NR 4X run used build10; build11 only added test-readback queue draining
+and corrected the nonlive consumer-fence diagnostic after that run.
+
+Presentation regression passed 4X -> 6X -> 4X, 40 source frames per cycle,
+114/190/114 generated frames, reset, queued presentation, 640 -> 320 -> 640
+resize, consumer-fence reuse protection and producer-first teardown.
+Maximum pixel error against each corresponding DLSS texture: 0; D3D12 errors: 0.
+Log: `out/logs/fg-presentation-verified-20260918.stdout.log` (exit 0).
+
+The supplied MKV settings regression passed 1 -> 2 -> 6 -> 1 -> 6, paused
+seek/resume and shutdown: 117 source frames, 172 generated, maximum generated
+count 5. Log: `out/logs/fg-final-settings-20260918.stdout.log` (exit 0).
+
+Final delivery gate passed in 62.5811217 seconds (26 checks):
+`logs/delivery/4a5b5a11d376481184994f93e376659f/result.json`.
+Its executable hash matches the hash above. This gate does not supersede
+the failed full-enhancement throughput controls or hardware acceptance limits.
+
+Commands (run from repository root):
+
+```powershell
+& cmd.exe /c 'out\build\veyra-build-x64-release.cmd'
+& out/build/post140-hdr-preflight-20260918/veyra_presentation_worker_tests.exe
+& out/build/post140-hdr-preflight-20260918/veyra_repair_contract_tests.exe
+& out/build/post140-hdr-preflight-20260918/veyra_fg_sustained_tests.exe 'capture:0:0:-1:0' out/logs/fg-final-nr4-20260918 4 on 180 nr 0.95
+& out/build/post140-hdr-preflight-20260918/veyra_fg_sustained_tests.exe 'capture:0:0:-1:0' out/logs/fg-final-nr6-20260918 6 on 180 nr 0.95
+& out/build/post140-hdr-preflight-20260918/veyra_fg_sustained_tests.exe 'capture:0:0:-1:0' out/logs/fg-final-full4-20260918 4 on 45 on 0.95
+& out/build/post140-hdr-preflight-20260918/veyra_fg_sustained_tests.exe 'capture:0:0:-1:0' out/logs/fg-final-full6-20260918 6 on 45 on 0.95
+& scripts/run-short-test.ps1 -Exe out/build/post140-hdr-preflight-20260918/veyra_fg_presentation_tests.exe -Arguments @('out/logs/fg-presentation-verified-20260918') -TimeoutSeconds 60 -LogPrefix out/logs/fg-presentation-verified-20260918
+& scripts/run-short-test.ps1 -Exe out/build/post140-hdr-preflight-20260918/veyra_fg_settings_tests.exe -Arguments @('C:/Users/123/Desktop/Money.Heist.2019.S03E02.V2.1080p.NF.WEB-DL.H264.DDP5.1-LeagueNF.mkv','out/logs/fg-final-settings-20260918') -TimeoutSeconds 240 -LogPrefix out/logs/fg-final-settings-20260918
+& scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/post140-hdr-preflight-20260918
+```
+
+## Changed files and remaining acceptance
+
+This sustained repair changes `include/veyra/diagnostics/FrameMetrics.h`,
+`include/veyra/engine/{FgRecoveryBudget,TimingWindow,VideoPresenter}.h`,
+`src/engine/{EngineController,VideoPresenter}.cpp`,
+`include/veyra/pipeline/EnhanceGraph.h`, `src/pipeline/EnhanceGraph.cpp`,
+`tests/unit/{LiveGpuSchedulerTests,RepairContractTests}.cpp`, `CMakeLists.txt`,
+and adds `tests/integration/{FgSustainedTests,FgPresentationTests}.cpp`.
+Evidence is recorded here and in `docs/WORKLOG.md`; earlier repair documents
+also correct their DRED description. Other existing branch edits are retained.
+
+Full 4K enhancement still exceeds the local 60 Hz source budget (approximately
+17.3 ms at 4X and 20.8 ms at 6X). Neither a driver update nor low total GPU
+utilization proves these serial stages meet their deadlines. This remains an
+open performance limit; no multiplier reduction is presented as a fix.
+
+RTX30/40/5090 physical tests were not executed. The affected 5090 NR -> XeSS
+device removal (`0x887A002B`) remains unreproduced locally; its useful DRED
+evidence and the original export-worker first-error log remain unavailable.
+Content-dependent synthetic interpolation-position failures also remain open.
+No all-issues-complete claim is made.
+
+Next acceptance task: run this exact build with the affected user's unchanged
+4X/6X configuration and capture application/engine logs spanning the first
+limited transition, so remaining serial GPU cost can be separated from a
+recurring scheduling failure on that hardware.
diff --git a/docs/EXPORT_GATE_REMOVAL_2026-09-18.md b/docs/EXPORT_GATE_REMOVAL_2026-09-18.md
new file mode 100644
index 00000000..99d9edb2
--- /dev/null
+++ b/docs/EXPORT_GATE_REMOVAL_2026-09-18.md
@@ -0,0 +1,124 @@
+# Export Gate Removal, 2026-09-18
+
+## Request and Evidence
+
+The user explicitly requested removing export restrictions and validation,
+including the full decode of the completed output. This supersedes older
+requirements for product-side CFR rejection and output integrity verification.
+Changes remain on `codex/post140-field-repair-20260917`; no publication or merge.
+
+User log: `E:/wechat/xwechat_files/wxid_kcmlgkgv70mv22_d585/msg/file/2026-09/export-worker-17508(1).log`.
+At 19:37:28.533 it reports 51,248 source/output frames and successful NVENC calls.
+At 19:37:28.765 it starts reopening the HEVC output using a single-thread software
+decoder. At 19:48:43.861 verification reports 51,248/51,248 frames, EOF and PASS.
+This redundant stage took approximately 675 seconds. The log does not contain
+the reported GUI failure and does not establish a driver failure.
+
+## Implementation
+
+- `src/engine/VideoExportJob.cpp`: remove the 120-frame CFR qualification scan,
+ source reopen, per-source strict CFR rejection, child FG compatibility probe,
+ audio codec-query rejection and corrupt-packet flag rejection. The actual graph,
+ encoder, decoder and mux operations still return their real errors.
+- Remove all post-export reopen/decode/dimension/color/timestamp/count checks.
+ Flush the encoder, write the trailer, close the file, then rename the partial.
+- The encoder still receives sequential frame IDs; a small in-flight timestamp
+ queue translates completed packets into source-relative microseconds. A single
+ pending compressed packet obtains its duration from the next packet. Irregular
+ frame intervals and long gaps retain their real duration without dropping any
+ decoded source frame, or generating an unbounded run of duplicate frames.
+ FG timestamps subdivide each actual source interval. Missing/backward source
+ timestamps are repaired using the nominal interval, counted and logged.
+ Their original timing cannot be reconstructed when the source is malformed.
+- HDR plus an H.264 request selects HEVC Main10 with an explicit outcome note.
+ XeSS/FSR export retains the existing explicit DLSS substitution.
+- `src/sink/NvencD3D12Encoder.cpp`: API version and maximum-dimension/10-bit
+ capability queries are diagnostic only. Real CreateInstance/Open/Initialize
+ results select NVENC or the existing system-encoder fallback. ABI structures
+ remain the audited 13.0 layout; no guessed version-field rewriting.
+- `apps/veyra/ui/AppShell.cpp`: exporting no longer requires a successful preview
+ frame or a completed preview effect transaction. Freeze the requested effective
+ UI settings for the independent worker.
+- `src/engine/ExportJobManager.cpp`: remove verification claims and preserve
+ the worker's success notes, including codec/backend substitutions.
+
+Bounds needed to allocate planes or parse shared memory, existing-file protection,
+actual encoding/I/O/mux failures and cancellation remain. Removing those would
+cause memory errors, data loss or false success, rather than enable an export.
+An unavailable requested enhancement still reports its actual initialization
+failure; the requested multiplier is not silently reduced.
+
+## Verification
+
+Hardware: RTX5070, driver 616.56. No RTX30/40 hardware execution in this change.
+All test processes are bounded to 300 seconds or less. Independent test decoding
+is intentionally retained outside the application.
+
+Build: `cmd.exe /c out\build\scheduling-audit-build.cmd`, exit 0.
+Final build log: `out/logs/export-relaxed-build-final-20260918.log`.
+
+`tests/integration/ExportTimingTests.ps1 -BuildDirectory out/build/scheduling-audit-20260918 -OutputDirectory out/logs/export-relaxed-timing-final-20260918`:
+PASS H.264 NVENC, HEVC DLSS 6X, forced Media Foundation, and injected NVENC failure
+with successful Media Foundation fallback. The fixture changes from 30 to 15 fps.
+Every source frame remains at its original relative time (measured error zero),
+generated frames subdivide the actual intervals, sample durations are contiguous,
+AC-3 audio remains present, and independent FFmpeg decoding succeeds. Real output
+creation failure remains exit 1. Results: 60/360/60/60 frames; 6X consists of
+60 source + 295 generated + 5 explicitly counted tail holds. DLSSG Create is
+`0x1`, NVENC EncodePicture/LockBitstream status 0. Logs beside `result.json`.
+The initial test script failed because `$error` is a reserved PowerShell variable;
+renamed to `$timestampError` before the successful full run. The first failed
+script run remains in `out/logs/export-relaxed-timing-20260918.log`.
+
+All following executables run from `out/build/scheduling-audit-20260918`, through
+`scripts/run-short-test.ps1`:
+
+- `veyra_scheduling_chain_tests.exe out/logs/rtx30-package-motion-fixture.mkv out/logs/export-relaxed-cancel-20260918 export`, limit 90s: PASS cancellation after
+ 1/3/5 source frames, partial retained, no false completion; subsequent 12-frame
+ job succeeds. Initial shell invocation incorrectly passed an array through
+ `pwsh -File`; corrected to invoke the script with `&` before execution.
+- `veyra_export_worker_failure_tests.exe probe out/logs/rtx30-package-motion-fixture.mkv out/logs/export-relaxed-probe-bypass.mp4`, limit 40s: PASS. A forced
+ compatibility-probe rejection no longer blocks the worker. Real 6X exports
+ 72 frames from 12 sources; `logs/export-worker-16804.log`.
+- `veyra.exe out/hdr-audio-fixtures/pq-tagged-51.mp4 --export-out out/logs/export-relaxed-hdr-auto.mp4 --no-nr --no-sr --no-fg --max-frames 12`, limit 60s:
+ PASS without `--hevc`. Independent ffprobe confirms HEVC, yuv420p10le,
+ BT2020/PQ and AAC audio.
+- `veyra_export_worker_failure_tests.exe encoder out/hdr-audio-fixtures/pq-tagged-51.mp4 out/logs/export-relaxed-real-encoder-error.mp4`, limit 40s: PASS actual
+ initialization-failure reporting. Injected NVENC status 15 plus unavailable HDR
+ system fallback produces failure with the worker-log path, not false success.
+- `veyra_audio_track_output_tests.exe out/audio-tracks-fixture.mkv out/logs/export-relaxed-audio-tracks`, limit 120s: PASS selected English audio, measured 880 Hz,
+ through both the independent worker and controller export paths.
+
+## Delivery Status
+
+`scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/scheduling-audit-20260918`:
+PASS 26 checks, 60.406 seconds. Evidence:
+`logs/delivery/35f686779486445f9b4e0e51e9cbe49c/result.json`.
+This includes actual NR/NVOF, native 4K H.264/HEVC 2X encoding, independent
+decode/frame-count/audio checks, cancellation and source switching.
+
+EXE SHA256: `38E7A3ED8B5156A4962FF227391698D6CD71BFCBED4DA98807B03A6F6E5E7599`.
+
+Packaging command: `scripts/package-portable.ps1 -Root . -Version 1.4.0 -Label '-test-20260918-r3' -OutputDirectory C:/veyra-test-packages/post140-20260918-r3 -BuildDirectory out/build/scheduling-audit-20260918`.
+`out/tmp/finalize-post140-package.ps1 -SkipSource -Revision r3` adds the testing
+instructions and existing third-party license texts, audits all 113 archive
+entries against their manifest hashes and rejects debug/SDK/private-media data.
+Evidence: `out/logs/export-relaxed-package-r3-audit.log`.
+
+Portable: `C:/veyra-test-packages/post140-20260918-r3/Veyra-1.4.0-test-20260918-r3-win64-portable.zip`.
+SHA256: `BEC301B6BF19419246E04FD8D0849A461FC73EEFE168532E500161C635898215`.
+
+`out/tmp/smoke-r3-export.ps1` runs the independently extracted executable from
+TEMP with only Windows directories in PATH. PASS actual HEVC 6X export, packaged
+FFmpeg/FG module paths, 60 source + 295 generated + 5 holds = 360 frames, no
+post-export decode, and independent FFmpeg decode of the completed output.
+Evidence: `out/logs/export-relaxed-packaged-6x.json` and
+`out/logs/export-relaxed-packaged-smoke.log`.
+
+The matching worktree source snapshot and unchanged FFmpeg/RemotePlay source
+archives are provided alongside the portable archive, with SHA256 sidecars and
+`delivery-verification.json`. r2 is unchanged. Runtime identities and patched
+FFmpeg are unchanged. No merge, push or public release. `git diff --check` passes.
+Next acceptance: reproduce the user's original export with r3; its exact GUI
+failure was not present in the supplied worker log. Target RTX30 hardware
+acceptance from the preceding repair remains open.
diff --git a/docs/PLAYER_TRACKS_SETTINGS_REPAIR_2026-09-18.md b/docs/PLAYER_TRACKS_SETTINGS_REPAIR_2026-09-18.md
new file mode 100644
index 00000000..e27829a5
--- /dev/null
+++ b/docs/PLAYER_TRACKS_SETTINGS_REPAIR_2026-09-18.md
@@ -0,0 +1,125 @@
+# Player field repairs, 2026-09-18
+
+Branch: `codex/post140-field-repair-20260917`. This extends the post-1.4.0
+repair without merging, publishing, or adding local runtime/media to Git.
+
+## Initial evidence
+
+- RTX 4060 Ti log: community NR Feature 18 creates successfully before restart;
+ subsequent original NR selection fails with `0xFFFFFFFFBAD00001`. WM_CLOSE
+ unconditionally logs a corrupt-preferences warning and never calls save.
+- NR then XeSS log: first Present fails with `0x887A0005`, device removal
+ reason `0x887A002B`, e.g. 2026-09-17T13:51:11.608Z. Initialization succeeds.
+ Establish the resource/queue failure with a local sequence test; do not
+ label this insufficient GPU performance or claim an untested fix.
+- Subtitle popup returns an index correctly. Existing flat menu mixes 32 main
+ and 32 secondary tracks with settings; selecting a track does not enable
+ subtitles. Async listing currently withholds cue updates until a whole-file
+ scan completes. Improve selection and incremental availability.
+- File audio decoder selects only av_find_best_stream. Add enumeration and
+ explicit selection, preserving position, pause, gain and channel layout.
+- Measure open and seek against the supplied MKV, including audio/probing and
+ subtitle work. Retain truthful timestamps and complete export processing.
+- Prevent idle display/system sleep and screen saver only while playing.
+
+## Validation contract
+
+Build, preference restart tests (including bypass and NR runtime choice),
+subtitle scrolling/selection with 32 tracks, selected audio PCM/timestamps,
+open/seek timings, NR/XeSS in both orders, playback power lifecycle and delivery
+gate. Hardware here is RTX 5070: RTX 30/40/5090 remains explicitly unverified.
+Record commands, results and remaining limits below and in WORKLOG.
+
+## Implemented
+
+- `AppShell.cpp` splits the subtitle popup into audio, primary subtitle and
+ secondary subtitle selectors. Choosing a subtitle enables its display.
+ Audio rows map to container stream IDs, not popup indices. Selection uses
+ the current session ID so a stale request cannot affect a different file.
+- `Subtitles.cpp` publishes cues after 250 ms and subsequently once per second
+ during its bounded, cancellable single demux scan. Opening playback does not
+ wait for the full subtitle scan. User choices, offsets and external tracks
+ survive progressive updates. Existing text/ASS support is not a claim of
+ newly implemented bitmap subtitle support.
+- `AudioTrack.h`, `WasapiAudioSink`, `EngineController` enumerate audio language,
+ title, codec and channel count. Switching stops the decoder worker, opens the
+ candidate decoder before replacing the current one, restarts the endpoint
+ with the selected channel layout and restores position/pause/volume. Invalid
+ stream IDs are rejected. MKV audio seeks now use the container video index
+ followed by PCM timestamp trimming, avoiding a long scan from a sparse audio
+ index. `SeekPreview.h` avoids submitting the same final seek twice.
+- `ExportJobManager`, worker IPC v2 and `VideoExportJob` carry and validate the
+ selected audio stream. The legacy `EngineController::startExport` path also
+ preserves it across settings conversion. Export retains selected audio
+ metadata; tests verify decoded content, not only the language tag.
+- `UiPreferenceStore.h` adds a v5 master-enabled field and migrates older
+ preferences. `AppShell.cpp` now actually saves on normal close. Successful
+ applied settings are saved when available; otherwise the configured draft
+ is saved, including while master enhancement is off. Removed the stale
+ last-successful cache that could restore an older source's settings.
+- `PlaybackPowerGuard.h` holds an execution-state request on the UI thread
+ while video is playing. Pause, stop, failure and close release it. The main
+ window suppresses screen saver/monitor-off system commands while playing.
+- `PresentSink.cpp` acquires the proxy swapchain's current buffer index once;
+ `VideoPresenter.cpp` uses that same index for the resource barriers, RTV and
+ recorded last buffer. This repairs an inconsistent resource/descriptor
+ selection contract. It is NOT established as the cause of the user's
+ `DXGI_ERROR_ACCESS_DENIED` device removal.
+
+## Actual validation
+
+All tests below passed on RTX 5070 / driver 616.56 with patched FFmpeg at
+`C:/veyra-deps/ffmpeg-ps5-dav1d-installed`. Each test ran under 300 seconds.
+Build directory: `out/build/post140-hdr-preflight-20260918`.
+EXE SHA256 at this validation checkpoint (superseded by the sustained-FG repair):
+`5B35FDAD4291168A03A1EA0E9D911B952123DFD800C57237A08CB07F6DB1529D`.
+
+| Check | Actual evidence |
+| --- | --- |
+| Full build | `out/logs/player-tracks-build3-20260918.log`, exit 0 |
+| Supplied 4.27 GB MKV | `out/logs/player-tracks2-result-20260918.log`: 17 tracks switched in both playing and paused states, stale session/invalid ID rejected; first frame 367.05 ms, seeks to 30/1200/90 seconds 31.3501/30.8197/30.6269 ms. Warm cache; earlier open was 974 ms. These are local measurements, not all-machine limits. |
+| Audio content and export | `out/logs/audio-track-output-result-20260918.log`: 440/880 Hz tracks switched twice, each 24000 decoded PCM frames at 1000 ms; both worker and legacy exports contain the selected 880 Hz English track, 240 encoded video frames. Worker log `logs/export-worker-33780.log`. AAC skipped-sample warnings on output decode did not fail PCM/timestamp assertions. |
+| Progressive subtitles | `out/logs/subtitle32-progressive-result-20260918.log`: intermediate cue publication observed, all 32 tracks usable, 15720 cues, background scan 5753.49 ms; cancellation 15.1261 ms. FFmpeg emitted an incomplete-probe warning during cancellation. |
+| Actual normal GUI | `out/logs/player-shell-result-20260918.log`: normal close/restart retained NR, SR, community runtime choice and bypass draft; selected 32nd subtitle (stream 49), audio stream 1, fullscreen/pause/resume/close power lifecycle passed. Sandbox `out/tests/player-shell-d033d14c6d80468c95313d82508df4a6`, including four application logs and separate writable preferences. User preferences were not overwritten. |
+| Popup and preferences | `out/logs/popup33-result-20260918.log`, `veyra_ui_contract_tests.exe out/tests/ui-preferences-20260918-a`: 33-row scrolling/keyboard selection, disk round trip, master off/on and corrupt-original protection passed. |
+| NR / XeSS order | `out/logs/player-xess-exact-window-result-20260918.log`: 4K/50fps capture replay, AMD optical flow, exact 1155x741 client size; NR-first and XeSS-first each repeated twice, 501 processed frames, each combined stage 26-36 actual generated frames. NR Create `0x1`, XeSS initialization `0`; no device removal. Logs in `out/logs/player-xess-exact-window-20260918`. This is replay on 5070, not the user's capture card or 5090. No pixel-quality comparison in this order test. |
+| Latest delivery gate | `logs/delivery/81a8d951f689467a868456f023550dbd/result.json`: PASS, 61.575757 s, matching EXE hash. Covers actual NR/NVOF, native 4K correctness, playback, controls, image output, H.264/HEVC decode/audio/frame accounting and cancellation. Not hardware acceptance or endurance testing. |
+
+Commands executed (from the repository root; fixture paths are ignored):
+
+```powershell
+$build = 'out/build/post140-hdr-preflight-20260918'
+$media = 'C:/Users/123/Desktop/Money.Heist.2019.S03E02.V2.1080p.NF.WEB-DL.H264.DDP5.1-LeagueNF.mkv'
+& cmd.exe /c 'out\build\veyra-build-x64-release.cmd' *> out/logs/player-tracks-build3-20260918.log
+& "$build/veyra_player_tracks_tests.exe" $media out/logs/player-tracks2-20260918 *> out/logs/player-tracks2-result-20260918.log
+& "$build/veyra_audio_track_output_tests.exe" out/audio-tracks-fixture.mkv out/logs/audio-track-output-20260918 *> out/logs/audio-track-output-result-20260918.log
+& "$build/veyra_subtitle_loading_tests.exe" $media 32 *> out/logs/subtitle32-progressive-result-20260918.log
+& "$build/veyra_player_tracks_tests.exe" out/xess-live-amd-4k50.mp4 out/logs/player-xess-exact-window-20260918 xess-live-amd *> out/logs/player-xess-exact-window-result-20260918.log
+& tests/integration/PlayerShellTests.ps1 -BuildDirectory $build -Media $media *> out/logs/player-shell-result-20260918.log
+& scripts/gates/delivery.ps1 -Root . -BuildDirectory $build *> out/logs/player-tracks-delivery-20260918.log
+```
+
+The audio fixture is an 8-second 640x360/30 H.264 video with two AAC 48 kHz
+sine tracks (440 Hz / spa, 880 Hz / eng). The order fixture is 4K/50 H.264.
+Neither fixture nor any runtime/SDK is added to source Git.
+
+## Remaining evidence limits and next task
+
+- The RTX 4060 Ti report contains successful community NR creation followed
+ by original NR failure after restart. Saving the runtime preference repairs
+ that concrete failure chain. No physical RTX 40 retest was performed here.
+- The 5090 NR-first failure remains unreproduced. Both orders pass locally,
+ but that cannot establish a fix for error `0x887A002B`. Device removal may
+ precede its first visible Present failure. `PresentSink.cpp` already queries
+ DRED breadcrumbs and page faults after device failure. Forced collection
+ enablement and useful evidence from the affected machine are not established.
+- Playback power checks exercised successful Windows requests, their release
+ and the screen-saver message path. They did not wait through a physical
+ sleep timeout or test every enterprise power policy.
+- Earlier RTX 30/40 6X work and the content-dependent synthetic interpolation
+ position failures remain recorded in the post-1.4.0 plan. No physical RTX
+ 30/40/5090 test was performed, and the affected export user's original worker
+ log is still missing. This patch is not an all-issues-complete claim.
+- Next task: run this exact build on affected RTX 30/40/5090 hardware, retain
+ the application/probe/export-worker logs and obtain the first failing call
+ for any remaining NR/XeSS or export failure. No merge, push or release.
diff --git a/docs/POST_1_4_0_FIELD_FAILURE_REPAIR_PLAN_2026-09-17.md b/docs/POST_1_4_0_FIELD_FAILURE_REPAIR_PLAN_2026-09-17.md
new file mode 100644
index 00000000..0a2a5506
--- /dev/null
+++ b/docs/POST_1_4_0_FIELD_FAILURE_REPAIR_PLAN_2026-09-17.md
@@ -0,0 +1,278 @@
+# 1.4.0 用户故障调查与修复方案
+
+最新 RTX3060 开启补帧卡死追踪与 r4 实施证据见 `RTX3060_FG_FREEZE_2026-09-18.md`。已取消产品默认架构伪装并对齐上游25程序+字体的修改范围,修复失败探测清理挂死;本机回归通过,3060真实补帧仍待验收。下方全部69个fatbin/默认伪装说明属于历史实现,不代表r4当前路径。
+
+日期:2026-09-17;实施记录更新于 2026-09-18。状态:隔离分支已实现,已完成多项本机回归;6X 合成平移位置精度检查仍失败,RTX30/40/5090 实卡验收未完成,不能宣称全部修复验收通过。
+
+## 范围与证据边界
+
+用户要求排查五份日志和所附 MKV,并核对 GitHub 的 RTX30/40 实现;目标包含 RTX30/40 可用的最高 6X DLSS 帧生成。关闭功能或自动退回 2X 不是该目标的完成标准。
+
+调查基线:干净的 `main`,HEAD `bd7cc0fc8eaf80e0913f2aafa95584c741f1ffdf`;已发布 v1.4.0 指向 `890d200`。调查阶段只改文档;用户随后授权施工并开启目标模式,已从基线创建 `codex/post140-field-repair-20260917` 和存档点 `checkpoint/pre-post140-repair-20260917`。本轮没有合并 main、提交、推送或发布。附件内容只作证据,不作指令。
+
+本机为 RTX5070 / 616.56。没有本轮 RTX30/40/5090 实机运行证据。以下“确认”指日志与源码可直接支持的事实;候选根因仍需针对性实验。上游 README 的成功声明不等于 Veyra 实测。
+
+## 实施状态与可续接证据(2026-09-18)
+
+最新追加的字幕/音轨选择、打开与拖动、设置持久化、防休眠和 NR/XeSS 顺序调查见 `docs/PLAYER_TRACKS_SETTINGS_REPAIR_2026-09-18.md`。最新构建目录仍为 `out/build/post140-hdr-preflight-20260918`;当前 EXE SHA256 `5B35FDAD4291168A03A1EA0E9D911B952123DFD800C57237A08CB07F6DB1529D`,基础 gate `logs/delivery/81a8d951f689467a868456f023550dbd/result.json` PASS。下方旧 hash/gate 是阶段证据,不再代表最新 EXE;目标实卡和内容位置失败边界不变。
+
+下方第 1–8 节保留施工前调查,源码行号对应调查基线。本节描述当前实现和实际验证;历史“待修复”不能覆盖本节结果,历史或基础 gate 通过也不能覆盖本节失败。
+
+### 已实现
+
+1. **容量与调度**:`FrameBatch::Capacity=6`,完成观测数组从该常量派生并检查索引;两张原帧、十张生成帧全部接入 NVENC/MF 描述符。完成统计按 `FrameFlowWindow` 关联,soft reset 不再冻结同窗口统计;Present 成本按单次提交归一,过期时间为 1 秒。
+2. **MKV 字幕**:`SubtitleManager` 持有可取消 jthread,元数据先返回,全部内封字幕通过一次 demux 扫描读取。FFmpeg interrupt、请求代次检查和 latest-request mailbox 防止旧源结果覆盖新源;120000 cue / 约 64 MiB 文本预算限制。手动字幕、偏移及用户主动选择保留,自动对齐等待正文加载完成。CLI 双轨选择与异步结果同步已修复。
+3. **导出初始化**:使用固定 NVENC **13.0 完整 ABI**,移除仅改 session apiVersion 的伪回退;先查询驱动 max API(编码为 major<<4|minor),各结构体/函数表一致。NVENC 阶段、状态码和 last-error 与 MF 独立错误链传回主进程/UI。只有确证驱动 API 太旧才建议更新驱动。HDR 无 MF 10bit 回退时明确说明。系统 NVENC DLL 不复制入包。
+4. **倍率与 worker**:导出不再把请求 6X 静默改为 2X/关闭;present-sink FG 转 DLSS 导出路径有明确日志。主日志保留 jobId、PID、绝对 worker 日志路径和最终源帧/生成帧/hold/编码数;失败消息附 worker 路径。
+5. **RTX40/30 初始化**:移植固定 MIT 上游 discovery、startup 和 Create gate 逻辑,建立独占 `FgCompatibilitySession`。程序/PTX 和 NVAPI 兼容在 NGX Init 前安装;绑定实际 device/LUID、provider identity、两张原帧与十张生成帧。Ada 保留原生 Available 判断;Ampere 有完整 SM86 程序路径和限定 startup/Create 门控。能力 5 只表示可尝试,实际 Create/Evaluate 必须成功。
+6. **兼容生命周期**:patch 发布与还原检查页保护、字节一致性和指令缓存刷新;失败记录不会被抹掉。NGX Shutdown 后才还原补丁与释放资源;还原无法证明时进程标为不健康,拒绝后续 NGX,保留相关模块/资源到进程退出。测试失败注入通过。已确证恢复原指针的 patch 存储可释放,不能一概声称所有内部存储都永久保留。
+7. **卡死隔离**:产品在兼容初始化前运行同 LUID/尺寸/倍率/HDR/provider 的子进程预检,真实执行三帧 Create/Evaluate。60 秒有界等待,可取消;受限句柄继承、先挂 job 再恢复线程、job 关闭杀进程。缓存只记录成功且包含驱动/provider hash。预检不能保证父进程后续调用永不挂死,不以其成功代替实卡画质检查。
+8. **FG 参数与诊断**:零向量不再被指定为 invalid motion,使用不可用的 float 极大值作为哨兵。静态相机补齐正交方向基以及互逆的透视投影矩阵,与 near/far/FOV 一致;该修正未改变下述合成位置偏差,不能算作偏差已修复。直接 NGX `--fg-planar6` 诊断与图内检查都保留失败结果。
+9. **HDR 兼容预检修正**:追加实际导出发现预检只设 `hdrOutput`、仍使用 SDR RGB 输入,必然触发 `HDR output requires an explicit HDR input contract`。现在 HDR 预检同时设置 `hdrInput`,使用显式 limited-range P010/PQ/BT.2020-NCL/BT.2020 测试帧,再进入 RGB10 FG。SDR 预检保留 RGBA 路径。修复前 `post140-ampere6-hdr-final` exit 1,子进程 PID35616/stage2/generated0;修复后强制 Ampere/Ada 的完整 HDR 6X 导出均通过。
+
+源码范围:`src/engine/{EngineController,ExportJobManager,VideoExportJob,Subtitles,FgCompatibilityProbe}.cpp`,`src/ngx/{DlssFgBackend,AdaMfgUnlock,AmpereMfgUnlock,NvapiArchSpoof,FgCompatibilitySession}.cpp` 与 `src/ngx/compat/`,`src/pipeline/EnhanceGraph.cpp`,三个编码器文件,`D3D12DeviceContext`,对应 include,AppShell/main,CMake,单元/集成测试与 `tools/fg_harness/`。新增适配源码的来源、固定提交与许可证见 `THIRD_PARTY_NOTICES.md`,不是从 NVIDIA SDK 拷贝实现。
+
+### 本机证据
+
+所有下列 `post140-*` 日志前缀均在 `out/logs/`,标准输出/错误分别为 `.stdout.log` / `.stderr.log`。测试使用 `scripts/run-short-test.ps1`,单项 timeout 不超过 300 秒。强制 Ada/Ampere 只在独立测试进程通过环境变量开启,**不代表 RTX30/40 实卡**。
+
+| 检查 | 结果与日志 |
+| --- | --- |
+| 构建 | `post140-build-publication.log`、`post140-build-camera.log`、`post140-build-direct-planar.log` 均 exit 0;目录 `out/build/post140-field-repair-20260917` |
+| 容量/soft-reset/Present 过期 | `post140-contract`、`post140-scheduler` PASS |
+| 32 轨大 MKV | `post140-subtitle-dual-final` PASS:32 usable tracks、15720 cues,primary=3/secondary=5/offset=700ms 保留,扫描 2576.748ms,播放 425 帧,failed=false;较早冷缓存扫描约 9.4–10.3s,不能把热缓存值当固定耗时 |
+| 字幕取消/源切换 | `post140-subtitle-cancel-final` PASS;首次 MKV 测试 first decode 44ms / first valid 120ms,未等完整字幕扫描 |
+| 12 个编码输入槽 | `post140-pool-{h264,hevc,mf-h264,mf-hevc}` PASS;实际逐槽写不同灰度、编码、解码比对,D3D12 debug 检查 |
+| NVENC 错误分流 | `post140-nvenc-invalid-version`(注入 status 15)、`post140-nvenc-unsupported`(注入非版本错误)PASS,MF SDR 回退可编码;不是模拟降低版本后当真机通过 |
+| 2–6X 反复创建/reset/分辨率变化/退出 | 原生 `post140-native-lifecycle`;强制兼容 `post140-ada-publication-lifecycle`、`post140-ampere-publication-lifecycle` PASS;倍率序列 6,2,5,3,4,6、尺寸 640×360/368 |
+| 回滚失败 | `post140-rollback-publication-final` PASS:强制 Ampere + rollback-fail,失败后保留必要资源且拒绝 reinit |
+| 子进程卡住 | `post140-probe-timeout` PASS:测试专用 2s timeout,产品为 60s;`post140-worker-probe-reject`、`post140-worker-probe-cancel` PASS |
+| 6X SDR 完整导出 | `post140-ampere6-cow` H264、`post140-ada6-final-hevc` HEVC PASS(均为 5070 强制路径);12 source + 55 generated + 5 明示 CFR holds = 72 encoded,解码 72 帧,1920×1080/360fps/.2s,AAC mono/.213333s |
+| 6X HDR 完整导出 | `post140-hdr6-hevc` PASS(5070 原生):HEVC Main10/yuv420p10le/BT2020nc/PQ/BT2020,1920×1080/180fps/72 decoded/.4s,AAC 6ch 5.1;5 个 CFR holds 不计作插值 |
+| 6X HDR 兼容预检与导出 | `post140-ampere6-hdr-repaired`、`post140-ada6-hdr-repaired` PASS(5070 强制路径):预检 PID37608/34920 均 exit0/stage4/generated10;随后各 12 source + 55 generated + 5 holds = 72 encoded。`ffprobe -count_frames` 实际解码各 72 帧,Main10/PQ/BT2020/1920×1080/180fps/.4s,AAC 6ch 5.1/.405333s;兼容补丁恢复成功 |
+| worker 暂停/继续/取消 | `post140-worker6` PASS:120 source + 595 generated + 5 holds = 720 encoded,前台继续播放;`post140-worker-cancel-final` PASS |
+| 初始化失败实际消息链 | `post140-worker-error-tagged` PASS,PID40072:`OpenD3D12Session status=15` + `HDR 10bit 不支持此系统编码路径(仅 8bit NV12)`,source/generated/encoded 均为 0,没有输出文件,主日志有完整 worker 路径。最初 `post140-worker-error-final` FAIL 是测试误用了未标记 HDR 的素材,MF 正常成功;保留该失败,不当作产品失败 |
+| 基础 delivery | 最终产品代码 `logs/delivery/2c9372ba16774e3d9f7529825f623fa3/result.json` PASS,62.0575379s;EXE SHA256 `DD117A0F3D484E8DAF6101B3E877A04B4884F1CE733E26A0D32415993330FACB` |
+| 2X 正弦纹理对照 | `post140-native2-planar-control` PASS,11/11 生成帧满足原定位置门槛 |
+| 6X 非周期纹理对照 | `post140-native6-planar-detail`、`post140-ada6-planar-detail`、`post140-ampere6-planar-detail`、`post140-native6-planar-detail-nvof` 全部 PASS,分别 55/55;前三项精确 motion,最后一项产品 NVOF。仍是 5070 本机,不是目标实卡 |
+
+实际构建命令:
+
+```powershell
+& cmd.exe /c 'out\build\veyra-build-x64-release.cmd' *> out/logs/post140-build-direct-planar.log
+& scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/post140-field-repair-20260917
+& scripts/run-short-test.ps1 -Exe out/build/post140-field-repair-20260917/veyra_export_worker_failure_tests.exe -Arguments @('encoder','out/hdr-audio-fixtures/pq-tagged-51.mp4','out/logs/post140-worker-error-tagged.mp4') -TimeoutSeconds 40 -LogPrefix out/logs/post140-worker-error-tagged
+& scripts/run-short-test.ps1 -Exe out/build/post140-field-repair-20260917/veyra_repair_fg_tests.exe -Arguments @('mfg6-exact-rgb-planar') -TimeoutSeconds 90 -LogPrefix out/logs/post140-native6-camera-planar
+& scripts/run-short-test.ps1 -Exe out/build/post140-field-repair-20260917/veyra_fg_harness.exe -Arguments @('--fg-planar6') -TimeoutSeconds 60 -LogPrefix out/logs/post140-native6-direct-planar
+```
+
+回滚测试实际命令在设置 `VEYRA_TEST_FORCE_AMPERE_UNLOCK=1` 的独立 shell 中运行 `run-short-test.ps1 -Exe out/build/post140-field-repair-20260917/veyra_fg_lifecycle_tests.exe -Arguments @('rollback-fail') -TimeoutSeconds 60 -LogPrefix out/logs/post140-rollback-publication-final`,finally 删除该环境变量。普通 RTX50 无强制变量时不安装兼容补丁。
+
+### 未通过项,不作完成声明
+
+- **6X 位置精度 FAIL**:精确 16px/源帧平移的合成纹理,目标位移 `[2.667,5.333,8,10.667,13.333]`,测得 `[2.25,7.75,8,11.25,12.25]`。55 张生成帧彼此不同、不同于两端原帧、不是线性混合,API/禁用标记正常,但只有 33/55 满足 ±1px 原定门槛。普通方块 39/55、纹理方块 45/55 也保留原结果。
+- 原生 5070、强制 Ada/Ampere 都复现;RGB 直入、精确运动向量、NVOF/零/反向 motion、诊断串行等待、FrameID 类型对照和相机矩阵对照没有解除偏差。串行等待/指针 FrameID 的临时产品开关已移除。
+- **直接 NGX 隔离也 FAIL**:`post140-native6-direct-planar` 记录 `directNGX=true generated=55 distinct=55 contentValid=33 graphUsed=false`,Create/Evaluate/Release/Shutdown 均 success。这排除了该实验中的播放器调度、图帧池、颜色转换与 NVOF;仍不能区分 `DlssFgBackend` 参数/资源契约与运行库内部插值行为,也不能声称 NVIDIA 模型就是根因。没有放宽精度阈值,没有用 2X 或重复帧冒充 6X。
+- **追加对照限制了上述结论的范围**:非周期双线性格点纹理保持 16px/帧平移、同一 ±1px 门槛和 PTS/真实插值/lease 检查,原生、强制 Ada/Ampere、产品 NVOF 均 55/55 通过。代表位移 `[3.25,5.5,8,10.5,12.75]`。因此存在可通过的真实 6X 内容路径,不能把正弦图案的失败概括为所有 6X 都时序错误;同样不能用新通过项覆盖旧正弦/方块失败。当前结论是内容相关的多帧位置误差,具体机理仍未证实。追加仅改测试 fixture,构建日志 `post140-build-detail-fixture.log` exit 0,未改产品 EXE。
+- 30/40/5090 真机未执行。子进程预检/生命周期和 5070 强制路径只能证明本地接线及部分内存安全;不能证明 SM86/SM89 在目标硬件的程序执行、VRAM、速度或画质。
+- 用户导出 worker 原始文件仍缺失,无法倒推其首错。现在已修 ABI 和诊断缺陷,不能据此称该用户机器实测修好。`PresentSink.cpp` 已有设备失败后的 DRED breadcrumbs/page fault 查询;尚未确认强制采集启用及受影响机器的有效证据。字幕烧录导出不是本轮新增能力,不声明已通过。
+
+**下一项唯一任务**:以直接 NGX 的 6X 合成复现继续核对资源/输入契约及 upstream 行为,保留原生 5070 基线与所有失败证据;随后取得 RTX30/40/5090 实卡复测和用户导出 worker 首错。没有这些证据前不发布“30/40 全型号 6X 已验证”结论。
+
+追加对照命令:`scripts/run-short-test.ps1 -Exe out/build/post140-field-repair-20260917/veyra_repair_fg_tests.exe -Arguments @('mfg6-exact-rgb-planar-detail') -TimeoutSeconds 90 -LogPrefix out/logs/post140-native6-planar-detail`。强制兼容分别在单独 shell 设置 `VEYRA_TEST_FORCE_ADA_UNLOCK=1` / `VEYRA_TEST_FORCE_AMPERE_UNLOCK=1`,使用对应日志前缀,finally 删除变量。NVOF 对照去掉模式中的 `-exact`,其日志记录 `nvOFDestroy status=0 executes=11`。原有正弦 fixture 未更改,仍可独立复现失败。变更/新增文件二进制扩展名及本地依赖目录审计 PASS;已跟踪/未跟踪文件空白检查 PASS。
+
+### HDR 预检追加构建(2026-09-18)
+
+旧目录的 `veyra.exe` 被正在运行的 PID9468 占用,构建日志 `out/logs/post140-build-probe-hdr.log` 记录 LNK1104。保留该窗口,改为独立构建目录 `out/build/post140-hdr-preflight-20260918`。完整构建 exit0,日志 `out/logs/post140-build-probe-hdr-isolated.log`;新 EXE SHA256 `880A3D585C3C01E574F5840C86AFF53F5B4D4F271D8264656057EF2BABED47CC`。旧目录 EXE 不包含本次 HDR 预检修正。新目录执行 `scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/post140-hdr-preflight-20260918` 再次 PASS,57.483224 秒,报告 `logs/delivery/ff9bea6b541d4934a52d0f6c0826f5bc/result.json`。最新完整基础 gate 以此为准,仍不覆盖目标实卡或未通过的内容位置检查。
+
+```powershell
+& scripts/build.ps1 -Root . -Preset x64-release -BuildDirectory out/build/post140-hdr-preflight-20260918 -FfmpegRoot C:/veyra-deps/ffmpeg-ps5-dav1d-installed -RemotePlay -ChiakiCheckout C:/veyra-deps/chiaki-source -ChiakiStage 'C:/Users/123/Desktop/Veyra DLSS Video Player/out/remoteplay/chiaki-msvc-stage' -RemotePlayPrefixPath C:/veyra-deps/remoteplay-installed/x64-windows-static -ProtocPath C:/veyra-deps/remoteplay-installed/x64-windows/tools/protobuf/protoc.exe -PkgConfigPath C:/veyra-deps/vcpkg/downloads/tools/msys2/3e71d1f8e22ab23f/mingw64/bin/pkg-config.exe
+$env:VEYRA_TEST_FORCE_AMPERE_UNLOCK='1'
+try {
+ & scripts/run-short-test.ps1 -Exe out/build/post140-hdr-preflight-20260918/veyra.exe -Arguments @('out/hdr-audio-fixtures/pq-tagged-51.mp4','--export-out','out/logs/post140-ampere6-hdr-repaired.mp4','--hevc','--max-frames','12','--fg-multiplier','6','--fg-dlss','--no-nr','--no-sr') -TimeoutSeconds 90 -LogPrefix out/logs/post140-ampere6-hdr-repaired
+} finally { Remove-Item Env:VEYRA_TEST_FORCE_AMPERE_UNLOCK -ErrorAction SilentlyContinue }
+```
+
+Ada 用独立 shell 设置 `VEYRA_TEST_FORCE_ADA_UNLOCK=1` 并替换输出/日志前缀为 `post140-ada6-hdr-repaired`,finally 清理。两项输出都用 `ffprobe -v error -count_frames -show_entries stream=codec_type,codec_name,profile,width,height,pix_fmt,color_space,color_transfer,color_primaries,avg_frame_rate,duration,nb_read_frames,channels,channel_layout -of json <output>` 核对。仍未执行 RTX30/40 实卡,新增通过项不覆盖上述内容位置失败。
+
+追加审计:已跟踪与新增文件的 `diff --check` 通过;修改列表没有 DLL/SDK/模型/媒体。再次计算 DLSSG/NR SHA256 与前述原件一致。没有合并、提交、推送或发布。
+
+### 播放与设置切换追加验证(2026-09-18)
+
+所附 32 轨 MKV 完整播放短测:`post140-ampere6-mkv-preview`、`post140-ada6-mkv-preview` 均 exit0,分别 170 source / 840 generated、196 source / 970 generated,failed=false;没有 backend-recovery 降档。Ada 终态 `generatedPresented=965 generatedExpiredAfterEval=0 presentSubmitFps=144`。这是提交统计,不是屏幕实测刷新率。Ampere 本次全字幕扫描 10790.259ms,播放未等全扫。命令为 `run-short-test.ps1 -Exe out/build/post140-hdr-preflight-20260918/veyra.exe -Arguments @(<所附 MKV 绝对路径>,'--smoke-seconds','12','--fg-multiplier','6','--fg-dlss','--no-nr','--no-sr') -TimeoutSeconds 90`,分别在独立 shell 设置对应强制兼容变量并 finally 清理。
+
+新增 `tests/integration/FgSettingsTests.cpp` 检查完整播放器设置工作流,发现关闭补帧启动后再开启,底层已生成帧但能力 snapshot 仍为 0。修复前日志 `post140-ampere-settings` FAIL:`desired=2 applied=2 frames=1571 generated=1558 cap=0 failed=0`。原因是 `EngineController.cpp` 仅在首次打开时发布 capability。已提取局部 `publishFrameGenerationCapabilities`,在首次打开、设置重建/恢复旧图、运行错误恢复和处理失败回滚后更新真实 provider 能力,删除过时的 Ada=2X 注释。
+
+构建 `cmd.exe /c out\build\veyra-build-x64-release.cmd`,`post140-build-settings-repaired.log`、`post140-build-settings-final.log` exit0。最终测试要求每次切换后至少新增 12 张源帧,补帧开启时新增至少 10 张生成帧,防止旧累计计数造成假通过。`post140-native-settings-final`、`post140-ada-settings-final`、`post140-ampere-settings-final` 全部 exit0:同进程 1→2→6→1→6、两次暂停 seek 后 6X 恢复、最终排空停止。每次 6X 的 requested/applied 都为 6,能力为 5 张生成帧。真实子进程预检 Create/Evaluate 成功,仍是 RTX5070 上的强制兼容测试。
+
+```powershell
+& scripts/run-short-test.ps1 -Exe out/build/post140-hdr-preflight-20260918/veyra_fg_settings_tests.exe -Arguments @('C:/Users/123/Desktop/Money.Heist.2019.S03E02.V2.1080p.NF.WEB-DL.H264.DDP5.1-LeagueNF.mkv','out/logs/post140-native-settings-final') -TimeoutSeconds 240 -LogPrefix out/logs/post140-native-settings-final
+```
+
+Ada/Ampere 分别设置 `VEYRA_TEST_FORCE_ADA_UNLOCK=1` / `VEYRA_TEST_FORCE_AMPERE_UNLOCK=1`,替换对应输出/日志前缀,finally 删除变量。最新 EXE 仍在 `out/build/post140-hdr-preflight-20260918/veyra.exe`,SHA256 已更新为 `231ECD897E19B7A45295EA3AE4694BD5717BA03113F33DD4E81E69CEBC84909A`,上节 HDR 修复时的 hash 是历史版本。该切换测试不替代内容位置检查或目标显卡验收。
+
+最终基础交付检查:`scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/post140-hdr-preflight-20260918` PASS,61.7707815 秒;报告 `logs/delivery/f0de8f4ef17a46418be3ce8733ebca54/result.json`,EXE hash 与本节一致。此报告取代上节作为最新基础 gate,未通过项仍以“未通过项,不作完成声明”为准。已跟踪/新增文件空白检查与源码/二进制隔离审计通过。首轮审计脚本把 `git diff --no-index --check` 的差异退出码 1 误判为失败;重新同时检查诊断输出和文件名单后通过,无文件内容修正。
+
+当前本地没有新的已证实根因可继续定点修复。下一项是让受影响的 RTX30/40/5090 使用上述构建复测并取得完整主日志、对应 `logs/export-worker-*.log` 和 `logs/fg-probe-*.log`;这将区分目标硬件的 Create/Evaluate、调度与编码首错。内容位置偏差保留为未解决问题,不以重复本机成功测试覆盖,也不在目标卡无证据时宣称 6X 全型号可用。未提交、合并、推送或发布。
+
+## 1. 先修:6X 路径存在确定的数组越界
+
+- `include/veyra/pipeline/FrameBatch.h:37` 已有 6 个 `BatchFrame`。
+- `src/engine/EngineController.cpp:466` 的 `CompletionWatch::frameReadyObserved` 仍只有 4 项。
+- 同文件 `530-531` 按 `batch.batch.count` 遍历;`1137` 按 `s.next` 访问。5X/6X 批次会访问数组外内存。已用 `git show 890d200:src/engine/EngineController.cpp` 确认发布版同样存在。
+
+这是内存安全缺陷,必须在继续解锁实验前修复。但不能倒推它导致了所有附件中的 device lost:4060 的 DLSS 实际退回 2X;30 系另一处设备丢失发生时 FG 已关闭。
+
+修复:统一批次容量定义,让观测数组由同一容量派生;审计所有帧数、描述符、fence、生成帧索引和队列上限,区分“6 个输出”和“5 个生成帧”。对批次计数建立边界检查。添加覆盖 2-6X、取消、部分完成、reset 的容量测试,使用可用的 ASan/边界检查验证。不要仅把这一处 4 改成 6 就宣称整条链已安全。
+
+## 2. RTX5090:调度长期拒绝补帧,呈现统计被软重置冻结
+
+### 直接证据
+
+`5090显卡补帧受限,显卡占用仅为百分之30.log:43903`,revision=12:
+
+```text
+sourceAccepted=7430 realSubmitted=7430
+fgCandidate=22290 fgSkippedBeforeEval=22287 fgEvaluated=3 fgWarmup=3
+fgReadyValid=0 generatedPresented=0 presentSubmitFps=30
+epoch=87 resetEpoch=80
+```
+
+同段持续约四分钟。末次 admission:`remainingDeadlineMs=22.359 predictedMs=25.396 elapsedMs=1.285 presentP95Ms=27.265 admitted=false`。`displaySubmits=3` 长期冻结,但 `presentationCompletedReal` 继续增加;另一路 Present CPU P95 为 3.159ms。
+
+### 源码对应与判断
+
+`EngineController.cpp:929-932` 只在 hard reset 时推进 `metricsWindowEpoch`;Drop/预览跳帧是 soft reset,图的历史 epoch 仍改变。`1035-1045` 仅在统计窗口重开时更新 `liveStats.identity`。`1204/1214` 却要求每个完成批次的图 epoch 与该旧 identity 相等,之后的新批次统计因此被丢弃。
+
+`945-960` 的准入继续读取 `livePresent.p95()`。`TimingWindow` 只有样本数量上限,没有墙钟过期;FG 预算自身 GPU 样本的过期无法使这个外部 Present 成本过期。由此形成“旧高耗时一直保留、没有新统计纠正、继续拒绝 FG”的反馈问题。这是与日志高度吻合的代码缺陷,尚未通过修复前后实机对照闭环。
+
+修复:统计会话/设置身份与时序历史 epoch 分开管理;拒绝旧会话完成事件,同时接纳同一统计窗口内新的 soft-reset epoch。Present 样本增加时间戳与有效期。拆分冷启动、实际 Present CPU 工作、节拍等待和 ready 等待;`1151` 的 `s.presentMs` 是整批累计值,必须核对预算按批还是按单次使用,不能混用。保留有界、受 deadline 约束的恢复探测。
+
+验收:构造一次 Drop 后继续呈现,验证统计继续更新;注入暂时高 Present 成本后解除,验证 FG 在有限时间恢复;再测真实欠速时仍能守住音频一倍速及预览延迟。比较生成有效帧、实际提交节奏、过期帧和 CPU/GPU 阶段耗时。文件名中的“30% 占用”没有对应硬件监测数据,不能据此断定 GPU 算力或驱动限制。
+
+## 3. 大 MKV 打开卡住:字幕逐轨整文件扫描阻塞 UI
+
+`src/engine/Subtitles.cpp:391-469` 对每条字幕轨循环 `av_read_frame`,直到文件末尾,再 seek 到开头扫下一条。`apps/veyra/ui/AppShell.cpp:125-140,292` 在 `engine.open()` 之前同步执行加载。
+
+合并日志中,HEVC 文件字幕轨 2-39 的首末完成记录相隔 85.110 秒,随后 D3D11VA 解码成功;Money Heist 的轨 18-49 相隔 64.066 秒。这些是首末字幕完成记录间隔,尚未包含第一轨扫描之前的等待,不能当作完整打开耗时。
+
+所附 4,272,359,225 字节 MKV 实为 H.264 1080p24、17 条 E-AC-3 音轨、32 条 SubRip 字幕,时长 2542.88 秒。系统 FFmpeg 8.1.1 读取前 5 秒视频 exit=0、0.974 秒;单次整文件 demux 提取首条字幕 exit=0、1.998 秒。这说明样本可读,也支持重复扫描造成大量额外工作;这些不是 Veyra 或随包 patched FFmpeg 的硬解测试。
+
+修复:元数据枚举与字幕正文加载分离;播放器启动不等待整文件字幕扫描。可取消 worker 用一次 demux 分发主/副轨,或在明确内存上限内缓存所有文本轨。使用源 generation 标识,切源后的旧结果不得写回;长读操作设 interrupt callback,seek/切轨/关闭可取消。主副字幕、时间偏移、ASS 样式及导出共享一致的轨道快照,禁止后台线程直接操作 UI 或播放 demuxer。
+
+验收:此文件的打开耗时不再随 32 轨重复全扫增长;UI 可响应;读取次数证明确为单次;切源/关闭期间取消安全;主副轨、拖动、偏移与导出字幕一致。首次画面和字幕就绪时间分开记录。
+
+## 4. RTX40:补丁命中不等于 NGX 已发布 6X 能力
+
+合并日志同时含 RTX4070 Laptop 和 RTX4060 Laptop 会话,不能全部归于 4060。4060 段记录:Ada 架构门控 2 项、count/index gate 1 项、descriptor slots 8 项、kernel 1 项,`identityVerified=1 applied=1`;之后仍是 `FG.Available=true MultiFrameCountMax=1`。请求 6X 被应用层自动改成 2X。2X 段确有 real/generated 各 124 帧的记录。
+
+`src/pipeline/EnhanceGraph.cpp:865` 先 `coreHost_->initialize()`,`877/880` 才调用 Ada/Ampere 补丁,再查询 capability。初始化阶段已缓存旧能力、补丁目标与实际活跃 provider 不一致,都是必须验证的候选;目前没有证据足以从中选定唯一根因。现有“不是已审计运行库”的警告不能由 `max=1` 单独推出,尤其同段已经记录 `identityVerified=1`。
+
+修复实验:
+
+1. 记录核心/provider 的绝对路径、SHA256、模块基址、导出函数归属、load generation、适配器 LUID,以及补丁前/后和初始化前/后的能力及原始返回码。
+2. 对照上游的 early-provider 生命周期,在确认模块依赖与加载顺序后,将需要提前生效的处理移到正确阶段。不要只机械地移动两行调用。
+3. 单独验证 NGX requirements/capability 与 provider count/index/kernel 门控。上游明确说明 count/index gate 不是 NGX 的共享 feature-support 查询。
+4. 已验证 provider/适配器/资源容量之后,按上游契约提供受限启动能力处理;真实 Create/Evaluate 仍必须成功。禁止全局写 `Available=true/max=5` 后就报通过。
+5. 在真实 Ada 上分别测 2X/3X/4X/5X/6X 和重复初始化。UI 同时呈现 requested/applied/reason;2X 回退保留为运行失败兜底,不计入 6X 完成。
+
+## 5. RTX30:缺失完整启动兼容路径,现有拒绝不是“不可能”的证明
+
+两份日志涉及 RTX3070 Ti 桌面及 Laptop。架构 spoof、fatbin 重建和预检命中后仍有:
+
+```text
+FG.Available=false
+FeatureInitResult=18446744072548777995
+MultiFrameCountMax Get=0xFFFFFFFFBAD00010
+```
+
+第一个数低 32 位是 `0xBAD0000B`,即 `UnableToInitializeFeature`;第二个是 `UnsupportedParameter`,不是“查到最大帧数为 0”的成功查询。失败在这些会话的 Create 之前。Laptop 日志 `HwSchMode=-1` 表示未得到该注册表值,不能直接解释成 HAGS 关闭。
+
+Veyra 主要移植了架构门控、GPU 程序重建与 spoof;当前本地上游 `ampere_backend.cpp:1555,1604,1643,2541` 还包括 requirements、启动 capability bootstrap、真实适配器/provider/load generation 校验,以及 Create 时 caller/缓冲分配验证。它并非简单取消一个 `Available` 检查。该上游路径包含游戏 wrapper/swapchain 前置条件,Veyra 必须映射到自己的直接 NGX host 和输出资源,不能生搬 wrapper 的判断。
+
+实施方向:基于有源码、可归因的上游,把 provider 生命周期、requirements/启动能力、sm_86 程序、创建参数和输出缓冲这几部分作为一条完整路径接入。保留直接 NGX,不加入 Streamline/ReShade。先用独立子进程探针定位失败阶段,设置超时,避免未知 Create 卡住播放器;实际产品创建/恢复策略依据探针结果制定。先建立真实 2X 的 Create/Evaluate 闭环,再逐项验证 3-6X;这只是定位次序,交付目标仍是最高 6X。
+
+过去“5070 强制 Ampere 路径通过”只能证明该路径在 5070 上运行,不证明 GA10x CUDA 程序、驱动和资源在 30 系可用。也不能从一次 3060 Create 失败推广到整个 30 系永远不可用。
+
+## 6. GitHub 核对(固定来源)
+
+| 项目 | 核对提交 | 当前结论 |
+| --- | --- | --- |
+| [dashdogy/RTX40MFG-Unlock](https://github.com/dashdogy/RTX40MFG-Unlock/tree/b77e6e55c9211faf58932fc67eaaad9feb9df934) | `b77e6e55c9211faf58932fc67eaaad9feb9df934`,v1.3.3 Hotfix 1 | MIT;40 系最高 6X;30 系标为 very early experimental / DX12。可用源码作为主要移植来源,但不能宣传所有机器已验证。 |
+| [sdli1995/dlssg_for_sm86](https://github.com/sdli1995/dlssg_for_sm86/tree/126d0f768f2293dad6f0da9d3b8fd6961ed88bdc) | `126d0f768f2293dad6f0da9d3b8fd6961ed88bdc`,v0.3.2 | README 声称在 3080Ti/3070 开发、310.9 支持 6X;当前树主要为二进制与文档,未见可移植实现源码或 LICENSE.md;README 声称项目源码 GPLv3,不能按旧说明当成 MIT。 |
+| [ImDreamt/MFGAdaUnlock-RenoDx](https://github.com/ImDreamt/MFGAdaUnlock-RenoDx/tree/a8aa0d9289471facc1e32013d17fd9c1195bc2cd) | `a8aa0d9289471facc1e32013d17fd9c1195bc2cd` | MIT,现有 notices 已归因;仅采用许可源码,不加载其 RenoDX add-on。 |
+
+本地 RTX40MFG-Unlock clone 固定于 `33b41835dc39c5d8ab1ef93efb2449be31139c09`,比核对 HEAD 少一个 hotfix commit。compare 和 README 显示该次更新主要涉及启动/菜单/诊断,provider policy/GPU payload 没有因此更换;“更新上游就好”没有证据。
+
+上游 [issue 38](https://github.com/dashdogy/RTX40MFG-Unlock/issues/38) 仍有 4070 3X/4X 卡住、2X 正常,也有 4080 3X 成功反馈,说明存在配置差异。[issue 28](https://github.com/dashdogy/RTX40MFG-Unlock/issues/28) 的 4060 Laptop 游戏问题不能直接作为 Veyra 同根因证明。
+
+`dlssg_for_sm86` 新版已转向 proxy 路径,旧原生 host 的兼容性结论需要重查。它是 30 系多帧可行性的上游证据,但当前不能直接复制缺失的源码;优先移植上表 MIT 实现,后续若拿到该项目源码/明确接口再比较。不得为追版本擅自提取或替换 NVIDIA 二进制;新 runtime 的本地/分发授权分别遵守 AGENTS。
+
+## 7. 导出:错误被分流到未提供的 worker 日志
+
+`导出问题.log` 仅记录启动 PID `43964/44892/44228/46492/38640`。`src/engine/ExportJobManager.cpp:76` 将实际执行写入独立 `logs/export-worker-<PID>.log`;`poll()` 读取退出码和共享错误消息,但没有把终态持久化回主日志。附件和本地已查位置没有这些对应 worker 日志,因此尚不能判断 NVENC、CFR、复用器或源解码哪个阶段失败。
+
+主日志在 13:16:27 有 `Present FAILED hr=0x887A0005 removedReason=0x887A0005`,之后 NGX 出现 `BAD00002`(PlatformError)。能确认 device lost 及后续失败,不能从主进程 Present 错误确定独立导出进程的首个失败。30 Laptop 另一处 device lost 前已有数百帧 `nr=0/fg=0/nvof=0`,不能归咎正在运行的 MFG。
+
+先补诊断:启动记录 jobId、PID、worker 绝对日志路径;结束回写退出码、最后阶段、原始错误码与错误文本;诊断导出聚合 worker 文件。补齐 DRED breadcrumbs/page fault、各队列错误与首个 device removal 记录,在丢失设备后按现有会话边界重建,禁止继续用失效资源循环 Create。DRED 是后续取证方案,不是已经得到的崩溃原因。
+
+收到对应 worker 日志后再针对首错修复;现有 NVENC 回退/CFR 补帧代码不等于本次已定位。预览使用 present-sink FG 时,导出后端的替代/降档也必须明确记录,不能将成功输出 2X 当作请求 6X 已完成。
+
+### 截图追加取证:泛化提示与 NVENC 回退缺陷
+
+用户随后提供截图 `C:/Users/123/AppData/Local/Temp/codex-clipboard-4a7bb8d7-aa77-442b-a59e-51dd0d4e223e.png`,显示“NVIDIA NVENC 与系统硬件编码器都无法初始化;请更新显卡驱动后重试;未生成输出文件”,进度 0%、源帧 0 / 编码 0;用户反馈驱动已经最新。是否最新尚未独立核实,既有日志记录的是 RTX5070 Laptop / 32.0.16.1664。
+
+`src/sink/VideoEncoderFactory.cpp:47` 证实这句提示仅由 NVENC/MF 两条 `open()` 均失败触发,没有任何驱动过旧判断。失败可来自 codec/尺寸/HDR/资源/会话/着色器等阶段;`MfVideoEncoder.cpp:198` 在 HDR 下直接拒绝,所以这条提示甚至不能证明系统硬件编码器实际尝试过激活。截图定位到正式编码开始前的初始化失败,不能再把本次截图对应失败归于末帧/CFR 收尾。
+
+进一步确认当前版本回退实现的问题(`src/sink/NvencD3D12Encoder.cpp:45-79`):
+
+- CMake 引用的本地头文件为 API 13.1。真实首开失败后,循环用 `major==NVENCAPI_MAJOR_VERSION` 跳过同主版本候选,导致 13.1 失败时连 13.0 也跳过,只试 12.0/11.0;它没有比较完整 major/minor。尚未独立确定用户发布包编译时头文件的 minor 版本,不能据此宣称这就是该用户首错。
+- `VEYRA_TEST_NVENC_FIRST_OPEN_FAILS=1` 使上述跳过条件失效。前次测试因此会尝试 13.0,无法证明真实失败路径的候选序列正确。PowerShell 对现有分支的枚举结果为:真实路径 `12.0,11.0`,测试路径 `13.0,13.0,12.0,11.0`;这只是控制流验证,未调用 NVENC。
+- 只改 `open.apiVersion`,函数表、open 及后续配置等结构体仍用编译期版本;这些版本宏包含 API major/minor,部分结构体布局也有演进。因此尚未实现有依据的跨版本 ABI 兼容。前置 `CreateInstance` 若失败,会在回退之前直接返回。
+- 当前没有调用 `NvEncodeAPIGetMaxSupportedVersion`,也没有按失败状态筛选版本回退;任何首开失败都会尝试降低版本,无法正确区分版本不兼容与其他错误。
+
+把编码器初始化修复加入 P5:先输出实际加载 DLL 路径/身份、驱动支持 API、应用 API、每阶段状态和 `nvEncGetLastErrorString`;保留 NVENC/MF 两条独立错误链,并传给 UI/主日志。查询 max-supported 时按头文件约定解析 major/minor(与 `NVENCAPI_VERSION` 的编码不同)。兼容层采用已验证的结构体/接口版本组合或兼容基线,不盲目改结构体版本位;测试必须覆盖真实返回 `INVALID_VERSION` 的分支及非版本失败。提示只在证据明确支持时建议升级驱动,HDR 无 MF 回退时明确说明。用户机器首错仍待对应 worker 日志,不能宣称上述实现缺陷已被证明是这台机器的根因。
+
+## 8. 施工顺序与验收
+
+| 顺序 | 最小闭环 | 完成证据 |
+| --- | --- | --- |
+| P0 | 统一 6X 容量并修越界 | 容量/取消/reset 测试,无越界;真实输出后再测生命周期 |
+| P1 | 软重置统计与 FG 准入恢复 | Drop 后统计继续更新;临时高成本消退后恢复;欠速时不拖慢声音 |
+| P2 | MKV 字幕元数据/正文分离,异步单遍读取 | 所附 32 字幕样本首帧不等全扫;取消/双字幕/seek/导出正确 |
+| P3 | RTX40 provider/能力初始化闭环 | 真实 Ada 2-6X Create/Evaluate 和输出证据,requested=applied |
+| P4 | RTX30 完整兼容路径 | 真实 GA10x 2-6X,逐型号/驱动记录;不以 50 系代验 |
+| P5 | 导出 worker 首错取证及定点修复 | 指定失败样本重现后修复,音轨/PTS/末帧/调色/字幕/倍率验证 |
+
+施工前计划:导出日志聚合可以在前面阶段先做,不必等到 P5 才开始收集;当时下一项任务是 P0。当前实现、失败与下一步以文首实施状态为准。
+
+统一要求:单次测试不超过 300 秒;按变更范围构建与运行针对性测试,交付前执行适用的 `scripts/gates/delivery.ps1`。RTX50 路径不安装 Ada/Ampere 补丁,并对 NR/SR、原生 FG、切换及退出做负向回归。若需要分次长时稳定性测试,分别记录,不能伪装一次连续长测。
+
+6X 成功必须在运动素材上证明每个有效源间隔有 5 个有效、时间位置正确的生成帧和原帧,检查输出内容、时序和 fence,不能靠 UI 数字、成功 counter、重复帧或线性混合交差。静止画面相同像素不能用于证明或否定插值。显示刷新率不足以展示全部输出时,分别报告生成/提交/实际显示,不混为一个 FPS。诊断离线抓帧可用于验收,正常播放/导出不得新增 GPU→CPU 回读。
+
+所有移植固定提交、逐文件记录来源/许可证/修改,并更新 `THIRD_PARTY_NOTICES.md`。运行库只做进程内处理,源码 Git 不纳入 DLL/SDK/媒体;本轮没有新增运行组件或发布授权。
+
+## 附录:输入身份与本轮命令
+
+原始输入位于 `C:/Users/123/Desktop/`,不复制进 Git。
+
+| 文件 | 字节 | SHA256 |
+| --- | ---: | --- |
+| 5090显卡补帧受限,显卡占用仅为百分之30.log | 13248726 | `4DAFFAB5222BE64EF09F54A0342AA4EB5D56C6AF9F953A8E1823218FD76213BE` |
+| 大MKV卡死+4060无法6x,选了自动跳2x.log | 322438 | `94C1BCECF71D3B65631EC6A7B4FBF74BF69D7298BF3C8685C557461C7080EC1D` |
+| 30系列 dlss.log | 3375244 | `2A64F693FD3B3CC571E528CB571F960CF45A218D1B0B89B225F14958C6C50058` |
+| 30系列dlss2.log | 1149877 | `F7D11D1ACA15CB42681712F9CE9F02BC3FFB1B198D2DBF9C64CB4C2FFE9269E9` |
+| 导出问题.log | 1661137 | `612D01986FF186099F8746AF3A6E96F302D96E360BD11ABFF706D2ACB7AE5FEB` |
+| Money.Heist.2019.S03E02.V2.1080p.NF.WEB-DL.H264.DDP5.1-LeagueNF.mkv | 4272359225 | `D4F41DDE491E0F8CDEB3C18D75E91F16B0ED0CFF80523B0CAF2C40398E464C9E` |
+
+已执行 `git status --short`、`git rev-parse HEAD`、`git show 890d200:src/engine/EngineController.cpp`、`rg` 源码/日志定位、`Get-FileHash -Algorithm SHA256`、`gh api` 查询上述仓库提交/tree/README/issue/compare,以及以下样本检查(`<sample>` 表示上表完整绝对路径):
+
+```text
+ffprobe -v error -show_entries stream=index,codec_name,codec_type,width,height,r_frame_rate:format=duration,size -of json <sample>
+ffmpeg -v error -nostdin -i <sample> -map 0:v:0 -an -sn -t 5 -f null -
+ffmpeg -v error -nostdin -i <sample> -map 0:s:0 -c copy -f null -
+gh api repos/dashdogy/RTX40MFG-Unlock/compare/33b41835dc39c5d8ab1ef93efb2449be31139c09...b77e6e55c9211faf58932fc67eaaad9feb9df934
+gh api repos/sdli1995/dlssg_for_sm86/git/trees/126d0f768f2293dad6f0da9d3b8fd6961ed88bdc
+```
+
+以上为施工前调查命令:当时 FFmpeg/gh 输出保留于工具记录,未执行 Veyra GPU 测试。用户授权施工后的实际 Create/Evaluate、构建和测试日志列在文首;不能将调查读日志等同于本机运行通过。
diff --git a/docs/RTX3060_FG_FREEZE_2026-09-18.md b/docs/RTX3060_FG_FREEZE_2026-09-18.md
new file mode 100644
index 00000000..82f62ce7
--- /dev/null
+++ b/docs/RTX3060_FG_FREEZE_2026-09-18.md
@@ -0,0 +1,109 @@
+# RTX3060 DLSS FG freeze: r4 candidate
+
+Branch: `codex/post140-field-repair-20260917`. No merge, push or release.
+Status: implementation and local regression complete; actual RTX3060 2X/6X
+execution remains unverified. Recovery to playback is not FG support.
+
+## Evidence and diagnosis
+
+User files: `C:/Users/123/Desktop/logs/fg-probe-{10060,1872,2808}.log`
+and `veyra-app.log`. RTX3060 12GB, device 0x2504, driver 32.0.16.1047.
+DLSSG 310.7.0.0 SHA256
+`135EAF0733C1E37381A8C28ABCF7A862404A54132B81787C04E35D09EFC5E36F`.
+Create returns 0x1/non-null handle; warmup succeeds; formal Evaluate fails
+0xBAD00002 / SEH 0xC0000005 at frameId2/subframe1. Probe stays at stage3
+until cancellation (about 6/13/36 seconds in the three captures).
+The log establishes failed evaluation and stalled teardown, not GPU saturation.
+The exact teardown lock is not observable from these logs.
+
+r3 spoofed Blackwell globally and rebuilt all 69 inventoried fatbins. Upstream
+RTX40MFG-Unlock commit `33b41835dc39c5d8ab1ef93efb2449be31139c09`
+preserves the real architecture and rebuilds 25 registered programs plus font.
+Global spoof can alter architecture-specific network selection. This is a
+candidate explanation for the target failure, not confirmed RTX3060 causality.
+
+Local controlled comparison (RTX5070/616.56): forcing reported Ampere produces
+25 NGXCubinD3D12 CreateKernel failures (nvapi -1), EndpointDL4RT creation
+failure, then a null-pointer access at provider RVA 0x6BBF0. Preserving real
+Blackwell with the same rebuilt program path succeeds. CUDA preflight and
+NGX Create success alone do not prove usable frame generation.
+
+## Changes
+
+- `src/ngx/AmpereMfgUnlock.cpp`, corresponding header: rebuild only registered
+ 25 programs; publish pointer and supplied length; preserve compressed-entry
+ expanded-header semantics from upstream. Add exact-hash font PTX adaptation,
+ in-place publication and per-page restoration including Windows private
+ WRITECOPY behavior. Keep network and other auxiliary blobs untouched.
+- CUDA module/function preflight now checks all 26 programs on the D3D12
+ adapter's LUID, instead of assuming CUDA ordinal0; restore the caller context.
+- `src/pipeline/EnhanceGraph.cpp`: retain real NVAPI architecture by default;
+ keep existing scoped capability/startup/Create compatibility and 6X ceiling.
+ Spoof is diagnostic-only. Logs distinguish inventory from actual mutations.
+- `src/engine/FgCompatibilityProbe.cpp`: failed actual initialization/evaluation
+ terminates the disposable child before poisoned-provider teardown. Enable
+ provider logging in that child. Parent retains existing explicit error and
+ base-playback recovery; no fabricated generated frames.
+- `tests/integration/FgSettingsTests.cpp`: test actual provider failure through
+ the child and resumed playback within 15 seconds.
+- Correct source comments and `THIRD_PARTY_NOTICES.md`. All provider writes
+ remain process-local; on-disk runtime binaries are unchanged.
+
+## Actual commands and results
+
+Build: `cmd.exe /c out\build\3060-incremental.cmd`, exit0. Final build output
+`out/logs/3060-r4-build.log`. Existing FFmpeg conversion warnings remain.
+Product EXE SHA256:
+`4DB42A6D9D74065FA5708FA9A7755FF6751323A44488F6D0BB710AF0724D5428`.
+
+All tests used `scripts/run-short-test.ps1`; environment overrides were set
+only in separate test shells. Paths below are relative to the repository.
+
+| Test | Command arguments / override | Evidence and result |
+| --- | --- | --- |
+| Ampere lifecycle | `veyra_fg_lifecycle_tests.exe`, timeout45, `VEYRA_TEST_FORCE_AMPERE_UNLOCK=1` | `out/logs/3060-r4-real-arch-lifecycle-final.stdout.log`, PASS: 6,2,5,3,4,6; 26/26 CUDA preflight, Create/Evaluate, reset and release |
+| Ada regression | Same executable, timeout45, `VEYRA_TEST_FORCE_ADA_UNLOCK=1` | `out/logs/3060-r4-ada-lifecycle.stdout.log`, PASS |
+| Settings | `veyra_fg_settings_tests.exe out/logs/rtx30-package-motion-fixture.mkv out/logs/3060-r4-settings`, timeout100, force Ampere | `out/logs/3060-r4-settings.stdout.log`, PASS 1->2->6->1->6, pause/seek/resume, 310 source/167 generated |
+| Actual failure recovery | Settings executable plus `probe-failure`, output `out/logs/3060-r4-probe-failure`, timeout30, force Ampere and `VEYRA_TEST_NVAPI_SPOOF_ARCH=0x170` | PASS: child30756 exit1/stage-1 after actual Evaluate AV; parent advances from12 to24 source frames in3107ms; `logs/fg-probe-30756.log` contains original internal errors |
+| 6X content | `veyra_repair_fg_tests.exe mfg6-exact-rgb-planar-detail`, timeout90, force Ampere | `out/logs/3060-r4-content.stdout.log`, exit0; real interpolated content checked with existing position criterion |
+| Delivery | `scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/scheduling-audit-20260918` | `logs/delivery/dc4993094fea4a4a8f6bdd15b3ab78e5/result.json`, PASS61.41s, native5070 NR/FG/4K/export checks |
+
+Initial r4 font publication failed because the generic patch helper required
+WRITECOPY to remain numerically WRITECOPY after privatization. Evidence retained
+in `3060-r4-real-arch-lifecycle.stdout.log`; fixed by adapting upstream's private
+working-set proof and rerunning the lifecycle successfully. Earlier forced
+architecture failures in `3060-upstream-header` and `3060-native-arch` remain
+research evidence, not target GPU tests.
+
+## Remaining verification
+
+Local package:
+`C:/veyra-test-packages/post140-20260918-r4/Veyra-1.4.0-test-20260918-r4-win64-portable.zip`
+(464935003 bytes), SHA256
+`6F4DF97C899FF8EDB028AC6769A78932199C99233F53170615DE7014662B9460`.
+Created with `scripts/package-portable.ps1 -Root . -Version 1.4.0 -Label
+'-test-20260918-r4' -OutputDirectory C:/veyra-test-packages/post140-20260918-r4
+-BuildDirectory out/build/scheduling-audit-20260918`, finalized/audited with
+`out/tmp/finalize-post140-package.ps1 -Revision r4 -SkipSource`.
+113 archive files verified against the package manifest; proprietary runtime
+identity and source/media/config exclusions checked; patched FFmpeg retained.
+
+Extracted-package smoke command: `out/tmp/smoke-post140-package.ps1 -Revision
+r4 -CaseFilter forcedAmpere6 -OutputSuffix '-ampere' -MediaOverride
+'C:/Users/123/Desktop/Veyra DLSS Video Player/out/logs/rtx30-package-motion-fixture.mkv'
+-RequireNonblank`; repeated with `forcedAda6` and `'-ada'`.
+Both pass on RTX5070 with actual NR and FG, package-local DLL resolution,
+85/295 and 116/450 source/generated frames, nonblank screenshot pixel checks,
+and exit0. Evidence: `out/logs/package-post140-smoke-20260918-r4-final-{ampere,ada}/result.json`.
+Source snapshot is generated separately after this record is finalized.
+
+No RTX3060 or RTX40 physical execution was performed locally. User reported
+RTX40 unlock working on the earlier candidate. r4 needs RTX3060 2X followed
+by 6X, then NR/SR combinations; retain application and all fg-probe logs.
+Existing content-dependent synthetic 6X position deviations remain documented
+in the main repair plan. Export failure teardown is outside this isolated
+preview probe fix; the user's export-gate removals remain in this build.
+
+Do not mark the broader 30-series goal achieved until actual generated output
+and stability have been verified on the target card. Next task: evaluate r4's
+RTX3060 application/probe logs and visible output from that test.
diff --git a/docs/RTX30_CAPTURE_FOLLOWUP_2026-09-18.md b/docs/RTX30_CAPTURE_FOLLOWUP_2026-09-18.md
new file mode 100644
index 00000000..2d32ec4b
--- /dev/null
+++ b/docs/RTX30_CAPTURE_FOLLOWUP_2026-09-18.md
@@ -0,0 +1,196 @@
+# RTX30 startup and capture interruption follow-up
+
+Scope: local isolated branch `codex/post140-field-repair-20260917`, preserving
+the user's successful RTX40 result and the native RTX50 path. No publication.
+Deliver a complete r2 portable test package with matching source.
+
+## Evidence and Plan
+
+- New RTX3060 logs in `C:/Users/123/Desktop/30系列,无法开启` fail both 2X and
+ 6X before evaluation: cached FeatureInitResult and Create are 0xBAD0000B.
+ Driver update is not requested. Provider identity and SM86 patch preparation
+ succeeded. Actual RTX30 hardware remains unavailable locally.
+- Upstream RTX40MFG-Unlock commit 33b41835dc39c5d8ab1ef93efb2449be31139c09
+ applies metadata compatibility during startup, including NGX initialization.
+ Veyra only covered requirements/capabilities/Create. Extend the verified
+ Ampere metadata scope to Init, retaining verified restoration on failure.
+- Capture screenshots report intermittent simultaneous audio/video stalls;
+ no accompanying capture log proves the specific incident's cause.
+ CaptureAudioSession::push currently stops counting arriving input when the
+ output endpoint reports an error. After 3 seconds AudioInputRecovery then
+ restarts the shared A/V graph despite continuing input. Reproduce with a
+ four-second owned output outage, fix input progress accounting, and verify
+ real missing input still triggers recovery.
+- Build, run targeted lifecycle/output-loss regressions, physical capture if
+ available, and delivery gate. Package the earlier three scheduling fixes too.
+
+## Status
+
+Implemented both fixes and the startup-seek fix discovered during package smoke.
+RTX40 success is user-reported, not a local RTX40 test.
+Local adapter is RTX5070 / 616.56. RTX3060 initialization remains a candidate
+repair until the same user's hardware runs it; forced routes cannot reproduce
+Ampere's native rejection. The child preflight still requires actual successful
+Create/Evaluate and does not silently lower the requested multiplier.
+
+## Verification
+
+Build: `cmd.exe /c out\build\scheduling-audit-build.cmd`, directory
+`out/build/scheduling-audit-20260918`. Final build logs:
+`out/logs/rtx30-capture-build3.log`, `rtx30-capture-build4.log`, exit 0;
+final startup-seek build `out/logs/rtx30-startup-fix-build.log`, exit 0.
+Build 2 encountered LNK1104 because a test executable was running while linking;
+the test exited normally, then build 3 completed. No user process was stopped.
+Final EXE SHA256: `656E671F62F005C95F4883AD232482917B2936BD50B2550F80E4461AC6FFEBF8`.
+Earlier lifecycle/capture checks used the pre-seek-fix EXE
+`0E03B9946997347DAAB4E029183A95B1EAB8BB36C7FC33BF4BBE1369F0FD149F`.
+
+Tests use `scripts/run-short-test.ps1`, timeout 25-100 seconds per test, with
+`out/build/post140-hdr-preflight-20260918` added to PATH for dependency DLLs.
+All following log prefixes are under `out/logs/`:
+
+| Test | Result |
+| --- | --- |
+| capture audio `--long-endpoint-loss`, before fix | FAIL: 403 callbacks during outage, only 247/650 counted, 2 false input-recovery decisions |
+| same test after fix | PASS: 650/650 counted, zero false decisions, real input-stall policy still fires; `rtx30-capture-outage-fixed` |
+| physical USB3 source `--output-outage` | PASS: 421 video frames in 7 s, max read gap 16.833 ms, 703 audio blocks, endpoint recovers without restarting graph; `rtx30-capture-physical-outage` |
+| forced Ampere lifecycle | PASS 6,2,5,3,4,6X with actual generation and reset/shutdown; `rtx30-init-ampere-lifecycle` |
+| forced Ampere `init-failure` | PASS injected Init failure restores metadata/session, followed by all six successful lifecycles; `rtx30-init-failure-lifecycle` |
+| forced Ada lifecycle | PASS; `rtx30-ada-regression` |
+| native RTX50 lifecycle | PASS; no compatibility session/patch log; `rtx30-native-regression` |
+| forced Ampere `mfg6-exact-rgb-planar-detail` | PASS 55/55 generated images meet hash, non-blend and displacement checks; retained slot overwrite rejected; `rtx30-content6` |
+| stereo / 5.1 `--jitter` | PASS 500 blocks each, no additional resets/underruns, P95 skew 23.970/23.001 ms; `rtx30-audio-jitter`, `rtx30-audio-jitter51` |
+
+The long output outage is injected into the owned audio renderer, not a physical
+speaker unplug. Physical capture test uses the real USB3 card and the product's
+recoverAudio call. It proves this internal restart defect is fixed, not that the
+user's screenshot has the same cause or that all intermittent stalls are gone.
+Output failure still discards unavailable audio as before; no growing recovery
+queue or stale audio replay is introduced. Fatal audio worker errors retain the
+existing input recovery path.
+
+GitHub rechecked with `gh api repos/<repo>/commits/HEAD`: RTX40MFG-Unlock
+`b77e6e55c9211faf58932fc67eaaad9feb9df934` preserves GPU payload/provider policy;
+dlssg_for_sm86 `5e79459c2d521f8c3276ce9ee02342c0e2686982` changes README wording.
+The port remains pinned and attributed to the audited MIT commit above.
+No runtime was replaced or patched on disk. DLSSG SHA256 remains
+`135EAF0733C1E37381A8C28ABCF7A862404A54132B81787C04E35D09EFC5E36F`.
+
+## Additional Startup Seek Deadlock
+
+The first package smoke failed in `community6`: NR startup overlapped the scripted
+pause/seek/resume. Audio's initial prefill was interrupted by seek. The subsequent
+seek anchored real PCM successfully, but left `endpointRecovering_` true. Video
+waited for audio recovery, while audio waited for the first presented video frame.
+Both original and repeat package logs show no presented frame. Failures remain in
+`out/logs/rtx30-package-smoke.log`, `rtx30-package-community-repro.log` and their
+`package-post140-smoke-20260918-r2-final*` directories.
+
+`src/sink/WasapiAudioSink.cpp` now clears recovery after a successful seek anchor,
+or a successful exhausted-audio seek with a healthy endpoint. Failed anchoring
+still enters recovery. `tests/integration/AudioTimelineTests.cpp --startup-seek`
+opens real muted WASAPI three times and seeks immediately during initialization.
+Before the fix all three attempts failed the recovery-state assertion; after the
+fix all three pass, including actual PCM anchoring, held clock, release by video
+and bounded queue. Full audio timeline regression also passes.
+
+Commands (all through `scripts/run-short-test.ps1`):
+
+- `-Exe out/build/scheduling-audit-20260918/veyra_audio_timeline_tests.exe -Arguments @('out/logs/rtx30-startup-seek-before','--startup-seek') -TimeoutSeconds 25 -LogPrefix out/logs/rtx30-startup-seek-before`: exit 1 before product fix.
+- Same command with prefix/argument `rtx30-startup-seek-fixed`: exit 0 after fix.
+- Same executable, `-Arguments @('out/logs/rtx30-audio-timeline-final') -TimeoutSeconds 60 -LogPrefix out/logs/rtx30-audio-timeline-final`: exit 0.
+
+Final delivery: `scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/scheduling-audit-20260918`
+passes all 26 checks in 62.7948212 s. Evidence:
+`logs/delivery/b7425358ff0342339bca643c7483a5a8/result.json` and
+`out/logs/rtx30-final-delivery.log`. The previous gate on the earlier binary remains
+in `logs/delivery/fa45435aa440435dbb7dff31ac9cb57d/result.json`.
+
+## Changed Files
+
+- `include/veyra/ngx/FgCompatibilitySession.h`, `src/ngx/FgCompatibilitySession.cpp`,
+ `src/ngx/NgxCoreHost.cpp`, `src/pipeline/EnhanceGraph.cpp`,
+ `tests/integration/FgLifecycleTests.cpp`, `THIRD_PARTY_NOTICES.md`: Init scope,
+ restoration, injection regression and attribution.
+- `include/veyra/sink/CaptureAudioSession.h`, `src/sink/CaptureAudioSession.cpp`,
+ `tests/integration/CaptureAudioTests.cpp`, `tests/integration/CaptureSourceTests.cpp`:
+ input liveness during output recovery and synthetic/physical regressions.
+- `src/sink/WasapiAudioSink.cpp`, `tests/integration/AudioTimelineTests.cpp`:
+ startup seek recovery publication and real endpoint regression.
+- This document and `docs/WORKLOG.md`: evidence and delivery state.
+
+## Portable Package Verification
+
+Command: `scripts/package-portable.ps1 -Root . -Version 1.4.0 -Label '-test-20260918-r2' -OutputDirectory C:/veyra-test-packages/post140-20260918-r2 -BuildDirectory out/build/scheduling-audit-20260918`.
+Final build log: `out/logs/rtx30-package-build-final.log`. The first attempt failed
+for missing FFmpeg dependency DLLs in the build directory. These were copied from
+the actual patched FFmpeg installation, with provenance hashes checked by the
+packager. No older/unpatched replacement was used. Earlier incomplete and
+pre-startup-fix packages are preserved in clearly named subdirectories.
+
+`out/tmp/finalize-post140-package.ps1 -SkipSource` adds the test instructions and
+HDE/RTX40MFG license texts, updates the manifest, checks all archive file hashes,
+rejects SDK/debug/private media/configuration payloads, and extracts an independent
+verification directory. Result: 113 entries, audit PASS.
+Portable archive: `C:/veyra-test-packages/post140-20260918-r2/Veyra-1.4.0-test-20260918-r2-win64-portable.zip`.
+SHA256: `BE603292C5D776D88D5FE33E02C3B97E95A4306C57D491B845E708CEE9BE8E1B`.
+
+`out/tmp/smoke-post140-package.ps1 -OutputSuffix '-verified'` launches the extracted
+EXE with only Windows directories in PATH and TEMP as the working directory.
+All FFmpeg/VC runtime and selected NR/FG modules must resolve inside the package.
+The original MKV pause/seek/resume timing is unchanged. All seven cases pass
+process, real NR/FG work, module-path and saved-frame checks:
+
+| Case | Decoded frames | Generated frames |
+| --- | ---: | ---: |
+| Baseline | 188 | 0 |
+| Original NR + 6X | 120 | 470 |
+| Community NR + 6X | 113 | 435 |
+| Ampere NR + 6X | 118 | 460 |
+| Forced Ampere 2X | 81 | 55 |
+| Forced Ampere 6X | 63 | 185 |
+| Forced Ada 6X | 64 | 190 |
+
+Evidence: `out/logs/rtx30-package-smoke-final.log` and
+`out/logs/package-post140-smoke-20260918-r2-final-verified/result.json`.
+Forced Ampere 6X logs show Init `0x1`, restored metadata, DLSSG Create `0x1`,
+warm-up Evaluate `0x1` and actual generated presentation. This is RTX5070 evidence.
+
+Visual inspection found the enhanced MKV snapshots entirely black at startup;
+the baseline snapshot shows the intro logo. The source at approximately one second
+is almost black. These snapshots cannot establish correct enhanced image content,
+so a separate moving-color fixture with real audio was also tested below.
+No product/test timing was changed to avoid the
+startup-seek regression.
+
+Fixture command: `ffmpeg -hide_banner -loglevel error -f lavfi -i 'testsrc2=size=1920x1080:rate=24' -f lavfi -i 'sine=frequency=440:sample_rate=48000' -t 12 -c:v libx264 -preset veryfast -crf 20 -pix_fmt yuv420p -c:a ac3 -ac 2 out/logs/rtx30-package-motion-fixture.mkv`.
+This diagnostic fixture is not included in any delivered archive.
+Run: `out/tmp/smoke-post140-package.ps1 -OutputSuffix '-motion' -MediaOverride 'C:/Users/123/Desktop/Veyra DLSS Video Player/out/logs/rtx30-package-motion-fixture.mkv' -RequireNonblank`.
+All seven cases PASS, including the same transport operations and module checks.
+Each screenshot has 8160/8160 sampled pixels above the nonblack threshold, with
+RGB-sum ranges spanning 423 or more levels. Forced Ampere 6X and community 6X
+screenshots were visually inspected: distinct test patterns and time labels are
+visible. This proves meaningful saved output, not interpolation accuracy.
+Generated counts in case order above: 0,565,580,560,63,325,455.
+Evidence: `out/logs/rtx30-package-motion-smoke.log` and
+`out/logs/package-post140-smoke-20260918-r2-final-motion/result.json`.
+
+Unchanged dependency corresponding-source archives were copied and hash-verified:
+
+- `Veyra-1.4.0-test-20260918-r1-FFmpeg-source.zip`:
+ `A83293849960802E9AFD0E685E7E094B986E5FED19FA8371410E7E2E6F0DAAF7`.
+ The r1 filename is retained because the patched FFmpeg dependency is unchanged.
+- `Veyra-1.4.0-RemotePlay-source.zip`:
+ `1D69DDA5BB1AFA3B78E917569BF396338A338BF2184D4458C2F1E1D88CE881DF`.
+ The new r2 application snapshot supersedes any old application tag guidance.
+
+Local repair/build/package checks are complete. The matching application source
+snapshot is `Veyra-1.4.0-test-20260918-r2-source.zip`, generated from the actual
+worktree after this record, with SHA256 sidecars alongside all archives. Source
+verification hashes each entry against the worktree and rejects binary/media
+payloads. Packaging evidence and hashes are recorded beside the archives.
+`git diff --check` passes; no runtime/SDK/test media was added to source Git.
+No merge, push or publication was performed. Target-hardware acceptance remains
+open, so the broader repair goal is not marked fully achieved.
+Next user acceptance: RTX3060 2X then 6X and prolonged capture playback. Retain
+the main log plus the matching fg-probe log if initialization still fails.
diff --git a/docs/SCHEDULING_CHAIN_AUDIT_2026-09-18.md b/docs/SCHEDULING_CHAIN_AUDIT_2026-09-18.md
new file mode 100644
index 00000000..59fad2c4
--- /dev/null
+++ b/docs/SCHEDULING_CHAIN_AUDIT_2026-09-18.md
@@ -0,0 +1,147 @@
+# Scheduling Chain Audit, 2026-09-18
+
+Scope: user requested a full-chain scheduling audit while testing the r1
+package. Work stays on `codex/post140-field-repair-20260917`, preserving the
+existing repairs. The r1 package and the user's running player are unchanged.
+No merge, push, release, runtime replacement, or hardware compatibility claim.
+
+Changed in this audit: `src/engine/EngineController.cpp`,
+`include/veyra/engine/VideoPresenter.h`, `src/engine/VideoExportJob.cpp`,
+`tests/integration/SchedulingChainTests.cpp`,
+`tests/integration/FgPresentationTests.cpp`, `CMakeLists.txt`, this report and
+`docs/WORKLOG.md`. Earlier field repairs in these files are preserved.
+
+## Confirmed Defects
+
+1. Silent-file master clock reanchored after every successful presentation in
+ `EngineController.cpp`. This erased accumulated lateness. A real 60 fps
+ silent-video regression with 60 ms injected processing work advanced only
+ 0.750 media seconds in 3.009 wall seconds (0.249x), with zero skipped
+ opportunities. Keep the clock origin until an explicit transport reanchor.
+ Fixed run: 2.850/3.010 seconds (0.947x), 129 skipped opportunities, then
+ catches up. Pause, paused seek and resume passed.
+2. DLSS presentation now uses a private queue/ring, but the admission service
+ calculation subtracted waits from the shared producer ring. Read allocator
+ wait deltas from the ring actually used by `VideoPresenter`. CPU service
+ must not charge a GPU dependency wait a second time. This establishes the
+ accounting defect, not its contribution on the user's RTX30/40 machines.
+3. Export's scope guard captured `encoder.get()` before the encoder opened,
+ leaving it null. Cancellation/errors could destroy callback captures before
+ encoder teardown drained pending packets. The guard now owns a reference
+ to the encoder owner and resets it while all writer captures remain alive.
+ Real NVENC cancellation after 1, 3 and 5 submitted source frames passed;
+ subsequent normal 12-frame export decoded and validated successfully.
+ No pre-fix crash or sanitizer result is claimed for this lifetime defect.
+
+## Chain Review
+
+| Area | Finding |
+| --- | --- |
+| File clock / preview | Silent clock defect fixed; audio clock has a separate exhausted-stream wall-clock handoff and endpoint recovery freeze. Preview skips retain real PTS and reset history. |
+| File demux / decode | Still synchronous on the GPU owner. Slow read/decode can block advancement of queued presentation. Architectural risk; no measured slow-disk reproduction in this audit. |
+| Physical capture | Nonblocking latest-frame read; compressed decode has a separate worker, bounded payload queue and leased frame pool. No new proven persistent throttle found. |
+| PS5 | Separate decode and PCM feeding workers; capacity-one decoded mailbox; interruptible reconnect waits. Actual console/network session not tested in this audit. |
+| Flow / NR / SR / color | Creation waits and teardown drains are lifecycle operations; steady processing uses command slots and GPU fence dependencies. Actual serial GPU cost remains real, even if aggregate GPU utilization looks low. |
+| DLSS presentation | Producer/consumer fences and private ring are explicit. Service accounting fixed. `fgTiming` uses the shared fence but current callers only invoke it for XeSS/FSR, which use that fence; no cross-fence bug claimed for this call path. |
+| XeSS | Actual overload/recovery test passed: 60 ms injected work suppresses generation; reducing work to 10 ms restores it within a 5-second observation, with 233 additional generated frames and 1.033x media pace. |
+| File / capture audio | Separate WASAPI owner; capture backlog bounded; transport reanchors distinct from steady playback. Fresh physical-capture video observations use matching original arrival. |
+| Video export | Full frame processing, bounded four-slot NVENC output, CFR holds explicitly counted. Per-batch generation resolution still serializes export with GPU completion, including non-FG jobs. This is throughput headroom, not evidence of persistent adaptive throttling. |
+| AMD/Intel export | MF encoder copies Y/UV to CPU and waits each frame. Existing implementation conflicts with the no-readback performance contract; not a zero-copy path. Needs a separate D3D11/DXGI surface handoff implementation and actual adapter validation. |
+| Export policy | Playback-priority option intentionally waits 50 ms between source frames. Final export verification decodes the completed file; both can lower visible utilization without being an admission bug. |
+| Images / paused view | No media pacing or preview frame dropping. GPU completion waits protect a requested full result. |
+
+## Evidence
+
+Fixture command:
+
+```powershell
+ffmpeg -hide_banner -loglevel error -f lavfi -i testsrc2=size=640x360:rate=60 -t 24 -an -c:v libx264 -preset ultrafast -y out/scheduling-silent-20260918.mp4
+```
+
+New test: `tests/integration/SchedulingChainTests.cpp` (playback, XeSS and
+export modes); private-ring accounting regression extends
+`tests/integration/FgPresentationTests.cpp`.
+
+Logs:
+- `out/logs/scheduling-before-playback.stdout.log`: reproduces silent slow motion.
+- `out/logs/scheduling-fixed-playback.stdout.log`: fixed timing and transport pass.
+- `out/logs/scheduling-fixed-export.stdout.log`: pending cancellation and export pass.
+- `out/logs/scheduling-build-before.log`: initial test build failed on wrong
+ ExportCounts field names, corrected to source/encoded.
+- `out/logs/scheduling-build-before2.log`: baseline test build passed.
+- `out/logs/scheduling-build-fixed.log`: libraries/tests built; executable link
+ failed LNK1104 because the user is running that executable. Do not stop it.
+- `out/logs/scheduling-isolated-build.log`: separate complete build passed (561 steps).
+- `out/logs/scheduling-isolated-build-final.log`: final presentation-test rebuild passed.
+- `out/logs/scheduling-fixed-export-audio.stdout.log`: the supplied MKV with audio
+ passed cancellation at 1/3/5 source frames and subsequent 12-frame export.
+- `out/logs/scheduling-xess-before.stdout.log`: process launch failed with
+ -1073741515, before main, because the new build directory lacked dependency
+ DLLs. This was a test environment failure, not a XeSS result.
+- `out/logs/scheduling-xess-before2.stdout.log`: dependency PATH corrected;
+ XeSS recovery, silent clock and transport checks passed. Despite the log
+ filename, this run includes the silent-clock fix.
+- `out/logs/scheduling-private-presentation.stdout.log`: producer allocator wait
+ 54.8609 ms, private-ring wait 0 ms; 4X/6X/4X generated 114/190/114 frames;
+ presented texture max pixel error 0, D3D12 errors 0. This verifies texture
+ presentation, not the visual quality or temporal position of interpolation.
+- `out/logs/scheduling-dlss4.stdout.log` and `scheduling-dlss6.stdout.log`:
+ NR + DLSS 4X/6X, 30 seconds each, injected 55 ms processing work at seconds
+ 15-17, both recovered and exited 0. Recovered mean submissions 142.75/203.375
+ per second. These runs replay the MKV as a simulated live source: its actual
+ processing cadence exceeds the nominal 24 fps, and expired generated frames
+ remain (including after recovery). Neither the submission counts nor the
+ nominal-target assertion prove correct 24 fps pacing, full delivery of all
+ generated frames, display scanout rate, or real USB/PS5 capture throughput.
+- `out/logs/scheduling-audio-underrate.stdout.log`: simulated 51/60 video
+ underrate, wall 4008.89 ms / audio 3988.90 ms, no additional audio pauses,
+ underruns or PCM overruns; passed.
+- `out/logs/scheduling-veyra_presentation_worker_tests.log`,
+ `scheduling-veyra_realtime_preview_tests.log`, and
+ `scheduling-veyra_repair_contract_tests.log`: passed; repair contracts
+ 205 checks, zero failures.
+- `logs/delivery/62df9939d564489fb42ca7b24292fd08/result.json`: fresh delivery
+ gate passed, 26 checks, 62.4984434 seconds. Includes actual NR/NVOF, native
+ 4K correctness, realtime-profile playback, transport, color page, images,
+ native 4K H.264/HEVC exports with audio, cancellation and compressed capture
+ decoder hardware/software parity (ALL PASS, not skipped). The decoder test
+ uses files, not a physical capture device. Quality probe: 60 NR evaluations,
+ zero failures, D3D diagnostics errors and normal-path readbacks.
+- `out/logs/scheduling-dlss6/engine.log`: NR Feature 18 Create `0x1`, DLSSG
+ Create `0x1`, FG warm-up Evaluate `0x1`, maxGeneratedFrames=5.
+- Independent EXE SHA256:
+ `BD9C8B275560E4DDBD0BDB20DCE868818311E6FED54678BFF1550B4D178A2249`.
+- `git diff --check` passed; no proprietary runtime, SDK or test media was
+ added to source tracking. Existing LF/CRLF conversion warnings remain.
+
+Build command: `cmd.exe /c out\build\scheduling-audit-build.cmd`.
+The independent build retains patched FFmpeg at
+`C:/veyra-deps/ffmpeg-ps5-dav1d-installed`, the existing approved runtime paths,
+and RemotePlay dependencies. It is a developer build, not a new portable pack.
+
+Commands for the isolated tests (each run limited to at most 80 seconds):
+
+```powershell
+$env:PATH=(Resolve-Path out/build/post140-hdr-preflight-20260918).Path+';'+$env:PATH
+& scripts/run-short-test.ps1 -Exe out/build/scheduling-audit-20260918/veyra_scheduling_chain_tests.exe -Arguments @('out/scheduling-silent-20260918.mp4','out/logs/scheduling-xess-before2','xess') -TimeoutSeconds 60 -LogPrefix out/logs/scheduling-xess-before2
+& scripts/run-short-test.ps1 -Exe out/build/scheduling-audit-20260918/veyra_fg_presentation_tests.exe -Arguments @('out/logs/scheduling-private-presentation') -TimeoutSeconds 60 -LogPrefix out/logs/scheduling-private-presentation
+foreach($multiplier in @('4','6')) {
+ & scripts/run-short-test.ps1 -Exe out/build/scheduling-audit-20260918/veyra_fg_sustained_tests.exe -Arguments @('C:/Users/123/Desktop/Money.Heist.2019.S03E02.V2.1080p.NF.WEB-DL.H264.DDP5.1-LeagueNF.mkv',"out/logs/scheduling-dlss$multiplier",$multiplier,'on','30','nr','0.95') -TimeoutSeconds 80 -LogPrefix "out/logs/scheduling-dlss$multiplier"
+}
+& scripts/run-short-test.ps1 -Exe out/build/scheduling-audit-20260918/veyra_audio_timeline_tests.exe -Arguments @('out/logs/scheduling-audio-underrate','--underrate') -TimeoutSeconds 30 -LogPrefix out/logs/scheduling-audio-underrate
+& scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/scheduling-audit-20260918
+```
+
+Completed test directories intentionally reject overwriting export files; use
+fresh output paths when rerunning export modes.
+
+## Remaining Boundaries
+
+Hardware: RTX5070, driver 616.56. RTX30/40/5090, physical capture, AMD/Intel
+export and a real PS5 session were not exercised in this audit. The previous
+4K full NR+SR throughput failures and interpolation-position mismatch remain
+open; short lifecycle checks do not supersede those failures.
+
+Next acceptance task: collect the user's r1 RTX30/40 results and full logs,
+then reproduce any remaining limiter state with the same settings. The three
+additional fixes here are only in the branch/developer build, not in r1.
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 7b55409e..eb0991d6 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,176 @@
# 2026-09-11 继续修复目标模式执行中
+## 2026-09-18 RTX3060 开启 DLSS 补帧卡死,r4 候选
+
+依据用户 `Desktop/logs/`:Create 成功、正式 Evaluate `0xBAD00002 / 0xC0000005` 后子进程停在 stage3。修正全局 Blackwell 架构伪装及全部69个 fatbin 改写,按固定上游只重建25个注册程序和精确匹配的字体程序,保留真实架构;补齐描述符长度、CUDA 函数预检和 D3D12 LUID 匹配。失败探测子进程直接退出,绕过异常运行库的清理挂死,保留错误和播放器恢复。
+
+实际修改、命令、失败记录和证据见 `docs/RTX3060_FG_FREEZE_2026-09-18.md`。构建 exit0;本机5070上强制Ampere/Ada生命周期2X至6X、播放设置切换、6X内容检查通过;真实异常探测后3107ms恢复播放。最终 delivery `logs/delivery/dc4993094fea4a4a8f6bdd15b3ab78e5/result.json` PASS,61.41s。EXE SHA256 `4DB42A6D9D74065FA5708FA9A7755FF6751323A44488F6D0BB710AF0724D5428`。
+
+最初字体写入因Windows写时复制页的实际保护值变化被拒绝,已按上游工作集检查修正并重测;原失败日志保留。RTX3060实卡未执行,架构选择是待目标机器验证的根因假设,不能把恢复播放算成6X支持。保持隔离分支,无合并、推送或发布,无SDK/运行时入Git。下一步为r4目标3060的真实2X/6X复测。
+
+r4完整包位于 `C:/veyra-test-packages/post140-20260918-r4/`,ZIP SHA256 `6F4DF97C899FF8EDB028AC6769A78932199C99233F53170615DE7014662B9460`,113文件清单/哈希/排除项审计通过。解压包以最小PATH运行本机强制Ampere/Ada的NR+6X均通过,分别85/295、116/450源帧/生成帧,截图非黑屏、正常退出,DLL来自包内。完整命令见上述修复文档。
+
+## 2026-09-18 按用户要求取消导出门禁与整片复检
+
+新日志 `export-worker-17508(1).log` 实际已经编码 51248 帧成功,收尾后 CPU 单线程重解码校验从 19:37:28.765 持续到 19:48:43.861,约额外 11 分 15 秒,校验也是 PASS。日志没有最终界面报错,不能归因于驱动。按本次明确要求,取消产品的 120 帧 CFR 资格扫描、逐源帧 CFR 拒绝、独立 FG 预探测、音频 codec-query/corrupt-flag 拦截,以及全部输出重开/逐帧解码复检;编码、封装和文件关闭成功后直接保存。
+
+不能删检查后让 VFR 音画跑偏:编码器仍使用递增帧号,封装通过在途时间戳队列保留真实源时间间隔,FG 均分对应源帧间隔;每张已解码源帧均保留。缺失/倒退 PTS 自动补齐并记录,损坏源的原始节奏无法还原。NVENC 版本/能力查询只诊断,实际调用决定是否可用,失败保留系统编码器回退。HDR 选择 H.264 时自动改用 HEVC Main10 并说明。UI 导出不再等待预览成功出帧/应用完效果,独立 worker 冻结当前有效请求设置。实际硬件/编码/封装/写盘失败、内存边界和已有文件保护仍保留,不把失败冒充成功。
+
+修改:`VideoExportJob.cpp`、`NvencD3D12Encoder.cpp`、`ExportJobManager.cpp`、`AppShell.cpp`;补充 `ExportTimingTests.ps1` 与 worker 探测拒绝不阻断的回归。`cmd.exe /c out\build\scheduling-audit-build.cmd` exit0;帧率中途从 30 改为 15 的视频分别通过 NVENC H264、DLSS 6X HEVC、系统编码器及 NVENC 失败自动回退,输出 60/360/60/60 帧,源 PTS 误差实测 0,音轨保留,独立测试解码通过。DLSSG Create `0x1`,NVENC 编码/取码流 status0。取消 1/3/5 帧和后续正常导出、HDR 自动 HEVC Main10、真实编码失败报告、英语音轨 880Hz 检查均 PASS。测试脚本初次误用 PowerShell 保留变量和命令数组参数,修正后重跑通过,失败记录保留。
+
+完整短测 `scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/scheduling-audit-20260918` 26 checks PASS / 60.406 秒,证据 `logs/delivery/35f686779486445f9b4e0e51e9cbe49c/result.json`。EXE SHA256 `38E7A3ED8B5156A4962FF227391698D6CD71BFCBED4DA98807B03A6F6E5E7599`。独立解压包在 TEMP/仅系统 PATH 下真实 HEVC 6X 导出 60 源 + 295 生成 + 5 重复 = 360 帧,包内依赖与输出解码均 PASS;产品没有后置解码。具体命令、日志与局限见 `docs/EXPORT_GATE_REMOVAL_2026-09-18.md`。
+
+完整 r3:`C:/veyra-test-packages/post140-20260918-r3/Veyra-1.4.0-test-20260918-r3-win64-portable.zip`,SHA256 `BEC301B6BF19419246E04FD8D0849A461FC73EEFE168532E500161C635898215`;113 文件逐项 manifest 审核通过,附对应工作区源码和未变的 patched FFmpeg/RemotePlay 对应源码。本机 RTX5070 实测,不宣称 RTX30/40 实卡通过;r2 不覆盖,不合并/推送/发布。下一项验收:用户原导出任务在 r3 上复测,原 GUI 失败原因因日志缺失仍未确认。
+
+## 2026-09-18 RTX30 初始化与采集音频误重启追加修复
+
+用户确认 RTX40 解锁成功,但 RTX3060 的 2X/6X 均在 Evaluate 前失败:FeatureInitResult/Create 为 `0xBAD0000B`,不要求更新驱动。核对固定 MIT 上游后,补齐 `FgCompatibilitySession` 对 NGX Init 的 Ampere metadata 作用域与还原,禁止未成功 Init 就进入能力查询。`NgxCoreHost` 增加仅测试使用的 Init 失败注入,验证失败退出后可正常重建。没有降低请求倍率,没有改磁盘运行库;RTX50 原生路径不打补丁。3060 仍需用户实卡验证,不能拿 5070 强制路径通过冒充 30 系成功。
+
+采集侧确认并复现:输出端点错误时 `CaptureAudioSession::push` 停止统计仍然到达的输入,3 秒后 `AudioInputRecovery` 会误停整个 DirectShow 音视频图。现在区分可恢复输出错误与致命工作线程错误,输出恢复期间继续记录输入存活、不积压旧音频。4 秒输出故障注入由修复前 2 次误重启判定/247 个被统计输入块,变为 0 次/650 个;真正输入断流仍触发恢复。真实 USB3 卡 7 秒故障注入通过:421 视频帧、703 音频块、最大读帧间隔 16.833ms,无采集图重启。截图缺少对应日志,不能断言这就是用户卡顿的唯一原因。
+
+构建 `cmd.exe /c out\build\scheduling-audit-build.cmd` 通过;一次并行构建因本轮测试占用 exe 发生 LNK1104,测试正常结束后重建通过。强制 Ampere/Ada 与原生 RTX50 的 2–6X 生命周期、Init 失败还原、6X 55/55 生成帧内容检查、双声道与 5.1 音频抖动检查均通过。这批测试使用的 EXE SHA256 为 `0E03B9946997347DAAB4E029183A95B1EAB8BB36C7FC33BF4BBE1369F0FD149F`,随后另修复启动 seek 死锁并重做最终交付检查,见下文。具体文件、命令、日志与限制见 `docs/RTX30_CAPTURE_FOLLOWUP_2026-09-18.md`。
+
+打包测试发现并重复复现 community NR 启动期间 seek 后零呈现:第一次音频预读被打断,seek 已成功锚定 PCM,却没有清除 `endpointRecovering_`,音视频互等。`WasapiAudioSink.cpp` 现在在成功 seek 锚定后清除状态;健康端点 seek 到音轨结束也清除。新增真实静音 WASAPI 启动 seek 回归,修复前 3/3 恢复标志断言失败,修复后 3/3 通过,完整音频时钟/断连/暂停回归也通过。保留 `rtx30-startup-seek-before`、`rtx30-startup-seek-fixed`、`rtx30-audio-timeline-final` 日志。最终构建日志 `out/logs/rtx30-startup-fix-build.log` exit0。
+
+最终 EXE SHA256 `656E671F62F005C95F4883AD232482917B2936BD50B2550F80E4461AC6FFEBF8`。`scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/scheduling-audit-20260918` PASS,26 checks/62.7948212 秒,`logs/delivery/b7425358ff0342339bca643c7483a5a8/result.json`。独立解压、仅系统 PATH 下,MKV 七组和有声彩色运动测试片七组均通过;每组检查实际出帧、所选 NR/FG 与依赖加载位置。MKV 开头增强截图为黑图,未用它证明内容通过;另用运动片七组均通过非黑/非纯色像素检查,并目视两张输出。详见 `out/logs/rtx30-package-smoke-final.log`、`rtx30-package-motion-smoke.log`。这些是 RTX5070 本机证据,RTX30 实卡仍未执行。
+
+完整 r2 包:`C:/veyra-test-packages/post140-20260918-r2/Veyra-1.4.0-test-20260918-r2-win64-portable.zip`,SHA256 `BE603292C5D776D88D5FE33E02C3B97E95A4306C57D491B845E708CEE9BE8E1B`,113 文件清单逐项校验通过。同目录提供 `TESTING.md`(包内)、应用对应源码快照与未变的 patched FFmpeg/RemotePlay 对应源码及 SHA256 文件。打包中缺失依赖的失败和修复前包留在命名子目录,r1 未覆盖。包含前一节调度审计三处修复;不合并、不推送或公开发布。唯一下一项验收:RTX3060 2X/6X 与原采集配置长时间运行,失败时保留主日志及对应 fg-probe 日志。
+
+## 2026-09-18 全链路调度审计与三处追加修复
+
+用户测试 r1 包期间,审计文件播放、采集、PS5、光流/NR/SR/调色/FG、呈现、音频及导出调度。继续使用 `codex/post140-field-repair-20260917`,保留既有修改;没有合并、推送、发布、替换运行组件或改动 r1 包。详细范围、命令、证据与限制见 `docs/SCHEDULING_CHAIN_AUDIT_2026-09-18.md`。
+
+修复三处:`EngineController.cpp` 无声文件每帧重设墙钟起点导致欠速被掩盖,改为仅在明确等待首帧时重设;`VideoPresenter.h` 提供实际呈现环等待统计,调度成本扣除改用私有呈现环,避免错用生产者环;`VideoExportJob.cpp` 的释放保护原先在编码器打开前捕获空指针,改为引用 owner 并在回调捕获变量失效前 reset。新增 `SchedulingChainTests.cpp`、扩展 `FgPresentationTests.cpp` 并接入 CMake。没有复现修复前的导出崩溃或运行 sanitizer,生命周期缺陷由代码证明,实际取消回归另行验证。
+
+60fps 无声片注入 60ms 处理延迟,修复前 3.009 秒现实时间仅前进 0.750 秒媒体时间(0.249x,无跳帧);修复后 3.010 秒前进 2.850 秒(0.947x,129 次过期机会跳过),恢复、暂停、暂停 seek 与继续播放通过。日志 `out/logs/scheduling-{before,fixed}-playback.stdout.log`。XeSS 过载抑制后降到 10ms 处理负载,5 秒观察内恢复,新增 233 张生成帧,速度 1.033x,`out/logs/scheduling-xess-before2.stdout.log` PASS。
+
+真实 NVENC 在提交 1/3/5 张源帧后取消(取消前分别仅输出 0/0/1 帧),保留 partial、不报告成功,之后正常导出 12 帧并完整解码验证;无声片及用户带音轨 MKV 均通过,见 `out/logs/scheduling-fixed-export{,-audio}.stdout.log`。私有呈现环测试:生产者等待 54.8609ms、呈现环 0ms;4X/6X/4X 实际生成 114/190/114 帧,呈现纹理最大像素误差 0,D3D12 errors=0,见 `out/logs/scheduling-private-presentation.stdout.log`。
+
+本机 RTX5070 / driver 616.56,NR+DLSS 4X/6X 各 30 秒模拟 live 回放,15–17 秒注入卡顿,均恢复(exit0),`out/logs/scheduling-dlss{4,6}.stdout.log`。恢复后平均提交 142.75/203.375 次每秒;此回放实际处理节奏高于 MKV 标称 24fps,恢复后仍有过期生成帧,不能用此数字证明正确媒体节奏、所有生成帧均呈现、屏幕扫描帧率或真实采集满速。6X 日志 NR Create、DLSSG Create、FG warm-up Evaluate 均 `0x1`,实际 cap=5。音频 51/60 欠速测试现实 4008.89ms/音频 3988.90ms,额外停音与 underrun 均 0,见 `out/logs/scheduling-audio-underrate.stdout.log`。呈现 worker、实时预览和 repair contract 单测通过,后者 205 checks/0 failures。
+
+实际执行 `cmd.exe /c out\build\scheduling-audit-build.cmd`,完整隔离构建 561 步通过,日志 `out/logs/scheduling-isolated-build.log`,最终测试增量构建 `scheduling-isolated-build-final.log` 通过。先前原目录构建因用户正在运行 EXE 而 LNK1104,保留进程后换独立构建目录;新目录首次 XeSS 测试因缺少依赖 DLL 启动失败(-1073741515,未进入 main),补齐测试 PATH 指向旧构建依赖后通过。早期新增测试使用错误 ExportCounts 字段名导致编译失败,改为 source/encoded 后通过,原始日志保留。
+
+实际执行 `scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/scheduling-audit-20260918`,26 checks PASS,62.4984434 秒,`logs/delivery/62df9939d564489fb42ca7b24292fd08/result.json`。涵盖实际 NR/NVOF、4K 正确性、播放、调色、图片、4K H.264/HEVC 带音轨导出、取消导出和文件驱动的采集解码软硬一致性(非 SKIP)。EXE SHA256 `BD9C8B275560E4DDBD0BDB20DCE868818311E6FED54678BFF1550B4D178A2249`。`git diff --check` 通过,无 proprietary runtime/SDK/media 新增到源码跟踪。
+
+未修性能隐患:文件读取/解码仍同步占用 GPU owner(慢盘阻塞尚未实测);MF 的 AMD/Intel 导出仍逐帧 GPU→CPU 回读及等待,违反既定无回读性能合同,需独立实现 D3D11/DXGI 表面交接并实卡验证。导出逐批等待 generation resolve、播放优先的 50ms 主动让步、最终完整解码验证也会影响吞吐,未据此宣称持续限帧缺陷。此次未执行 RTX30/40/5090、物理采集卡、真实 PS5 或 AMD/Intel 导出;既有 4K 全增强吞吐及插值位置问题仍未解决。下一项唯一验收任务:收集用户 r1 包的 RTX30/40 完整日志,按相同配置复现剩余受限;本节三处修复尚未进入 r1 包。
+
+## 2026-09-18 RTX30/40 本地测试包交付
+
+用户授权打包到 RTX30/40 实机测试。继续使用隔离分支,无新增产品代码改动,无合并、推送或正式发布。输出目录 `C:/veyra-test-packages/post140-20260918-r1`,便携包 `Veyra-1.4.0-test-20260918-r1-win64-portable.zip`,464932607 bytes,SHA256 `8A7EA089C6B2287495FFD388BF410AEBA5EAE3AA31604426043BA5F8A5039232`。界面版本仍为 1.4.0;EXE SHA256 `9F63750E652C8FBE2CE6185D3D21CFBD7E7CAA19BB7A66E2DDFB297D875B7251`。
+
+实际执行 `scripts/package-portable.ps1 -Root . -Version 1.4.0 -Label '-test-20260918-r1' -OutputDirectory C:/veyra-test-packages/post140-20260918-r1 -BuildDirectory out/build/post140-hdr-preflight-20260918`,随后 `out/tmp/finalize-post140-package.ps1` 核对 ZIP 全部 113 文件的大小/哈希并独立解压。沿用已批准的 11 个增强运行组件,携带组件清单、许可证和 TESTING.md;无 SDK、个人配置、测试媒体、日志、PDB/LIB 混入便携包。证据 `out/logs/package-post140-test-20260918-r1.log`、`out/logs/package-post140-finalize-20260918-r1.log` 及输出目录 `package-audit.json`。
+
+执行 `out/tmp/smoke-post140-package.ps1`,独立解压目录运行,PATH 限定 Windows 系统目录,工作目录为 TEMP;检查 FFmpeg/CRT/NR/DLSSG 模块从包内加载。本机 RTX5070 / driver 616.56,四个 8 秒检查全部 exit0 并保存 JPEG:普通播放 188 源帧;original/community/Ampere NR + DLSS6X 分别 71/225、100/370、90/320 源帧/生成帧。证据 `out/logs/package-post140-smoke-20260918-r2.log` 与同名目录 `result.json`。首轮脚本遗漏触发截图所需的 `--smoke-controls`,仅截图断言失败,普通播放 185 帧 exit0;修正脚本后重跑,保留 r1 原始日志。以上不代表 RTX30/40 硬件路径已验收。
+
+另附源码快照 `Veyra-1.4.0-test-20260918-r1-source.zip`(735 文件,12136817 bytes,SHA256 `6401644D4B4700B8C18581928C73D27E0A001C07D53F77DF3A042C88CC5AD94B`),包含构建时当前产品源码,不含本条后补交付记录。实际执行 `python scripts/package-ffmpeg-source.py --prefix C:/veyra-deps/ffmpeg-ps5-dav1d-installed --vcpkg C:/veyra-deps/vcpkg --source C:/veyra-deps/ffmpeg-ps5-slices-source --dav1d-source C:/veyra-deps/vcpkg/buildtrees/dav1d/src/1.5.4-179377b46e.clean --output C:/veyra-test-packages/post140-20260918-r1/Veyra-1.4.0-test-20260918-r1-FFmpeg-source.zip --version 1.4.0` exit0,10809 文件,25277828 bytes,SHA256 `A83293849960802E9AFD0E685E7E094B986E5FED19FA8371410E7E2E6F0DAAF7`,日志 `out/logs/package-post140-ffmpeg-source-20260918-r1.log`。RemotePlay 依赖未变,复用并校验 `Veyra-1.4.0-RemotePlay-source.zip`,SHA256 `1D69DDA5BB1AFA3B78E917569BF396338A338BF2184D4458C2F1E1D88CE881DF`;其中旧版应用源码 tag 指引由本次独立应用源码快照取代。
+
+RTX30/40 实卡未执行,4K 全增强吞吐与其他未解问题继续按下节记录,不标全部修复。下一项唯一任务:用户在目标显卡按 TESTING.md 测试,4X/6X 至少各 3 分钟并覆盖原复现时长,反馈完整 logs 目录和效果配置。
+
+## 2026-09-18 持续运行后 DLSS 4X/6X 受限追加修复
+
+继续使用 `codex/post140-field-repair-20260917`,保留此前播放器与兼容修复。详细调查、失败实验、命令和验收边界见 `docs/DLSS_SUSTAINED_REPAIR_2026-09-18.md`。没有合并、推送或发布。
+
+已修正 6X 的 Fg4/Fg5 时间戳覆盖 FgBatch/Blit、Present 共用增强分配器导致等待和预算重复收费、采集截止时间遗漏 B 帧基础处理、CPU 延时抵扣尚未提交的 FG、固定 250ms 冷却丢弃正常恢复机会。DLSS 呈现使用独立三槽 DIRECT queue/fence,增强保持六槽,输出按 parity 做生产者/消费者 GPU 同步,复用及退出均覆盖在途读取;采集在读取最新 mailbox 前等待上一增强批完成并继续服务呈现。
+
+`cmd.exe /c out\build\veyra-build-x64-release.cmd` 第 11 次构建 exit0(`out/logs/fg-sustained-build11-20260918.log`)。调度单测 PASS,repair contracts 205 checks/0 failures。真实 USB3 1080p60、NR+4X 连续 180 秒,注入 55ms CPU 卡顿两秒后平均 239.981 次提交/秒,95% 目标断言通过,恢复后无新增过期帧;日志 `out/logs/fg-final-nr4-result-20260918.log`。这不是显示器扫描帧率。
+
+新增呈现测试三轮 4X/6X/4X,各 40 源帧,实际生成 114/190/114 帧;含 reset、异步呈现、窗口 resize、消费者 fence 阻止复用及 producer 先退出。呈现与对应 DLSS 纹理逐像素最大误差 0,D3D12 errors=0。命令 `scripts/run-short-test.ps1 -Exe out/build/post140-hdr-preflight-20260918/veyra_fg_presentation_tests.exe -Arguments @('out/logs/fg-presentation-verified-20260918') -TimeoutSeconds 60 -LogPrefix out/logs/fg-presentation-verified-20260918` exit0。初版测试重复保存同名 PNG 失败已留档,不能解释为产品画面错误;此测试也不能证明插值位置/画质正确。
+
+NR+6X 连续 180 秒通过:同样注入卡顿,恢复后平均 359.943 次提交/秒,158 个恢复采样无受限,expired 保持 7,实际生成 53410 帧;NGX Create/Release 均为 `0x1`。日志 `out/logs/fg-final-nr6-result-20260918.log`。4K 全增强 4X/6X 各 45 秒对照仍 FAIL(exit1):生命周期恢复,但平均 177.609/191.130 次提交每秒,低于 240/360 目标;测得每源帧约 17.3/20.8ms,超过 60Hz 时限。保留 `out/logs/fg-final-full{4,6}-result-20260918.log`,不能因总 GPU 未满载就宣称该串行链路已满速。
+
+所附 MKV 设置回归 `scripts/run-short-test.ps1` 运行 `veyra_fg_settings_tests.exe` exit0,1→2→6→1→6、暂停 seek/resume 和关闭通过,117 源帧/172 生成帧,日志 `out/logs/fg-final-settings-20260918.stdout.log`。最终 `scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/post140-hdr-preflight-20260918` PASS,26 checks,62.5811217 秒,证据 `logs/delivery/4a5b5a11d376481184994f93e376659f/result.json`。最终 EXE SHA256 `9F63750E652C8FBE2CE6185D3D21CFBD7E7CAA19BB7A66E2DDFB297D875B7251`。NR+4X 使用 build10,其后 build11 产品改动仅测试读回等待及非 live consumer-fence 日志值;其余最终检查使用 build11。
+
+RTX30/40/5090 实卡未执行,缺失用户 export-worker 首错、5090 NR→XeSS device removal 和既有合成运动位置偏差仍未解决。另纠正此前文档错误:PresentSink 已有 DRED 失败后查询,不是尚未实现;强制采集启用和受影响机器有效证据仍未确认。下一项唯一验收任务:受影响用户按原配置运行本次构建,保留首次受限前后的完整日志。目标不标全部完成,没有合并、推送或发布。
+
+## 2026-09-18 播放器字幕、音轨、打开拖动、设置记忆与防休眠
+
+继续在 `codex/post140-field-repair-20260917` 施工。实现范围、实际命令、测试日志、原始失败和未验证边界见 `docs/PLAYER_TRACKS_SETTINGS_REPAIR_2026-09-18.md`。
+
+- 字幕改为主/副字幕独立选择,选中即启用;单次后台扫描渐进发布正文。真实窗口可选第 32 条字幕(stream 49),所附 MKV 共 32 条可用字幕、15720 cues。增加 17 路内嵌音轨选择,保留播放位置、暂停和音量;所选音轨传到 worker 与旧导出入口,解码 PCM 验证不是只改标签。
+- 修复音频 seek 依赖稀疏音轨索引导致的大量回读,改用视频索引后按真实 PCM PTS 裁切;去除拖动结束重复 seek。所附 4.27GB MKV 本机热缓存首帧 367.05ms,跳到 30/1200/90 秒为 31.35/30.82/30.63ms,不是其他机器或冷缓存保证。
+- WM_CLOSE 原来没有保存设置,现实际保存 NR/SR/运行时选择以及总开关关闭时的草稿,移除跨会话陈旧成功缓存。4060 Ti 用户日志 community NR Create `0x1`,重启后 original NR `0xFFFFFFFFBAD00001`,与运行时选择丢失吻合;不据此宣布 RTX40 全功能真机验收。
+- 新增播放期间 Windows display/system execution request,暂停、停止、失败和关闭释放,并处理屏保消息。正式 GUI 自动化验证重启持久化、字幕/音轨菜单和全屏防休眠生命周期,使用独立配置沙箱,未覆盖用户设置。
+- 呈现改为一次取得代理 swapchain buffer index,资源屏障/RTV/last buffer 使用同一索引。5090 NR→XeSS 日志 `Present 0x887A0005 / removedReason 0x887A002B` 尚未本机复现;此一致性修正不能冒充已确证根因。RTX5070 上按 4K50、AMD 光流和 1155x741 窗口,两种启用顺序各两轮通过(501 帧,NR Create `0x1`、XeSS init `0`,每个联合阶段有 26–36 实际生成帧),不是受影响实卡/真实采集链路证据。
+
+构建命令 `cmd.exe /c out\build\veyra-build-x64-release.cmd` exit0,日志 `out/logs/player-tracks-build3-20260918.log`。`veyra_player_tracks_tests`、`veyra_audio_track_output_tests`、`veyra_subtitle_loading_tests`、`veyra_popup_selector_tests`、`veyra_ui_contract_tests` 与 `tests/integration/PlayerShellTests.ps1` 均通过;音频测试同时验证两路频率、时间戳和两种导出入口。正常窗口证据 `out/tests/player-shell-d033d14c6d80468c95313d82508df4a6`。
+
+最新 `scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/post140-hdr-preflight-20260918` PASS,61.575757 秒,`logs/delivery/81a8d951f689467a868456f023550dbd/result.json`。EXE SHA256 `5B35FDAD4291168A03A1EA0E9D911B952123DFD800C57237A08CB07F6DB1529D`。早先 gate/hash 仅代表此前代码。没有合并、提交、推送、发布或新增 proprietary runtime/SDK/media 到 Git。
+
+未执行 RTX30/40/5090 实卡、实际长时间休眠等待,未取得用户导出 worker 首错;既有 6X 合成图案位置误差仍保留,目标不标全部完成。下一项唯一任务是受影响显卡运行此构建并保留 application/probe/worker 首错证据。
+
+## 2026-09-18 追加修复播放中切换的能力同步
+
+RTX5070 强制 Ampere/Ada 的所附 MKV 6X 播放各 exit0:170/196 源帧、840/970 生成帧,未降档;Ada Present 提交 144fps,不代表屏幕实测。日志 `out/logs/post140-{ampere,ada}6-mkv-preview.stdout.log`。
+
+新增 `tests/integration/FgSettingsTests.cpp` 和 CMake 目标,用真实播放器覆盖 1→2→6→1→6、暂停/seek/resume、停止排空。首轮 `post140-ampere-settings` FAIL:底层已生成 1558 帧,但 snapshot 能力仍为 0。`EngineController.cpp` 原来仅首次打开发布 capability;改为重建、回滚和运行错误恢复后同步实际能力。保留失败日志。
+
+实际执行 `cmd.exe /c out\build\veyra-build-x64-release.cmd`,日志 `out/logs/post140-build-settings-repaired.log`、`post140-build-settings-final.log` exit0。通过 `scripts/run-short-test.ps1` 运行新测试(timeout240s、所附 MKV,完整命令见修复方案),`post140-native-settings-final`、`post140-ada-settings-final`、`post140-ampere-settings-final` 全部 exit0;每次切换要求新增源帧/生成帧,6X requested=applied,cap=5。兼容变量仅在独立 shell 设置并 finally 清理。新 EXE:`out/build/post140-hdr-preflight-20260918/veyra.exe`,SHA256 `231ECD897E19B7A45295EA3AE4694BD5717BA03113F33DD4E81E69CEBC84909A`。
+
+最终执行 `scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/post140-hdr-preflight-20260918`,`logs/delivery/f0de8f4ef17a46418be3ce8733ebca54/result.json` PASS,61.7707815 秒,EXE hash 一致。已跟踪/新增文件空白检查、源码/二进制隔离审计通过。一次审计命令误将 no-index 的差异退出码 1 当成格式错误,核对输出并重新检查通过,未因此改内容。
+
+这批测试验证设置与生命周期,未消除既有合成图案位置偏差,未执行 RTX30/40/5090 实卡,未获得用户原始导出 worker 日志;没有合并、提交、推送或发布。后续需要目标卡运行与完整 worker/probe 日志,现有本机成功证据不支持“全部修好”。
+
+## 2026-09-18 追加修复 HDR 6X 兼容预检
+
+在当前隔离分支实际运行强制 Ampere HDR 导出,`post140-ampere6-hdr-final` exit1:预检 PID35616/stage2/generated0,日志明确 `HDR output requires an explicit HDR input contract`。原因是预检 descriptor 只设置 `hdrOutput`,测试帧仍为 SDR RGB;这会阻止目标兼容路径进入真正的 FG。修改 `src/engine/FgCompatibilityProbe.cpp`:HDR 同时声明 HDR 输入,使用 limited P010/PQ/BT.2020-NCL/BT.2020 测试帧,SDR 路径保持 RGBA。
+
+旧构建的 EXE 正被 PID9468 运行,`post140-build-probe-hdr.log` 记录 LNK1104;保留该进程,使用 `scripts/build.ps1` 另建 `out/build/post140-hdr-preflight-20260918`,保持 patched FFmpeg/RemotePlay/固定 NVENC13.0 依赖。完整命令在修复方案“ HDR 预检追加构建”节;`post140-build-probe-hdr-isolated.log` exit0。新 EXE SHA256 `880A3D585C3C01E574F5840C86AFF53F5B4D4F271D8264656057EF2BABED47CC`,旧 EXE 不包含此修正。
+
+`post140-ampere6-hdr-repaired`、`post140-ada6-hdr-repaired` 均 PASS:各自通过真实子进程预检(PID37608/34920,stage4/generated10),随后 `source=12 generated=55 hold=5 output=72 multiplier=6`,兼容补丁成功恢复。两项 `ffprobe -count_frames` 解码结果均为 HEVC Main10/yuv420p10le/PQ/BT2020/1920×1080/180fps/72帧/.4s,AAC 5.1/.405333s。环境变量只在独立测试 shell 生效并 finally 清理。测试硬件为 RTX5070,不是 30/40 实卡;此前合成位置失败仍保留。
+
+新目录执行 `scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/post140-hdr-preflight-20260918`,`logs/delivery/ff9bea6b541d4934a52d0f6c0826f5bc/result.json` PASS,57.483224 秒,报告 EXE hash 与上述一致。已跟踪/新增文件空白检查、二进制与依赖目录隔离审计 PASS;再次核对 DLSSG/NR 原件 SHA256 不变。没有提交、合并或发布。下一项仍是内容相关位置偏差定位与目标实卡验收;没有把目标标为全部完成。
+
+## 2026-09-18 1.4.0 隔离修复实施与验收记录(未全部通过)
+
+用户授权新分支施工与目标模式。分支 `codex/post140-field-repair-20260917`,基线 `bd7cc0fc8eaf80e0913f2aafa95584c741f1ffdf`,存档 `checkpoint/pre-post140-repair-20260917`。本机 RTX5070 / 616.56;未合并 main、未推送、未发布。完整文件范围、原始调查、上游固定提交、命令和逐项证据见 `docs/POST_1_4_0_FIELD_FAILURE_REPAIR_PLAN_2026-09-17.md`。
+
+已实施:6X 完成数组与编码描述符容量统一;soft reset 后完成统计继续接纳同窗口帧、Present 成本按单次归一且 1 秒过期;MKV 全轨字幕改可取消的单次异步 demux,保留双轨/偏移/手动字幕;NVENC 固定 13.0 完整 ABI,删除仅改 apiVersion 的回退,传递实际 NVENC/MF 错误及 worker 路径;导出不再静默把 6X 改 2X/关闭。RTX30/40 兼容接入 early-provider/startup/Create、资源生命周期与有界子进程真实 Evaluate 预检,失败回滚检查完整;RTX50 普通路径不安装补丁。来源及改动记录已更新 `THIRD_PARTY_NOTICES.md`。
+
+实际构建命令 `cmd.exe /c out\build\veyra-build-x64-release.cmd`,最终构建日志 `out/logs/post140-build-direct-planar.log`,exit 0。执行 `scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/post140-field-repair-20260917`,`logs/delivery/2c9372ba16774e3d9f7529825f623fa3/result.json` 为 PASS,62.0575379 秒,Veyra.exe SHA256 `DD117A0F3D484E8DAF6101B3E877A04B4884F1CE733E26A0D32415993330FACB`。该 gate 覆盖 NR/NVOF 1080p/native 4K、播放 FG 同步/控制/调色、图片和 4K 2X H264/HEVC 导出计数/音轨/取消等,不包含下面失败的 6X 内容位置验收,也不证明未连接设备通过。
+
+针对性测试均通过 `scripts/run-short-test.ps1` 执行,单次不超过 300 秒,日志在 `out/logs/`:
+
+- `post140-contract`、`post140-scheduler` PASS:容量、soft reset 统计与 Present 样本过期。
+- `post140-subtitle-dual-final`、`post140-subtitle-cancel-final` PASS:所附大 MKV 32 轨 / 15720 cues / 单次扫描;425 播放帧,双轨 3/5 与 700ms 偏移保留。热缓存扫描 2576.748ms,较早冷缓存 9.4–10.3s;首次有效画面另次测量 120ms,不能混为同次测试或承诺固定耗时。
+- `post140-pool-{h264,hevc,mf-h264,mf-hevc}` PASS:12 个不同灰度输入槽实际编码、解码比对。`post140-nvenc-invalid-version`、`post140-nvenc-unsupported` 验证错误分流与 SDR MF 回退。
+- `post140-native-lifecycle`、`post140-ada-publication-lifecycle`、`post140-ampere-publication-lifecycle` PASS:6,2,5,3,4,6 倍率、尺寸变化、reset、释放。`post140-rollback-publication-final` PASS:故障注入后拒绝重新初始化并保留必要资源。强制兼容只是在 5070 测试,不是 30/40 验收。
+- `post140-ampere6-cow`、`post140-ada6-final-hevc` PASS:实际 12 source + 55 generated + 5 明示 CFR holds = 72 encoded,H264/HEVC 输出解码各 72 帧,保留音轨。`post140-hdr6-hevc` PASS:Main10/PQ/BT2020、72 解码帧、AAC 5.1。这些计数检查不覆盖 6X 内容位置精度。
+- `post140-worker6`、`post140-worker-cancel-final` PASS:720 帧导出、暂停/恢复/取消、前台继续播放。`post140-probe-timeout`、`post140-worker-probe-reject`、`post140-worker-probe-cancel` PASS:挂起/拒绝/取消隔离。
+- `post140-worker-error-tagged` PASS:真实消息链包含 `OpenD3D12Session status=15` 与 MF 拒绝 HDR 10bit 的原因,零源帧/零编码帧、没有输出文件,worker PID40072 的路径可定位。较早 `post140-worker-error-final` FAIL 是测试素材未标记 HDR,MF 正常成功;保留失败记录,不冒充产品修复证明。
+
+**尚未通过:6X 合成位置精度。** `post140-native6-camera-planar`、`post140-native6-direct-planar` 均 FAIL:55 张不同生成帧,33 张满足原定 ±1px 门槛。精确 16px 平移时目标 `[2.667,5.333,8,10.667,13.333]`,测得 `[2.25,7.75,8,11.25,12.25]`。直接 NGX 测试绕开图调度/帧池/颜色转换/NVOF,Create/Evaluate/Release/Shutdown 均成功;仍不能把根因确定为 NVIDIA 模型。零向量 invalid 哨兵和相机基/投影修正未解除偏差,没有放宽阈值。追加命令 `scripts/run-short-test.ps1 -Exe out/build/post140-field-repair-20260917/veyra_repair_fg_tests.exe -Arguments @('mfg2-exact-rgb-planar') -TimeoutSeconds 90 -LogPrefix out/logs/post140-native2-planar-control` PASS,11/11;4X 原始对照 22/33,仅中点通过不能替代多帧验收。
+
+运行时原件未修改:DLSSG SHA256 `135EAF0733C1E37381A8C28ABCF7A862404A54132B81787C04E35D09EFC5E36F`,NR SHA256 `E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E`。构建 SDK/运行时/测试媒体留在忽略目录;`git -c core.safecrlf=false diff --check` 通过。新增文件是源代码、测试、许可证和文档。
+
+追加对照:`RepairFgTests.cpp` 增加 `-planar-detail` 非周期双线性格点纹理,仍为 16px 平移及 ±1px 门槛,原始正弦测试保留。`post140-build-detail-fixture.log` 构建 exit 0,仅测试程序更新。`post140-native6-planar-detail`、`post140-ada6-planar-detail`、`post140-ampere6-planar-detail`、`post140-native6-planar-detail-nvof` **全部 PASS,各 55/55**,后三者分别核实兼容补丁实际安装/回滚、产品 NVOF executes=11。实际命令沿用上面的短测工具,模式 `mfg6-exact-rgb-planar-detail`;NVOF 模式移除 `-exact`,强制兼容使用对应 `VEYRA_TEST_FORCE_*_UNLOCK` 环境变量并在 finally 清理。这证明本机存在位置/PTS/内容检查通过的真实 6X,不能将正弦失败推广为所有 6X 错误;也没有消除低频纹理/方块已有失败。变化依赖内容,具体机理尚未确认。变更/新增文件二进制与忽略依赖目录审计、已跟踪/未跟踪文件空白检查均 PASS。
+
+限制:RTX30/40/5090 真机均未执行;用户原始导出 worker 日志缺失,不能倒推其首错或声称该机器已修好。子进程通过不保证父进程永不挂死。没有新增字幕烧录导出或 DRED,不将其记为完成。下一项唯一任务为继续定位内容相关的多帧位置偏差,并以目标实卡验证兼容执行/速度/稳定性;目标尚未标记完成。
+
+## 2026-09-17 导出截图追加调查(未改产品)
+
+用户截图显示 NVENC/MF 初始化失败并要求更新驱动,反馈驱动已最新。定位 `VideoEncoderFactory.cpp:47`:这是两个 `open()` 失败后的通用提示,没有驱动版本判定。HDR 下 MF 会主动拒绝,提示仍相同;截图对应正式编码前失败,不能归于 CFR 尾帧。
+
+追加发现 `NvencD3D12Encoder.cpp` 的回退按主版本去重,编译 API 13.1 时真实失败会跳过 13.0;强制测试开关却绕过这一条件。PowerShell 枚举分支证实真实候选 `12.0/11.0`,测试候选 `13.0/13.0/12.0/11.0`,未调用 NVENC。只降低 session apiVersion 而不处理函数表/结构体 ABI,且未查询 max-supported,不能视为完整兼容实现。
+
+更新方案第 7 节,补齐证据与初始化修复要求。实际执行 `rg`、源码/本地 SDK 头文件读取和分支枚举;本地 CMakeCache 预期路径不存在,未据此推断用户包编译版本。未执行构建/GPU/导出,具体用户首错仍缺 worker 日志。仅文档修改,执行 `git diff --check` 无空白错误。
+
+## 2026-09-17 1.4.0 用户日志调查与 RTX30/40 6X 方案(仅调查,未修产品)
+
+用户提供五份故障日志和 Money Heist MKV,要求排查并核对 GitHub,目标含 RTX30/40 最高 6X,不能用关闭功能或退 2X 代替完成。
+
+调查基线 `main` / `bd7cc0fc8eaf80e0913f2aafa95584c741f1ffdf`,开始时干净。完整证据、输入 SHA256、固定上游版本、源码位置、修复顺序和验收见 `docs/POST_1_4_0_FIELD_FAILURE_REPAIR_PLAN_2026-09-17.md`。
+
+- 确认 6X 内存越界:批次容量 6,`CompletionWatch::frameReadyObserved` 仍为 4;发布版 `890d200` 也存在。不能据此认定附件中的全部 device lost 原因。
+- 5090:revision 12 的 22290 个 FG 候选有 22287 个在 Evaluate 前被拒,最终 generatedPresented=0。源码发现 soft reset 推进图 epoch 后,旧统计 identity 拒收新完成事件,Present 预算又不过期;是与日志吻合的故障链,待修复前后实机对照。
+- 大 MKV:UI 在 engine.open 前逐字幕轨扫描全文件;日志首末字幕完成相隔约 85/64 秒。所附样本 32 字幕、17 EAC3 音轨;系统 FFmpeg 8.1.1 前 5 秒视频解码 exit 0 / 0.974s,首字幕整文件单次 demux exit 0 / 1.998s。未验证随包 FFmpeg 或 Veyra 播放。
+- RTX40:补丁 identityVerified=1 后仍报 maxGeneratedFrames=1;NGX 先初始化后补丁是待验证的生命周期问题,不能武断归因 DLL 不对。RTX30:FeatureInitResult 低 32 位为 BAD0000B,能力阶段失败;上游 requirements/启动 capability/provider 生命周期处理没有完整对应到 Veyra。
+- GitHub:RTX40MFG-Unlock `b77e6e5` / MIT,30 系仍标早期实验;dlssg_for_sm86 `126d0f7` 声称 310.9 6X,但当前树缺实现源码/许可证正文,不能沿用旧 MIT 判断或直接作为可移植源码。RenoDx 来源 `a8aa0d9` 未变。
+- 导出:主日志缺 worker 终态;对应 PID 为 43964/44892/44228/46492/38640,所需 `export-worker-<PID>.log` 尚未取得。确认 device lost,不虚构 NVENC/CFR 首错。
+
+实际命令:`git status --short`、`git rev-parse HEAD`、`git show 890d200:src/engine/EngineController.cpp`、`rg`、`Get-FileHash`、`gh api` 仓库/commit/tree/compare/issue/README 查询;FFmpeg/ffprobe 完整参数见方案附录。输出保留于本轮工具记录,无独立本机 GPU 测试日志。`git diff --check` 与新增方案的 `git diff --no-index --check -- NUL <plan>` 均通过。
+
+只修改本 WORKLOG 和新增方案;未改产品、未构建、未执行 NGX Create/Evaluate 或 delivery gate、未提交/推送/发布、未新增二进制。下一项唯一产品任务:P0 统一 6X 容量与越界修复;30/40 实卡与导出 worker 首错证据仍待补齐。
+
## 2026-09-17 1.4.0 正式发布到 GitHub(用户授权,已完成)
**发布地址**:https://github.com/Likely7/Veyra-NRVideo/releases/tag/v1.4.0 (非草稿、非预发布)
diff --git a/include/veyra/diagnostics/FrameMetrics.h b/include/veyra/diagnostics/FrameMetrics.h
index 1509037b..5956f8d6 100644
--- a/include/veyra/diagnostics/FrameMetrics.h
+++ b/include/veyra/diagnostics/FrameMetrics.h
@@ -5,7 +5,9 @@
#include "veyra/pipeline/FrameBatch.h"
#include "veyra/pipeline/ResolutionPlan.h"
namespace veyra::diagnostics {
-enum class GpuStage { Color, Sr, Flow, Nr, Residual, Fg1, Fg2, Fg3, FgBatch, Blit, Count };
+enum class GpuStage { Color, Sr, Flow, Nr, Residual, Fg1, Fg2, Fg3, Fg4, Fg5, FgBatch, Blit, Count };
+static_assert(unsigned(GpuStage::Fg5)-unsigned(GpuStage::Fg1)==4);
+static_assert(unsigned(GpuStage::FgBatch)>unsigned(GpuStage::Fg5));
enum class SampleState { NotExecuted, Pending, Measured, Unavailable };
enum class CpuStage { Decode, Submit, SlotWait, ReadyWait, DeadlineWait, Present, DecodedQueue, EnhancementDelayEstimate, Count };
enum class PairTiming { ArrivalInterval, GeneratedFromA, GeneratedFromB, Count };
diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.h
index dafc920d..80d53641 100644
--- a/include/veyra/engine/EngineController.h
+++ b/include/veyra/engine/EngineController.h
@@ -11,6 +11,7 @@
#include "veyra/engine/PreviewView.h"
#include "veyra/sink/CaptureAudioSession.h"
#include "veyra/remoteplay/SessionInbox.h"
+#include "veyra/media/AudioTrack.h"
namespace veyra::source { struct RemotePlayConnectDesc; class RemotePlaySessionSource; }
namespace veyra::remoteplay { struct ControllerState;struct ControllerFeedback; }
namespace veyra::sink { struct RgbaImage; }
@@ -18,6 +19,7 @@ namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }
namespace veyra::engine {
class FrameFlowWindow;
struct PlayerOptions { bool nr=false,sr=false,fg=false,realtime=true; uint32_t fgMultiplier=2; EnhancementSettings settings;
+ int audioStreamIndex=-1; // export selection; -1 selects the container default
bool captureReplayForTest=false; // file-backed live scheduler test; never enabled by UI
bool captureReplayDisableFgAdmissionForTest=false; // controlled scheduler A/B only
bool captureCpuUnpack=false; // N1 diagnostic: legacy per-pixel CPU unpack
@@ -36,6 +38,8 @@ struct PlayerSnapshot {
std::wstring colorStatus;
sink::CaptureAudioState captureAudio;
unsigned audioInputChannels=0,audioOutputChannels=0;
+ std::vector<media::AudioTrack> audioTracks;
+ int selectedAudioTrack=-1;
bool audioRebuffering=false;
uint64_t audioVideoWaits=0;
bool audioEndpointRecovering=false;HRESULT audioEndpointError=S_OK;uint64_t audioEndpointRecoveries=0;
@@ -100,6 +104,7 @@ public:
void previewView(PreviewView view){if(!std::isfinite(view.zoom)||!std::isfinite(view.centerX)||!std::isfinite(view.centerY))return;std::lock_guard lock(mutex_);view.zoom=std::clamp(view.zoom,.05f,64.0f);previewView_=view;}
PreviewView previewView()const{std::lock_guard lock(mutex_);return previewView_;}
void setVolume(float gain,bool mute);
+ bool selectAudioTrack(uint64_t sessionId,int streamIndex);
void seek(double seconds){if(!std::isfinite(seconds)||seconds<0)return;std::lock_guard lock(mutex_);snapshot_.seekTarget=seconds;++snapshot_.seekRequested;seekSeconds_.store(seconds);}
void saveFrame(const std::wstring& path);
void startExport(const std::wstring& input,const std::wstring& output,PlayerOptions,bool hevc);
@@ -122,6 +127,7 @@ private:
std::atomic<bool> stop_{false},paused_{false},muted_{false};
std::atomic<float> volume_{1};uint64_t sessionId_=0;
std::atomic<double> seekSeconds_{-1};
+ int pendingAudioTrack_=-1;uint64_t pendingAudioSession_=0; // mutex_
std::atomic<int> comparisonMode_{0};std::atomic<bool> comparisonBase_{false};std::atomic<float> comparisonSplit_{.5f};
// Guarded by mutex_: DLSSG MultiFrameCountMax of the active session.
int fgMultiFrameMaxCap_=0;
diff --git a/include/veyra/engine/ExportJobManager.h b/include/veyra/engine/ExportJobManager.h
index 5206e817..ba5a019e 100644
--- a/include/veyra/engine/ExportJobManager.h
+++ b/include/veyra/engine/ExportJobManager.h
@@ -8,7 +8,8 @@ struct ExportJobSnapshot {
double progress=0;
uint64_t jobId=0,frozenRevision=0,sourceFrames=0,generated=0,holds=0,encoded=0;
EnhancementSettings frozen;
- std::wstring message,output;
+ std::wstring message,output,workerLog;
+ uint32_t workerPid=0;
bool active()const{return state>=ExportState::Preparing&&state<=ExportState::Finishing;}
};
// One isolated NGX context in a child process. Anonymous inherited mapping is
@@ -16,7 +17,7 @@ struct ExportJobSnapshot {
class ExportJobManager {
public:
ExportJobManager();~ExportJobManager();
- bool start(const std::wstring&,const std::wstring&,EnhancementSettings,bool hevc,unsigned maxFrames=0);
+ bool start(const std::wstring&,const std::wstring&,EnhancementSettings,bool hevc,unsigned maxFrames=0,int audioStreamIndex=-1);
void cancel();void pause(bool);void watching(bool);
ExportJobSnapshot poll();
private:struct Impl;std::unique_ptr<Impl> p_;
diff --git a/include/veyra/engine/FgCompatibilityProbe.h b/include/veyra/engine/FgCompatibilityProbe.h
new file mode 100644
index 00000000..d7f16eb0
--- /dev/null
+++ b/include/veyra/engine/FgCompatibilityProbe.h
@@ -0,0 +1,12 @@
+#pragma once
+#include <atomic>
+#include <string>
+#include <windows.h>
+namespace veyra::pipeline { struct EnhanceGraphDesc; }
+namespace veyra::gfx { class D3D12DeviceContext; }
+namespace veyra::engine {
+// Installed by the executable that implements --fg-compat-probe.
+void setFgCompatibilityProbeExecutable(std::wstring path);
+bool checkFgCompatibility(const pipeline::EnhanceGraphDesc&, const gfx::D3D12DeviceContext&, const std::atomic<bool>& cancel);
+int runFgCompatibilityProbe(HANDLE mapping);
+}
diff --git a/include/veyra/engine/FgRecoveryBudget.h b/include/veyra/engine/FgRecoveryBudget.h
index ca90b3c0..b390a94d 100644
--- a/include/veyra/engine/FgRecoveryBudget.h
+++ b/include/veyra/engine/FgRecoveryBudget.h
@@ -14,7 +14,6 @@ class FgRecoveryBudget {
std::deque<Sample> base_,fg_,warmup_;
bool limited_=false;
unsigned recoveryPairs_=0;
- int64_t retryAt_=0;
static void add(std::deque<Sample>& values,int64_t now,double ms){
if(!std::isfinite(ms)||ms<0)return;
while(!values.empty()&&(values.size()>=64||values.front().time<now-10000000))values.pop_front();
@@ -28,7 +27,7 @@ class FgRecoveryBudget {
std::nth_element(current.begin(),current.begin()+index,current.end());return current[index];
}
public:
- void reset(){base_.clear();fg_.clear();warmup_.clear();limited_=false;recoveryPairs_=0;retryAt_=0;}
+ void reset(){base_.clear();fg_.clear();warmup_.clear();limited_=false;recoveryPairs_=0;}
void fgCost(double ms,int64_t now){add(fg_,now,ms);}
void complete(std::optional<double> measuredMs,bool evaluated,bool warmup,int64_t now,std::optional<double> measuredFg={}){
// Missing GPU timestamps are unknown, not CPU polling delay. Let old
@@ -42,21 +41,30 @@ public:
add(base_,now,std::max(0.0,ms-extra.value_or(0)));
}
std::optional<double> predicted(int64_t now)const{
- const auto base=p95(base_,now,10000000);
+ const auto base=baseCost(now);
if(!base)return {};
return *base+p95(fg_,now,20000000).value_or(0);
}
+ std::optional<double> baseCost(int64_t now)const{return p95(base_,now,10000000);}
+ // A/B interpolation needs B first; enhancement of B is additional work.
+ // Schedule its measured base cost before the subframe cadence, bounded to
+ // one source interval. Sample before submitting this pair, never at ready.
+ int64_t processingAllowance(int64_t now,int64_t interval)const{
+ return int64_t(std::min(double(std::max<int64_t>(0,interval)),baseCost(now).value_or(0)*10000));
+ }
bool admit(int64_t now,int64_t deadline,double elapsed,double present){
const auto cost=predicted(now);
- const bool fits=double(deadline-now)/10000+10>=std::max(0.0,cost.value_or(elapsed)-elapsed)+std::max(0.0,present);
+ // FG has not been submitted at admission. CPU time can at most cover
+ // the base work; it must never erase the cost of future FG calls.
+ const double progress=std::clamp(elapsed,0.0,baseCost(now).value_or(0));
+ const bool fits=double(deadline-now)/10000+10>=std::max(0.0,cost.value_or(0)-progress)+std::max(0.0,present);
if(!fits){
- if(!limited_||recoveryPairs_){retryAt_=now+2500000;}
limited_=true;recoveryPairs_=0;return false;
}
if(limited_){
- if(now<retryAt_)return false;
// A probe consists of consecutive admitted pairs, not an isolated
- // warmup. Every pair still checks its actual deadline above.
+ // warmup. A fresh pair that fits can recover immediately; a fixed
+ // cooldown otherwise discards 15 healthy 60 Hz opportunities.
if(++recoveryPairs_>=2){limited_=false;recoveryPairs_=0;}
}
return true;
diff --git a/include/veyra/engine/Subtitles.h b/include/veyra/engine/Subtitles.h
index 0333a11f..bc7c5a76 100644
--- a/include/veyra/engine/Subtitles.h
+++ b/include/veyra/engine/Subtitles.h
@@ -7,6 +7,10 @@
// explicit note instead of silently disappearing.
#include <string>
#include <vector>
+#include <functional>
+#include <memory>
+#include <optional>
+#include <stop_token>
namespace veyra::engine {
@@ -50,7 +54,22 @@ struct SubtitleTrack {
SubtitleTrack loadSubtitleFile(const std::wstring& path);
// Text subtitle tracks inside the container (Matroska/MP4/...).
-std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path);
+std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path,std::stop_token stop={},
+ const std::function<void(const std::vector<SubtitleTrack>&)>& metadata={});
+
+// One worker, one pending source and one published snapshot. Replacing a source
+// interrupts its demuxer and prevents stale results from reaching the UI.
+class SubtitleLoader {
+public:
+ struct Result {uint64_t generation=0;bool complete=false;std::vector<SubtitleTrack> tracks;};
+ SubtitleLoader();
+ ~SubtitleLoader();
+ uint64_t request(std::wstring path);
+ std::optional<Result> poll();
+private:
+ struct Impl;
+ std::unique_ptr<Impl> p_;
+};
// Cues overlapping `seconds`, newest first, at most `limit`; binary searched.
std::vector<const SubtitleCue*> cuesAt(const SubtitleTrack&,double seconds,size_t limit=4);
diff --git a/include/veyra/engine/TimingWindow.h b/include/veyra/engine/TimingWindow.h
index 7396259a..845a2719 100644
--- a/include/veyra/engine/TimingWindow.h
+++ b/include/veyra/engine/TimingWindow.h
@@ -6,17 +6,26 @@
#include <vector>
namespace veyra::engine {
class TimingWindow {
- std::deque<double> values_;
+public:
+ using Clock=std::chrono::steady_clock;
+private:
+ struct Sample {double value;Clock::time_point time;};
+ mutable std::deque<Sample> values_;
+ Clock::duration maxAge_;
mutable double cached_=0;
- mutable std::chrono::steady_clock::time_point refresh_{};
+ mutable Clock::time_point refresh_{};
+ void expire(Clock::time_point now)const{
+ while(!values_.empty()&&now-values_.front().time>=maxAge_){values_.pop_front();refresh_={};}
+ }
public:
- void add(double v){if(!std::isfinite(v)||v<0)return;values_.push_back(v);if(values_.size()>1200)values_.pop_front();}
+ explicit TimingWindow(Clock::duration maxAge=Clock::duration::max()):maxAge_(maxAge){}
+ void add(double v,Clock::time_point now=Clock::now()){if(!std::isfinite(v)||v<0)return;expire(now);values_.push_back({v,now});if(values_.size()>1200)values_.pop_front();}
void clear(){values_.clear();cached_=0;refresh_={};}
size_t size()const{return values_.size();}
- double p95()const{
- if(values_.empty())return 0;const auto now=std::chrono::steady_clock::now();
+ double p95(Clock::time_point now=Clock::now())const{
+ expire(now);if(values_.empty())return 0;
if(now<refresh_)return cached_;
- std::vector<double> sorted(values_.begin(),values_.end());const size_t i=(sorted.size()-1)*95/100;
+ std::vector<double> sorted;sorted.reserve(values_.size());for(const auto& sample:values_)sorted.push_back(sample.value);const size_t i=(sorted.size()-1)*95/100;
std::nth_element(sorted.begin(),sorted.begin()+i,sorted.end());cached_=sorted[i];refresh_=now+std::chrono::milliseconds(250);return cached_;
}
};
diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.h
index 44cf4482..18aa5b35 100644
--- a/include/veyra/engine/VideoPresenter.h
+++ b/include/veyra/engine/VideoPresenter.h
@@ -3,6 +3,7 @@
#include "veyra/gfx/PresentSink.h"
#include "veyra/pipeline/GpuPassUtils.h"
#include "veyra/engine/PreviewView.h"
+#include "veyra/gfx/CommandSlotRing.h"
#include <chrono>
namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }
namespace veyra::pipeline { class EnhanceGraph; }
@@ -10,15 +11,18 @@ namespace veyra::sink { struct RgbaImage; }
namespace veyra::engine {
class VideoPresenter {
public:
+ ~VideoPresenter(){close();}
bool open(gfx::D3D12DeviceContext&, HWND, pipeline::EnhanceGraph&, bool captureCompatible=false);
bool present(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,pipeline::EnhanceGraph&,unsigned slot,bool generated,bool referencesValid=true,int comparison=0,bool baseReference=false,float split=.5f,pipeline::FrameIdentity identity={},PreviewView view={});
void close();
// Explicit integration-test capture only; never called by playback/export.
bool readPresentedFrameForTest(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,sink::RgbaImage&);
- // Test-only borrowed buffer reference for lossless HDR readback. Caller
- // drains the queue and releases this before resize/close; no playback use.
- Microsoft::WRL::ComPtr<ID3D12Resource> presentedResourceForTest() const;
+ // Test-only buffer reference for lossless HDR readback. Drains the private
+ // queue; caller drains the shared queue and releases before resize/close.
+ Microsoft::WRL::ComPtr<ID3D12Resource> presentedResourceForTest();
uint64_t submittedCount() const {return sink_.presentCount();}
+ uint64_t consumerFenceValue(uint64_t sharedValue)const{return presentationQueue_?presentationRing_.lastSignaledValue():sharedValue;}
+ double cpuWaitMilliseconds(const gfx::CommandSlotRing& shared)const{return presentationQueue_?presentationRing_.cpuWaitMilliseconds():shared.cpuWaitMilliseconds();}
uint64_t xessGeneratedCount() const {return sink_.xess()?sink_.xess()->generatedCount():0;}
uint64_t xessPresentedCount() const {return sink_.xess()?sink_.xess()->presentedCount():0;}
bool xessActive() const {return sink_.xess()!=nullptr;}
@@ -35,14 +39,18 @@ public:
// per-frame history reset, never a per-frame toggle.
void setXessGenerationSuppressed(bool v){xessGenerationSuppressed_=v;}
bool xessGenerationSuppressed() const {return xessGenerationSuppressed_;}
- diagnostics::GpuSample blitTiming(ID3D12Fence* f,uint64_t revision=0,uint64_t epoch=0){gpuTimer_.collect(f);if((revision&&gpuTimer_.last().identity.settingsRevision!=revision)||(epoch&&gpuTimer_.last().identity.epoch!=epoch)){diagnostics::GpuSample pending;pending.state=diagnostics::SampleState::Pending;return pending;}return gpuTimer_.last().gpu[size_t(diagnostics::GpuStage::Blit)];}
+ diagnostics::GpuSample blitTiming(ID3D12Fence* f,uint64_t revision=0,uint64_t epoch=0){gpuTimer_.collect(presentationFence_?presentationFence_.Get():f);if((revision&&gpuTimer_.last().identity.settingsRevision!=revision)||(epoch&&gpuTimer_.last().identity.epoch!=epoch)){diagnostics::GpuSample pending;pending.state=diagnostics::SampleState::Pending;return pending;}return gpuTimer_.last().gpu[size_t(diagnostics::GpuStage::Blit)];}
// Application-side frame-generation timing for present-sink backends
// (XeSS/FSR): the copies, barriers and provider prepare work recorded on
// our list. collect() is idempotent, so this is safe alongside blitTiming.
diagnostics::GpuSample fgTiming(ID3D12Fence* f,uint64_t revision=0,uint64_t epoch=0){gpuTimer_.collect(f);if((revision&&gpuTimer_.last().identity.settingsRevision!=revision)||(epoch&&gpuTimer_.last().identity.epoch!=epoch)){diagnostics::GpuSample pending;pending.state=diagnostics::SampleState::Pending;return pending;}return gpuTimer_.last().gpu[size_t(diagnostics::GpuStage::FgBatch)];}
-std::vector<diagnostics::GpuFrameTiming> takeGpuTimings(ID3D12Fence* fence){gpuTimer_.collect(fence);return gpuTimer_.takeCompleted();}
+std::vector<diagnostics::GpuFrameTiming> takeGpuTimings(ID3D12Fence* fence){gpuTimer_.collect(presentationFence_?presentationFence_.Get():fence);return gpuTimer_.takeCompleted();}
void recordGpuTimings(){gpuTimer_.recordCompleted();}
private:
+ Microsoft::WRL::ComPtr<ID3D12CommandQueue> presentationQueue_;
+ Microsoft::WRL::ComPtr<ID3D12Fence> presentationFence_;
+ HANDLE presentationEvent_=nullptr;
+ gfx::CommandSlotRing presentationRing_;
diagnostics::GpuTimer gpuTimer_;
gfx::PresentSink sink_;
pipeline::GraphicsPass pass_;
@@ -51,6 +59,7 @@ private:
unsigned lastBuffer_=0;bool hasPresented_=false;
HWND window_=nullptr;
std::chrono::steady_clock::time_point lastResize_{};
+ std::chrono::steady_clock::time_point nextCostLog_{};
std::chrono::steady_clock::time_point lastXessFrame_{};
pipeline::FrameIdentity lastXessIdentity_{};
bool xessWasEnabled_=false;
diff --git a/include/veyra/gfx/D3D12DeviceContext.h b/include/veyra/gfx/D3D12DeviceContext.h
index 63855a61..ae360ea7 100644
--- a/include/veyra/gfx/D3D12DeviceContext.h
+++ b/include/veyra/gfx/D3D12DeviceContext.h
@@ -32,6 +32,7 @@ struct DeviceContextDesc {
bool enableDebugLayer = false;
uint32_t commandSlotCount = 4;
uint32_t requiredVendorId = 0; // 0: highest-performance hardware adapter
+ uint64_t requiredLuid = 0; // 0: no adapter identity constraint
};
// One DXGI adapter + one ID3D12Device + one direct command queue + one fence
diff --git a/include/veyra/gfx/PresentSink.h b/include/veyra/gfx/PresentSink.h
index 0a7a5c92..ad775d04 100644
--- a/include/veyra/gfx/PresentSink.h
+++ b/include/veyra/gfx/PresentSink.h
@@ -65,7 +65,7 @@ public:
// Returns the current back buffer (transitioned state is the caller's
// responsibility; the buffer is in COMMON/PRESENT state on acquire).
- ID3D12Resource* currentBackBuffer();
+ ID3D12Resource* currentBackBuffer(uint32_t* acquiredIndex = nullptr);
// Presents the current back buffer. Returns false on device-lost class
// failures (caller must trigger recovery).
diff --git a/include/veyra/media/AudioTrack.h b/include/veyra/media/AudioTrack.h
new file mode 100644
index 00000000..4a18bc92
--- /dev/null
+++ b/include/veyra/media/AudioTrack.h
@@ -0,0 +1,10 @@
+#pragma once
+#include <string>
+
+namespace veyra::media {
+struct AudioTrack {
+ int streamIndex = -1;
+ std::string language, title, codec;
+ unsigned channels = 0;
+};
+}
diff --git a/include/veyra/ngx/AdaMfgUnlock.h b/include/veyra/ngx/AdaMfgUnlock.h
index 2295a675..12c8923c 100644
--- a/include/veyra/ngx/AdaMfgUnlock.h
+++ b/include/veyra/ngx/AdaMfgUnlock.h
@@ -117,7 +117,7 @@ public:
// Restores every patched byte and frees the rebuilt fatbin. Safe to call
// repeatedly and when nothing was applied.
- static void release();
+ static bool release();
static State snapshot();
static bool applied();
diff --git a/include/veyra/ngx/AmpereMfgUnlock.h b/include/veyra/ngx/AmpereMfgUnlock.h
index 4d771566..43b7b6f6 100644
--- a/include/veyra/ngx/AmpereMfgUnlock.h
+++ b/include/veyra/ngx/AmpereMfgUnlock.h
@@ -20,12 +20,11 @@ namespace veyra::ngx {
// referenced by eight identical 25-entry registration tables of 48-byte
// records whose +8 field holds the fatbin pointer (8x25 = 200 slot
// pointers);
-// * 44 neural-network fatbins live in .rdata and are referenced by a single
-// RIP-relative `lea` each; 6 auxiliary fatbins (font / capture / clear)
-// live in .data and are referenced the same way (50 lea sites total);
-// * RTX 30 has no sm_86 target anywhere in the provider, so every one of
-// these fatbins is rebuilt as a single-entry sm_86 PTX fatbin and the
-// references are redirected to the rebuilt copies. The temporal slot's
+// * 38 network and 6 auxiliary fatbins are inventoried (44 LEA sites).
+// Only the 25 registered programs and hash-identified font program are
+// rebuilt, matching upstream's scope. Network programs stay untouched.
+// The font is replaced in place to preserve all its references.
+// The temporal slot's
// PTX additionally gets the midpoint correction (compiled-in 0.5 replaced
// with the kernel's own temporal parameter), exactly as on Ada;
// * the two architecture compares (0x1b0, Blackwell) are retargeted to
@@ -98,11 +97,13 @@ public:
// audited structure matches. Callers that make the provider see Blackwell
// through the NVAPI spoof must pass false so the provider's own 0x1b0
// compare stays byte-identical and therefore passes.
- static State apply(HMODULE module, bool retargetArchGates = true);
+ // The product supplies its D3D12 adapter LUID; zero selects CUDA device 0
+ // only for standalone diagnostics without a D3D12 context.
+ static State apply(HMODULE module, bool retargetArchGates = true, uint64_t adapterLuid = 0);
// Restores every patched byte and frees the rebuilt fatbins. Safe to call
// repeatedly and when nothing was applied.
- static void release();
+ static bool release();
static State snapshot();
static bool applied();
diff --git a/include/veyra/ngx/DlssFgBackend.h b/include/veyra/ngx/DlssFgBackend.h
index a2f211ee..3c607eee 100644
--- a/include/veyra/ngx/DlssFgBackend.h
+++ b/include/veyra/ngx/DlssFgBackend.h
@@ -28,10 +28,12 @@
namespace veyra::ngx {
class NgxCoreHost;
+class FgCompatibilitySession;
class DlssFgBackend {
public:
DlssFgBackend() = default;
+ void setCompatibility(FgCompatibilitySession* session) { compatibility_=session; }
~DlssFgBackend();
DlssFgBackend(const DlssFgBackend&) = delete;
@@ -102,12 +104,16 @@ public:
uint32_t height() const { return height_; }
private:
+ FgCompatibilitySession* compatibility_=nullptr;
NVSDK_NGX_Handle* handle_ = nullptr;
uint64_t createResult_ = 0;
uint64_t evaluateCount_ = 0;
uint64_t resetCount_ = 0;
uint32_t width_ = 0;
uint32_t height_ = 0;
+ // A provider-side access violation or failed Evaluate poisons the
+ // feature wrapper. Never call the same handle again after that point.
+ bool fatal_ = false;
};
} // namespace veyra::ngx
diff --git a/include/veyra/ngx/FgCompatibilitySession.h b/include/veyra/ngx/FgCompatibilitySession.h
new file mode 100644
index 00000000..8813e74e
--- /dev/null
+++ b/include/veyra/ngx/FgCompatibilitySession.h
@@ -0,0 +1,33 @@
+#pragma once
+#include <d3d12.h>
+#include <nvsdk_ngx.h>
+#include <memory>
+#include <span>
+#include <string>
+
+namespace veyra::ngx {
+// Exclusive owner of process-local provider patches. Destroy after NGX shutdown.
+class FgCompatibilitySession {
+public:
+ FgCompatibilitySession();
+ ~FgCompatibilitySession();
+ FgCompatibilitySession(const FgCompatibilitySession&) = delete;
+ FgCompatibilitySession& operator=(const FgCompatibilitySession&) = delete;
+ static bool requested(uint32_t vendor, uint32_t device);
+ static bool processHealthy();
+ bool open(ID3D12Device* device, uint32_t vendor, uint32_t deviceId, const std::wstring& directory);
+ HMODULE provider() const;
+ bool prepareDriver(const std::wstring& directory, const char* project, const char* engine);
+ bool bindResources(std::span<ID3D12Resource* const> real, std::span<ID3D12Resource* const> generated);
+ bool beginInitialization();
+ bool endInitialization(bool success);
+ bool beginCapabilities();
+ bool endCapabilities();
+ bool publishStartup(NVSDK_NGX_Parameter* parameters);
+ bool beginCreate(ID3D12GraphicsCommandList* list);
+ bool endCreate(bool success);
+private:
+ struct Impl;
+ std::unique_ptr<Impl> impl_;
+};
+}
diff --git a/include/veyra/ngx/NvapiArchSpoof.h b/include/veyra/ngx/NvapiArchSpoof.h
index d21dbdda..34508c9f 100644
--- a/include/veyra/ngx/NvapiArchSpoof.h
+++ b/include/veyra/ngx/NvapiArchSpoof.h
@@ -7,20 +7,12 @@
namespace veyra::ngx {
-// Makes the DLSS-G provider see a different GPU architecture than the physical
-// card reports. The audited 310.7 build has exactly one place that turns the
-// driver's NV_GPU_ARCH_INFO into the value the provider stores and compares
-// (DLSSGInstanceManager::SetGPUArch, "mov eax,[rsp+294h]" at RVA 0x20DCA). That
-// seven-byte load is replaced with "mov eax,<architecture>" so the provider
-// sees the requested id while everything else - including the real
-// implementation/revision fields it later reads - stays intact. Process memory
-// only, fully reverted on release.
-//
-// Used on RTX 30 (sm_86): the provider's frame-generation availability gate
-// reads the architecture and refuses Ampere outright. Reporting Blackwell makes
-// every architecture-based check pass; the kernel rewrite (AmpereMfgUnlock) is
-// still required so the programs can actually run on sm_86. Nothing here runs
-// on Ada or Blackwell - those keep their untouched native paths.
+// Diagnostic-only architecture substitution, enabled explicitly through
+// VEYRA_TEST_NVAPI_SPOOF_ARCH. Hooks the audited provider's GetArchInfo wrapper
+// using a relocated trampoline, modifying the returned architecture for all
+// provider callers. This affects network selection as well as capabilities:
+// normal Ampere operation must preserve the real architecture. Process memory
+// only, restored on release. Ada/Blackwell product paths never install it.
class NvapiArchSpoof {
public:
static constexpr uint32_t kNvapiGetArchInfoId = 0xD8265D24u; // nvapi_QueryInterface id
@@ -32,7 +24,7 @@ public:
// `module` is the loaded nvngx_dlssg.dll. `reportedArchitecture` is an
// NV_GPU_ARCHITECTURE_ID; 0 refuses.
static bool install(HMODULE module, uint32_t reportedArchitecture);
- static void release();
+ static bool release();
static bool installed();
struct State {
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index 060fb409..026929d7 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -49,6 +49,7 @@ class NgxCoreHost;
class DlssSrBackend;
class VideoSrBackend;
class DlssFgBackend;
+class FgCompatibilitySession;
class DlssNrRuntimeAdapter;
class NvOfSession;
}
@@ -61,6 +62,7 @@ struct HardwareSurfaceInput;
// One generated-frame texture per (parity, subframe): 2 parities x 5 generated
// frames = 6X multi-frame generation. Sized once, reused for every FG backend.
inline constexpr unsigned kGeneratedPoolSlots=10;
+inline constexpr unsigned kOutputPoolSlots=2+kGeneratedPoolSlots;
struct EnhanceGraphDesc {
uint32_t sourceWidth = 0;
@@ -107,6 +109,8 @@ struct EnhanceGraphDesc {
std::wstring runtimeAbsPath; // absolute runtime_local/nvidia path
// Optional stage instrumentation hook (GPU timing experiments).
std::function<void(const char*)> stageMark;
+ // Product host supplies a cancellable, isolated compatibility startup probe.
+ std::function<bool(const EnhanceGraphDesc&,const gfx::D3D12DeviceContext&)> compatibilityPreflight;
// Output dither step for the 8/10-bit write paths, in coded units. -1 keeps
// the product default (one LSB while the colour grade is active, nothing
// otherwise) so ungraded output stays byte-identical; tests and diagnostics
@@ -119,6 +123,8 @@ struct EnhanceGraphDesc {
// working-extent RG16F current->previous pixel motion, ready in SRV state.
// Caller retains it through graph drain/shutdown, synchronizing any writes.
ID3D12Resource* srMotionProbe = nullptr;
+ // Same borrowed diagnostic contract as srMotionProbe, for FG only.
+ ID3D12Resource* fgMotionProbe = nullptr;
};
class EnhanceGraph {
@@ -167,10 +173,18 @@ public:
bool process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId = 0, const ColorDescription* color = nullptr, const HardwareSurfaceInput* hardwareSurface = nullptr, bool retainReferences = true, const FgAdmission& admitFg = {});
bool nextFrameSlotAvailable()const {
const unsigned slot=unsigned(realFrameIndex_%2);
+ if(presentationFences_[slot]&&presentationFences_[slot]->GetCompletedValue()<presentationValues_[slot])return false;
if(!realLeases_[slot].expired())return false;
for(unsigned i=slot;i<kGeneratedPoolSlots;i+=2)if(!generatedLeases_[i].expired())return false;
return true;
}
+ uint64_t presentationReadyFence(unsigned slot,bool generated)const {
+ if(generated&&slot<kGeneratedPoolSlots){if(auto lease=generatedLeases_[slot].lock())return lease->readyFence;}
+ return uploadFences_[slot%2];
+ }
+ void presentationSubmitted(unsigned slot,ID3D12Fence* fence,uint64_t value){
+ presentationFences_[slot%2]=fence;presentationValues_[slot%2]=value;
+ }
// Nonblocking. The scheduler polls at a GPU-ready/deadline boundary; no
// full image readback and no waits inside the graph's individual passes.
bool resolveGeneration(FrameOutputs& out);
@@ -296,6 +310,7 @@ private:
// resolves NvAPI_GPU_GetArchInfo once and caches the architecture decision.
void prepareAmpereFgSpoof();
bool ampereSpoofed_ = false;
+ std::unique_ptr<ngx::FgCompatibilitySession> fgCompatibility_;
bool createComputePasses();
gfx::D3D12DeviceContext& context_;
@@ -402,6 +417,8 @@ private:
std::weak_ptr<FrameLease> realLeases_[2],generatedLeases_[kGeneratedPoolSlots];
uint32_t nextListSlot_ = 0;
uint64_t uploadFences_[2] = {};
+ std::array<Microsoft::WRL::ComPtr<ID3D12Fence>,2> presentationFences_;
+ std::array<uint64_t,2> presentationValues_{};
// FFmpeg may recycle a hardware surface as soon as its AVFrame is freed.
// Retain each imported surface until our last consumer fence completes.
std::shared_ptr<AVFrame> hardwareInputFrames_[2];
diff --git a/include/veyra/pipeline/FrameBatch.h b/include/veyra/pipeline/FrameBatch.h
index c441e1d5..03031748 100644
--- a/include/veyra/pipeline/FrameBatch.h
+++ b/include/veyra/pipeline/FrameBatch.h
@@ -29,21 +29,22 @@ struct BatchFrame {
std::shared_ptr<FrameLease> lease;
};
struct FrameBatch {
+ static constexpr uint32_t Capacity=6;
uint64_t batchId=0;
FrameIdentity identity;
int64_t a100ns=0,b100ns=0;
// 6X multi-frame generation needs one real frame plus up to five generated
// frames in a single batch.
- std::array<BatchFrame,6> frames{};
+ std::array<BatchFrame,Capacity> frames{};
uint32_t count=0;
static int64_t interpolate(int64_t a,int64_t b,uint32_t j,uint32_t n) {
// The application accepts at most one second between continuous endpoints.
- if(n<2||n>6||j==0||j>=n||b<=a||a>INT64_MAX-10000000||b>a+10000000)
+ if(n<2||n>Capacity||j==0||j>=n||b<=a||a>INT64_MAX-10000000||b>a+10000000)
throw std::invalid_argument("invalid interpolation interval");
const int64_t d=b-a;return a+(d/n)*j+((d%n)*j+n/2)/n;
}
void append(BatchFrame frame) {
- if(count==frames.size()||frame.identity!=identity||(count&&frame.pts100ns<=frames[count-1].pts100ns))
+ if(count>=frames.size()||frame.identity!=identity||(count&&frame.pts100ns<=frames[count-1].pts100ns))
throw std::invalid_argument("cross-revision or unordered frame batch");
frames[count++]=std::move(frame);
}
diff --git a/include/veyra/sink/CaptureAudioSession.h b/include/veyra/sink/CaptureAudioSession.h
index b090d710..ce0140ce 100644
--- a/include/veyra/sink/CaptureAudioSession.h
+++ b/include/veyra/sink/CaptureAudioSession.h
@@ -9,6 +9,7 @@ namespace veyra::sink {
struct WavePcmFormat;
struct CaptureAudioState {
bool available=false,running=false,clockEstimated=true,limited=false;
+ bool outputRecovering=false;
unsigned inputChannels=0,outputChannels=0;uint32_t inputChannelMask=0,outputChannelMask=0;
uint32_t inputSampleRate=0;unsigned inputContainerBits=0,inputValidBits=0;bool inputFloating=false;
// Non-empty when the input is a compressed bitstream (Dolby/DTS) that was
diff --git a/include/veyra/sink/NvencD3D12Encoder.h b/include/veyra/sink/NvencD3D12Encoder.h
index 465ba52b..a43ae8a9 100644
--- a/include/veyra/sink/NvencD3D12Encoder.h
+++ b/include/veyra/sink/NvencD3D12Encoder.h
@@ -19,6 +19,7 @@ public:
std::vector<uint8_t> headers() const override;
EncoderBackend backend() const override {return EncoderBackend::Nvenc;}
std::wstring describe() const override;
+ std::wstring lastError() const override;
private:
struct Impl;std::unique_ptr<Impl> p_;
};
diff --git a/include/veyra/sink/VideoEncoder.h b/include/veyra/sink/VideoEncoder.h
index 6eea9344..d10ad139 100644
--- a/include/veyra/sink/VideoEncoder.h
+++ b/include/veyra/sink/VideoEncoder.h
@@ -60,6 +60,7 @@ public:
// Human-readable identity for logs and the export status line, e.g.
// "NVIDIA NVENC H.264 (D3D12)" or "Media Foundation HEVC (NVIDIA ... MFT)".
virtual std::wstring describe() const=0;
+ virtual std::wstring lastError() const=0;
};
// Capability-driven selection. Returns nullptr when no usable encoder exists
diff --git a/include/veyra/sink/WasapiAudioSink.h b/include/veyra/sink/WasapiAudioSink.h
index da825c56..6cd0db50 100644
--- a/include/veyra/sink/WasapiAudioSink.h
+++ b/include/veyra/sink/WasapiAudioSink.h
@@ -24,6 +24,7 @@
#include "veyra/sink/AudioPcmSource.h"
#include "veyra/sink/AudioFrameTimeline.h"
#include "veyra/sink/CaptureAudioDsp.h"
+#include "veyra/media/AudioTrack.h"
struct AVFormatContext;
struct AVCodecContext;
@@ -48,6 +49,10 @@ public:
~AudioPipeline();
bool open(const std::wstring& path);
+ const std::vector<media::AudioTrack>& tracks() const { return tracks_; }
+ int selectedTrack() const { return streamIndex_; }
+ // Owner thread only, after stopThread(). Failure preserves the old decoder.
+ bool selectTrack(int streamIndex);
AudioFormat pcmFormat()const override{return pcmFormat_;}
double bufferedMs() const;
@@ -88,8 +93,8 @@ public:
// Returns the PTS of the first buffered sample after seek.
double requestSeek(double targetMs);
- void runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint = false);
- void startThread(AudioRenderer* renderer, bool ownEndpoint = false);
+ void runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint = false, double initialMs = -1);
+ void startThread(AudioRenderer* renderer, bool ownEndpoint = false, double initialMs = -1);
bool endpointRecovering()const{return endpointRecovering_.load();}
HRESULT endpointError()const{return endpointError_.load();}
uint64_t endpointRecoveries()const{return endpointRecoveries_.load();}
@@ -111,6 +116,7 @@ private:
friend class AudioThread;
AudioFormat pcmFormat_;
+ std::vector<media::AudioTrack> tracks_;
AVFormatContext* fmt_ = nullptr;
AVCodecContext* codecCtx_ = nullptr;
AVStream* stream_ = nullptr;
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 15228617..08fbed39 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -1,4 +1,5 @@
#include "veyra/engine/EngineController.h"
+#include "veyra/engine/FgCompatibilityProbe.h"
#include "veyra/engine/VideoPresenter.h"
#include "veyra/engine/VideoExportJob.h"
#include "veyra/engine/LivePresentationTiming.h"
@@ -85,6 +86,12 @@ void EngineController::remotePlayLoginPin(std::string pin){std::lock_guard lock(
void EngineController::stop(){std::lock_guard lock(mutex_);stop_=true;pending_={};snapshot_.transport=busy_?TransportState::Stopping:TransportState::Empty;}
void EngineController::pause(bool p){paused_=p;std::lock_guard lock(mutex_);if(snapshot_.running)snapshot_.transport=p?TransportState::Paused:TransportState::Playing;}
void EngineController::setVolume(float gain,bool mute){if(!std::isfinite(gain))return;volume_=std::clamp(gain,0.0f,1.0f);muted_=mute;}
+bool EngineController::selectAudioTrack(uint64_t session,int streamIndex){
+ std::lock_guard lock(mutex_);
+ if(session!=snapshot_.sessionId||!snapshot_.running||snapshot_.failed||snapshot_.capture||snapshot_.image)return false;
+ if(std::none_of(snapshot_.audioTracks.begin(),snapshot_.audioTracks.end(),[&](const auto& t){return t.streamIndex==streamIndex;}))return false;
+ pendingAudioSession_=session;pendingAudioTrack_=streamIndex;return true;
+}
bool EngineController::requestSettings(EnhancementSettings s){
if(!s.validate().empty()){veyra::log::warn("settings","invalid whole settings transaction rejected");status(L"整套设置无效,未应用任何字段",false);return false;}
std::lock_guard lock(mutex_);if(snapshot_.image)s.multiplier=1;
@@ -123,7 +130,8 @@ bool EngineController::requestSettings(EnhancementSettings s){
}
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){
- const auto frozen=opts.snapshot();post([this,input,output,frozen,hevc]{CoInitializeEx(nullptr,COINIT_MULTITHREADED);bool ok=exportVideo(input,output,PlayerOptions::from(frozen),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();});
+ const auto frozen=opts.snapshot();const int audioStream=opts.audioStreamIndex;
+ post([this,input,output,frozen,audioStream,hevc]{CoInitializeEx(nullptr,COINIT_MULTITHREADED);auto options=PlayerOptions::from(frozen);options.audioStreamIndex=audioStream;bool ok=exportVideo(input,output,options,hevc,stop_,[this](double p,const std::wstring& s){std::lock_guard lock(mutex_);snapshot_.status=s;snapshot_.position=p;snapshot_.duration=1;snapshot_.running=true;});{std::lock_guard lock(mutex_);snapshot_.running=false;snapshot_.failed=!ok&&!stop_;}CoUninitialize();});
}
PlayerSnapshot EngineController::snapshot()const{
std::lock_guard lock(mutex_);auto copy=snapshot_;copy.volume=volume_;copy.muted=muted_;
@@ -165,7 +173,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
#endif
const bool isCapture=physicalCapture||options.captureReplayForTest||isRemote;
const bool pairAnchoredLive=physicalCapture||options.captureReplayForTest||isRemote;
- const bool useLiveFgAdmission=!(options.captureReplayForTest&&options.captureReplayDisableFgAdmissionForTest);
+ const bool useLiveFgAdmission=!options.captureReplayDisableFgAdmissionForTest;
source::IFrameSource* activeSource=physicalCapture?static_cast<source::IFrameSource*>(&captureSource):&source;
#ifdef VEYRA_ENABLE_REMOTEPLAY
if(remote)activeSource=remote.get();
@@ -274,6 +282,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
gd.hdrOutput=options.settings.useHdrPreview(gd.hdrInput,gfx::PresentSink::hdrDisplayActive(window));
veyra::log::info("display-color",std::format("hdrInput={} hdrOutput={} forceSdrPreview={}",gd.hdrInput,gd.hdrOutput,options.settings.forceSdrPreview));
gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
+ gd.compatibilityPreflight=[this](const auto& desc,const auto& device){return checkFgCompatibility(desc,device,stop_);};
std::wstring backendRecoveryWarning;
auto initializePreview=[&](pipeline::EnhanceGraphDesc& desc,PlayerOptions& selected){
backendRecoveryWarning.clear();
@@ -347,13 +356,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
}
return false;
};
- const auto initialRequested=options.snapshot();
- const bool previewInitialized=initializePreview(gd,options);
- {
- // Publish the runtime's multi-frame capability so the UI can
- // offer only what this GPU can honour (Ada=2X, Blackwell=6X).
- // Published on failure too: a rejected multiplier must still
- // teach the settings UI what the ceiling is.
+ auto publishFrameGenerationCapabilities=[&]{
+ // Read the active provider after every rebuild or rollback;
+ // an initial effects-off graph has no DLSS capability yet.
std::lock_guard lock(mutex_);
fgMultiFrameMaxCap_=graph.fgMultiFrameCountMax();
snapshot_.fgMultiFrameMax=fgMultiFrameMaxCap_;
@@ -370,7 +375,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(fgMultiFrameMaxCap_>0)veyra::log::info("settings",std::format("frame-generation capability: maxGeneratedFrames={} maxMultiplier={}",fgMultiFrameMaxCap_,fgMultiFrameMaxCap_+1));
veyra::log::info("settings",std::format("xess capability: maxInterpolatedFrames={} unlockApplied={} => maxMultiplier={}",xessState.maxInterpolations,xessState.applied,xessMaxInterpolatedFramesCap_+1));
if(fsrMaxGeneratedFramesCap_>0)veyra::log::info("settings",std::format("fsr capability: generatedPerPresent={} => maxMultiplier={}",fsrMaxGeneratedFramesCap_,fsrMaxGeneratedFramesCap_+1));
- }
+ };
+ const auto initialRequested=options.snapshot();
+ const bool previewInitialized=initializePreview(gd,options);
+ publishFrameGenerationCapabilities();
if(!previewInitialized){status(L"视频初始化失败,请查看对应组件的诊断日志",true);break;}
if(!backendRecoveryWarning.empty()){
std::lock_guard lock(mutex_);desired_.rejectVideoRequest(initialRequested,options.snapshot());snapshot_.desired=desired_;snapshot_.backendWarning=backendRecoveryWarning;
@@ -401,6 +409,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
uint64_t seekDecoded=0;
bool fileAwaitingVideo=true,fileAudioAlignPending=true,fileInputEnded=false;double lastFilePresentedMs=0,lastFilePresentLateness=0;std::deque<double> latenessSamples;
if(!isImage&&!isCapture&&audioPipe.open(path)){
+ {std::lock_guard lock(mutex_);snapshot_.audioTracks=audioPipe.tracks();snapshot_.selectedAudioTrack=audioPipe.selectedTrack();}
audioPipe.holdForVideo();audioPipe.startThread(&audio,true);audioStarted=true;
std::lock_guard lock(mutex_);snapshot_.audioAvailable=true;
}
@@ -447,9 +456,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// and may skip expired enhancement opportunities, never PCM.
// Graph, query collection and presentation remain on this owner.
graph.recordGpuTimings();presenter.recordGpuTimings();
- struct LiveStats {pipeline::FrameIdentity identity;uint64_t submitted=0,expired=0;double waitMs=0,presentMs=0,readyMs=0,ageMs=0,fps=0,ageP95=0,waitP95=0,presentP95=0,readyP95=0;diagnostics::GpuSample blit;};
+ struct LiveStats {uint64_t submitted=0,expired=0;double waitMs=0,presentMs=0,readyMs=0,ageMs=0,fps=0,ageP95=0,waitP95=0,presentP95=0,readyP95=0;diagnostics::GpuSample blit;};
LiveStats liveStats;std::deque<int64_t> liveSubmissions;
- TimingWindow liveAges,liveWaits,livePresent,liveReady;
+ TimingWindow liveAges,liveWaits,liveReady;
+ TimingWindow livePresent{std::chrono::seconds(1)};
+ TimingWindow livePresentService{std::chrono::seconds(1)};
FgRecoveryBudget fgBudget;uint64_t fgBudgetRevision=options.settings.revision;
int64_t nextFgAdmissionLog=0;
std::atomic<uint64_t> historyResets=0,presentationDrains=0,presentationCompletedReal=0,presentationSkippedGenerated=0,presentationCancelledJobs=0;
@@ -463,7 +474,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
bool real=false;
std::atomic<bool> ready=false;
Clock::time_point readyObserved{};
- std::array<int64_t,4> frameReadyObserved{};
+ std::array<int64_t,pipeline::FrameBatch::Capacity> frameReadyObserved{};
};
int64_t nextFgDeadlineLog=0;
std::vector<std::shared_ptr<CompletionWatch>> pendingCompletions;
@@ -724,6 +735,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
markResetStage(diagnostics::ResetStage::Create);
if(!accepted){presenter.close();graph.shutdown();if(!graph.initialize(gd)||!presenter.open(ctx,window,graph,options.settings.captureCompatible)||!graph.createViews()){status(L"设置失败且旧资源恢复失败,已停止",true);break;}}
}else if(accepted)accepted=graph.applySettings(requested);
+ if(rebuild)publishFrameGenerationCapabilities();
if(accepted){
if(xessPresentationRecovery){backendRecoveryWarning=L"XeSS 呈现失败,已关闭补帧并恢复播放;错误码见日志";xessPresentationRecovery=false;}
if(fsrPresentationRecovery){backendRecoveryWarning=L"AMD FSR 帧生成呈现失败,已关闭补帧并恢复播放;错误码见日志";fsrPresentationRecovery=false;}
@@ -759,6 +771,20 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
}
}
if(stop_)break;
+ int track=-1;double trackPosition=0;
+ {std::lock_guard lock(mutex_);if(pendingAudioSession_==snapshot_.sessionId)track=pendingAudioTrack_;pendingAudioTrack_=-1;trackPosition=snapshot_.position;}
+ bool switchedAudio=false;
+ if(track>=0&&audioStarted&&track!=audioPipe.selectedTrack()){
+ const double clock=audio.mediaTimeMs();if(std::isfinite(clock))trackPosition=clock/1000;
+ holdFileAudio();audioPipe.stopThread();
+ const bool changed=audioPipe.selectTrack(track);
+ audioPipe.setPaused(paused_);audioPipe.startThread(&audio,true,std::max(0.0,trackPosition*1000));
+ switchedAudio=true;
+ {std::lock_guard lock(mutex_);snapshot_.selectedAudioTrack=audioPipe.selectedTrack();snapshot_.audioInputChannels=audioPipe.pcmFormat().channels;
+ if(!changed)snapshot_.backendWarning=L"音轨切换失败,已保留原音轨";
+ if(seekSeconds_.load()<0){snapshot_.seekTarget=trackPosition;++snapshot_.seekRequested;seekSeconds_=trackPosition;}}
+ log::info("audio-track",std::format("requested={} selected={} changed={} positionSeconds={:.3f}",track,audioPipe.selectedTrack(),changed,trackPosition));
+ }
double seek;{std::lock_guard lock(mutex_);seek=seekSeconds_.exchange(-1);if(seek>=0)activeSeekId=snapshot_.seekRequested;}
if(seek>=0&&!isImage&&!isCapture){
seekStarted=Clock::now();seekDecoded=0;
@@ -767,7 +793,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(!ring.drainQueue()||!activeSource->seek({static_cast<int64_t>(seek*1000000),1000000})){status(L"跳转失败",true);break;}
veyra::log::info("seek-latency",std::format("request={} targetSeconds={:.3f} drainAndDemuxMs={:.3f}",activeSeekId,seek,elapsedMs(seekStarted)));
initialFileFramePending=false;av_frame_free(&cachedFrame);out={};hasOutput=false;
- discardBefore=seek*1000;seekPreviewPending=true;reset=true;pendingResetCause=pipeline::ResetReason::Seek;anchorMs=discardBefore;anchor=Clock::now();lastAudioClockMs=discardBefore;audioClockExhausted=false;audioRebuffering=false;if(audioStarted){audioPipe.setPaused(paused_);audioPipe.requestSeek(discardBefore);}
+ discardBefore=seek*1000;seekPreviewPending=true;reset=true;pendingResetCause=pipeline::ResetReason::Seek;anchorMs=discardBefore;anchor=Clock::now();lastAudioClockMs=discardBefore;audioClockExhausted=false;audioRebuffering=false;if(audioStarted){audioPipe.setPaused(paused_);if(!switchedAudio||std::abs(seek-trackPosition)>.001)audioPipe.requestSeek(discardBefore);}
}
if(!transaction&&((paused_&&!seekPreviewPending)||(isImage&&hasOutput))){
// A parameter change while paused (or on a still image) only
@@ -805,14 +831,15 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// Backpressure before reading the capacity-one source mailbox:
// when a lease frees we consume the newest available sample.
if(liveScheduler&&!transaction){
+ const auto enhancementPending=[&]{return isCapture&&options.fg&&!presentSinkFrameGeneration(options.settings.frameGenerationBackend)&&!pendingCompletions.empty();};
const auto leaseWaitStart=Clock::now();
- while((liveScheduler->occupancy()>=2||!graph.nextFrameSlotAvailable())&&!stop_&&(!paused_||seekPreviewPending)&&!liveScheduler->failed()){
+ while((liveScheduler->occupancy()>=2||!graph.nextFrameSlotAvailable()||enhancementPending())&&!stop_&&(!paused_||seekPreviewPending)&&!liveScheduler->failed()){
advanceLive();if(seekSeconds_>=0)break;
if(liveScheduler->occupancy()==0&&!graph.nextFrameSlotAvailable()&&elapsedMs(leaseWaitStart)>2000){status(L"等待输出纹理释放超时",true);stop_=true;break;}
- if(liveScheduler->occupancy()>=2||!graph.nextFrameSlotAvailable())waitLive();
+ if(liveScheduler->occupancy()>=2||!graph.nextFrameSlotAvailable()||enhancementPending())waitLive();
std::lock_guard lock(mutex_);if(desired_.revision!=options.settings.revision)break;
}
- if(stop_||seekSeconds_>=0||(paused_&&!seekPreviewPending)||liveScheduler->failed()||liveScheduler->occupancy()>=2||!graph.nextFrameSlotAvailable())continue;
+ if(stop_||seekSeconds_>=0||(paused_&&!seekPreviewPending)||liveScheduler->failed()||liveScheduler->occupancy()>=2||!graph.nextFrameSlotAvailable()||enhancementPending())continue;
}
const auto decodeStart=Clock::now();
if(injectSourceGap&&frames>=12){
@@ -939,17 +966,20 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(injectedReject)veyra::log::error("settings-test","test-only reject NR-disable transaction before graph process; no driver failure");
pipeline::EnhanceGraph::FgAdmission admitFg;
if(fgBudgetRevision!=options.settings.revision){fgBudget.reset();fgBudgetRevision=options.settings.revision;}
+ const auto liveInterval=liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps);
+ const auto processingAllowance=isCapture&&options.fg&&!presentSinkFrameGeneration(options.settings.frameGenerationBackend)?
+ fgBudget.processingAllowance(host100ns(),liveInterval):0;
// DLSS can reseed after a skipped pair. XeSS
// owns generation inside its presenter and has no graph admission.
if(isCapture&&!rereadCached&&useLiveFgAdmission&&!presentSinkFrameGeneration(options.settings.frameGenerationBackend)){
- const auto presentP95=livePresent.p95();
+ const auto presentP95=livePresentService.p95();
admitFg=[&,presentP95](const pipeline::FrameBatch& batch){
// Physical capture and PS5 delivery clocks are not
// guaranteed to match the host clock. Anchor each new
// input pair before enhancement, so a 59.94-vs-60Hz
// mismatch cannot accumulate into a stale deadline.
// Never extend it based on processing/ready completion.
- if(pairAnchoredLive)liveTimeline.resetPair(batch.identity.epoch,batch.b100ns,liveInputReady,liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps));
+ if(pairAnchoredLive)liveTimeline.resetPair(batch.identity.epoch,batch.b100ns,liveInputReady,liveInterval+processingAllowance);
else if(!liveTimeline.anchored(batch.identity.epoch))liveTimeline.reset(batch.identity.epoch,batch.b100ns,liveInputReady,liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps));
const auto interval=liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps);
const auto a=(historyReset||batch.b100ns<=batch.a100ns||batch.b100ns-batch.a100ns>10000000)?batch.b100ns-interval:batch.a100ns;
@@ -957,7 +987,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
const auto now=host100ns(),deadline=liveTimeline.deadline(lastGenerated);
const double elapsed=elapsedMs(processStart);
const bool admitted=fgBudget.admit(now,deadline,elapsed,presentP95);
- if(now>=nextFgAdmissionLog){nextFgAdmissionLog=now+10000000;veyra::log::info("live-fg-admission",std::format("timeline={} admitted={} remainingDeadlineMs={:.3f} predictedMs={:.3f} elapsedMs={:.3f} decodedAgeMs={:.3f} callbackAgeMs={:.3f} presentP95Ms={:.3f}",pairAnchoredLive?(isRemote?"decoded-pair":"capture-pair"):"continuous",admitted,double(deadline-now)/10000,fgBudget.predicted(now).value_or(-1),elapsed,double(now-liveInputReady)/10000,double(now-captureArrival)/10000,presentP95));}
+ if(now>=nextFgAdmissionLog){nextFgAdmissionLog=now+10000000;veyra::log::info("live-fg-admission",std::format("timeline={} admitted={} remainingDeadlineMs={:.3f} predictedMs={:.3f} elapsedMs={:.3f} decodedAgeMs={:.3f} callbackAgeMs={:.3f} presentP95Ms={:.3f} processingAllowanceMs={:.3f}",pairAnchoredLive?(isRemote?"decoded-pair":"capture-pair"):"continuous",admitted,double(deadline-now)/10000,fgBudget.predicted(now).value_or(-1),elapsed,double(now-liveInputReady)/10000,double(now-captureArrival)/10000,presentP95,double(processingAllowance)/10000));}
return admitted;
};
}
@@ -972,7 +1002,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
const auto a=(historyReset||batch.b100ns<=batch.a100ns||batch.b100ns-batch.a100ns>10000000)?batch.b100ns-interval:batch.a100ns;
const auto lastGenerated=pipeline::FrameBatch::interpolate(a,batch.b100ns,options.fgMultiplier-1,options.fgMultiplier);
const auto now=host100ns();
- return fgBudget.admit(now,now+lastGenerated-int64_t(nowMs()*10000.0),elapsedMs(processStart),livePresent.p95());
+ return fgBudget.admit(now,now+lastGenerated-int64_t(nowMs()*10000.0),elapsedMs(processStart),livePresentService.p95());
};
}
uint64_t processWaitBase=0,processSubmitBase=0;double processWaitMsBase=0,processSlotWaitMs=0;
@@ -999,6 +1029,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
gd.workWidth=plan.base.width;gd.workHeight=plan.base.height;gd.nrWidth=plan.nr.width;gd.nrHeight=plan.nr.height;gd.flowWidth=plan.flow.width;gd.flowHeight=plan.flow.height;
gd.enableNr=options.nr&&nvidiaAdapter;gd.enableSr=plan.srApplied&&(nvidiaAdapter||options.settings.videoSrQuality==kVideoSrFsr);gd.enableFg=options.fg&&(nvidiaAdapter||presentSinkFrameGeneration(reduced.frameGenerationBackend));gd.fgMultiplier=options.fgMultiplier;gd.enableNvofStandalone=gd.enableNr;gd.settingsRevision=reduced.revision;gd.nrBeforeSr=!isImage&&reduced.lowLatency&&gd.enableNr&&gd.enableSr;
if(!initializePreview(gd,options)){status(L"增强故障后的基础图重建失败",true);break;}
+ publishFrameGenerationCapabilities();
backendRecoveryWarning=std::wstring(backendFailureName(failedComponent))+L"运行失败,已关闭对应效果;错误码见日志"+(backendRecoveryWarning.empty()?L"":L";"+backendRecoveryWarning);
{std::lock_guard lock(mutex_);desired_.rejectVideoRequest(attempted,options.snapshot());snapshot_.desired=desired_;snapshot_.applied=options.snapshot();snapshot_.applying=desired_!=snapshot_.applied;snapshot_.backendWarning=backendRecoveryWarning;}
veyra::log::warn("backend-recovery",std::format("runtime component={} disabled; rebuilt revision={} nr={} sr={} multiplier={}; retry next source frame",unsigned(failedComponent),options.settings.revision,options.nr,options.sr,options.snapshot().multiplier));
@@ -1011,6 +1042,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
ring.drainQueue();out={};presenter.close();graph.shutdown();options=PlayerOptions::from(previous);
gd=previousDesc;
if(graph.initialize(gd)&&presenter.open(ctx,window,graph,options.settings.captureCompatible)&&graph.createViews()&&graph.process(frame,pts,true,out,pkt.sequence,&pkt.colorInfo,&pkt.hardwareSurface,comparisonMode_!=0)){
+ publishFrameGenerationCapabilities();
finishReset(diagnostics::ResetOutcome::RolledBack);
std::lock_guard lock(mutex_);desired_.rejectVideoRequest(requested,previous);snapshot_.desired=desired_;snapshot_.rejectedRevision=requested.revision;snapshot_.applying=desired_!=previous;snapshot_.status=L"参数执行失败,已整套回滚";transaction=false;
}else{status(L"参数回滚失败,已停止",true);break;}
@@ -1042,7 +1074,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// soft preview-skip history breaks do NOT reopen them.
if(settingsChanged){xessGenerationGate.reset();presenter.setXessGenerationSuppressed(false);fedXessPresented=fedXessGenerated=fedFsrPresented=fedFsrGenerated=0;}
playbackSpeedLastWall={};
- if(liveScheduler){liveStats={};liveStats.identity=out.batch.identity;liveSubmissions.clear();liveAges.clear();liveWaits.clear();livePresent.clear();liveReady.clear();}
+ if(liveScheduler){liveStats={};liveSubmissions.clear();liveAges.clear();liveWaits.clear();livePresent.clear();livePresentService.clear();liveReady.clear();}
if(settingsChanged||!completionRates)completionRates=std::make_shared<FrameCompletionRates>(host100ns());
frameFlow=std::shared_ptr<FrameFlowWindow>(new FrameFlowWindow(runSessionId,out.batch.identity,host100ns(),completionRates),[](FrameFlowWindow* window){logFrameFlow(window->snapshot(monotonic100ns()),"closed");delete window;});
if(resetRecord)frameFlow->resetLifecycle(*resetRecord);else if(lastResetRecord)frameFlow->resetLifecycle(*lastResetRecord);
@@ -1079,7 +1111,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// clock. Physical capture without FG presents as soon as ready.
const bool paceSourcePts=options.fg||!physicalCapture;
if(!liveTimeline.anchored(out.batch.identity.epoch)||(pairPacing&&frames==0))veyra::log::info("capture-timeline",std::format("interval100ns={} packetDurationKnown={} packetDurationPositive={} nominalFps={} FG={} pacing={}",duration100ns,!pkt.duration.isUnknown(),pkt.duration.num>0,activeSource->info().averageFps,options.fg,pairAnchoredLive?(isRemote?"decoded-pair":"capture-pair"):paceSourcePts?"source-pts":"capture-ready"));
- if(pairPacing||isRemote)liveTimeline.resetPair(out.batch.identity.epoch,out.batch.b100ns,liveInputReady,options.fg?duration100ns:0,paceSourcePts);
+ if(pairPacing||isRemote)liveTimeline.resetPair(out.batch.identity.epoch,out.batch.b100ns,liveInputReady,options.fg?duration100ns+processingAllowance:0,paceSourcePts);
else if(!liveTimeline.anchored(out.batch.identity.epoch))liveTimeline.reset(out.batch.identity.epoch,out.batch.b100ns,liveInputReady,options.fg?duration100ns:0,paceSourcePts);
}
if(!isImage&&!isCapture&&frames==0){anchor=Clock::now();anchorMs=lastAudioClockMs=pts;}
@@ -1146,9 +1178,18 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
}
const auto waited=elapsedMs(*s.deadlineStart);s.deadlineStart.reset();s.waitMs+=waited;flow->cpu(diagnostics::CpuStage::DeadlineWait,waited,host100ns());
const auto begin=Clock::now();const auto before=presenter.submittedCount();
+ const auto presentSlotWaitBefore=presenter.cpuWaitMilliseconds(ring);
if(!presenter.present(ctx,ring,graph,item.lease->slot,generated,item.lease->referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity,previewView()))return {State::Failed};
- item.lease->consumerFence=ring.lastSignaledValue();const bool didPresent=presenter.submittedCount()>before;s.blit=presenter.blitTiming(ctx.fence());
+ item.lease->consumerFence=presenter.consumerFenceValue(ring.lastSignaledValue());const bool didPresent=presenter.submittedCount()>before;s.blit=presenter.blitTiming(ctx.fence());
const auto elapsed=elapsedMs(begin);s.presentMs+=elapsed;flow->cpu(diagnostics::CpuStage::Present,elapsed,host100ns());
+ // A soft history reset retains this metrics window. Older
+ // session/revision windows must not update its admission cost.
+ if(flow==frameFlow){
+ livePresent.add(elapsed);
+ // Allocator reuse waits on graph work already charged
+ // by GPU timestamps; it is not additional blit service.
+ livePresentService.add(std::max(0.0,elapsed-(presenter.cpuWaitMilliseconds(ring)-presentSlotWaitBefore)));
+ }
if(didPresent){
traceFrame(diagnostics::TraceKind::Present,item.identity,batch.batch.batchId,item.lease->consumerFence,item.pts100ns,item.subframe,1,elapsed);
if(veyra::log::verboseFrameLogs())veyra::log::info("submit",std::format("batch={} epoch={} revision={} subframe={} pts100ns={} host100ns={} fence={} (submission, display unmeasured)",batch.batch.batchId,item.identity.epoch,item.identity.settingsRevision,item.subframe,item.pts100ns,host100ns(),item.lease->consumerFence));
@@ -1175,8 +1216,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
double nextPts=itemPtsMs+sourceIntervalMs;
for(unsigned next=s.next+1;next<batch.batch.count;++next){const auto& candidate=batch.batch.frames[next];if(candidate.kind!=pipeline::FrameKind::Generated||(candidate.validity==pipeline::GenerationValidity::Valid&&comparisonMode_==0)){nextPts=double(candidate.pts100ns)/10000;break;}}
if(audioStarted){audioPipe.videoPresented(nextPts);audioPipe.setPaused(paused_);}
- if(fileAwaitingVideo)veyra::log::info("audio-sync",std::format("file lookahead anchor ptsMs={:.3f} queued={} (continuous audio after bounded prefill)",itemPtsMs,liveScheduler->occupancy()));
- fileAwaitingVideo=false;anchor=Clock::now();anchorMs=itemPtsMs;seekPreviewPending=false;
+ if(fileAwaitingVideo){
+ veyra::log::info("audio-sync",std::format("file lookahead anchor ptsMs={:.3f} queued={} (continuous audio after bounded prefill)",itemPtsMs,liveScheduler->occupancy()));
+ // Silent playback keeps one wall-clock origin between
+ // transport changes; per-frame reanchoring hides lateness.
+ anchor=Clock::now();anchorMs=itemPtsMs;
+ }
+ fileAwaitingVideo=false;seekPreviewPending=false;
if(graph.xessEnabled()&&presenter.xessActive()&&xessGenerationGate.observe(nowMs()-itemPtsMs,sourceIntervalMs)){
presenter.setXessGenerationSuppressed(xessGenerationGate.suppressed());
veyra::log::info("xess-fg-gate",std::format("event={} revision={} lateMs={:.3f}",xessGenerationGate.suppressed()?"suppress":"resume",item.identity.settingsRevision,nowMs()-itemPtsMs));
@@ -1201,7 +1247,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
}
if(didPresent&&generated&&lineage)flow->generatedLatency(*lineage,host100ns());
if(didPresent){++s.handled;++s.count;flow->presented(generated,item.lease->consumerFence,host100ns());if(!generated)++presentationCompletedReal;s.ageMs=double(host100ns()-captureArrival)/10000;
- if(liveStats.identity.epoch==batch.batch.identity.epoch&&liveStats.identity.settingsRevision==batch.batch.identity.settingsRevision){const auto time=host100ns();liveSubmissions.push_back(time);while(liveSubmissions.size()>1&&time-liveSubmissions.front()>10000000)liveSubmissions.pop_front();}}
+ if(flow==frameFlow){const auto time=host100ns();liveSubmissions.push_back(time);while(liveSubmissions.size()>1&&time-liveSubmissions.front()>10000000)liveSubmissions.pop_front();}}
++s.next;
}
return {State::Complete};
@@ -1211,10 +1257,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(s.handled<batch.batch.count)++presentationCancelledJobs;
if(s.handled<batch.batch.count)traceFrame(diagnostics::TraceKind::Cancelled,batch.batch.identity,batch.batch.batchId,0,batch.batch.b100ns,0,batch.batch.count-s.handled,0);
flow->update([&](auto& m){m.counters.cancelledBeforePresent+=batch.batch.count-s.handled;m.gpuReadyWaitMs=s.readyMs;m.deadlineWaitMs=s.waitMs;if(s.count)m.captureArrivalToPresentReturnMs=s.ageMs;m.counters.generatedExpiredAfterEval+=s.dropped;});
- if(liveStats.identity.epoch!=batch.batch.identity.epoch||liveStats.identity.settingsRevision!=batch.batch.identity.settingsRevision)return;
+ if(flow!=frameFlow)return;
liveStats.submitted+=s.count;liveStats.expired+=s.dropped;
if(s.count){liveStats.waitMs=s.waitMs;liveStats.presentMs=s.presentMs;liveStats.readyMs=s.readyMs;liveStats.ageMs=s.ageMs;liveStats.blit=s.blit;
- liveAges.add(s.ageMs);liveWaits.add(s.waitMs);livePresent.add(s.presentMs);liveReady.add(s.readyMs);liveStats.ageP95=liveAges.p95();liveStats.waitP95=liveWaits.p95();liveStats.presentP95=livePresent.p95();liveStats.readyP95=liveReady.p95();}
+ liveAges.add(s.ageMs);liveWaits.add(s.waitMs);liveReady.add(s.readyMs);liveStats.ageP95=liveAges.p95();liveStats.waitP95=liveWaits.p95();liveStats.presentP95=livePresent.p95();liveStats.readyP95=liveReady.p95();}
liveStats.fps=liveSubmissions.size()>1?double(liveSubmissions.size()-1)*1e7/(liveSubmissions.back()-liveSubmissions.front()):0;
})){status(L"视频呈现队列失败",true);break;}
frameFlow->update([&](auto& m){m.pendingOutputFrames+=step->remaining;});
@@ -1238,7 +1284,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(!item.lease)continue;
const auto begin=Clock::now();const auto before=presenter.submittedCount();
if(!presenter.present(ctx,ring,graph,item.lease->slot,false,item.lease->referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity,previewView())){presentFailed=true;break;}
- item.lease->consumerFence=ring.lastSignaledValue();framePresentMs+=elapsedMs(begin);
+ item.lease->consumerFence=presenter.consumerFenceValue(ring.lastSignaledValue());framePresentMs+=elapsedMs(begin);
frameFlow->cpu(diagnostics::CpuStage::Present,elapsedMs(begin),host100ns());
if(presenter.submittedCount()>before){++submitted;frameFlow->presented(false,item.lease->consumerFence,host100ns());}
}
diff --git a/src/engine/ExportJobManager.cpp b/src/engine/ExportJobManager.cpp
index cfed14b9..b14e8435 100644
--- a/src/engine/ExportJobManager.cpp
+++ b/src/engine/ExportJobManager.cpp
@@ -8,19 +8,27 @@
#include <type_traits>
namespace veyra::engine {
namespace {
+std::string utf8(std::wstring_view value) {
+ if(value.empty())return {};
+ const int bytes=WideCharToMultiByte(CP_UTF8,0,value.data(),int(value.size()),nullptr,0,nullptr,nullptr);
+ std::string result(bytes,'\0');
+ if(bytes)WideCharToMultiByte(CP_UTF8,0,value.data(),int(value.size()),result.data(),bytes,nullptr,nullptr);
+ return result;
+}
constexpr DWORD magic=0x56585931;
struct Shared {
- DWORD signature=magic,version=1,bytes=sizeof(Shared);
+ DWORD signature=magic,version=2,bytes=sizeof(Shared);
EnhancementSettings settings;
wchar_t input[32768]{},output[32768]{};
unsigned hevc=0,maxFrames=0;
+ int audioStreamIndex=-1;
volatile LONG64 sourceFrames=0,generated=0,holds=0,encoded=0;
volatile LONG messageLock=0;wchar_t message[1024]{};
volatile LONG cancel=0,pause=0,watching=0,state=LONG(ExportState::Preparing),progress=0;
};
static_assert(std::is_trivially_copyable_v<Shared>);
void close(HANDLE& h){if(h&&h!=INVALID_HANDLE_VALUE)CloseHandle(h);h=nullptr;}
-const wchar_t* label(ExportState s){switch(s){case ExportState::Preparing:return L"正在准备独立导出任务";case ExportState::Running:return L"正在编码 · 原生NR · D3D12 NVENC";case ExportState::Paused:return L"导出已暂停,观看继续";case ExportState::Finishing:return L"正在封装和验证输出";case ExportState::Succeeded:return L"导出完成,输出解码验证通过";case ExportState::Failed:return L"导出失败;详见独立任务日志,partial已保留";case ExportState::Cancelled:return L"导出已取消;已写入的partial保留";default:return L"尚无导出任务";}}
+const wchar_t* label(ExportState s){switch(s){case ExportState::Preparing:return L"正在准备独立导出任务";case ExportState::Running:return L"正在编码";case ExportState::Paused:return L"导出已暂停,观看继续";case ExportState::Finishing:return L"正在封装和保存输出";case ExportState::Succeeded:return L"导出完成";case ExportState::Failed:return L"导出失败;详见独立任务日志,partial已保留";case ExportState::Cancelled:return L"导出已取消;已写入的partial保留";default:return L"尚无导出任务";}}
}
struct ExportJobManager::Impl {
HANDLE mapping=nullptr,process=nullptr,job=nullptr;Shared* shared=nullptr;
@@ -30,7 +38,7 @@ struct ExportJobManager::Impl {
};
ExportJobManager::ExportJobManager():p_(std::make_unique<Impl>()){}
ExportJobManager::~ExportJobManager(){cancel();if(p_->process)WaitForSingleObject(p_->process,5000);p_->clear();}
-bool ExportJobManager::start(const std::wstring& input,const std::wstring& output,EnhancementSettings settings,bool hevc,unsigned maxFrames){
+bool ExportJobManager::start(const std::wstring& input,const std::wstring& output,EnhancementSettings settings,bool hevc,unsigned maxFrames,int audioStreamIndex){
if(poll().active())return false;p_->clear();p_->snapshot={};
auto fail=[&](const wchar_t* message){const DWORD error=GetLastError();p_->clear();p_->snapshot.state=ExportState::Failed;p_->snapshot.message=message;log::error("export-worker",std::format("launch failed error={}",error));return false;};
if(input.empty()||output.empty()||input.size()>=32768||output.size()>=32768||!settings.validate().empty()||input.starts_with(L"capture:")||input.starts_with(L"capture2:"))return fail(L"请选择本地视频与有效导出设置");
@@ -40,6 +48,7 @@ bool ExportJobManager::start(const std::wstring& input,const std::wstring& outpu
if(!p_->mapping)return fail(L"无法创建导出通信资源");
p_->shared=static_cast<Shared*>(MapViewOfFile(p_->mapping,FILE_MAP_ALL_ACCESS,0,0,sizeof(Shared)));if(!p_->shared)return fail(L"无法映射导出通信资源");
new(p_->shared) Shared{};auto& s=*p_->shared;s.settings=settings;s.settings.nrPolicy=pipeline::NrSizePolicy::Native;s.hevc=hevc;s.maxFrames=maxFrames;
+ s.audioStreamIndex=audioStreamIndex;
wcscpy_s(s.input,input.c_str());wcscpy_s(s.output,output.c_str());
p_->job=CreateJobObjectW(nullptr,nullptr);JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if(!p_->job||!SetInformationJobObject(p_->job,JobObjectExtendedLimitInformation,&limits,sizeof(limits)))return fail(L"无法建立导出进程生命周期");
@@ -54,7 +63,9 @@ bool ExportJobManager::start(const std::wstring& input,const std::wstring& outpu
if(!AssignProcessToJobObject(p_->job,p_->process)){TerminateProcess(p_->process,1);CloseHandle(pi.hThread);return fail(L"导出进程隔离失败");}
if(ResumeThread(pi.hThread)==DWORD(-1)){TerminateProcess(p_->process,1);CloseHandle(pi.hThread);return fail(L"无法运行导出进程");}CloseHandle(pi.hThread);
p_->snapshot.state=ExportState::Preparing;p_->snapshot.output=output;p_->snapshot.jobId=(GetTickCount64()<<16)^pi.dwProcessId;p_->snapshot.frozenRevision=settings.revision;p_->snapshot.frozen=s.settings;
- log::info("export-worker",std::format("started pid={} frozenRevision={} nativeNR=true independentPlayback=true",pi.dwProcessId,settings.revision));return true;
+ p_->snapshot.workerPid=pi.dwProcessId;
+ p_->snapshot.workerLog=std::filesystem::absolute(runtime::logsDirectory()/std::format("export-worker-{}.log",pi.dwProcessId)).wstring();
+ log::info("export-worker",std::format("started jobId={} pid={} frozenRevision={} nativeNR=true independentPlayback=true log={}",p_->snapshot.jobId,pi.dwProcessId,settings.revision,std::filesystem::path(p_->snapshot.workerLog).string()));return true;
}
void ExportJobManager::cancel(){if(p_->shared&&p_->snapshot.active()){InterlockedExchange(&p_->shared->cancel,1);if(!p_->cancelAt)p_->cancelAt=GetTickCount64();}}
void ExportJobManager::pause(bool v){if(p_->shared)InterlockedExchange(&p_->shared->pause,v);}
@@ -64,15 +75,19 @@ ExportJobSnapshot ExportJobManager::poll(){
auto& s=*p_->shared;p_->snapshot.sourceFrames=InterlockedCompareExchange64(&s.sourceFrames,0,0);p_->snapshot.generated=InterlockedCompareExchange64(&s.generated,0,0);p_->snapshot.holds=InterlockedCompareExchange64(&s.holds,0,0);p_->snapshot.encoded=InterlockedCompareExchange64(&s.encoded,0,0);p_->snapshot.state=static_cast<ExportState>(InterlockedCompareExchange(&s.state,0,0));p_->snapshot.progress=InterlockedCompareExchange(&s.progress,0,0)/10000.0;
if(p_->cancelAt&&GetTickCount64()-p_->cancelAt>5000&&WaitForSingleObject(p_->process,0)==WAIT_TIMEOUT)TerminateJobObject(p_->job,3);
if(WaitForSingleObject(p_->process,0)==WAIT_OBJECT_0){DWORD code=1;GetExitCodeProcess(p_->process,&code);p_->snapshot.state=code==0?ExportState::Succeeded:code==3||p_->cancelAt?ExportState::Cancelled:ExportState::Failed;if(code==0)p_->snapshot.progress=1;
- // The completed worker owns the final failure explanation, including
- // whether preflight stopped before a partial file was ever created.
- const bool explained=p_->snapshot.state==ExportState::Failed&&InterlockedCompareExchange(&s.state,0,0)==LONG(ExportState::Failed)&&s.message[0];
- p_->snapshot.message=explained?s.message:label(p_->snapshot.state);p_->clear();}
+ // Preserve the worker's actual outcome, including codec substitutions.
+ const bool explained=(p_->snapshot.state==ExportState::Failed||p_->snapshot.state==ExportState::Succeeded)&&InterlockedCompareExchange(&s.state,0,0)==LONG(p_->snapshot.state)&&s.message[0];
+ p_->snapshot.message=explained?s.message:label(p_->snapshot.state);
+ const auto& final=p_->snapshot;
+ log::info("export-worker",std::format("finished jobId={} pid={} exit={} state={} source={} generated={} holds={} encoded={} log={}",final.jobId,final.workerPid,code,int(final.state),final.sourceFrames,final.generated,final.holds,final.encoded,std::filesystem::path(final.workerLog).string()));
+ log::info("export-worker",utf8(final.message));
+ if(final.state==ExportState::Failed)p_->snapshot.message+=L"\n日志:"+final.workerLog;
+ p_->clear();}
if(p_->shared&&InterlockedCompareExchange(&p_->shared->messageLock,1,0)==0){if(p_->shared->message[0])p_->snapshot.message=p_->shared->message;InterlockedExchange(&p_->shared->messageLock,0);}if(p_->snapshot.message.empty()||p_->snapshot.state==ExportState::Paused||p_->snapshot.state==ExportState::Cancelled)p_->snapshot.message=label(p_->snapshot.state);return p_->snapshot;
}
int runExportWorker(HANDLE mapping){
auto s=static_cast<Shared*>(MapViewOfFile(mapping,FILE_MAP_ALL_ACCESS,0,0,sizeof(Shared)));if(!s)return 1;
- if(s->signature!=magic||s->version!=1||s->bytes!=sizeof(Shared)||!s->settings.validate().empty()||s->input[32767]||s->output[32767]){UnmapViewOfFile(s);CloseHandle(mapping);return 1;}
+ if(s->signature!=magic||s->version!=2||s->bytes!=sizeof(Shared)||s->audioStreamIndex< -1||!s->settings.validate().empty()||s->input[32767]||s->output[32767]){UnmapViewOfFile(s);CloseHandle(mapping);return 1;}
Logger::instance().openFile((runtime::logsDirectory()/std::format("export-worker-{}.log",GetCurrentProcessId())).wstring());
const auto settings=s->settings;log::info("export-frozen",std::format("revision={} nr={} sr={} multiplier={} intensity={} tone={} structure={} skin={} style={} autoMask={} ui={} total={} darken={} brighten={} color={} luminance={} flow={} content={} nativeNR=true",settings.revision,settings.nr,settings.sr,settings.multiplier,settings.model.intensity,settings.model.tone,settings.model.structure,settings.model.skin,settings.model.style,settings.model.autoMask,settings.model.uiCorrection,settings.residual.total,settings.residual.darken,settings.residual.brighten,settings.residual.color,settings.residual.luminance,int(settings.flow),int(settings.content)));std::atomic<bool> cancel=false,done=false;
std::thread monitor([&]{while(!done){if(InterlockedCompareExchange(&s->cancel,0,0))cancel=true;std::this_thread::sleep_for(std::chrono::milliseconds(10));}});
@@ -84,7 +99,8 @@ int runExportWorker(HANDLE mapping){
if(InterlockedCompareExchange(&s->watching,0,0))for(int i=0;i<5&&!cancel;++i)std::this_thread::sleep_for(std::chrono::milliseconds(10));
return !cancel;
};
- bool ok=false;try{ok=exportVideo(s->input,s->output,PlayerOptions::from(settings),s->hevc!=0,cancel,[&](double p,const std::wstring& message){if(InterlockedCompareExchange(&s->messageLock,1,0)==0){wcsncpy_s(s->message,message.c_str(),_TRUNCATE);InterlockedExchange(&s->messageLock,0);}
+ auto options=PlayerOptions::from(settings);options.audioStreamIndex=s->audioStreamIndex;
+ bool ok=false;try{ok=exportVideo(s->input,s->output,options,s->hevc!=0,cancel,[&](double p,const std::wstring& message){if(InterlockedCompareExchange(&s->messageLock,1,0)==0){wcsncpy_s(s->message,message.c_str(),_TRUNCATE);InterlockedExchange(&s->messageLock,0);}
InterlockedExchange(&s->progress,LONG(std::clamp(p,0.0,.999)*10000));if(p>=.99)InterlockedExchange(&s->state,LONG(ExportState::Finishing));},s->maxFrames,frameBoundary,[&](const ExportCounts& count){InterlockedExchange64(&s->sourceFrames,count.source);InterlockedExchange64(&s->generated,count.generated);InterlockedExchange64(&s->holds,count.holds);InterlockedExchange64(&s->encoded,count.encoded);});}catch(...){log::error("export-worker","unhandled job exception");}
done=true;monitor.join();InterlockedExchange(&s->state,LONG(ok?ExportState::Succeeded:cancel?ExportState::Cancelled:ExportState::Failed));UnmapViewOfFile(s);CloseHandle(mapping);return ok?0:cancel?3:1;
}
diff --git a/src/engine/FgCompatibilityProbe.cpp b/src/engine/FgCompatibilityProbe.cpp
new file mode 100644
index 00000000..d2bce8b2
--- /dev/null
+++ b/src/engine/FgCompatibilityProbe.cpp
@@ -0,0 +1,177 @@
+#include "veyra/engine/FgCompatibilityProbe.h"
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/ngx/FgCompatibilitySession.h"
+#include "veyra/FileIdentity.h"
+#include "veyra/RuntimePaths.h"
+#include "veyra/Log.h"
+#include <algorithm>
+#include <cstdlib>
+#include <format>
+#include <mutex>
+#include <set>
+#include <type_traits>
+extern "C" {
+#include <libavutil/frame.h>
+#include <libavutil/pixfmt.h>
+}
+namespace veyra::engine {
+namespace {
+std::wstring executable;
+std::mutex cacheMutex;
+std::set<std::wstring> passed;
+constexpr DWORD signature=0x56464732;
+struct Shared {
+ DWORD magic=signature,bytes=sizeof(Shared);
+ uint64_t luid=0;
+ uint32_t width=0,height=0,multiplier=0,hdr=0;
+ wchar_t runtime[32768]{};
+ char hash[65]{};
+ volatile LONG stage=0,generated=0;
+};
+static_assert(std::is_trivially_copyable_v<Shared>);
+struct Handle {
+ HANDLE value=nullptr;
+ ~Handle(){if(value&&value!=INVALID_HANDLE_VALUE)CloseHandle(value);}
+};
+struct View {
+ Shared* value=nullptr;
+ ~View(){if(value)UnmapViewOfFile(value);}
+};
+std::filesystem::path logPath(DWORD pid){return runtime::logsDirectory()/std::format("fg-probe-{}.log",pid);}
+[[noreturn]] void failProbe(Shared& shared, const char* operation) {
+ // This disposable process owns all probe resources. A failed provider may
+ // hold an internal lock, so neither ReleaseFeature nor DLL detach is safe.
+ InterlockedExchange(&shared.stage,-1);
+ log::error("fg-probe",std::format("{} failed; terminating isolated probe before provider teardown",operation));
+ Logger::instance().flush();
+ TerminateProcess(GetCurrentProcess(),1);
+ std::abort();
+}
+}
+void setFgCompatibilityProbeExecutable(std::wstring path){executable=std::move(path);}
+bool checkFgCompatibility(const pipeline::EnhanceGraphDesc& desc,const gfx::D3D12DeviceContext& ctx,const std::atomic<bool>& cancel){
+ if(!desc.enableFg||desc.noFeatures||desc.noNgx||desc.frameGenerationBackend!=FrameGenerationBackend::Dlss||
+ !ngx::FgCompatibilitySession::requested(ctx.adapter().vendorId,ctx.adapter().deviceId))return true;
+ if(executable.empty()){
+ log::warn("fg-probe","diagnostic host has no child entry; external test timeout required");return true;
+ }
+ FileIdentity identity;IdentityError error;
+ if(!computeFileIdentity((std::filesystem::path(desc.runtimeAbsPath)/L"nvngx_dlssg.dll").wstring(),identity,error))return false;
+ const auto key=std::format(L"{}:{}:{}:{}:{}:{}:{}:{}",ctx.adapter().luid,ctx.adapter().deviceId,ctx.adapter().driverVersion,
+ std::wstring(identity.sha256Upper.begin(),identity.sha256Upper.end()),desc.workWidth,desc.workHeight,desc.fgMultiplier,desc.hdrOutput);
+ {std::lock_guard lock(cacheMutex);if(passed.contains(key))return !cancel;}
+ if(cancel||desc.runtimeAbsPath.size()>=32768)return false;
+ SECURITY_ATTRIBUTES security{sizeof(security),nullptr,TRUE};
+ Handle mapping{CreateFileMappingW(INVALID_HANDLE_VALUE,&security,PAGE_READWRITE,0,sizeof(Shared),nullptr)};
+ if(!mapping.value)return false;
+ View view{static_cast<Shared*>(MapViewOfFile(mapping.value,FILE_MAP_ALL_ACCESS,0,0,sizeof(Shared)))};
+ if(!view.value)return false;
+ auto& s=*new(view.value) Shared{};
+ s.luid=ctx.adapter().luid;s.width=desc.workWidth;s.height=desc.workHeight;s.multiplier=desc.fgMultiplier;s.hdr=desc.hdrOutput;
+ wcscpy_s(s.runtime,desc.runtimeAbsPath.c_str());strcpy_s(s.hash,identity.sha256Upper.c_str());
+ Handle job{CreateJobObjectW(nullptr,nullptr)};
+ JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
+ if(!job.value||!SetInformationJobObject(job.value,JobObjectExtendedLimitInformation,&limits,sizeof(limits)))return false;
+ SIZE_T bytes=0;InitializeProcThreadAttributeList(nullptr,1,0,&bytes);std::vector<std::byte> attrs(bytes);
+ STARTUPINFOEXW startup{};startup.StartupInfo.cb=sizeof(startup);startup.StartupInfo.dwFlags=STARTF_USESHOWWINDOW;startup.StartupInfo.wShowWindow=SW_HIDE;
+ startup.lpAttributeList=reinterpret_cast<PPROC_THREAD_ATTRIBUTE_LIST>(attrs.data());
+ if(!InitializeProcThreadAttributeList(startup.lpAttributeList,1,0,&bytes))return false;
+ const bool inherited=UpdateProcThreadAttribute(startup.lpAttributeList,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,&mapping.value,sizeof(HANDLE),nullptr,nullptr)!=FALSE;
+ auto command=std::format(L"\"{}\" --fg-compat-probe {}",executable,reinterpret_cast<uintptr_t>(mapping.value));
+ PROCESS_INFORMATION info{};
+ const bool started=inherited&&CreateProcessW(executable.c_str(),command.data(),nullptr,nullptr,TRUE,
+ EXTENDED_STARTUPINFO_PRESENT|CREATE_NO_WINDOW|CREATE_SUSPENDED,nullptr,nullptr,&startup.StartupInfo,&info);
+ DeleteProcThreadAttributeList(startup.lpAttributeList);SetHandleInformation(mapping.value,HANDLE_FLAG_INHERIT,0);
+ if(!started){log::error("fg-probe",std::format("launch failed win32={}",GetLastError()));return false;}
+ Handle process{info.hProcess},thread{info.hThread};
+ if(!AssignProcessToJobObject(job.value,process.value)||ResumeThread(thread.value)==DWORD(-1)){
+ TerminateProcess(process.value,1);WaitForSingleObject(process.value,5000);return false;
+ }
+ log::info("fg-probe",std::format("started pid={} multiplier={} extent={}x{} log={}",info.dwProcessId,s.multiplier,s.width,s.height,logPath(info.dwProcessId).string()));
+ const auto start=GetTickCount64();DWORD wait=WAIT_TIMEOUT;
+ const ULONGLONG timeout=GetEnvironmentVariableW(L"VEYRA_TEST_FG_PROBE_HANG",nullptr,0)?2000:60000;
+ while(!cancel&&GetTickCount64()-start<timeout&&(wait=WaitForSingleObject(process.value,100))==WAIT_TIMEOUT){}
+ if(wait!=WAIT_OBJECT_0){
+ TerminateJobObject(job.value,124);WaitForSingleObject(process.value,5000);
+ log::error("fg-probe",std::format("cancelled={} timeoutOrWaitFailure=true stage={} log={}",cancel.load(),InterlockedCompareExchange(&s.stage,0,0),logPath(info.dwProcessId).string()));return false;
+ }
+ DWORD code=1;GetExitCodeProcess(process.value,&code);
+ const LONG stage=InterlockedCompareExchange(&s.stage,0,0),generated=InterlockedCompareExchange(&s.generated,0,0);
+ const bool ok=code==0&&stage==4&&generated==LONG(2*(s.multiplier-1));
+ log::info("fg-probe",std::format("finished pid={} exit={} stage={} generated={} passed={} log={}",info.dwProcessId,code,stage,generated,ok,logPath(info.dwProcessId).string()));
+ if(ok){std::lock_guard lock(cacheMutex);passed.insert(key);}return ok&&!cancel;
+}
+int runFgCompatibilityProbe(HANDLE inherited){
+ Handle mapping{inherited};View view{static_cast<Shared*>(MapViewOfFile(mapping.value,FILE_MAP_ALL_ACCESS,0,0,sizeof(Shared)))};
+ if(!view.value)return 1;
+ auto& s=*view.value;
+ if(s.magic!=signature||s.bytes!=sizeof(Shared)||s.runtime[32767]||s.hash[64]||s.width<64||s.height<64||s.width>8192||s.height>8192||s.multiplier<2||s.multiplier>6)return 1;
+ Logger::instance().openFile(logPath(GetCurrentProcessId()).wstring());
+ // Keep provider-internal errors in the disposable child's diagnostic log.
+ SetEnvironmentVariableW(L"VEYRA_TEST_NGX_VERBOSE", L"1");
+ if(GetEnvironmentVariableW(L"VEYRA_TEST_FG_PROBE_HANG",nullptr,0))Sleep(INFINITE);
+ if(GetEnvironmentVariableW(L"VEYRA_TEST_FG_PROBE_FAIL",nullptr,0))return 1;
+ FileIdentity identity;IdentityError error;
+ if(!computeFileIdentity((std::filesystem::path(s.runtime)/L"nvngx_dlssg.dll").wstring(),identity,error)||identity.sha256Upper!=s.hash)return 1;
+ CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ bool ok=false;
+ {
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;pipeline::EnhanceGraph graph(ctx,ring);Status status;
+ gfx::DeviceContextDesc device;device.requiredVendorId=0x10de;device.requiredLuid=s.luid;device.commandSlotCount=6;
+ InterlockedExchange(&s.stage,1);
+ if(ctx.initialize(device,status)&&ctx.adapter().luid==s.luid&&ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,status)){
+ pipeline::EnhanceGraphDesc desc;desc.sourceWidth=desc.workWidth=s.width;desc.sourceHeight=desc.workHeight=s.height;
+ desc.enableNr=false;desc.enableSr=false;desc.enableFg=true;desc.fgMultiplier=s.multiplier;desc.runtimeAbsPath=s.runtime;
+ desc.hdrInput=desc.hdrOutput=s.hdr!=0;desc.rgbInput=!desc.hdrInput;
+ InterlockedExchange(&s.stage,2);
+ ok=graph.initialize(desc)&&graph.createViews();
+ if(!ok)failProbe(s,"initialization");
+ AVFrame* frame=av_frame_alloc();if(!frame)ok=false;
+ if(frame){
+ frame->format=s.hdr?AV_PIX_FMT_P010LE:AV_PIX_FMT_RGBA;
+ frame->width=int(s.width);frame->height=int(s.height);
+ frame->color_range=s.hdr?AVCOL_RANGE_MPEG:AVCOL_RANGE_JPEG;
+ if(s.hdr){
+ frame->colorspace=AVCOL_SPC_BT2020_NCL;
+ frame->color_primaries=AVCOL_PRI_BT2020;
+ frame->color_trc=AVCOL_TRC_SMPTE2084;
+ frame->chroma_location=AVCHROMA_LOC_LEFT;
+ }
+ ok=ok&&av_frame_get_buffer(frame,32)>=0;
+ }
+ if(ok)InterlockedExchange(&s.stage,3);
+ for(unsigned i=0;ok&&i<3;++i){
+ if(s.hdr){
+ // Match the product's explicit PQ YUV ingress before testing RGB10 FG.
+ for(unsigned y=0;y<s.height;++y){
+ auto* row=reinterpret_cast<uint16_t*>(frame->data[0]+size_t(y)*frame->linesize[0]);
+ for(unsigned x=0;x<s.width;++x)row[x]=uint16_t((128+((x+i*8)/32+y/32)%2*480)<<6);
+ }
+ for(unsigned y=0;y<(s.height+1)/2;++y){
+ auto* row=reinterpret_cast<uint16_t*>(frame->data[1]+size_t(y)*frame->linesize[1]);
+ std::fill_n(row,2*((s.width+1)/2),uint16_t(512<<6));
+ }
+ }else{
+ for(unsigned y=0;y<s.height;++y)for(unsigned x=0;x<s.width;++x){auto* p=frame->data[0]+size_t(y)*frame->linesize[0]+x*4;const unsigned value=32+((x+i*8)/32+y/32)%2*180;p[0]=p[1]=p[2]=uint8_t(value);p[3]=255;}
+ }
+ pipeline::EnhanceGraph::FrameOutputs output;
+ ok=graph.process(frame,i*(1000.0/60),i==0,output)&&ring.waitIdle()&&graph.resolveGeneration(output);
+ if(!ok)failProbe(s,"Create/Evaluate or GPU completion");
+ unsigned valid=0;
+ for(unsigned j=0;ok&&j<output.batch.count;++j)if(output.batch.frames[j].kind==pipeline::FrameKind::Generated&&output.batch.frames[j].validity==pipeline::GenerationValidity::Valid)++valid;
+ if(i&&valid!=s.multiplier-1)ok=false;
+ if(!ok)failProbe(s,"generated output validation");
+ InterlockedExchangeAdd(&s.generated,LONG(valid));
+ }
+ av_frame_free(&frame);ok=ring.drainQueue()&&ok;
+ }
+ graph.shutdown();ring.shutdown();ctx.shutdown();
+ }
+ ok=ok&&ngx::FgCompatibilitySession::processHealthy();
+ if(ok)InterlockedExchange(&s.stage,4);
+ log::info("fg-probe",std::format("Create/Evaluate probe passed={} generated={}; image quality requires separate content validation",ok,InterlockedCompareExchange(&s.generated,0,0)));
+ Logger::instance().flush();CoUninitialize();return ok?0:1;
+}
+}
diff --git a/src/engine/Subtitles.cpp b/src/engine/Subtitles.cpp
index 3a33a003..b6466592 100644
--- a/src/engine/Subtitles.cpp
+++ b/src/engine/Subtitles.cpp
@@ -11,6 +11,9 @@
#include <fstream>
#include <map>
#include <sstream>
+#include <condition_variable>
+#include <mutex>
+#include <thread>
extern "C" {
#include <libavcodec/avcodec.h>
@@ -388,19 +391,28 @@ std::wstring subtitleAt(const std::vector<SubtitleCue>& cues,double seconds){
return {};
}
-std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path){
+std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path,std::stop_token stop,
+ const std::function<void(const std::vector<SubtitleTrack>&)>& metadata){
std::vector<SubtitleTrack> tracks;
- AVFormatContext* input=nullptr;
+ if(stop.stop_requested())return tracks;
+ const auto started=std::chrono::steady_clock::now();
+ AVFormatContext* input=avformat_alloc_context();
+ if(!input)return tracks;
+ input->interrupt_callback={[](void* opaque){return static_cast<std::stop_token*>(opaque)->stop_requested()?1:0;},&stop};
+ struct InputCleanup {AVFormatContext*& input;~InputCleanup(){avformat_close_input(&input);}} cleanup{input};
const auto utf8Path=utf8(path);
if(avformat_open_input(&input,utf8Path.c_str(),nullptr,nullptr)<0||!input){
log::warn("subtitle","cannot open media for embedded subtitle listing");
return tracks;
}
if(avformat_find_stream_info(input,nullptr)<0){
- avformat_close_input(&input);
return tracks;
}
+ struct DecoderCleanup {void operator()(AVCodecContext* context)const{avcodec_free_context(&context);}};
+ std::vector<std::unique_ptr<AVCodecContext,DecoderCleanup>> decoders;
+ std::vector<int> streamToTrack(input->nb_streams,-1);
for(unsigned streamIndex=0;streamIndex<input->nb_streams;++streamIndex){
+ if(stop.stop_requested())return {};
AVStream* stream=input->streams[streamIndex];
if(stream->codecpar->codec_type!=AVMEDIA_TYPE_SUBTITLE)continue;
SubtitleTrack track;
@@ -414,6 +426,8 @@ std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path){
}
if(track.name.empty())track.name=track.language.empty()?std::format(L"字幕轨 {}",tracks.size()+1):track.language;
track.styles.push_back(SubtitleStyle{});
+ streamToTrack[streamIndex]=int(tracks.size());
+ decoders.emplace_back();
if(!isTextSubtitleCodec(track.codec)){
track.note=L"图形/字幕格式不支持(本版本仅支持文本字幕)";
log::info("subtitle",std::format("embedded track {} codec={} listed as unsupported",streamIndex,codecName?codecName:""));
@@ -428,14 +442,25 @@ std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path){
tracks.push_back(std::move(track));
continue;
}
- AVPacket* packet=av_packet_alloc();
- const double timeBase=av_q2d(stream->time_base);
- bool ssaStyle=lower(track.codec)==L"ass"||lower(track.codec)==L"ssa";
- while(packet&&av_read_frame(input,packet)>=0&&track.cues.size()<kMaxCues){
- if(packet->stream_index!=int(streamIndex)){av_packet_unref(packet);continue;}
+ decoders.back().reset(context);
+ tracks.push_back(std::move(track));
+ }
+ if(metadata&&!stop.stop_requested())metadata(tracks);
+ if(std::none_of(decoders.begin(),decoders.end(),[](const auto& decoder){return bool(decoder);}))return tracks;
+ AVPacket* packet=av_packet_alloc();
+ struct PacketCleanup {AVPacket*& packet;~PacketCleanup(){av_packet_free(&packet);}} packetCleanup{packet};
+ constexpr size_t maxCacheBytes=64u*1024u*1024u;
+ size_t cacheBytes=0,totalCues=0;uint64_t packets=0;
+ auto nextPublish=std::chrono::steady_clock::now()+std::chrono::milliseconds(250);
+ while(packet&&!stop.stop_requested()&&av_read_frame(input,packet)>=0){
+ ++packets;
+ const int index=packet->stream_index>=0&&size_t(packet->stream_index)<streamToTrack.size()?streamToTrack[packet->stream_index]:-1;
+ if(index<0||!decoders[index]){av_packet_unref(packet);continue;}
+ auto& track=tracks[index];auto* context=decoders[index].get();
+ const double timeBase=av_q2d(input->streams[packet->stream_index]->time_base);
AVSubtitle subtitle{};
int got=0;
- if(avcodec_decode_subtitle2(context,&subtitle,&got,packet)<0||!got){av_packet_unref(packet);continue;}
+ if(avcodec_decode_subtitle2(context,&subtitle,&got,packet)<0||!got){avsubtitle_free(&subtitle);av_packet_unref(packet);continue;}
const double packetSeconds=packet->pts==AV_NOPTS_VALUE?0:double(packet->pts)*timeBase;
for(unsigned rect=0;rect<subtitle.num_rects;++rect){
const auto* entry=subtitle.rects[rect];
@@ -450,24 +475,74 @@ std::vector<SubtitleTrack> loadEmbeddedSubtitleTracks(const std::wstring& path){
cue.end=subtitle.end_display_time>subtitle.start_display_time?packetSeconds+double(subtitle.end_display_time)/1000.0:cue.begin+3.0;
cue.text=std::move(text);
cue.alignOverride=alignOverride;cue.posX=posX;cue.posY=posY;
- if(cue.end>cue.begin&&track.cues.size()<kMaxCues)track.cues.push_back(std::move(cue));
+ const size_t bytes=sizeof(SubtitleCue)+sizeof(double)+cue.text.size()*sizeof(wchar_t);
+ if(cue.end>cue.begin){
+ if(totalCues>=kMaxCues||bytes>maxCacheBytes-cacheBytes){track.note=L"字幕缓存已达上限,后续字幕未加载";continue;}
+ cacheBytes+=bytes;++totalCues;track.cues.push_back(std::move(cue));
+ }
}
avsubtitle_free(&subtitle);
av_packet_unref(packet);
- }
- if(packet)av_packet_free(&packet);
- avcodec_free_context(&context);
- if(!ssaStyle&&track.styles.empty())track.styles.push_back(SubtitleStyle{});
+ if(metadata&&std::chrono::steady_clock::now()>=nextPublish){
+ for(auto& t:tracks)t.rebuildIndex();
+ metadata(tracks);
+ nextPublish=std::chrono::steady_clock::now()+std::chrono::seconds(1);
+ }
+ }
+ if(stop.stop_requested())return {};
+ for(auto& track:tracks){
track.rebuildIndex();
- log::info("subtitle",std::format("embedded track {} codec={} cues={}",streamIndex,codecName?codecName:"",track.cues.size()));
- tracks.push_back(std::move(track));
- // av_read_frame consumed the shared demuxer: rewind for the next track.
- av_seek_frame(input,-1,0,AVSEEK_FLAG_BACKWARD);
+ log::info("subtitle",std::format("embedded track {} codec={} cues={}",track.streamIndex,utf8(track.codec),track.cues.size()));
}
- avformat_close_input(&input);
+ log::info("subtitle",std::format("single-pass complete tracks={} packets={} cues={} cacheBytes={} elapsedMs={:.3f}",tracks.size(),packets,totalCues,cacheBytes,std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-started).count()));
return tracks;
}
+struct SubtitleLoader::Impl {
+ std::mutex mutex;
+ std::condition_variable_any wake;
+ std::wstring pending;
+ uint64_t generation=0;
+ bool requested=false;
+ std::stop_source cancel;
+ std::optional<Result> ready;
+ std::jthread worker;
+ Impl():worker([this](std::stop_token shutdown){
+ while(!shutdown.stop_requested()){
+ std::unique_lock lock(mutex);
+ if(!wake.wait(lock,shutdown,[&]{return requested;}))break;
+ const auto path=std::move(pending);const auto id=generation;const auto stop=cancel.get_token();requested=false;
+ lock.unlock();
+ auto publish=[&](std::vector<SubtitleTrack> tracks,bool complete){
+ std::lock_guard guard(mutex);
+ if(id==generation&&!stop.stop_requested())ready=Result{id,complete,std::move(tracks)};
+ };
+ try{
+ std::vector<SubtitleTrack> external;
+ if(path.empty()||path.starts_with(L"capture:")||path.starts_with(L"capture2:")||path.starts_with(L"remoteplay:")){publish({},true);continue;}
+ for(const wchar_t* extension:{L".srt",L".ass",L".ssa",L".vtt"}){
+ if(stop.stop_requested())break;
+ auto candidate=std::filesystem::path(path);candidate.replace_extension(extension);
+ std::error_code ec;if(!std::filesystem::exists(candidate,ec))continue;
+ auto track=loadSubtitleFile(candidate.wstring());if(!track.usable())continue;
+ track.name=std::format(L"外挂 · {}",candidate.filename().wstring());external.push_back(std::move(track));break;
+ }
+ auto embedded=loadEmbeddedSubtitleTracks(path,stop,[&](const auto& tracks){auto listing=external;listing.insert(listing.end(),tracks.begin(),tracks.end());publish(std::move(listing),false);});
+ for(auto& track:embedded)external.push_back(std::move(track));
+ publish(std::move(external),true);
+ }catch(const std::exception& e){log::error("subtitle",std::format("loader failed: {}",e.what()));publish({},true);}
+ }
+ }){}
+ ~Impl(){cancel.request_stop();worker.request_stop();wake.notify_all();worker.join();}
+};
+SubtitleLoader::SubtitleLoader():p_(std::make_unique<Impl>()){}
+SubtitleLoader::~SubtitleLoader()=default;
+uint64_t SubtitleLoader::request(std::wstring path){
+ std::lock_guard lock(p_->mutex);p_->cancel.request_stop();p_->cancel=std::stop_source{};
+ p_->pending=std::move(path);p_->requested=true;p_->ready.reset();++p_->generation;p_->wake.notify_all();return p_->generation;
+}
+std::optional<SubtitleLoader::Result> SubtitleLoader::poll(){std::lock_guard lock(p_->mutex);auto result=std::move(p_->ready);p_->ready.reset();return result;}
+
SubtitleAlignResult alignSubtitleToAudio(const std::wstring& mediaPath,const SubtitleTrack& track,int maxShiftSeconds){
SubtitleAlignResult result;
if(track.cues.empty()){result.detail=L"没有可用的字幕内容";return result;}
diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cpp
index 0905b03c..aade2590 100644
--- a/src/engine/VideoExportJob.cpp
+++ b/src/engine/VideoExportJob.cpp
@@ -1,5 +1,4 @@
#include "veyra/engine/VideoExportJob.h"
-#include "veyra/engine/CfrTimeline.h"
#include "veyra/source/MediaFileSource.h"
#include "veyra/pipeline/EnhanceGraph.h"
#include "veyra/pipeline/ResolutionPlan.h"
@@ -12,11 +11,11 @@
#include <thread>
#include <chrono>
#include <cmath>
+#include <deque>
extern "C" {
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libavutil/mathematics.h>
-#include <libavutil/pixdesc.h>
#include <libavutil/mastering_display_metadata.h>
}
namespace veyra::engine {
@@ -28,10 +27,9 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
// reaches the application (XeSS-FG 3.0.2 exports only xefgSwapChain*, and
// the FSR-FG context owns the proxy swapchain). Refusing the job left those
// users with no file at all, so export now runs the in-graph DLSS path and
- // states the substitution; if that backend cannot initialise either, the
- // job still completes without frame generation instead of failing.
+ // states the substitution. A rejected requested multiplier fails the job
+ // explicitly; a successful export must retain the requested cadence.
std::wstring fgNote;
- auto appendFgNote=[&](const std::wstring& extra){if(!fgNote.empty())fgNote+=L";";fgNote+=extra;};
if(options.fg&&presentSinkFrameGeneration(options.settings.frameGenerationBackend)){
const auto requested=options.settings.frameGenerationBackend;
fgNote=std::format(L"{}补帧由显示交换链直接生成,导出取不到它的画面;本次导出改用 DLSS 补帧 {}X",
@@ -43,7 +41,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
std::unique_ptr<sink::VideoEncoder> encoder;
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;
- uint64_t tailSnapped=0,gapFilledSlots=0,gapFillEvents=0;
+ uint64_t repairedTimestamps=0;
std::wstring encoderName;
std::wstring failureReason;
auto failAv=[&](const wchar_t* stage,int code){
@@ -52,8 +50,6 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
veyra::log::error("export",std::format("stage={} code={} detail={}",utf8(stage),code,error));
return false;
};
- bool hdrExport=false;
- uint32_t outputWidth=0,outputHeight=0;AVRational outputRate{};
const auto partial=output+L".partial";
try { do {
Status st=Status::Ok;gfx::DeviceContextDesc dd;dd.commandSlotCount=6;
@@ -66,23 +62,16 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
if(!nvidiaAdapter)veyra::log::info("export",std::format("adapter={} vendor={}; DLSS NR/SR/FG and NVOF are unavailable, encoder falls back to the system Media Foundation hardware MFT",utf8(ctx.adapter().description),ctx.adapter().vendorIdHex));
source::SourceOpenDesc od;od.path=input;od.preferHardwareDecode=false;if(!source.open(od)){failureReason=source.errorMessage();break;}
auto info=source.info();if(!pipeline::Extent{info.width,info.height}.valid()){progress(0,L"输入尺寸超出GPU单纹理能力");break;}
- // Bounded metadata scan; decoded pixels are not retained. Rewind the
- // file source afterwards, preserving all source frames for the export.
- std::vector<double> samples;bool scanError=false;
- for(unsigned i=0;i<120&&!cancel;++i){pipeline::FramePacket p;const AVFrame* f=nullptr;const auto rs=source.read(p,&f);if(rs==source::SourceReadStatus::Eos)break;if(rs!=source::SourceReadStatus::Frame||p.pts.isUnknown()){failureReason=source.errorMessage();scanError=true;break;}samples.push_back(p.pts.toDouble());}
- if(scanError||samples.empty()||cancel)break;
- const auto [rateNum,rateDen]=CfrTimeline::select(info.nominalRateNum,info.nominalRateDen,info.timestampQuantum,samples);
- CfrTimeline timeline(rateNum,rateDen,info.timestampQuantum,samples.front());
- if(!timeline.valid()){progress(0,L"无法确认一致的恒定帧率,已停止导出");veyra::log::error("export-timeline","CFR rejected source=preflight; no timestamp-consistent rate candidate");break;}
- source.close();if(!source.open(od))break; // reopen from the true beginning, including negative PTS
// The first decoded frame is authoritative when container headers omit
- // transfer/range metadata. Do not build an SDR graph from stale header
- // defaults after the preflight discovered HDR/BT.2020 pixels.
+ // transfer/range metadata. Retain it instead of scanning and reopening.
pipeline::FramePacket firstPacket;const AVFrame* firstFrame=nullptr;
if(source.read(firstPacket,&firstFrame)!=source::SourceReadStatus::Frame||!firstFrame){failureReason=L"导出预读首帧失败";break;}
info=source.info(); // retain this frame for the export, without decoding it again
+ int rateNum=info.nominalRateNum,rateDen=info.nominalRateDen;
+ if(rateNum<=0||rateDen<=0){rateNum=30;rateDen=1;veyra::log::warn("export-timeline","missing nominal rate; encoder configured at 30 fps, source timestamps retained");}
+ const double sourceInterval=double(rateDen)/rateNum;
const auto resolution=pipeline::ResolutionPlan::make({info.width,info.height},options.sr,pipeline::NrSizePolicy::Native,true,options.settings.revision,options.settings.srTarget);
- pipeline::EnhanceGraphDesc gd;gd.hdrInput=gd.hdrOutput=info.color.isHdrPath();hdrExport=gd.hdrOutput;
+ pipeline::EnhanceGraphDesc gd;gd.hdrInput=gd.hdrOutput=info.color.isHdrPath();
// Plan v5.3: the grade changes the peak and the content light distribution.
// Recomputing MaxCLL/MaxFALL needs a full pre-pass before the header is
// written, which this exporter does not do yet, so say so instead of
@@ -90,7 +79,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
if(gd.hdrOutput&&options.settings.color.enabled&&!options.settings.color.neutral())
veyra::log::warn("color-export","HDR export with the colour grade active: MaxCLL/MaxFALL are carried over from the source and NOT recomputed for the graded output (marked as not updated)");
gd.captureBitDepth=info.color.pixelFormat==pipeline::SourcePixelFormat::P010?10:info.color.pixelFormat==pipeline::SourcePixelFormat::P016?16:8;
- if(gd.hdrOutput&&!hevc){failureReason=L"HDR视频请使用HEVC Main10导出(选择HEVC)";break;}
+ if(gd.hdrOutput&&!hevc){hevc=true;fgNote+=fgNote.empty()?L"HDR 视频自动使用 HEVC Main10 编码":L";HDR 视频自动使用 HEVC Main10 编码";}
// Adapter gate mirrors the preview rules (EngineController): DLSS NR,
// DLSS SR and the NVOF guidance need an NVIDIA device; AMD FSR
// upscaling is the only vendor-neutral video SR we ship. Requesting an
@@ -101,10 +90,8 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
if(options.sr&&!srAvailable)fgNote+=fgNote.empty()?L"当前显卡不能使用所选超分,本次导出关闭超分":L";当前显卡不能使用所选超分,本次导出关闭超分";
if(!nvidiaFeatures&&srAvailable)fgNote+=fgNote.empty()?L"本次导出使用 AMD FSR 超分":L";本次导出使用 AMD FSR 超分";
gd.sourceWidth=info.width;gd.sourceHeight=info.height;gd.workWidth=resolution.base.width;gd.workHeight=resolution.base.height;gd.nrWidth=resolution.nr.width;gd.nrHeight=resolution.nr.height;gd.flowWidth=resolution.flow.width;gd.flowHeight=resolution.flow.height;gd.enableSr=srAvailable;gd.videoSrQuality=options.settings.videoSrQuality;gd.enableNr=options.nr&&nvidiaFeatures;gd.nrRuntime=options.settings.nrRuntime;gd.enableFg=options.fg&&nvidiaFeatures;gd.fgMultiplier=options.fgMultiplier;gd.frameGenerationBackend=options.settings.frameGenerationBackend;gd.enableNvofStandalone=options.nr&&nvidiaFeatures;gd.model=options.settings.model;gd.residual=options.settings.residual;gd.protection=options.settings.protection;gd.color=options.settings.color;gd.settingsRevision=options.settings.revision;gd.flowQuality=options.settings.flow;gd.opticalFlowBackend=options.settings.opticalFlowBackend;gd.amdFlowHalfResolution=options.settings.amdFlowHalfResolution;gd.contentRate=options.settings.content;gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
- // One attempt per frame-generation request. A rejected multiplier is a
- // capability statement, not an infrastructure failure: retry at 2X (the
- // floor every DLSS-G capable GPU honours) and only then fall back to a
- // real-frames-only export, so the user keeps a usable file either way.
+ // Keep the requested multiplier. Changing it after initialization fails
+ // would produce a successful-looking file with different settings.
bool graphReady=false,fgFailure=false;
auto startGraph=[&](bool fg,uint32_t multiplier){
gd.enableFg=fg;gd.fgMultiplier=fg?multiplier:1;
@@ -112,32 +99,20 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
fgFailure=graph.failedBackend()==FailedBackend::Fg;
graph.shutdown();
};
- if(options.fg&&!nvidiaFeatures){options.fg=false;options.fgMultiplier=1;}
+ if(options.fg&&!nvidiaFeatures){failureReason=L"当前导出设备不能执行所请求的 DLSS 补帧,未降低倍率";break;}
if(options.fg){
startGraph(true,options.fgMultiplier);
- if(!graphReady&&fgFailure&&options.fgMultiplier>2){
- startGraph(true,2);
- if(graphReady){
- veyra::log::warn("export",std::format("DLSS frame generation rejected multiplier={} on this adapter; exporting at 2X",options.fgMultiplier));
- options.fgMultiplier=2;appendFgNote(L"DLSS 补帧在该显卡上不支持请求的倍率,本次导出降为 2X");
- }
- }
if(!graphReady&&fgFailure){
- startGraph(false,1);
- if(graphReady){
- veyra::log::warn("export","DLSS frame generation unavailable; exporting real frames only");
- options.fg=false;options.fgMultiplier=1;appendFgNote(L"DLSS 补帧无法初始化,本次导出只输出原始帧(补帧关闭)");
- }
+ failureReason=std::format(L"DLSS {}X 补帧初始化失败,未降低倍率;请查看任务诊断日志",options.fgMultiplier);
}
} else startGraph(false,1);
if(!graphReady){if(failureReason.empty())failureReason=L"增强管线初始化失败,请查看诊断";break;}
if(!fgNote.empty())progress(0,fgNote);
const AVRational rate=av_mul_q({rateNum,rateDen},{int(options.fg?options.fgMultiplier:1),1});
- outputRate=rate;
- veyra::log::info("export-timeline",std::format("CFR declared={}/{} candidate={}/{} timestampQuantum={} sampled={} output={}/{} fg={} backend={} note={} (timestamp-consistent candidate, quantized short clips may be ambiguous; every PTS validated)",info.nominalRateNum,info.nominalRateDen,rateNum,rateDen,info.timestampQuantum,samples.size(),rate.num,rate.den,options.fg?options.fgMultiplier:1,frameGenerationBackendName(options.settings.frameGenerationBackend),utf8(fgNote)));
- outputWidth=gd.workWidth;outputHeight=gd.workHeight;
+ constexpr AVRational mediaTimeBase{1,1000000};
+ veyra::log::info("export-timeline",std::format("source-timed export nominal={}/{} encoder={}/{} fg={} backend={} note={} (no CFR preflight or output decode verification)",rateNum,rateDen,rate.num,rate.den,options.fg?options.fgMultiplier:1,frameGenerationBackendName(options.settings.frameGenerationBackend),utf8(fgNote)));
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;
+ videoStream=avformat_new_stream(mux,nullptr);if(!videoStream)break;videoStream->time_base=mediaTimeBase;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;
if(gd.hdrOutput){cp->format=AV_PIX_FMT_YUV420P10LE;cp->color_space=AVCOL_SPC_BT2020_NCL;cp->color_primaries=AVCOL_PRI_BT2020;cp->color_trc=AVCOL_TRC_SMPTE2084;cp->profile=AV_PROFILE_HEVC_MAIN_10;}
// Plan v5.3: this exporter cannot recompute content light levels (that
@@ -155,24 +130,50 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
if(avformat_open_input(&audioInput,inputUtf8.c_str(),nullptr,nullptr)<0||avformat_find_stream_info(audioInput,nullptr)<0){progress(0,L"无法读取源音轨信息,已停止导出");break;}
{
audioIndex=av_find_best_stream(audioInput,AVMEDIA_TYPE_AUDIO,-1,-1,nullptr,0);
+ if(options.audioStreamIndex>=0){
+ if(unsigned(options.audioStreamIndex)>=audioInput->nb_streams||audioInput->streams[options.audioStreamIndex]->codecpar->codec_type!=AVMEDIA_TYPE_AUDIO){progress(0,L"选定音轨已不存在,已停止导出");break;}
+ audioIndex=options.audioStreamIndex;
+ }
+ log::info("export-audio",std::format("selected stream={}",audioIndex));
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"此音频编码不能封装为MP4,已停止导出");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(&audioStream->metadata,audioInput->streams[audioIndex]->metadata,0);
}
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);const int readResult=av_read_frame(audioInput,audioPacket);if(readResult==AVERROR_EOF){audioEof=true;return true;}if(readResult<0){veyra::log::error("export-audio",std::format("source packet read failed code={}",readResult));return false;}if(audioPacket->stream_index!=audioIndex)continue;if(audioPacket->flags&AV_PKT_FLAG_CORRUPT){veyra::log::error("export-audio","corrupt source audio packet");return false;}audioPending=true;}
+ for(;;){if(!audioPending){if(audioEof)return true;av_packet_unref(audioPacket);const int readResult=av_read_frame(audioInput,audioPacket);if(readResult==AVERROR_EOF){audioEof=true;return true;}if(readResult<0)return failAv(L"读取音轨",readResult);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;const int rc=av_interleaved_write_frame(mux,audioPacket);if(rc<0)return failAv(L"写入音轨",rc);
}};
- 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 int rc=av_interleaved_write_frame(mux,pkt);av_packet_free(&pkt);if(rc<0)return failAv(L"写入视频帧",rc);++written;audioEndSeconds=(pts+1)*double(rate.den)/rate.num;return writeAudioUntil(audioEndSeconds);};
+ // Encoders retain ordinal timestamps; only the bounded in-flight queue
+ // maps them to media time. Hold one compressed packet for its duration.
+ std::deque<std::pair<int64_t,int64_t>> timestamps;
+ auto freePacket=[](AVPacket* p){av_packet_free(&p);};
+ std::unique_ptr<AVPacket,decltype(freePacket)> pendingVideo(av_packet_alloc(),freePacket);
+ if(!pendingVideo)break;
+ auto flushVideo=[&](int64_t endUs){
+ auto* pkt=pendingVideo.get();if(!pkt->size)return true;
+ pkt->duration=std::max<int64_t>(1,endUs-pkt->pts);
+ audioEndSeconds=(pkt->pts+pkt->duration)/1000000.0;
+ av_packet_rescale_ts(pkt,mediaTimeBase,videoStream->time_base);
+ const int rc=av_interleaved_write_frame(mux,pkt);av_packet_unref(pkt);
+ if(rc<0)return failAv(L"写入视频帧",rc);
+ ++written;return writeAudioUntil(audioEndSeconds);
+ };
+ auto writer=[&](const uint8_t* bytes,size_t size,int64_t pts,bool key){
+ if(!headerWritten)return false;
+ if(timestamps.empty()||timestamps.front().first!=pts){failureReason=L"编码器返回了未知帧序号";return false;}
+ const auto timeUs=timestamps.front().second;timestamps.pop_front();
+ if(!flushVideo(timeUs))return false;
+ auto* pkt=pendingVideo.get();if(av_new_packet(pkt,int(size))<0)return false;
+ memcpy(pkt->data,bytes,size);pkt->stream_index=videoStream->index;pkt->pts=pkt->dts=timeUs;
+ if(key)pkt->flags|=AV_PKT_FLAG_KEY;return true;
+ };
// Must drain before rate/writeAudioUntil/writer leave scope, including cancel/error.
- struct EncoderCloser {sink::VideoEncoder* encoder;~EncoderCloser(){if(encoder)encoder->close();}} closer{encoder.get()};
+ struct EncoderCloser {std::unique_ptr<sink::VideoEncoder>& encoder;~EncoderCloser(){encoder.reset();}} closer{encoder};
sink::EncoderConfig encoderConfig;encoderConfig.hevc=hevc;encoderConfig.fpsNum=unsigned(rate.num);encoderConfig.fpsDen=unsigned(rate.den);encoderConfig.bitrateMbps=options.settings.exportBitrateMbps;
std::wstring encoderDetail;
encoder=sink::openVideoEncoder(ctx,ring,graph,encoderConfig,writer,encoderDetail);
@@ -190,48 +191,27 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
muxResult=avformat_write_header(mux,nullptr);
if(muxResult<0){failAv(L"写入MP4文件头",muxResult);break;}headerWritten=true;
uint64_t sourceCount=0,generatedCount=0,holdCount=0;int64_t outputIndex=0;bool error=false;std::shared_ptr<pipeline::FrameLease> lastReal;
- // Container duration x rate bounds the tail exception below: only the
- // last frames of the real stream may sit off the CFR grid.
- const double durationSeconds=info.duration.toDouble();
- const uint64_t estimatedFrames=durationSeconds>0?uint64_t(std::llround(durationSeconds*double(rateNum)/rateDen)):0;
+ double previousPts=0;int64_t lastOutputUs=-1;
+ const uint32_t multiplier=options.fg?options.fgMultiplier:1u;
+ auto encodeAt=[&](unsigned slot,bool generated,double seconds){
+ const int64_t timeUs=std::max(lastOutputUs+1,int64_t(std::llround(seconds*1000000)));
+ timestamps.emplace_back(outputIndex,timeUs);lastOutputUs=timeUs;
+ return encoder->encode(slot,generated,outputIndex++);
+ };
while(!cancel){if(frameBoundary&&!frameBoundary()){error=true;break;}pipeline::FramePacket packet;const AVFrame* frame=nullptr;
source::SourceReadStatus rs;
if(sourceCount==0){packet=firstPacket;frame=firstFrame;rs=source::SourceReadStatus::Frame;}
else rs=source.read(packet,&frame);
- if(rs==source::SourceReadStatus::Eos)break;if(rs!=source::SourceReadStatus::Frame||packet.pts.isUnknown()){failureReason=source.errorMessage();error=true;break;}
- if(sourceCount==0)videoOriginSeconds=packet.pts.toDouble();
- const double expectedPts=timeline.expected(sourceCount);
- if(!timeline.accepts(sourceCount,packet.pts.toDouble())){
- const double pts=packet.pts.toDouble(),deviationMs=(pts-expectedPts)*1000.0;
- if(timeline.tailAccepts(sourceCount,pts,estimatedFrames)){
- ++tailSnapped;
- veyra::log::warn("export-timeline",std::format("tail snap source={} pts={} expected={} deviationMs={:.3f} estimatedFrames={} outputIndex={}",sourceCount,pts,expectedPts,deviationMs,estimatedFrames,outputIndex));
- } else if(const uint64_t missing=timeline.missingSlots(sourceCount,pts);missing>0&&lastReal){
- // The source is missing whole samples here (a dropped frame
- // that kept the timeline). Repeat the previous real frame for
- // every missing slot so the exported grid stays continuous,
- // then re-align the validator. No interpolation is invented
- // for the hole and this is reported to the user, never silent.
- const uint32_t multiplier=options.fg?options.fgMultiplier:1u;
- veyra::log::warn("export-timeline",std::format(
- "gap filled source={} pts={} expected={} deviationMs={:.3f} missingSlots={} outputIndex={} multiplier={} (previous frame repeated; no interpolation invented)",
- sourceCount,pts,expectedPts,deviationMs,missing,outputIndex,multiplier));
- ++gapFillEvents;gapFilledSlots+=missing;
- bool fillOk=true;
- for(uint64_t slotIndex=0;slotIndex<missing&&fillOk;++slotIndex){
- for(uint32_t j=0;j<multiplier;++j){
- if(!encoder->encode(lastReal->slot,false,outputIndex++)){fillOk=false;break;}
- ++holdCount;
- }
- }
- if(!fillOk){if(failureReason.empty())failureReason=L"缺口补帧编码失败,请查看编码器诊断";error=true;break;}
- timeline.resync(sourceCount,pts);
- } else {
- progress(0,std::format(L"源文件第 {} 帧时间戳偏移 {:.1f} 毫秒,无法按恒定帧率无损对齐;已停止写入并保留 partial",sourceCount,deviationMs));
- veyra::log::error("export-timeline",std::format("CFR rejected source={} pts={} expected={} deviationMs={:.3f} estimatedFrames={} outputIndex={}",sourceCount,pts,expectedPts,deviationMs,estimatedFrames,outputIndex));error=true;break;
- }
+ if(rs==source::SourceReadStatus::Eos)break;if(rs!=source::SourceReadStatus::Frame){failureReason=source.errorMessage();error=true;break;}
+ double sourcePts=packet.pts.toDouble();
+ if(sourceCount==0)videoOriginSeconds=!packet.pts.isUnknown()&&std::isfinite(sourcePts)?sourcePts:0;
+ double pts=sourcePts-videoOriginSeconds;
+ const bool repairPts=packet.pts.isUnknown()||!std::isfinite(pts)||(sourceCount&&pts<=previousPts);
+ if(repairPts){
+ pts=sourceCount?previousPts+sourceInterval:0;++repairedTimestamps;
+ if(repairedTimestamps<=5)veyra::log::warn("export-timeline",std::format("timestamp repaired source={} raw={} output={}",sourceCount,sourcePts,pts));
}
- pipeline::EnhanceGraph::FrameOutputs out;if(!graph.process(frame,packet.pts.toDouble()*1000,sourceCount==0||pipeline::breaksHistory(packet.flags),out,packet.sequence,&packet.colorInfo,&packet.hardwareSurface,false)){error=true;break;}
+ pipeline::EnhanceGraph::FrameOutputs out;if(!graph.process(frame,(pts+videoOriginSeconds)*1000,sourceCount==0||repairPts||pipeline::breaksHistory(packet.flags),out,packet.sequence,&packet.colorInfo,&packet.hardwareSurface,false)){error=true;break;}
const auto readyStart=std::chrono::steady_clock::now();
while(!cancel&&!graph.resolveGeneration(out)){
if(std::chrono::steady_clock::now()-readyStart>std::chrono::seconds(2)){error=true;break;}
@@ -242,23 +222,26 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
for(uint32_t j=1;j<options.fgMultiplier;++j){
pipeline::BatchFrame* item=nullptr;
for(uint32_t k=0;k<out.batch.count;++k)if(out.batch.frames[k].subframe==j&&out.batch.frames[k].validity==pipeline::GenerationValidity::Valid)item=&out.batch.frames[k];
- if(item){if(!encoder->encode(item->lease->slot,true,outputIndex++)){error=true;break;}item->lease->consumerFence=ring.lastSignaledValue();++generatedCount;}
- else {if(!lastReal||!encoder->encode(lastReal->slot,false,outputIndex++)){error=true;break;}lastReal->consumerFence=ring.lastSignaledValue();++holdCount;}
+ const double generatedPts=previousPts+(pts-previousPts)*j/multiplier;
+ if(item){if(!encodeAt(item->lease->slot,true,generatedPts)){error=true;break;}item->lease->consumerFence=ring.lastSignaledValue();++generatedCount;}
+ else {if(!lastReal||!encodeAt(lastReal->slot,false,generatedPts)){error=true;break;}lastReal->consumerFence=ring.lastSignaledValue();++holdCount;}
}
}
if(error)break;
auto& real=out.batch.frames[out.batch.count-1];
- if(!encoder->encode(real.lease->slot,false,outputIndex++)){error=true;break;}
+ if(!encodeAt(real.lease->slot,false,pts)){error=true;break;}
real.lease->consumerFence=ring.lastSignaledValue();lastReal=real.lease;
- ++sourceCount;if(counts)counts({sourceCount,generatedCount,holdCount,uint64_t(written)});progress(info.duration.toDouble()>0?std::clamp((packet.pts.toDouble()-videoOriginSeconds)/info.duration.toDouble(),0.0,.99):0,std::format(L"正在导出:{}张源帧 / {}张编码帧({})",sourceCount,outputIndex,encoderName));
+ previousPts=pts;
+ ++sourceCount;if(counts)counts({sourceCount,generatedCount,holdCount,uint64_t(written)});progress(info.duration.toDouble()>0?std::clamp(pts/info.duration.toDouble(),0.0,.99):0,std::format(L"正在导出:{}张源帧 / {}张编码帧({})",sourceCount,outputIndex,encoderName));
if(maxFrames&&sourceCount>=maxFrames)break;
}
if(error||cancel)break;
- if(options.fg&&lastReal)for(uint32_t j=1;j<options.fgMultiplier;++j){if(!encoder->encode(lastReal->slot,false,outputIndex++)){error=true;break;}++holdCount;}
+ if(options.fg&&lastReal)for(uint32_t j=1;j<multiplier;++j){if(!encodeAt(lastReal->slot,false,previousPts+sourceInterval*j/multiplier)){error=true;break;}++holdCount;}
if(error)break;
- veyra::log::info("export-counts",std::format("source={} generated={} hold={} output={} multiplier={} tailSnapped={} gapFillEvents={} gapFilledSlots={} backend={} encoder={} bitrateMbps={} note={} (CFR holds are not DLSSG)",sourceCount,generatedCount,holdCount,outputIndex,options.fg?options.fgMultiplier:1,tailSnapped,gapFillEvents,gapFilledSlots,frameGenerationBackendName(options.settings.frameGenerationBackend),std::string(sink::encoderBackendName(encoder->backend())),options.settings.exportBitrateMbps,utf8(fgNote)));
+ veyra::log::info("export-counts",std::format("source={} generated={} hold={} output={} multiplier={} repairedTimestamps={} backend={} encoder={} bitrateMbps={} note={} (holds are not DLSSG)",sourceCount,generatedCount,holdCount,outputIndex,multiplier,repairedTimestamps,frameGenerationBackendName(options.settings.frameGenerationBackend),std::string(sink::encoderBackendName(encoder->backend())),options.settings.exportBitrateMbps,utf8(fgNote)));
progress(.99,L"正在收尾:等待编码器输出剩余帧");
if(!encoder->finish()){if(failureReason.empty())failureReason=L"编码器收尾失败,请查看编码器诊断";break;}
+ if(!flushVideo(lastOutputUs+std::max<int64_t>(1,int64_t(std::llround(sourceInterval*1000000/multiplier)))))break;
if(!writeAudioUntil(audioEndSeconds))break;
progress(.995,L"正在收尾:写入MP4索引");
muxResult=av_write_trailer(mux);
@@ -268,45 +251,14 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
encoder.reset();if(mux){if(mux->pb){const int rc=avio_closep(&mux->pb);if(rc<0){failAv(L"刷新并关闭输出文件",rc);ok=false;}}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){
- progress(.999,L"正在封装和验证输出");
- source::MediaFileSource check;source::SourceOpenDesc od;od.path=partial;od.preferHardwareDecode=false;
- ok=!cancel&&check.open(od);
- if(!ok&&!cancel){failureReason=L"无法重新打开输出验证:"+check.errorMessage();veyra::log::error("export-verify",utf8(failureReason));}
- const auto info=check.info();
- CfrTimeline verifiedTimeline(outputRate.num,outputRate.den,info.timestampQuantum,0);
- const bool headerValid=info.width==outputWidth&&info.height==outputHeight&&verifiedTimeline.valid();
- if(ok&&!headerValid)veyra::log::error("export-verify",std::format("header actual={}x{} expected={}x{} rate={}/{} quantum={}",info.width,info.height,outputWidth,outputHeight,outputRate.num,outputRate.den,info.timestampQuantum));
- ok=ok&&headerValid;
- uint64_t decoded=0;bool reachedEos=false;
- while(ok&&!cancel){
- pipeline::FramePacket pkt;const AVFrame* frame=nullptr;const auto rs=check.read(pkt,&frame);
- if(rs==source::SourceReadStatus::Eos){reachedEos=true;break;}
- if(rs!=source::SourceReadStatus::Frame||pkt.pts.isUnknown()||decoded>=uint64_t(written)||!verifiedTimeline.accepts(decoded,pkt.pts.toDouble())){
- veyra::log::error("export-verify",std::format("frame={} status={} pts={} expectedPts={} written={} decoder={}",decoded,int(rs),pkt.pts.toDouble(),verifiedTimeline.expected(decoded),written,utf8(check.errorMessage())));
- ok=false;break;
- }
- if(hdrExport){
- const auto* format=av_pix_fmt_desc_get(static_cast<AVPixelFormat>(frame->format));
- if(!format||format->comp[0].depth<10||pkt.colorInfo.transfer!=pipeline::TransferFunction::PQ||
- pkt.colorInfo.primaries!=pipeline::ColorPrimaries::BT2020||pkt.colorInfo.matrix!=pipeline::YuvMatrix::BT2020NCL){ok=false;break;}
- }
- ++decoded;
- if(decoded%120==0)progress(.999,std::format(L"正在逐帧验证:{} / {} 帧",decoded,written));
- }
- ok=ok&&!cancel&&reachedEos&&decoded==uint64_t(written);
- veyra::log::info("export-verify",std::format("decoded={} expected={} eof={} cancelled={} passed={}",decoded,written,reachedEos,bool(cancel),ok));
- check.close();
- if(!ok&&!cancel&&failureReason.empty())failureReason=std::format(L"输出验证未通过(解码 {} / {} 帧),详见export-verify日志",decoded,written);
- if(ok){
- progress(.999,L"验证通过,正在保存正式文件");
- ok=!cancel&&MoveFileExW(partial.c_str(),output.c_str(),MOVEFILE_WRITE_THROUGH)!=FALSE;
- if(!ok&&!cancel){const DWORD error=GetLastError();failureReason=std::format(L"视频验证已通过,但保存文件名失败(Windows错误 {});可保留partial文件",error);veyra::log::error("export-rename",std::format("MoveFileExW failed error={} partial={}",error,utf8(partial)));}
- }
+ progress(.999,L"正在保存正式文件");
+ ok=!cancel&&MoveFileExW(partial.c_str(),output.c_str(),MOVEFILE_WRITE_THROUGH)!=FALSE;
+ if(!ok&&!cancel){const DWORD error=GetLastError();failureReason=std::format(L"视频已编码,但保存文件名失败(Windows错误 {});可保留partial文件",error);veyra::log::error("export-rename",std::format("MoveFileExW failed error={} partial={}",error,utf8(partial)));}
+ if(ok)veyra::log::info("export","encoder drained, mux closed, output saved; no post-export decoding");
}
if(ok){
- std::wstring done=encoderName.empty()?L"视频导出完成,逐帧完整性验证通过":std::format(L"视频导出完成({}),逐帧完整性验证通过",encoderName);
- if(tailSnapped>0)done+=std::format(L"(尾部 {} 帧时间戳已按恒定帧率对齐)",tailSnapped);
- if(gapFilledSlots>0)done+=std::format(L"(源文件缺帧 {} 处/{} 帧,已按恒定帧率复制上一帧补齐)",gapFillEvents,gapFilledSlots);
+ std::wstring done=encoderName.empty()?L"视频导出完成":std::format(L"视频导出完成({})",encoderName);
+ if(repairedTimestamps>0)done+=std::format(L"(已修复 {} 帧缺失或倒退的时间戳)",repairedTimestamps);
progress(1,fgNote.empty()?done:fgNote+L";"+done);
}
else {
diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cpp
index 1695b390..5e1cbb96 100644
--- a/src/engine/VideoPresenter.cpp
+++ b/src/engine/VideoPresenter.cpp
@@ -5,10 +5,22 @@
#include "veyra/sink/ImageExportSink.h"
namespace veyra::engine {
bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::EnhanceGraph& graph,bool captureCompatible) {
- gpuTimer_.initialize(ctx.device(),ctx.directQueue());window_=window;RECT rc{};GetClientRect(window,&rc);
+ close();
+ Status st=Status::Ok;
+ if(graph.fgEnabled()&&!graph.xessEnabled()&&!graph.fsrEnabled()){
+ D3D12_COMMAND_QUEUE_DESC desc{};desc.Type=D3D12_COMMAND_LIST_TYPE_DIRECT;
+ HRESULT hr=ctx.device()->CreateCommandQueue(&desc,IID_PPV_ARGS(&presentationQueue_));
+ if(SUCCEEDED(hr))hr=ctx.device()->CreateFence(0,D3D12_FENCE_FLAG_NONE,IID_PPV_ARGS(&presentationFence_));
+ if(FAILED(hr)){veyra::log::error("present",std::format("DLSS presentation queue/fence hr=0x{:X}",unsigned(hr)));close();return false;}
+ presentationEvent_=CreateEventW(nullptr,FALSE,FALSE,nullptr);
+ if(!presentationEvent_||!presentationRing_.initialize(ctx.device(),presentationQueue_.Get(),presentationFence_.Get(),presentationEvent_,3,st)){close();return false;}
+ veyra::log::info("present","DLSS presentation uses independent queue/fence, 3 command slots; shared textures use producer/consumer GPU fences");
+ }
+ auto* queue=presentationQueue_?presentationQueue_.Get():ctx.directQueue();
+ gpuTimer_.initialize(ctx.device(),queue);window_=window;RECT rc{};GetClientRect(window,&rc);
gfx::PresentSink::Desc d;d.targetWindow=window;d.width=std::max(1L,rc.right);d.height=std::max(1L,rc.bottom);d.vsync=false;
d.hdr=graph.hdrOutput();d.hdr10=graph.hdr10Output();d.xess=graph.xessEnabled();d.fsr=graph.fsrEnabled();d.renderWidth=graph.workWidth();d.renderHeight=graph.workHeight();d.captureCompatible=captureCompatible;d.fgMultiplier=graph.fgMultiplier();lastXessFrame_={};lastXessIdentity_={};xessWasEnabled_=false;lastFsrFrame_={};lastFsrIdentity_={};fsrWasEnabled_=false;
- Status st=Status::Ok;if(!sink_.initialize(ctx.device(),ctx.directQueue(),d,st))return false;
+ if(!sink_.initialize(ctx.device(),queue,d,st))return false;
std::vector<uint8_t> vs,ps;
// SRV layout: 0..1 video frames, 2..11 generated frames (2 parities x 5
// subframes, 6X), 12..15 comparison references.
@@ -21,7 +33,11 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::Enh
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,bool referencesValid,int comparison,bool baseReference,float split,pipeline::FrameIdentity identity,PreviewView view) {
+bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& sharedRing,pipeline::EnhanceGraph& graph,unsigned slot,bool generated,bool referencesValid,int comparison,bool baseReference,float split,pipeline::FrameIdentity identity,PreviewView view) {
+ auto& ring=presentationQueue_?presentationRing_:sharedRing;
+ auto* fence=presentationFence_?presentationFence_.Get():ctx.fence();
+ const auto presentStart=std::chrono::steady_clock::now();
+ const auto slotWaitStart=ring.cpuWaitMilliseconds();
xessFailed_=false;fsrFailed_=false;
RECT rc{};GetClientRect(window_,&rc);if(rc.right<1||rc.bottom<1)return true;
const auto now=std::chrono::steady_clock::now();
@@ -34,14 +50,19 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
refresh(ctx.device());lastResize_=now;xessWasEnabled_=false;
}
if(sink_.xess()&&!sink_.xess()->beginFrame()){xessFailed_=true;return false;}
+ if(presentationQueue_){
+ const HRESULT hr=presentationQueue_->Wait(ctx.fence(),graph.presentationReadyFence(slot,generated));
+ if(FAILED(hr)){veyra::log::error("present",std::format("producer handoff wait hr=0x{:X}",unsigned(hr)));return false;}
+ }
Status st=Status::Ok;uint32_t commandSlot=0;auto* list=ring.acquireNext(commandSlot,st);if(!list)return false;
- gpuTimer_.frame(identity.sourceFrameId?identity:pipeline::FrameIdentity{0,0,submittedCount()+1},ctx.fence());gpuTimer_.mark(list,diagnostics::GpuStage::Blit);
- auto* source=generated?graph.generatedFrameResource(slot):graph.videoFrameResource(slot);auto* bb=sink_.currentBackBuffer();if(!bb)return false;
+ gpuTimer_.frame(identity.sourceFrameId?identity:pipeline::FrameIdentity{0,0,submittedCount()+1},fence);gpuTimer_.mark(list,diagnostics::GpuStage::Blit);
+ uint32_t backBufferIndex=0;
+ auto* source=generated?graph.generatedFrameResource(slot):graph.videoFrameResource(slot);auto* bb=sink_.currentBackBuffer(&backBufferIndex);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_};
+ D3D12_CPU_DESCRIPTOR_HANDLE rtv{rtvs_->GetCPUDescriptorHandleForHeapStart().ptr+size_t(backBufferIndex)*inc_};
const float black[4]={0,0,0,1};list->ClearRenderTargetView(rtv,black,0,nullptr);list->OMSetRenderTargets(1,&rtv,FALSE,nullptr);
// DXGI stretches the retained buffer while the native workspace unfolds.
// Compute contain in CURRENT client coordinates, then map back to buffer
@@ -129,17 +150,35 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
lastFsrFrame_=now;lastFsrIdentity_=identity;fsrWasEnabled_=enabled;
}
gpuTimer_.mark(list,diagnostics::GpuStage::Blit,true);gpuTimer_.resolve(list);
- if(!ring.submitAndSignal(commandSlot))return false;gpuTimer_.submitted(ring.lastSignaledValue());lastBuffer_=sink_.swapChain()->GetCurrentBackBufferIndex();hasPresented_=true;
- const bool presented=sink_.present(st);xessFailed_=sink_.xessFailed();fsrFailed_=fsrFailed_||sink_.fsrFailed();return presented;
+ if(!ring.submitAndSignal(commandSlot))return false;gpuTimer_.submitted(ring.lastSignaledValue());lastBuffer_=backBufferIndex;hasPresented_=true;
+ if(presentationQueue_)graph.presentationSubmitted(slot,fence,ring.lastSignaledValue());
+ const auto dxgiStart=std::chrono::steady_clock::now();
+ const bool presented=sink_.present(st);
+ const auto presentEnd=std::chrono::steady_clock::now();
+ if(presentEnd>=nextCostLog_){
+ nextCostLog_=presentEnd+std::chrono::seconds(1);
+ veyra::log::info("present-cost",std::format("generated={} totalMs={:.3f} recordSubmitMs={:.3f} slotWaitMs={:.3f} dxgiMs={:.3f}",generated,
+ std::chrono::duration<double,std::milli>(presentEnd-presentStart).count(),
+ std::chrono::duration<double,std::milli>(dxgiStart-presentStart).count(),ring.cpuWaitMilliseconds()-slotWaitStart,
+ std::chrono::duration<double,std::milli>(presentEnd-dxgiStart).count()));
+ }
+ xessFailed_=sink_.xessFailed();fsrFailed_=fsrFailed_||sink_.fsrFailed();return presented;
}
bool VideoPresenter::readPresentedFrameForTest(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,sink::RgbaImage& image){
+ if(presentationQueue_&&!presentationRing_.drainQueue())return false;
if(!hasPresented_||!sink_.swapChain()||!ring.drainQueue())return false;
Microsoft::WRL::ComPtr<ID3D12Resource> buffer;
return SUCCEEDED(sink_.swapChain()->GetBuffer(lastBuffer_,IID_PPV_ARGS(&buffer)))&&sink::readRgba8(ctx,ring,buffer.Get(),image);
}
-void VideoPresenter::close(){hasPresented_=false;gpuTimer_.close();rtvs_.Reset();pass_={};sink_.shutdown();}
-Microsoft::WRL::ComPtr<ID3D12Resource> VideoPresenter::presentedResourceForTest() const {
+void VideoPresenter::close(){
+ if(presentationRing_.initialized())presentationRing_.drainQueue();
+ hasPresented_=false;gpuTimer_.close();rtvs_.Reset();pass_={};sink_.shutdown();
+ presentationRing_.shutdown();presentationFence_.Reset();presentationQueue_.Reset();
+ if(presentationEvent_){CloseHandle(presentationEvent_);presentationEvent_=nullptr;}
+}
+Microsoft::WRL::ComPtr<ID3D12Resource> VideoPresenter::presentedResourceForTest() {
Microsoft::WRL::ComPtr<ID3D12Resource> buffer;
+ if(presentationQueue_&&!presentationRing_.drainQueue())return buffer;
if(hasPresented_&&sink_.swapChain())sink_.swapChain()->GetBuffer(lastBuffer_,IID_PPV_ARGS(&buffer));
return buffer;
}
diff --git a/src/gfx/D3D12DeviceContext.cpp b/src/gfx/D3D12DeviceContext.cpp
index 2d694e8e..ec6dc94f 100644
--- a/src/gfx/D3D12DeviceContext.cpp
+++ b/src/gfx/D3D12DeviceContext.cpp
@@ -175,7 +175,9 @@ bool D3D12DeviceContext::initialize(const DeviceContextDesc& desc, Status& statu
candidateDesc.DedicatedVideoMemory / (1024 * 1024),
narrow(candidateDesc.Description)));
- if ((!desc.requiredVendorId||candidateDesc.VendorId==desc.requiredVendorId) && !isSoftware &&
+ const auto candidateLuid=(uint64_t(uint32_t(candidateDesc.AdapterLuid.HighPart))<<32)|candidateDesc.AdapterLuid.LowPart;
+ if ((!desc.requiredVendorId||candidateDesc.VendorId==desc.requiredVendorId) &&
+ (!desc.requiredLuid||candidateLuid==desc.requiredLuid) && !isSoftware &&
SUCCEEDED(D3D12CreateDevice(candidate.Get(),D3D_FEATURE_LEVEL_12_0,__uuidof(ID3D12Device),nullptr))) {
adapter_ = candidate;
chosenDesc = candidateDesc;
diff --git a/src/gfx/PresentSink.cpp b/src/gfx/PresentSink.cpp
index 40516267..255f6bf0 100644
--- a/src/gfx/PresentSink.cpp
+++ b/src/gfx/PresentSink.cpp
@@ -279,8 +279,14 @@ bool PresentSink::processMessages(bool& windowClosed)
return true;
}
-ID3D12Resource* PresentSink::currentBackBuffer()
+ID3D12Resource* PresentSink::currentBackBuffer(uint32_t* acquiredIndex)
{
+ if(!swapChain_)return nullptr;
+ // Provider proxy swapchains own their buffer rotation. Acquire once for
+ // both the resource barriers and the matching render-target descriptor.
+ backBufferIndex_=swapChain_->GetCurrentBackBufferIndex();
+ if(backBufferIndex_>=3)return nullptr;
+ if(acquiredIndex)*acquiredIndex=backBufferIndex_;
return backBuffers_[backBufferIndex_].Get();
}
diff --git a/src/ngx/AdaMfgUnlock.cpp b/src/ngx/AdaMfgUnlock.cpp
index 1ae9d1c6..c624cb16 100644
--- a/src/ngx/AdaMfgUnlock.cpp
+++ b/src/ngx/AdaMfgUnlock.cpp
@@ -1,6 +1,8 @@
#include "veyra/ngx/AdaMfgUnlock.h"
#include "veyra/Log.h"
+#include "veyra/FileIdentity.h"
+#include "compat/RestoreMemory.h"
#include <bcrypt.h>
@@ -442,7 +444,7 @@ bool findMfgGateSite(uint8_t* base, const IMAGE_NT_HEADERS64* nt, MfgGateSite& s
return true;
}
-void patchGateSites(uint8_t* base, const IMAGE_NT_HEADERS64* nt,
+bool patchGateSites(uint8_t* base, const IMAGE_NT_HEADERS64* nt,
std::vector<std::pair<unsigned char*, unsigned char>>& sites) {
const auto* section = IMAGE_FIRST_SECTION(nt);
const size_t imageSize = nt->OptionalHeader.SizeOfImage;
@@ -463,18 +465,15 @@ void patchGateSites(uint8_t* base, const IMAGE_NT_HEADERS64* nt,
target = start + off + 2;
}
if (target == nullptr) continue;
- DWORD oldProtect = 0;
- if (VirtualProtect(target, 1, PAGE_EXECUTE_READWRITE, &oldProtect) == 0) continue;
sites.push_back({target, *target});
- *target = 0x90; // 0x1b0 -> 0x190 (Blackwell gate -> Ada passes it)
- DWORD ignored = 0;
- VirtualProtect(target, 1, oldProtect, &ignored);
+ const uint8_t replacement=0x90; // Blackwell gate -> Ada
+ if(!compat::restoreMemory(target,&replacement,1))return false;
if (target + 1 - start <= LONG(size)) {
off += 5; // the compare we just rewrote cannot start inside itself
}
}
}
- FlushInstructionCache(GetCurrentProcess(), base, size_t(nt->OptionalHeader.SizeOfImage));
+ return true;
}
} // namespace
@@ -577,30 +576,22 @@ AdaMfgUnlock::State AdaMfgUnlock::apply(HMODULE module, bool includeKernelFix) {
nt->FileHeader.TimeDateStamp == kKnownTimeDateStamp;
auto rollbackGates = [&]() {
+ bool restored = true;
for (const auto& site : g.gateSites) {
- DWORD oldProtect = 0;
- if (VirtualProtect(site.first, 1, PAGE_EXECUTE_READWRITE, &oldProtect) == 0) continue;
- *site.first = site.second;
- DWORD ignored = 0;
- VirtualProtect(site.first, 1, oldProtect, &ignored);
+ restored = compat::restoreMemory(site.first, &site.second, 1) && restored;
}
- g.gateSites.clear();
for (const auto& write : g.mfgGateWrites) {
- DWORD oldProtect = 0;
- if (VirtualProtect(write.jump, 2, PAGE_EXECUTE_READWRITE, &oldProtect) == 0) continue;
- std::memcpy(write.jump, write.original.data(), 2);
- FlushInstructionCache(GetCurrentProcess(), write.jump, 2);
- DWORD ignored = 0;
- VirtualProtect(write.jump, 2, oldProtect, &ignored);
+ restored = compat::restoreMemory(write.jump, write.original.data(), 2) && restored;
}
- g.mfgGateWrites.clear();
+ if (restored) { g.gateSites.clear(); g.mfgGateWrites.clear(); }
+ else log::error("ada-mfg", "gate rollback incomplete; retaining restoration records");
};
// Architecture gates first: without both of them the runtime advertises
// multi-frame and then renders black.
- patchGateSites(base, nt, g.gateSites);
+ const bool gatesWritten=patchGateSites(base, nt, g.gateSites);
state.archGateSites = g.gateSites.size();
- state.archGatesPatched = state.archGateSites >= kMinArchGateSites &&
+ state.archGatesPatched = gatesWritten && state.archGateSites >= kMinArchGateSites &&
state.archGateSites <= kMaxArchGateSites;
if (!state.archGatesPatched) {
rollbackGates();
@@ -633,21 +624,16 @@ AdaMfgUnlock::State AdaMfgUnlock::apply(HMODULE module, bool includeKernelFix) {
g.state = state;
return state;
}
+ g.mfgGateWrites.push_back({mfgGate.jump, mfgGateOriginal});
{
- DWORD oldProtect = 0;
- if (VirtualProtect(mfgGate.jump, 2, PAGE_EXECUTE_READWRITE, &oldProtect) == 0) {
+ if (!compat::restoreMemory(mfgGate.jump,kMfgGateReplacement,2)) {
rollbackGates();
state.archGatesPatched = false;
state.detail = L"count/index validator page is not writable; runtime left untouched";
g.state = state;
return state;
}
- std::memcpy(mfgGate.jump, kMfgGateReplacement, 2);
- FlushInstructionCache(GetCurrentProcess(), mfgGate.jump, 2);
- DWORD ignored = 0;
- VirtualProtect(mfgGate.jump, 2, oldProtect, &ignored);
}
- g.mfgGateWrites.push_back({mfgGate.jump, mfgGateOriginal});
state.mfgGatePatched = true;
if (includeKernelFix) {
@@ -674,16 +660,19 @@ AdaMfgUnlock::State AdaMfgUnlock::apply(HMODULE module, bool includeKernelFix) {
return state;
}
std::memcpy(mem, rebuilt.data(), rebuilt.size());
+ g.kernelAllocation = mem;
for (const auto& hit : hits) {
- DWORD oldProtect = 0;
- if (VirtualProtect(hit.slot, 8, PAGE_READWRITE, &oldProtect) == 0) continue;
g.descriptorSlots.push_back({hit.slot, *hit.slot});
- *hit.slot = reinterpret_cast<uint64_t>(mem);
- DWORD ignored = 0;
- VirtualProtect(hit.slot, 8, oldProtect, &ignored);
+ const uint64_t replacement=reinterpret_cast<uint64_t>(mem);
+ if(!compat::restoreMemory(hit.slot,&replacement,8)){
+ // Keep all records and storage for the owning session's rollback.
+ state.detail=L"descriptor publication failed; session rollback required";
+ g.state=state;return state;
+ }
}
if (g.descriptorSlots.empty()) {
VirtualFree(mem, 0, MEM_RELEASE);
+ g.kernelAllocation=nullptr;
rollbackGates();
state.archGatesPatched = false;
state.mfgGatePatched = false;
@@ -709,44 +698,31 @@ AdaMfgUnlock::State AdaMfgUnlock::apply(HMODULE module, bool includeKernelFix) {
return state;
}
-void AdaMfgUnlock::release() {
+bool AdaMfgUnlock::release() {
auto& g = global();
std::lock_guard lock(g.mutex);
if (!g.installed && g.gateSites.empty() && g.descriptorSlots.empty() && g.mfgGateWrites.empty()) {
- return;
+ return true;
}
+ bool restored = true;
for (const auto& slot : g.descriptorSlots) {
- DWORD oldProtect = 0;
- if (VirtualProtect(slot.first, 8, PAGE_READWRITE, &oldProtect) == 0) continue;
- *slot.first = slot.second;
- DWORD ignored = 0;
- VirtualProtect(slot.first, 8, oldProtect, &ignored);
- }
- g.descriptorSlots.clear();
- if (g.kernelAllocation != nullptr) {
- VirtualFree(g.kernelAllocation, 0, MEM_RELEASE);
- g.kernelAllocation = nullptr;
+ restored = compat::restoreMemory(slot.first, &slot.second, 8) && restored;
}
for (const auto& site : g.gateSites) {
- DWORD oldProtect = 0;
- if (VirtualProtect(site.first, 1, PAGE_EXECUTE_READWRITE, &oldProtect) == 0) continue;
- *site.first = site.second;
- DWORD ignored = 0;
- VirtualProtect(site.first, 1, oldProtect, &ignored);
+ restored = compat::restoreMemory(site.first, &site.second, 1) && restored;
}
- g.gateSites.clear();
for (const auto& write : g.mfgGateWrites) {
- DWORD oldProtect = 0;
- if (VirtualProtect(write.jump, 2, PAGE_EXECUTE_READWRITE, &oldProtect) == 0) continue;
- std::memcpy(write.jump, write.original.data(), 2);
- FlushInstructionCache(GetCurrentProcess(), write.jump, 2);
- DWORD ignored = 0;
- VirtualProtect(write.jump, 2, oldProtect, &ignored);
+ restored = compat::restoreMemory(write.jump, write.original.data(), 2) && restored;
}
+ if (!restored) { log::error("ada-mfg", "rollback incomplete; retaining kernel storage and records"); return false; }
+ g.descriptorSlots.clear();
+ g.gateSites.clear();
g.mfgGateWrites.clear();
+ if (g.kernelAllocation != nullptr) { VirtualFree(g.kernelAllocation, 0, MEM_RELEASE); g.kernelAllocation = nullptr; }
g.installed = false;
g.state = State{};
veyra::log::info("ada-mfg", "Ada multi-frame unlock rolled back (runtime image restored)");
+ return true;
}
AdaMfgUnlock::State AdaMfgUnlock::snapshot() {
@@ -762,12 +738,9 @@ bool AdaMfgUnlock::applied() {
}
bool AdaMfgUnlock::moduleIsAudited(const std::wstring& path) {
- std::error_code ec;
- const auto size = std::filesystem::file_size(path, ec);
- if (ec || size != kKnownModuleSize) return false;
- // Full hash verification happens in the probe and before any write; the UI
- // hint only needs the cheap size check plus the PE identity.
- return true;
+ FileIdentity identity;IdentityError error;
+ computeFileIdentity(path,identity,error);
+ return identity.sizeBytes==kKnownModuleSize&&identity.sha256Upper==kKnownModuleSha256;
}
} // namespace veyra::ngx
diff --git a/src/ngx/AmpereMfgUnlock.cpp b/src/ngx/AmpereMfgUnlock.cpp
index bfab0605..97d026da 100644
--- a/src/ngx/AmpereMfgUnlock.cpp
+++ b/src/ngx/AmpereMfgUnlock.cpp
@@ -1,8 +1,10 @@
#include "veyra/ngx/AmpereMfgUnlock.h"
#include "veyra/Log.h"
+#include "compat/RestoreMemory.h"
#include <bcrypt.h>
+#include <psapi.h>
#include <algorithm>
#include <array>
@@ -296,12 +298,15 @@ bool buildSm86Fatbin(const FatbinInfo& info, std::vector<uint8_t>& out, std::str
uint8_t* entry = out.data() + kOuterHeader;
std::memcpy(entry, info.address + info.entryOffset, info.entryHeaderBytes);
const uint64_t padded64 = padded;
- const uint32_t zero32 = 0;
+ // Match upstream BuildAmpereSm86Fatbin: compressed entries use the padded
+ // length after expansion; originally raw entries retain an explicit size.
+ const uint32_t actualPayloadBytes = (info.flags & kCompressedFlag) != 0
+ ? 0u : static_cast<uint32_t>(ptx.size());
const uint64_t zero64 = 0;
const uint32_t sm86 = kSm86;
const uint64_t uncompressed = info.flags & ~kCompressedFlag;
std::memcpy(entry + 8, &padded64, 8);
- std::memcpy(entry + 16, &zero32, 4);
+ std::memcpy(entry + 16, &actualPayloadBytes, 4);
std::memcpy(entry + 28, &sm86, 4);
std::memcpy(entry + 40, &uncompressed, 8);
std::memcpy(entry + 56, &zero64, 8);
@@ -334,6 +339,7 @@ struct SlotHit {
uint8_t* slot = nullptr; // address of the fatbin pointer field
const uint8_t* fatbin = nullptr;
size_t fatbinSize = 0;
+ std::string entryName;
};
// Find every registration-table slot: an 8-byte field inside a read-only,
@@ -356,12 +362,12 @@ std::vector<SlotHit> findSlotHits(const ImageLayout& image) {
if (value < imageStart || value >= imageStart + imageSize) continue;
const auto* candidate = reinterpret_cast<const uint8_t*>(value);
if (readU32(candidate) != kFatbinMagic) continue;
- uint64_t entryName = 0, descName = 0;
- std::memcpy(&entryName, sec + off + kEntryNameOffset, 8);
+ uint64_t entryNamePointer = 0, descName = 0;
+ std::memcpy(&entryNamePointer, sec + off + kEntryNameOffset, 8);
// The record's own name field sits 8 bytes before the slot; the
// following record's first field would read past a run's end.
std::memcpy(&descName, sec + off - 8, 8);
- if (!pointsToCString(image.base, imageSize, entryName, kEntryName)) continue;
+ if (!pointsToCString(image.base, imageSize, entryNamePointer, kEntryName)) continue;
if (!pointsToCString(image.base, imageSize, descName, kDescriptorName)) continue;
const size_t total = size_t(readU64(candidate + 8)) + kOuterHeader;
if (total < 1024 || total > kMaximumFatbinBytes) continue;
@@ -369,7 +375,17 @@ std::vector<SlotHit> findSlotHits(const ImageLayout& image) {
if (value < imageStart) continue;
FatbinInfo info{};
if (!parseFatbin(candidate, total, info)) continue;
- hits.push_back({sec + off, candidate, total});
+ uint64_t entryNameAddress = 0;
+ std::memcpy(&entryNameAddress, sec + off + kEntryNameOffset, 8);
+ std::string entryName;
+ if (entryNameAddress >= imageStart &&
+ entryNameAddress < imageStart + imageSize) {
+ const char* text = reinterpret_cast<const char*>(entryNameAddress);
+ const size_t maxLength = imageStart + imageSize - entryNameAddress;
+ const size_t length = strnlen_s(text, maxLength);
+ if (length > 0 && length < 96) entryName.assign(text, length);
+ }
+ hits.push_back({sec + off, candidate, total, std::move(entryName)});
}
}
return hits;
@@ -464,13 +480,50 @@ struct LeaWrite {
int32_t original = 0;
};
+struct FontWrite {
+ uint8_t* address = nullptr;
+ std::vector<uint8_t> original;
+ DWORD protection = 0;
+};
+
+// Adapted from upstream FontPageProtectionMatches/RestoreFontPage/WriteFont.
+// Windows may report a privatized WRITECOPY image page as READWRITE. Accept
+// that transition only after the working set proves the page is private.
+bool writeFontPage(const FontWrite& page, const uint8_t* bytes) {
+ if (GetEnvironmentVariableW(L"VEYRA_TEST_PATCH_RESTORE_FAIL", nullptr, 0)) return false;
+ DWORD ignored = 0;
+ const bool writable = VirtualProtect(page.address, page.original.size(), PAGE_WRITECOPY, &ignored) != FALSE;
+ if (writable) std::memcpy(page.address, bytes, page.original.size());
+ bool restored = false;
+ for (unsigned retry = 0; retry != 2 && !restored; ++retry) {
+ VirtualProtect(page.address, page.original.size(), page.protection, &ignored);
+ MEMORY_BASIC_INFORMATION memory{};
+ if (VirtualQuery(page.address, &memory, sizeof(memory)) != sizeof(memory) ||
+ memory.State != MEM_COMMIT || memory.Type != MEM_IMAGE) continue;
+ restored = memory.Protect == page.protection;
+ if (!restored && page.protection == PAGE_WRITECOPY && memory.Protect == PAGE_READWRITE) {
+ PSAPI_WORKING_SET_EX_INFORMATION working{};
+ working.VirtualAddress = page.address;
+ restored = K32QueryWorkingSetEx(GetCurrentProcess(), &working, sizeof(working)) &&
+ working.VirtualAttributes.Valid && !working.VirtualAttributes.Shared;
+ }
+ }
+ if (!restored) compat::memoryProtectionUncertain = true;
+ const bool ok = writable && restored && std::memcmp(page.address, bytes, page.original.size()) == 0;
+ if (!ok) log::error("ampere-mfg", std::format("font page write failed writable={} restored={} win32={}",
+ writable, restored, GetLastError()));
+ return ok;
+}
+
struct GlobalState {
std::mutex mutex;
AmpereMfgUnlock::State state{};
bool installed = false;
std::vector<std::pair<uint8_t*, uint8_t>> archGateWrites;
std::vector<std::pair<uint64_t*, uint64_t>> slotWrites;
+ std::vector<std::pair<uint8_t*, uint32_t>> sizeWrites;
std::vector<LeaWrite> leaWrites;
+ std::vector<FontWrite> fontWrites;
void* allocation = nullptr;
};
@@ -481,7 +534,7 @@ GlobalState& global() {
// Patch the 0x1b0 architecture compares to 0x170 (Ampere) so 30/40/50 series
// all pass; the gate only decides the reported multi-frame ceiling.
-void patchArchGates(uint8_t* base, const IMAGE_NT_HEADERS64* nt,
+bool patchArchGates(uint8_t* base, const IMAGE_NT_HEADERS64* nt,
std::vector<std::pair<uint8_t*, uint8_t>>& sites) {
const auto* section = IMAGE_FIRST_SECTION(nt);
for (WORD i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++section) {
@@ -501,18 +554,15 @@ void patchArchGates(uint8_t* base, const IMAGE_NT_HEADERS64* nt,
target = start + off + 2;
}
if (target == nullptr) continue;
- DWORD oldProtect = 0;
- if (VirtualProtect(target, 1, PAGE_EXECUTE_READWRITE, &oldProtect) == 0) continue;
sites.push_back({target, *target});
- *target = 0x70; // 0x1b0 -> 0x170 (Ampere passes)
- DWORD ignored = 0;
- VirtualProtect(target, 1, oldProtect, &ignored);
+ const uint8_t replacement=0x70;
+ if(!compat::restoreMemory(target,&replacement,1))return false;
if (target + 1 - start <= LONG(size)) {
off += 5;
}
}
}
- FlushInstructionCache(GetCurrentProcess(), base, size_t(nt->OptionalHeader.SizeOfImage));
+ return true;
}
// Allocate the rebuilt set inside an address window that every RIP-relative
@@ -557,7 +607,8 @@ void* allocateReachable(size_t bytes, const uint8_t* moduleBase) {
// compiles the sm_86 programs on the real Ampere device; on other hosts it at
// least proves the PTX/JIT path is legal.
bool preflightPrograms(const std::vector<std::pair<const uint8_t*, size_t>>& programs,
- std::string& why, size_t& loaded) {
+ const std::vector<std::string>& entryNames,
+ uint64_t adapterLuid, std::string& why, size_t& loaded) {
loaded = 0;
HMODULE cuda = LoadLibraryExW(L"nvcuda.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
if (cuda == nullptr) {
@@ -570,16 +621,31 @@ bool preflightPrograms(const std::vector<std::pair<const uint8_t*, size_t>>& pro
reinterpret_cast<void*>(GetProcAddress(cuda, "cuInit")));
const auto deviceGet = reinterpret_cast<int (*)(int*, int)>(
reinterpret_cast<void*>(GetProcAddress(cuda, "cuDeviceGet")));
+ const auto deviceGetCount = reinterpret_cast<int (*)(int*)>(
+ reinterpret_cast<void*>(GetProcAddress(cuda, "cuDeviceGetCount")));
+ const auto deviceGetLuid = reinterpret_cast<int (*)(char*, unsigned*, int)>(
+ reinterpret_cast<void*>(GetProcAddress(cuda, "cuDeviceGetLuid")));
const auto ctxCreate = reinterpret_cast<int (*)(void**, unsigned, int)>(
reinterpret_cast<void*>(GetProcAddress(cuda, "cuCtxCreate_v2")));
const auto ctxDestroy = reinterpret_cast<int (*)(void*)>(
reinterpret_cast<void*>(GetProcAddress(cuda, "cuCtxDestroy_v2")));
- const auto moduleLoad = reinterpret_cast<int (*)(void**, const void*, unsigned, void*, void*)>(
- reinterpret_cast<void*>(GetProcAddress(cuda, "cuModuleLoadDataEx")));
+ const auto ctxGetCurrent = reinterpret_cast<int (*)(void**)>(
+ reinterpret_cast<void*>(GetProcAddress(cuda, "cuCtxGetCurrent")));
+ const auto ctxPopCurrent = reinterpret_cast<int (*)(void**)>(
+ reinterpret_cast<void*>(GetProcAddress(cuda, "cuCtxPopCurrent_v2")));
+ const auto moduleLoad = reinterpret_cast<int (*)(void**, const void*)>(
+ reinterpret_cast<void*>(GetProcAddress(cuda, "cuModuleLoadData")));
+ const auto moduleGetFunction = reinterpret_cast<int (*)(void**, void*, const char*)>(
+ reinterpret_cast<void*>(GetProcAddress(cuda, "cuModuleGetFunction")));
+ const auto functionLoad = reinterpret_cast<int (*)(void*)>(
+ reinterpret_cast<void*>(GetProcAddress(cuda, "cuFuncLoad")));
const auto moduleUnload = reinterpret_cast<int (*)(void*)>(
reinterpret_cast<void*>(GetProcAddress(cuda, "cuModuleUnload")));
- if (init == nullptr || deviceGet == nullptr || ctxCreate == nullptr ||
- ctxDestroy == nullptr || moduleLoad == nullptr || moduleUnload == nullptr) {
+ if (init == nullptr || deviceGet == nullptr || deviceGetCount == nullptr ||
+ deviceGetLuid == nullptr || ctxCreate == nullptr ||
+ ctxDestroy == nullptr || ctxGetCurrent == nullptr || ctxPopCurrent == nullptr ||
+ moduleLoad == nullptr || moduleGetFunction == nullptr || moduleUnload == nullptr ||
+ programs.size() != entryNames.size()) {
why = "nvcuda.dll does not export the required driver API";
return false;
}
@@ -587,9 +653,37 @@ bool preflightPrograms(const std::vector<std::pair<const uint8_t*, size_t>>& pro
why = "cuInit failed";
return false;
}
- int device = 0;
- if (deviceGet(&device, 0) != 0) {
- why = "cuDeviceGet failed";
+ int device = -1, deviceCount = 0;
+ const int countResult = deviceGetCount(&deviceCount);
+ if (countResult != 0) {
+ why = std::format("cuDeviceGetCount failed result={}", countResult);
+ return false;
+ }
+ unsigned matches = 0;
+ for (int ordinal = 0; ordinal < deviceCount; ++ordinal) {
+ int candidate = -1;
+ const int getResult = deviceGet(&candidate, ordinal);
+ if (getResult != 0) {
+ why = std::format("cuDeviceGet failed ordinal={} result={}", ordinal, getResult);
+ return false;
+ }
+ uint64_t luid = 0;
+ unsigned nodeMask = 0;
+ const int luidResult = deviceGetLuid(reinterpret_cast<char*>(&luid), &nodeMask, candidate);
+ if ((adapterLuid == 0 && ordinal == 0) ||
+ (adapterLuid != 0 && luidResult == 0 && luid == adapterLuid && nodeMask != 0)) {
+ device = candidate;
+ ++matches;
+ }
+ }
+ if (matches != 1) {
+ why = std::format("CUDA adapter match failed D3D12 LUID=0x{:X} matches={}", adapterLuid, matches);
+ return false;
+ }
+ log::info("ampere-mfg", std::format("CUDA preflight adapter={} D3D12 LUID=0x{:X}", device, adapterLuid));
+ void* previousContext = nullptr;
+ if (ctxGetCurrent(&previousContext) != 0) {
+ why = "cuCtxGetCurrent failed";
return false;
}
void* context = nullptr;
@@ -600,17 +694,42 @@ bool preflightPrograms(const std::vector<std::pair<const uint8_t*, size_t>>& pro
bool ok = true;
for (size_t index = 0; index < programs.size(); ++index) {
void* module = nullptr;
- const int result = moduleLoad(&module, programs[index].first, 0, nullptr, nullptr);
+ const int result = moduleLoad(&module, programs[index].first);
if (result != 0) {
- why = std::format("the CUDA driver rejected rebuilt program {} (cuModuleLoadDataEx={})",
+ why = std::format("the CUDA driver rejected rebuilt program {} (cuModuleLoadData={})",
index, result);
ok = false;
break;
}
- if (module != nullptr) moduleUnload(module);
+ void* function = nullptr;
+ const char* entry = entryNames[index].empty() ? "main_kernel" : entryNames[index].c_str();
+ const int functionResult = module != nullptr
+ ? moduleGetFunction(&function, module, entry) : 200;
+ const int loadResult = functionResult == 0 && functionLoad != nullptr && function != nullptr
+ ? functionLoad(function) : functionResult == 0 && functionLoad == nullptr ? 0 : 200;
+ const int unloadResult = module != nullptr ? moduleUnload(module) : 200;
+ if (functionResult != 0 || loadResult != 0 || unloadResult != 0 || function == nullptr) {
+ why = std::format("CUDA function preflight failed for program {} entry={} module={} function={} cuModuleGetFunction={} cuFuncLoad={} cuModuleUnload={}",
+ index, entry, module != nullptr ? 1 : 0, function != nullptr ? 1 : 0,
+ functionResult, loadResult, unloadResult);
+ ok = false;
+ break;
+ }
++loaded;
}
- ctxDestroy(context);
+ void* current = nullptr;
+ const int currentResult = ctxGetCurrent(&current);
+ void* popped = nullptr;
+ const int popResult = currentResult == 0 && current == context ? ctxPopCurrent(&popped) : 201;
+ const int destroyResult = popResult == 0 && popped == context ? ctxDestroy(context) : 201;
+ void* restoredContext = nullptr;
+ const int restoredResult = ctxGetCurrent(&restoredContext);
+ if (popResult != 0 || popped != context || destroyResult != 0 ||
+ restoredResult != 0 || restoredContext != previousContext) {
+ why = std::format("CUDA private context cleanup failed pop={} destroy={} restored={}",
+ popResult, destroyResult, restoredResult == 0 && restoredContext == previousContext ? 1 : 0);
+ ok = false;
+ }
return ok;
}
@@ -774,7 +893,7 @@ bool AmpereMfgUnlock::adapterIsAmpere(uint32_t vendorId, uint32_t deviceId) {
return deviceId >= 0x2200 && deviceId < 0x2680;
}
-AmpereMfgUnlock::State AmpereMfgUnlock::apply(HMODULE module, bool retargetArchGates) {
+AmpereMfgUnlock::State AmpereMfgUnlock::apply(HMODULE module, bool retargetArchGates, uint64_t adapterLuid) {
auto& g = global();
std::lock_guard lock(g.mutex);
State state{};
@@ -922,15 +1041,23 @@ AmpereMfgUnlock::State AmpereMfgUnlock::apply(HMODULE module, bool retargetArchG
state.auxFatbins = auxCount;
state.leaSites = leaSites.size();
- // Rebuild every fatbin as a single-entry sm_86 program (the temporal slot
- // additionally gets the midpoint correction).
+ // Match upstream's 25 registered programs plus the exact auxiliary font.
+ // DL4RT network and other auxiliary programs remain provider-owned.
struct Replacement {
const uint8_t* original = nullptr;
std::vector<uint8_t> data;
};
std::vector<Replacement> replacements;
- replacements.reserve(fatbins.size());
- for (const auto& fb : fatbins) {
+ replacements.reserve(programAddresses.size());
+ for (const auto* address : programAddresses) {
+ const auto fbIt = std::find_if(fatbins.begin(), fatbins.end(),
+ [&](const FatbinInfo& fb) { return fb.address == address; });
+ if (fbIt == fatbins.end()) {
+ state.detail = L"registered kernel fatbin disappeared from the audited inventory";
+ g.state = state;
+ return state;
+ }
+ const auto& fb = *fbIt;
std::vector<uint8_t> data;
std::string why;
if (!buildSm86Fatbin(fb, data, why)) {
@@ -944,6 +1071,53 @@ AmpereMfgUnlock::State AmpereMfgUnlock::apply(HMODULE module, bool retargetArchG
replacements.push_back({fb.address, std::move(data)});
}
+ if (replacements.size() != programAddresses.size()) {
+ state.detail = L"rebuilt program count does not match registration slots";
+ g.state = state;
+ return state;
+ }
+
+ // The provider stores the CUDA kernel entry name in each registration
+ // record. Preserve that contract for cuModuleGetFunction preflight;
+ // assuming a generic name lets malformed PTX pass the cheap load check.
+ std::vector<std::string> entryNames;
+ entryNames.reserve(programAddresses.size());
+ for (const auto* address : programAddresses) {
+ const auto hit = std::find_if(hits.begin(), hits.end(),
+ [&](const SlotHit& slot) { return slot.fatbin == address; });
+ if (hit == hits.end() || hit->entryName.empty()) {
+ state.detail = L"a registered kernel is missing its CUDA entry name";
+ g.state = state;
+ return state;
+ }
+ entryNames.push_back(hit->entryName);
+ }
+
+ // Ported from upstream ampere_font_program.inl PrepareFont (MIT, pinned
+ // commit in the header). Rebuild PTX from the mapped image; no embedded
+ // native payload is copied into Veyra's source or written to disk.
+ constexpr size_t fontBytes = 6752;
+ constexpr char fontHash[] = "C6CC4129606AF4A3931C98BF7F7405EB9F5469F6522DA914FE7F3E5B39A224A1";
+ const FatbinInfo* font = nullptr;
+ for (const auto& fb : fatbins) {
+ if (classify(fb.address) != 2 || fb.size != fontBytes ||
+ !sha256Equals(fb.address, fb.size, fontHash)) continue;
+ if (font) {
+ state.detail = L"auxiliary font identity is not unique";
+ g.state = state;
+ return state;
+ }
+ font = &fb;
+ }
+ std::vector<uint8_t> fontData;
+ std::string fontWhy;
+ if (!font || !buildSm86Fatbin(*font, fontData, fontWhy) || fontData.size() > fontBytes) {
+ state.detail = std::format(L"auxiliary font rebuild refused: {}",
+ std::wstring(fontWhy.begin(), fontWhy.end()));
+ g.state = state;
+ return state;
+ }
+
// The driver must accept the whole rebuilt program set before anything is
// published; a rejected program is a refusal, never a half-installed set.
size_t preflightLoaded = 0;
@@ -953,8 +1127,10 @@ AmpereMfgUnlock::State AmpereMfgUnlock::apply(HMODULE module, bool retargetArchG
for (const auto& replacement : replacements) {
programData.push_back({replacement.data.data(), replacement.data.size()});
}
+ programData.push_back({fontData.data(), fontData.size()});
+ entryNames.push_back("cuda_font_kernel");
std::string preflightWhy;
- if (!preflightPrograms(programData, preflightWhy, preflightLoaded)) {
+ if (!preflightPrograms(programData, entryNames, adapterLuid, preflightWhy, preflightLoaded)) {
state.detail = std::format(L"CUDA preflight refused the rebuilt program set: {}",
std::wstring(preflightWhy.begin(), preflightWhy.end()));
g.state = state;
@@ -990,32 +1166,28 @@ AmpereMfgUnlock::State AmpereMfgUnlock::apply(HMODULE module, bool retargetArchG
};
auto rollbackAll = [&]() {
+ bool restored = true;
+ for (auto it = g.fontWrites.rbegin(); it != g.fontWrites.rend(); ++it) {
+ restored = writeFontPage(*it, it->original.data()) && restored;
+ }
for (auto it = g.leaWrites.rbegin(); it != g.leaWrites.rend(); ++it) {
- DWORD old = 0;
- if (VirtualProtect(it->disp32, 4, PAGE_EXECUTE_READWRITE, &old) == 0) continue;
- std::memcpy(it->disp32, &it->original, 4);
- DWORD ignored = 0;
- VirtualProtect(it->disp32, 4, old, &ignored);
+ restored = compat::restoreMemory(it->disp32, &it->original, 4) && restored;
}
- g.leaWrites.clear();
for (auto it = g.slotWrites.rbegin(); it != g.slotWrites.rend(); ++it) {
- DWORD old = 0;
- if (VirtualProtect(it->first, 8, PAGE_READWRITE, &old) == 0) continue;
- *it->first = it->second;
- DWORD ignored = 0;
- VirtualProtect(it->first, 8, old, &ignored);
+ restored = compat::restoreMemory(it->first, &it->second, 8) && restored;
+ }
+ for (auto it = g.sizeWrites.rbegin(); it != g.sizeWrites.rend(); ++it) {
+ restored = compat::restoreMemory(it->first, &it->second, 4) && restored;
}
- g.slotWrites.clear();
for (auto it = g.archGateWrites.rbegin(); it != g.archGateWrites.rend(); ++it) {
- DWORD old = 0;
- if (VirtualProtect(it->first, 1, PAGE_EXECUTE_READWRITE, &old) == 0) continue;
- *it->first = it->second;
- DWORD ignored = 0;
- VirtualProtect(it->first, 1, old, &ignored);
+ restored = compat::restoreMemory(it->first, &it->second, 1) && restored;
}
+ if (!restored) { log::error("ampere-mfg", "rollback incomplete; retaining kernel storage and records"); return; }
+ g.leaWrites.clear();
+ g.fontWrites.clear();
+ g.slotWrites.clear();
+ g.sizeWrites.clear();
g.archGateWrites.clear();
- FlushInstructionCache(GetCurrentProcess(), image.base,
- size_t(image.nt->OptionalHeader.SizeOfImage));
if (g.allocation != nullptr) {
VirtualFree(g.allocation, 0, MEM_RELEASE);
g.allocation = nullptr;
@@ -1026,8 +1198,8 @@ AmpereMfgUnlock::State AmpereMfgUnlock::apply(HMODULE module, bool retargetArchG
// the provider see Blackwell through the NVAPI spoof: then the provider's
// own compare must stay byte-identical so that the reported id matches it.
if (retargetArchGates) {
- patchArchGates(image.base, image.nt, g.archGateWrites);
- if (g.archGateWrites.size() < kMinArchGateSites ||
+ const bool written=patchArchGates(image.base, image.nt, g.archGateWrites);
+ if (!written || g.archGateWrites.size() < kMinArchGateSites ||
g.archGateWrites.size() > kMaxArchGateSites) {
const size_t found = g.archGateWrites.size();
rollbackAll();
@@ -1042,52 +1214,40 @@ AmpereMfgUnlock::State AmpereMfgUnlock::apply(HMODULE module, bool retargetArchG
}
state.archGatesPatched = true;
- // 2. registration slot pointers
+ // 2. Publish pointer AND supplied byte length, as upstream PatchProvider
+ // does at descriptor offsets +8/+16. Rebuilt PTX has a different size.
+ size_t redirectedSlots = 0;
for (const auto& hit : hits) {
const uint8_t* target = newAddressOf(hit.fatbin);
- if (target == nullptr) {
- rollbackAll();
- state.archGatesPatched = false;
- state.detail = L"internal error: rebuilt fatbin mapping missing for a slot";
- g.state = state;
- return state;
- }
- DWORD old = 0;
- if (VirtualProtect(hit.slot, 8, PAGE_READWRITE, &old) == 0) {
+ // Non-kernel records intentionally keep their original provider-owned
+ // network/auxiliary pointer and descriptor length.
+ if (target == nullptr) continue;
+ uint64_t original = 0;
+ std::memcpy(&original, hit.slot, 8);
+ g.slotWrites.push_back({reinterpret_cast<uint64_t*>(hit.slot), original});
+ const uint64_t replacement = reinterpret_cast<uint64_t>(target);
+ const auto size = static_cast<uint32_t>(readU64(target + 8) + kOuterHeader);
+ g.sizeWrites.push_back({hit.slot + 8, readU32(hit.slot + 8)});
+ if (!compat::restoreMemory(hit.slot,&replacement,8) ||
+ !compat::restoreMemory(hit.slot + 8, &size, 4)) {
rollbackAll();
state.archGatesPatched = false;
state.detail = L"a registration slot page is not writable; runtime left untouched";
g.state = state;
return state;
}
- uint64_t original = 0;
- std::memcpy(&original, hit.slot, 8);
- g.slotWrites.push_back({reinterpret_cast<uint64_t*>(hit.slot), original});
- const uint64_t replacement = reinterpret_cast<uint64_t>(target);
- std::memcpy(hit.slot, &replacement, 8);
- DWORD ignored = 0;
- VirtualProtect(hit.slot, 8, old, &ignored);
+ ++redirectedSlots;
}
// 3. RIP-relative references
for (const auto& site : leaSites) {
const uint8_t* target = newAddressOf(site.target);
if (target == nullptr) continue;
- DWORD old = 0;
- if (VirtualProtect(site.disp32, 4, PAGE_EXECUTE_READWRITE, &old) == 0) {
- rollbackAll();
- state.archGatesPatched = false;
- state.detail = L"a code page carrying a fatbin reference is not writable; runtime left untouched";
- g.state = state;
- return state;
- }
int32_t original = 0;
std::memcpy(&original, site.disp32, 4);
const int64_t displacement = intptr_t(target) -
(reinterpret_cast<intptr_t>(site.disp32) + 4);
if (displacement < INT32_MIN || displacement > INT32_MAX) {
- DWORD ignored0 = 0;
- VirtualProtect(site.disp32, 4, old, &ignored0);
rollbackAll();
state.archGatesPatched = false;
state.detail = L"a rebuilt fatbin is out of reach of its RIP-relative reference; runtime left untouched";
@@ -1096,59 +1256,87 @@ AmpereMfgUnlock::State AmpereMfgUnlock::apply(HMODULE module, bool retargetArchG
}
const int32_t replacement = static_cast<int32_t>(displacement);
g.leaWrites.push_back({site.disp32, original});
- std::memcpy(site.disp32, &replacement, 4);
- DWORD ignored = 0;
- VirtualProtect(site.disp32, 4, old, &ignored);
+ if(!compat::restoreMemory(site.disp32,&replacement,4)){
+ rollbackAll();state.archGatesPatched=false;
+ state.detail=L"fatbin code reference publication failed";
+ g.state=state;return state;
+ }
+ }
+
+ // Preserve the font's address and original supplied byte length. Record
+ // each page separately so adjacent globals retain their page protections.
+ fontData.resize(fontBytes, 0);
+ SYSTEM_INFO system{};
+ GetSystemInfo(&system);
+ for (size_t offset = 0; offset < fontBytes;) {
+ auto* address = const_cast<uint8_t*>(font->address) + offset;
+ const size_t bytes = std::min(fontBytes - offset,
+ size_t(system.dwPageSize) - reinterpret_cast<uintptr_t>(address) % system.dwPageSize);
+ DWORD protection = 0;
+ const bool queried = protected_pointer::QueryProtection(reinterpret_cast<uintptr_t>(address), protection, bytes);
+ if (queried && (protection == PAGE_READONLY || protection == PAGE_READWRITE || protection == PAGE_WRITECOPY))
+ g.fontWrites.push_back({address, std::vector<uint8_t>(address, address + bytes), protection});
+ else {
+ rollbackAll();
+ state.detail = L"auxiliary font page protection is not supported";
+ state.archGatesPatched = false;
+ g.state = state;
+ return state;
+ }
+ if (!writeFontPage(g.fontWrites.back(), fontData.data() + offset)) {
+ rollbackAll();
+ state.detail = L"auxiliary font publication failed";
+ state.archGatesPatched = false;
+ g.state = state;
+ return state;
+ }
+ offset += bytes;
}
- FlushInstructionCache(GetCurrentProcess(), image.base,
- size_t(image.nt->OptionalHeader.SizeOfImage));
g.installed = true;
state.fatbinsRedirected = true;
state.applied = state.archGatesPatched && state.fatbinsRedirected;
state.detail = std::format(
- L"runs={} slots={} fatbins={} lea={} gates={} preflight={}/{} (in-memory only)",
- slotRuns, hits.size(), replacements.size(), g.leaWrites.size(), state.archGateSites,
- preflightLoaded, replacements.size());
+ L"runs={} slots={} fatbins={} font=1 lea={} gates={} preflight={}/{} (in-memory only)",
+ slotRuns, redirectedSlots, replacements.size(), g.leaWrites.size(), state.archGateSites,
+ preflightLoaded, replacements.size() + 1);
g.state = state;
veyra::log::info("ampere-mfg",
- std::format("RTX 30 sm_86 unlock: {} runs / {} slot pointers, {} fatbins redirected, "
- "{} lea references, {} arch gates, identityVerified={}",
- slotRuns, hits.size(), replacements.size(), g.leaWrites.size(),
+ std::format("RTX 30 sm_86 unlock: {} runs / "
+ "{} redirected kernel slots, {} fatbins redirected, {} lea references, {} arch gates, identityVerified={}",
+ slotRuns, redirectedSlots, replacements.size(), g.leaWrites.size(),
state.archGateSites, state.identityVerified ? 1 : 0));
return state;
}
-void AmpereMfgUnlock::release() {
+bool AmpereMfgUnlock::release() {
auto& g = global();
std::lock_guard lock(g.mutex);
- if (!g.installed && g.archGateWrites.empty() && g.slotWrites.empty() &&
- g.leaWrites.empty() && g.allocation == nullptr) {
- return;
+ if (!g.installed && g.archGateWrites.empty() && g.slotWrites.empty() && g.sizeWrites.empty() &&
+ g.leaWrites.empty() && g.fontWrites.empty() && g.allocation == nullptr) {
+ return true;
+ }
+ bool restored = true;
+ for (auto it = g.fontWrites.rbegin(); it != g.fontWrites.rend(); ++it) {
+ restored = writeFontPage(*it, it->original.data()) && restored;
}
for (auto it = g.leaWrites.rbegin(); it != g.leaWrites.rend(); ++it) {
- DWORD old = 0;
- if (VirtualProtect(it->disp32, 4, PAGE_EXECUTE_READWRITE, &old) == 0) continue;
- std::memcpy(it->disp32, &it->original, 4);
- DWORD ignored = 0;
- VirtualProtect(it->disp32, 4, old, &ignored);
+ restored = compat::restoreMemory(it->disp32, &it->original, 4) && restored;
}
- g.leaWrites.clear();
for (auto it = g.slotWrites.rbegin(); it != g.slotWrites.rend(); ++it) {
- DWORD old = 0;
- if (VirtualProtect(it->first, 8, PAGE_READWRITE, &old) == 0) continue;
- *it->first = it->second;
- DWORD ignored = 0;
- VirtualProtect(it->first, 8, old, &ignored);
+ restored = compat::restoreMemory(it->first, &it->second, 8) && restored;
+ }
+ for (auto it = g.sizeWrites.rbegin(); it != g.sizeWrites.rend(); ++it) {
+ restored = compat::restoreMemory(it->first, &it->second, 4) && restored;
}
- g.slotWrites.clear();
for (auto it = g.archGateWrites.rbegin(); it != g.archGateWrites.rend(); ++it) {
- DWORD old = 0;
- if (VirtualProtect(it->first, 1, PAGE_EXECUTE_READWRITE, &old) == 0) continue;
- *it->first = it->second;
- DWORD ignored = 0;
- VirtualProtect(it->first, 1, old, &ignored);
+ restored = compat::restoreMemory(it->first, &it->second, 1) && restored;
}
+ if (!restored) { log::error("ampere-mfg", "rollback incomplete; retaining kernel storage and records"); return false; }
+ g.leaWrites.clear();
+ g.fontWrites.clear();
+ g.slotWrites.clear();
+ g.sizeWrites.clear();
g.archGateWrites.clear();
if (g.allocation != nullptr) {
VirtualFree(g.allocation, 0, MEM_RELEASE);
@@ -1157,6 +1345,7 @@ void AmpereMfgUnlock::release() {
g.installed = false;
g.state = State{};
veyra::log::info("ampere-mfg", "RTX 30 sm_86 unlock rolled back (runtime image restored)");
+ return true;
}
AmpereMfgUnlock::State AmpereMfgUnlock::snapshot() {
diff --git a/src/ngx/DlssFgBackend.cpp b/src/ngx/DlssFgBackend.cpp
index 02ba9b08..b34b0cbf 100644
--- a/src/ngx/DlssFgBackend.cpp
+++ b/src/ngx/DlssFgBackend.cpp
@@ -9,15 +9,43 @@
#pragma warning(pop)
#include <format>
+#include <filesystem>
#include "veyra/Log.h"
#include "veyra/NgxResult.h"
#include "veyra/ngx/NgxCoreHost.h"
+#include "veyra/ngx/FgCompatibilitySession.h"
namespace veyra::ngx {
namespace {
+int LogDlssgException(EXCEPTION_POINTERS* exception)
+{
+ const auto* record = exception->ExceptionRecord;
+ MEMORY_BASIC_INFORMATION memory{};
+ VirtualQuery(record->ExceptionAddress, &memory, sizeof(memory));
+ wchar_t module[MAX_PATH]{};
+ GetModuleFileNameW(static_cast<HMODULE>(memory.AllocationBase), module, MAX_PATH);
+ log::error("ngx", std::format("DLSSG exception code=0x{:X} module={} rva=0x{:X} access={} address=0x{:X} rcx=0x{:X} rdx=0x{:X} r8=0x{:X} r9=0x{:X}",
+ record->ExceptionCode, std::filesystem::path(module).filename().string(),
+ uintptr_t(record->ExceptionAddress) - uintptr_t(memory.AllocationBase),
+ record->NumberParameters ? record->ExceptionInformation[0] : 0,
+ record->NumberParameters > 1 ? record->ExceptionInformation[1] : 0,
+ exception->ContextRecord->Rcx, exception->ContextRecord->Rdx,
+ exception->ContextRecord->R8, exception->ContextRecord->R9));
+ void* frames[24]{};
+ const auto count = CaptureStackBackTrace(0, 24, frames, nullptr);
+ for (USHORT i = 0; i < count; ++i) {
+ VirtualQuery(frames[i], &memory, sizeof(memory));
+ GetModuleFileNameW(static_cast<HMODULE>(memory.AllocationBase), module, MAX_PATH);
+ log::error("ngx", std::format("DLSSG exception stack={} module={} rva=0x{:X}",
+ i, std::filesystem::path(module).filename().string(), uintptr_t(frames[i]) - uintptr_t(memory.AllocationBase)));
+ }
+ Logger::instance().flush();
+ return EXCEPTION_EXECUTE_HANDLER;
+}
+
// SEH-isolated calls into the proprietary runtime (Playbook discipline:
// every NGX call site must survive a runtime access violation).
__declspec(noinline) NVSDK_NGX_Result CallCreateDlssg(
@@ -35,7 +63,7 @@ __declspec(noinline) NVSDK_NGX_Result CallCreateDlssg(
result = NGX_D3D12_CREATE_DLSSG(cmdList, creationNodeMask,
visibilityNodeMask, handle, params, createParams);
}
- __except (EXCEPTION_EXECUTE_HANDLER) {
+ __except (LogDlssgException(GetExceptionInformation())) {
sehCode = static_cast<uint32_t>(GetExceptionCode());
result = NVSDK_NGX_Result_FAIL_PlatformError;
}
@@ -55,7 +83,22 @@ __declspec(noinline) NVSDK_NGX_Result CallEvaluateDlssg(
__try {
result = NGX_D3D12_EVALUATE_DLSSG(cmdList, handle, params, evalParams, optEvalParams);
}
- __except (EXCEPTION_EXECUTE_HANDLER) {
+ __except (LogDlssgException(GetExceptionInformation())) {
+ sehCode = static_cast<uint32_t>(GetExceptionCode());
+ result = NVSDK_NGX_Result_FAIL_PlatformError;
+ }
+ return result;
+}
+
+__declspec(noinline) NVSDK_NGX_Result CallReleaseDlssg(
+ NVSDK_NGX_Handle* handle, uint32_t& sehCode)
+{
+ sehCode = 0;
+ NVSDK_NGX_Result result = NVSDK_NGX_Result_Fail;
+ __try {
+ result = NVSDK_NGX_D3D12_ReleaseFeature(handle);
+ }
+ __except (LogDlssgException(GetExceptionInformation())) {
sehCode = static_cast<uint32_t>(GetExceptionCode());
result = NVSDK_NGX_Result_FAIL_PlatformError;
}
@@ -75,12 +118,15 @@ bool DlssFgBackend::queryCapability(NgxCoreHost& coreHost, Capability& caps, Sta
caps = Capability{};
NVSDK_NGX_Parameter* capParams = nullptr;
+ if(compatibility_&&!compatibility_->beginCapabilities()){status=Status::DeviceFailure;return false;}
const NVSDK_NGX_Result capResult = NVSDK_NGX_D3D12_GetCapabilityParameters(&capParams);
+ const bool restored=!compatibility_||compatibility_->endCapabilities();
log::info("ngx", std::format("fg-backend: capability query result={} params={}",
ngxResultString(static_cast<uint64_t>(capResult)), capParams != nullptr ? "non-null" : "null"));
- if (capParams == nullptr || capResult != NVSDK_NGX_Result_Success) {
+ if (capParams == nullptr || capResult != NVSDK_NGX_Result_Success || !restored) {
log::error("ngx",std::format("fg-backend capability failed result=0x{:X} nullParams={}",unsigned(capResult),capParams==nullptr));
status = Status::DeviceFailure;
+ if(capParams)NVSDK_NGX_D3D12_DestroyParameters(capParams);
return false;
}
@@ -138,6 +184,12 @@ bool DlssFgBackend::queryCapability(NgxCoreHost& coreHost, Capability& caps, Sta
caps.multiFrameCountMax, static_cast<uint64_t>(gMfU), static_cast<uint64_t>(gMfI),
caps.hagsRegistryMode));
+ if(compatibility_){
+ if(!compatibility_->publishStartup(capParams)){
+ NVSDK_NGX_D3D12_DestroyParameters(capParams);status=Status::DeviceFailure;return false;
+ }
+ caps.available=true;caps.multiFrameCountMax=5;
+ }
NVSDK_NGX_D3D12_DestroyParameters(capParams);
// Capability query itself succeeded (parameters were readable). Whether FG
@@ -156,6 +208,7 @@ bool DlssFgBackend::create(NgxCoreHost& coreHost,
if (handle_ != nullptr) {
release();
}
+ fatal_ = false;
width_ = desc.width;
height_ = desc.height;
@@ -185,15 +238,17 @@ bool DlssFgBackend::create(NgxCoreHost& coreHost,
createParams.DynamicResolutionScaling = desc.dynamicResolution ? 1u : 0u;
uint32_t sehCode = 0;
+ if(compatibility_&&!compatibility_->beginCreate(cmdList)){status=Status::DeviceFailure;return false;}
const NVSDK_NGX_Result result = CallCreateDlssg(cmdList, 1, 1, &handle_,
params, &createParams, sehCode);
+ const bool restored=!compatibility_||compatibility_->endCreate(result==NVSDK_NGX_Result_Success);
createResult_ = static_cast<uint64_t>(result);
log::info("ngx", std::format("fg-backend: Create DLSSG {}x{} (internal {}x{}) fmt={} result={} handle={} seh={}",
desc.width, desc.height, desc.renderWidth, desc.renderHeight, desc.backbufferFormat,
ngxResultString(createResult_), handle_ != nullptr ? "non-null" : "null", sehCode));
- if (result != NVSDK_NGX_Result_Success) {
+ if (result != NVSDK_NGX_Result_Success || !restored || handle_ == nullptr) {
log::error("ngx", std::format("fg-backend failed result=0x{:X} seh=0x{:X}", static_cast<unsigned>(result), sehCode));
// Query FeatureInitResult for diagnostic detail (user directive).
unsigned long long initResult = 0;
@@ -204,6 +259,8 @@ bool DlssFgBackend::create(NgxCoreHost& coreHost,
static_cast<uint64_t>(gir), initResult,
static_cast<uint64_t>(girI), static_cast<unsigned>(initResultI)));
status = Status::DeviceFailure;
+ fatal_ = true;
+ release();
return false;
}
return true;
@@ -212,9 +269,13 @@ bool DlssFgBackend::create(NgxCoreHost& coreHost,
void DlssFgBackend::release()
{
if (handle_ != nullptr) {
- const NVSDK_NGX_Result result = NVSDK_NGX_D3D12_ReleaseFeature(handle_);
+ uint32_t sehCode = 0;
+ const NVSDK_NGX_Result result = CallReleaseDlssg(handle_, sehCode);
(result == NVSDK_NGX_Result_Success ? log::info : log::error)("ngx", std::format("fg-backend: ReleaseFeature result={} evaluates={} resets={}",
ngxResultString(static_cast<uint64_t>(result)), evaluateCount_, resetCount_));
+ if (sehCode != 0) {
+ log::error("ngx", std::format("fg-backend: ReleaseFeature SEH=0x{:X}", sehCode));
+ }
handle_ = nullptr;
}
}
@@ -224,6 +285,10 @@ bool DlssFgBackend::evaluate(ID3D12GraphicsCommandList* cmdList,
const EvalDesc& desc,
Status& status)
{
+ if (fatal_) {
+ status = Status::DeviceFailure;
+ return false;
+ }
// Up to five generated frames (6X). The graph validates the requested
// multiplier against the runtime's MultiFrameCountMax before creating the
// feature; this is only the absolute API-level guard.
@@ -247,11 +312,11 @@ bool DlssFgBackend::evaluate(ID3D12GraphicsCommandList* cmdList,
// Never-provided optional resources stay null (declared at create time).
NVSDK_NGX_DLSSG_Opt_Eval_Params optParams{};
- // 2X fixed: one generated frame per real pair.
+ // Count excludes the real frame; indices are one-based.
optParams.multiFrameCount = desc.multiFrameCount;
optParams.multiFrameIndex = desc.multiFrameIndex;
- // Static synthetic camera: identity matrices, all motion carried by the
- // mvec buffer (cameraMotionIncluded = 1).
+ // A stationary synthetic camera. All temporal motion is in the mvec
+ // buffer, but projection/inverse and the camera basis must still agree.
for (int r = 0; r < 4; ++r) {
for (int c = 0; c < 4; ++c) {
const float v = (r == c) ? 1.0f : 0.0f;
@@ -270,6 +335,22 @@ bool DlssFgBackend::evaluate(ID3D12GraphicsCommandList* cmdList,
optParams.cameraFar = 1000.0f;
optParams.cameraFOV = 1.5707963f; // pi/2
optParams.cameraAspectRatio = static_cast<float>(width_) / static_cast<float>(height_);
+ optParams.cameraUp[1] = 1.0f;
+ optParams.cameraRight[0] = 1.0f;
+ optParams.cameraFwd[2] = 1.0f;
+ const float projectionX = 1.0f / optParams.cameraAspectRatio; // tan(FOV / 2) = 1
+ const float projectionZ = optParams.cameraFar / (optParams.cameraFar - optParams.cameraNear);
+ const float projectionW = -optParams.cameraNear * projectionZ;
+ optParams.cameraViewToClip[0][0] = projectionX;
+ optParams.cameraViewToClip[2][2] = projectionZ;
+ optParams.cameraViewToClip[2][3] = 1.0f;
+ optParams.cameraViewToClip[3][2] = projectionW;
+ optParams.cameraViewToClip[3][3] = 0.0f;
+ optParams.clipToCameraView[0][0] = 1.0f / projectionX;
+ optParams.clipToCameraView[2][2] = 0.0f;
+ optParams.clipToCameraView[2][3] = 1.0f / projectionW;
+ optParams.clipToCameraView[3][2] = 1.0f;
+ optParams.clipToCameraView[3][3] = -projectionZ / projectionW;
optParams.colorBuffersHDR = desc.hdr ? 1u : 0u; // HDR10 / RGB10 contract
optParams.depthInverted = 0;
optParams.cameraMotionIncluded = 1;
@@ -278,6 +359,8 @@ bool DlssFgBackend::evaluate(ID3D12GraphicsCommandList* cmdList,
optParams.notRenderingGameFrames = 0;
optParams.orthoProjection = 0;
optParams.motionVectorsDilated = 0;
+ // Zero is valid stationary motion, including either axis of a pan.
+ optParams.motionVectorsInvalidValue = 3.402823466e38f;
optParams.menuDetectionEnabled = 0;
optParams.backbufferSubrectSize={width_,height_};
optParams.outputInterpSubrectSize={width_,height_};
@@ -301,6 +384,9 @@ bool DlssFgBackend::evaluate(ID3D12GraphicsCommandList* cmdList,
if (result != NVSDK_NGX_Result_Success) {
log::error("ngx", std::format("fg-backend failed result=0x{:X} seh=0x{:X}", static_cast<unsigned>(result), sehCode));
+ fatal_ = true;
+ // Keep resources alive until the graph drains already submitted GPU
+ // work. Teardown releases the handle through the protected call.
status = Status::DeviceFailure;
return false;
}
diff --git a/src/ngx/FgCompatibilitySession.cpp b/src/ngx/FgCompatibilitySession.cpp
new file mode 100644
index 00000000..81a77da9
--- /dev/null
+++ b/src/ngx/FgCompatibilitySession.cpp
@@ -0,0 +1,288 @@
+// Startup capability and scoped driver gates adapted from
+// dashdogy/RTX40MFG-Unlock ampere_backend.cpp (MIT), commit
+// 33b41835dc39c5d8ab1ef93efb2449be31139c09. Veyra directly owns the
+// D3D12 buffers and NGX calls; no wrapper hooks or Streamline are used.
+#include "veyra/ngx/FgCompatibilitySession.h"
+#include "veyra/ngx/AdaMfgUnlock.h"
+#include "veyra/ngx/AmpereMfgUnlock.h"
+#include "veyra/ngx/NvapiArchSpoof.h"
+#include "veyra/FileIdentity.h"
+#include "veyra/Log.h"
+#include "compat/NgxDiscovery.h"
+#include "compat/protected_pointer.h"
+#include "compat/RestoreMemory.h"
+#include <dxgi1_4.h>
+#include <psapi.h>
+#include <wrl/client.h>
+#include <filesystem>
+#include <format>
+#include <mutex>
+#include <atomic>
+#include <vector>
+
+namespace veyra::ngx {
+namespace {
+std::mutex sessionMutex;
+std::atomic<uint64_t> generation{0};
+std::atomic<bool> poisoned{false};
+bool env(const wchar_t* name) { return GetEnvironmentVariableW(name,nullptr,0)>0; }
+bool sameLuid(LUID a,LUID b) { return a.LowPart==b.LowPart&&a.HighPart==b.HighPart; }
+struct Patch {
+ uintptr_t address=0;
+ uint8_t original=0;
+ bool active=false, privatePage=false, uncertain=false;
+ bool set(bool enable) {
+ if(!address)return false;
+ if(active==enable)return *reinterpret_cast<const uint8_t*>(address)==(enable?0xeb:original);
+ const uint8_t expected=enable?original:0xeb, replacement=enable?0xeb:original;
+ PSAPI_WORKING_SET_EX_INFORMATION working{};
+ working.VirtualAddress=reinterpret_cast<void*>(address);
+ const bool privateNow=QueryWorkingSetEx(GetCurrentProcess(),&working,sizeof(working))&&working.VirtualAttributes.Valid&&!working.VirtualAttributes.Shared;
+ const auto result=protected_pointer::ReplaceProtectedBytes(address,&expected,&replacement,1,PAGE_EXECUTE_READ,
+ &VirtualProtect,&FlushInstructionCache,privatePage||privateNow?PAGE_EXECUTE_READWRITE:PAGE_EXECUTE_WRITECOPY);
+ privatePage|=result.replacementWasPublished;
+ if(result.disposition==protected_pointer::PublishDisposition::ePublishedRestored)active=enable;
+ else if(result.disposition==protected_pointer::PublishDisposition::eIndeterminate)uncertain=true;
+ if(result.disposition!=protected_pointer::PublishDisposition::ePublishedRestored){
+ log::error("fg-compat","driver gate publication/restore failed");return false;
+ }
+ active=enable;return true;
+ }
+};
+NVSDK_NGX_Result requirementsCall(IDXGIAdapter* adapter,const NVSDK_NGX_FeatureDiscoveryInfo* discovery,NVSDK_NGX_FeatureRequirement* result) {
+ __try{return NVSDK_NGX_D3D12_GetFeatureRequirements(adapter,discovery,result);}
+ __except(EXCEPTION_EXECUTE_HANDLER){return NVSDK_NGX_Result_FAIL_PlatformError;}
+}
+}
+struct FgCompatibilitySession::Impl {
+ std::unique_lock<std::mutex> lock{sessionMutex,std::defer_lock};
+ HMODULE provider=nullptr, driver=nullptr;
+ Microsoft::WRL::ComPtr<ID3D12Device> device;
+ std::vector<Microsoft::WRL::ComPtr<ID3D12Resource>> resources;
+ uint64_t serial=0;
+ bool ampere=false, ready=false, allocated=false, initializing=false, initialized=false, startup=false, createAttempted=false, fatal=false, uncertainGate=false;
+ Patch metadata,validation;
+ uintptr_t deviceGate=0;
+ bool programs() const {
+ if(ampere){const auto s=AmpereMfgUnlock::snapshot();return s.applied&&s.identityVerified&&s.fatbinsRedirected;}
+ const auto s=AdaMfgUnlock::snapshot();return s.applied&&s.identityVerified&&s.kernelPatched&&s.mfgGatePatched;
+ }
+};
+FgCompatibilitySession::FgCompatibilitySession():impl_(std::make_unique<Impl>()){}
+FgCompatibilitySession::~FgCompatibilitySession(){
+ auto& s=*impl_;
+ if(!s.lock.owns_lock())return;
+ bool restored=!s.validation.uncertain&&!s.metadata.uncertain&&!s.uncertainGate&&!compat::memoryProtectionUncertain;
+ if(s.validation.active)restored=s.validation.set(false)&&restored;
+ if(s.metadata.active)restored=s.metadata.set(false)&&restored;
+ if(s.deviceGate){
+ const uint8_t before[]={0xeb,4},after[]={0x0f,0x84};
+ const auto result=protected_pointer::ReplaceProtectedBytes(s.deviceGate,before,after,2,PAGE_EXECUTE_READ,&VirtualProtect,&FlushInstructionCache,PAGE_EXECUTE_READWRITE);
+ restored=(result.disposition==protected_pointer::PublishDisposition::ePublishedRestored)&&restored;
+ }
+ restored=AdaMfgUnlock::release()&&restored;
+ restored=AmpereMfgUnlock::release()&&restored;
+ restored=NvapiArchSpoof::release()&&restored;
+ if(!restored){
+ poisoned=true;
+ log::error("fg-compat","rollback unproven; retaining modules/resources until process exit; restart required before further NGX use");
+ s.lock.unlock();
+ (void)impl_.release();
+ return;
+ }
+ s.resources.clear();
+ if(s.driver)FreeLibrary(s.driver);
+ if(s.provider)FreeLibrary(s.provider);
+ log::info("fg-compat",std::format("session released generation={}",s.serial));
+}
+bool FgCompatibilitySession::processHealthy(){return !poisoned.load()&&!compat::memoryProtectionUncertain.load();}
+bool FgCompatibilitySession::requested(uint32_t vendor,uint32_t device) {
+ return (!env(L"VEYRA_DISABLE_AMPERE_MFG_UNLOCK")&&(AmpereMfgUnlock::adapterIsAmpere(vendor,device)||env(L"VEYRA_TEST_FORCE_AMPERE_UNLOCK")))||
+ (!env(L"VEYRA_DISABLE_ADA_MFG_UNLOCK")&&(AdaMfgUnlock::adapterIsAda(vendor,device)||env(L"VEYRA_TEST_FORCE_ADA_UNLOCK")));
+}
+bool FgCompatibilitySession::open(ID3D12Device* device,uint32_t vendor,uint32_t deviceId,const std::wstring& directory) {
+ auto& s=*impl_;
+ if(!device||!requested(vendor,deviceId)||!s.lock.try_lock())return false;
+ if(!processHealthy()){s.lock.unlock();return false;}
+ s.ampere=AmpereMfgUnlock::adapterIsAmpere(vendor,deviceId)||env(L"VEYRA_TEST_FORCE_AMPERE_UNLOCK");
+ s.device=device;s.serial=++generation;
+ const auto path=std::filesystem::absolute(std::filesystem::path(directory)/L"nvngx_dlssg.dll");
+ FileIdentity identity;IdentityError error;
+ computeFileIdentity(path.wstring(),identity,error);
+ log::info("fg-compat",std::format("provider path={} sha256={} bytes={} generation={} LUID={:08X}:{:08X} adapter=0x{:04X}",
+ path.string(),identity.sha256Upper,identity.sizeBytes,s.serial,uint32_t(device->GetAdapterLuid().HighPart),device->GetAdapterLuid().LowPart,deviceId));
+ if(identity.sha256Upper!=AdaMfgUnlock::kKnownModuleSha256)return false;
+ s.provider=LoadLibraryExW(path.c_str(),nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_SYSTEM32);
+ if(!s.provider)return false;
+ wchar_t actual[32768]{};
+ if(!GetModuleFileNameW(s.provider,actual,32768)||!std::filesystem::equivalent(path,actual))return false;
+ const auto entry=GetProcAddress(s.provider,"NVSDK_NGX_D3D12_CreateFeature");
+ MEMORY_BASIC_INFORMATION memory{};
+ if(!entry||!VirtualQuery(reinterpret_cast<const void*>(entry),&memory,sizeof(memory))||memory.AllocationBase!=s.provider)return false;
+ log::info("fg-compat",std::format("provider module=0x{:X} ownedCreate=0x{:X}",uintptr_t(s.provider),uintptr_t(entry)));
+ return true;
+}
+HMODULE FgCompatibilitySession::provider() const{return impl_->provider;}
+bool FgCompatibilitySession::prepareDriver(const std::wstring& directory,const char* project,const char* engine) {
+ auto& s=*impl_;if(!s.provider||!s.programs()){log::error("fg-compat","prepareDriver: provider/programs missing");return false;}
+ if(!s.ampere){s.ready=true;return true;}
+ // The audited legacy provider has one preset. Preserve all count/index
+ // checks, changing only its Blackwell-only choice of maximum=5.
+ compat::Image providerImage;if(!providerImage.Open(s.provider)){log::error("fg-compat","prepareDriver: invalid image");return false;}
+ constexpr uint8_t pattern[]={0x84,0xd2,0x0f,0x84,0x03,0x01,0,0,0xbe,5,0,0,0};
+ uintptr_t gate=0;
+ const auto* sections=IMAGE_FIRST_SECTION(providerImage.nt);
+ for(unsigned i=0;i<providerImage.nt->FileHeader.NumberOfSections;++i){
+ const auto& section=sections[i];
+ if(!(section.Characteristics&IMAGE_SCN_MEM_EXECUTE))continue;
+ const auto begin=providerImage.base+section.VirtualAddress;
+ const auto length=std::max(section.Misc.VirtualSize,section.SizeOfRawData);
+ if(!providerImage.Readable(begin,length)){log::error("fg-compat",std::format("prepareDriver: unreadable section rva=0x{:X} length={}",section.VirtualAddress,length));return false;}
+ for(uint32_t n=0;uint64_t(n)+sizeof(pattern)<=length;++n){
+ const uintptr_t p=begin+n;
+ if(std::memcmp(reinterpret_cast<void*>(p),pattern,sizeof(pattern)))continue;
+ if(!providerImage.Executable(p)||!providerImage.Executable(p+0x10b)||!providerImage.Readable(p+0x10b,4)||gate){log::error("fg-compat","prepareDriver: count policy memory/uniqueness mismatch");return false;}
+ constexpr uint8_t target[]={0x41,0x83,0xf8,1};
+ if(std::memcmp(reinterpret_cast<void*>(p+0x10b),target,sizeof(target))){log::error("fg-compat","prepareDriver: count policy target mismatch");return false;}
+ gate=p;
+ }
+ }
+ if(!gate){log::error("fg-compat","prepareDriver: count policy not found");return false;}
+ // Replace 0F 84 with EB 04, retaining the displacement bytes as skipped data.
+ const uint8_t before[]={0x0f,0x84},after[]={0xeb,4};
+ PSAPI_WORKING_SET_EX_INFORMATION working{};
+ working.VirtualAddress=reinterpret_cast<void*>(gate+2);
+ const bool privatePage=QueryWorkingSetEx(GetCurrentProcess(),&working,sizeof(working))&&working.VirtualAttributes.Valid&&!working.VirtualAttributes.Shared;
+ auto patched=protected_pointer::ReplaceProtectedBytes(gate+2,before,after,2,PAGE_EXECUTE_READ,&VirtualProtect,&FlushInstructionCache,
+ privatePage?PAGE_EXECUTE_READWRITE:PAGE_EXECUTE_WRITECOPY);
+ if(patched.disposition==protected_pointer::PublishDisposition::ePublishedRestored)s.deviceGate=gate+2;
+ if(patched.disposition==protected_pointer::PublishDisposition::eIndeterminate)s.uncertainGate=true;
+ if(patched.disposition!=protected_pointer::PublishDisposition::ePublishedRestored){log::error("fg-compat",std::format("prepareDriver: count policy publication disposition={}",uint32_t(patched.disposition)));return false;}
+ Microsoft::WRL::ComPtr<IDXGIFactory4> factory;
+ Microsoft::WRL::ComPtr<IDXGIAdapter> adapter;
+ if(FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))||FAILED(factory->EnumAdapterByLuid(s.device->GetAdapterLuid(),IID_PPV_ARGS(&adapter))))return false;
+ const wchar_t* paths[]={directory.c_str()};
+ NVSDK_NGX_FeatureCommonInfo common{};common.PathListInfo.Path=paths;common.PathListInfo.Length=1;
+ NVSDK_NGX_FeatureDiscoveryInfo discovery{};
+ discovery.SDKVersion=NVSDK_NGX_Version_API;discovery.FeatureID=NVSDK_NGX_Feature_FrameGeneration;
+ discovery.Identifier.IdentifierType=NVSDK_NGX_Application_Identifier_Type_Project_Id;
+ discovery.Identifier.v.ProjectDesc={project,NVSDK_NGX_ENGINE_TYPE_CUSTOM,engine};
+ discovery.ApplicationDataPath=directory.c_str();discovery.FeatureInfo=&common;
+ NVSDK_NGX_FeatureRequirement requirements{};
+ // This public call asks the static NGX loader to resolve the installed
+ // driver. Its native result is evidence, not compatibility admission.
+ auto result=requirementsCall(adapter.Get(),&discovery,&requirements);
+ log::info("fg-compat",std::format("native requirements result=0x{:X} support={} minArch=0x{:X}",uint32_t(result),uint32_t(requirements.FeatureSupported),requirements.MinHWArchitecture));
+ std::array<HMODULE,2048> modules{};DWORD bytes=0;
+ if(!EnumProcessModules(GetCurrentProcess(),modules.data(),sizeof(modules),&bytes)||bytes>sizeof(modules))return false;
+ uintptr_t metadata=0,validation=0;
+ for(size_t i=0;i<bytes/sizeof(HMODULE);++i){
+ const auto module=modules[i];
+ const auto create=GetProcAddress(module,"NVSDK_NGX_D3D12_CreateFeature");
+ const auto caps=GetProcAddress(module,"NVSDK_NGX_D3D12_GetCapabilityParameters");
+ if(!create||!caps)continue;
+ compat::Image image;if(!image.Open(module)||!image.Executable(uintptr_t(create))||!image.Executable(uintptr_t(caps)))continue;
+ const auto m=compat::FindPattern(image,ampere_patterns::kAmpereNgxMetadataPattern.data(),ampere_patterns::kAmpereNgxMetadataPatternMask.data(),ampere_patterns::kAmpereNgxMetadataPattern.size(),ampere_patterns::kAmpereNgxMetadataBranchOffset);
+ const auto v=compat::FindCreateValidation(image,uintptr_t(create));
+ wchar_t path[32768]{};GetModuleFileNameW(module,path,32768);
+ log::info("fg-compat",std::format("driver discovery path={} base=0x{:X} metadataRva=0x{:X} validationRva=0x{:X}",std::filesystem::path(path).string(),image.base,m?m-image.base:0,v?v-image.base:0));
+ if(!m||!v)continue;
+ if(s.driver)return false;
+ if(!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,reinterpret_cast<LPCWSTR>(module),&s.driver)||s.driver!=module)return false;
+ metadata=m;validation=v;
+ }
+ if(!s.driver)return false;
+ s.metadata={metadata+ampere_patterns::kAmpereNgxMetadataBranchOffset,ampere_patterns::kAmpereNgxMetadataOriginal};
+ s.validation={validation+ampere_patterns::kAmpereNgxCreateValidationBranchOffset,ampere_patterns::kAmpereNgxCreateValidationOriginal};
+ if(!s.metadata.set(true))return false;
+ result=requirementsCall(adapter.Get(),&discovery,&requirements);
+ const bool restored=s.metadata.set(false);
+ log::info("fg-compat",std::format("scoped FG requirements result=0x{:X} support={} restored={}",uint32_t(result),uint32_t(requirements.FeatureSupported),restored));
+ const bool supported=result==NVSDK_NGX_Result_Success&&(requirements.FeatureSupported==NVSDK_NGX_FeatureSupportResult_Supported||requirements.FeatureSupported==NVSDK_NGX_FeatureSupportResult_AdapterUnsupported);
+ // The static loader can return NotImplemented for discovery after Shutdown1.
+ // Discovery is optional: the scoped capability query and real Create/Evaluate
+ // still decide whether this freshly allocated session is usable.
+ const bool bootstrap=result==NVSDK_NGX_Result_FAIL_FeatureNotSupported||result==NVSDK_NGX_Result_FAIL_FeatureNotFound||
+ result==NVSDK_NGX_Result_FAIL_NotImplemented;
+ s.ready=restored&&(supported||bootstrap)&&s.programs();
+ return s.ready;
+}
+bool FgCompatibilitySession::bindResources(std::span<ID3D12Resource* const> real,std::span<ID3D12Resource* const> generated) {
+ auto& s=*impl_;
+ if(!s.ready||s.createAttempted||real.size()!=2||generated.size()!=10)return false;
+ D3D12_RESOURCE_DESC first{};
+ std::vector<Microsoft::WRL::ComPtr<ID3D12Resource>> allocated;
+ for(const auto group:{real,generated})for(auto* resource:group){
+ if(!resource)return false;
+ Microsoft::WRL::ComPtr<ID3D12Device> device;
+ if(FAILED(resource->GetDevice(IID_PPV_ARGS(&device)))||device.Get()!=s.device.Get())return false;
+ for(const auto& prior:allocated)if(prior.Get()==resource)return false;
+ const auto d=resource->GetDesc();
+ if(d.Dimension!=D3D12_RESOURCE_DIMENSION_TEXTURE2D||d.SampleDesc.Count!=1||d.DepthOrArraySize!=1||d.MipLevels!=1||!(d.Flags&D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))return false;
+ if(allocated.empty())first=d;
+ if(d.Width!=first.Width||d.Height!=first.Height||d.Format!=first.Format)return false;
+ allocated.emplace_back(resource);
+ }
+ s.resources=std::move(allocated);s.allocated=true;
+ log::info("fg-compat",std::format("resource proof generation={} real=2 generated=10 extent={}x{} format={}",s.serial,first.Width,first.Height,uint32_t(first.Format)));
+ return true;
+}
+bool FgCompatibilitySession::beginInitialization(){
+ auto& s=*impl_;
+ if(!s.ready||!s.allocated||s.initializing||s.initialized||s.createAttempted||s.fatal)return false;
+ // NGX caches provider initialization failures before the capability query.
+ // Upstream BeginStartup covers this call as well as GetCapabilityParameters.
+ if(s.ampere&&!s.metadata.set(true)){s.fatal=true;return false;}
+ s.initializing=true;
+ log::info("fg-compat",std::format("Init scope generation={} ampereMetadata={}",s.serial,s.ampere));
+ return true;
+}
+bool FgCompatibilitySession::endInitialization(bool success){
+ auto& s=*impl_;
+ if(!s.initializing)return false;
+ const bool restored=!s.ampere||s.metadata.set(false);
+ s.initializing=false;s.initialized=success&&restored;
+ s.fatal|=!restored||!success;
+ log::info("fg-compat",std::format("Init completed generation={} success={} metadataRestored={}",s.serial,success,restored));
+ return !s.fatal;
+}
+bool FgCompatibilitySession::beginCapabilities(){
+ auto& s=*impl_;if(!s.ready||!s.allocated||!s.initialized||s.initializing||s.createAttempted||s.fatal)return false;
+ if(s.ampere&&!s.metadata.set(true)){s.fatal=true;return false;}return true;
+}
+bool FgCompatibilitySession::endCapabilities(){
+ auto& s=*impl_;if(s.ampere&&!s.metadata.set(false)){s.fatal=true;return false;}return !s.fatal;
+}
+bool FgCompatibilitySession::publishStartup(NVSDK_NGX_Parameter* parameters){
+ auto& s=*impl_;
+ if(!parameters||!s.ready||!s.allocated||!s.programs()||s.createAttempted||s.fatal)return false;
+ unsigned maximum=0,available=0;
+ const auto native=parameters->Get("DLSSG.MultiFrameCountMax",&maximum);
+ const auto availability=parameters->Get("FrameGeneration.Available",&available);
+ if(native==NVSDK_NGX_Result_Success&&maximum>5)return false;
+ // Ada still requires native FG availability. Ampere crosses only the
+ // separately verified metadata/Create gates and full SM86 program route.
+ if(!s.ampere&&(availability!=NVSDK_NGX_Result_Success||!available))return false;
+ parameters->Set("FrameGeneration.Available",1u);
+ parameters->Set("DLSSG.MultiFrameCountMax",5u);
+ if(parameters->Get("FrameGeneration.Available",&available)!=NVSDK_NGX_Result_Success||available!=1||
+ parameters->Get("DLSSG.MultiFrameCountMax",&maximum)!=NVSDK_NGX_Result_Success||maximum!=5)return false;
+ s.startup=true;
+ log::info("fg-compat",std::format("scoped startup generation={} maxGenerated=5; actual Create/Evaluate still required",s.serial));
+ return true;
+}
+bool FgCompatibilitySession::beginCreate(ID3D12GraphicsCommandList* list){
+ auto& s=*impl_;Microsoft::WRL::ComPtr<ID3D12Device> device;
+ if(!list||!s.startup||s.createAttempted||s.fatal||!s.programs()||!s.allocated||
+ FAILED(list->GetDevice(IID_PPV_ARGS(&device)))||device.Get()!=s.device.Get()||!sameLuid(device->GetAdapterLuid(),s.device->GetAdapterLuid()))return false;
+ s.createAttempted=true;
+ if(s.ampere&&!s.validation.set(true)){s.fatal=true;return false;}
+ return true;
+}
+bool FgCompatibilitySession::endCreate(bool success){
+ auto& s=*impl_;
+ if(s.ampere&&!s.validation.set(false))s.fatal=true;
+ log::info("fg-compat",std::format("Create completed generation={} success={} driverGateRestored={}",s.serial,success,!s.fatal));
+ return !s.fatal;
+}
+}
diff --git a/src/ngx/NgxCoreHost.cpp b/src/ngx/NgxCoreHost.cpp
index 6f06356a..f211b104 100644
--- a/src/ngx/NgxCoreHost.cpp
+++ b/src/ngx/NgxCoreHost.cpp
@@ -11,6 +11,11 @@ namespace veyra::ngx {
namespace {
+void NVSDK_CONV runtimeLog(const char* message, NVSDK_NGX_Logging_Level, NVSDK_NGX_Feature)
+{
+ if (message) log::info("ngx-runtime", message);
+}
+
// SEH boundary: no C++ objects with destructors may live in a __try scope,
// so the external call sits in its own frame (Playbook section 7.2).
__declspec(noinline) NVSDK_NGX_Result CallInitWithProjectId(
@@ -25,6 +30,8 @@ __declspec(noinline) NVSDK_NGX_Result CallInitWithProjectId(
{
sehCode = 0;
NVSDK_NGX_Result result = NVSDK_NGX_Result_Fail;
+ if(GetEnvironmentVariableW(L"VEYRA_TEST_NGX_INIT_FAILURE",nullptr,0)>0)
+ return NVSDK_NGX_Result_FAIL_UnableToInitializeFeature;
__try {
result = NVSDK_NGX_D3D12_Init_with_ProjectID(projectId, engineType, engineVersion,
applicationDataPath, device, featureInfo, sdkVersion);
@@ -108,6 +115,11 @@ bool NgxCoreHost::initialize(ID3D12Device* device,
NVSDK_NGX_FeatureCommonInfo common{};
common.PathListInfo.Path = const_cast<const wchar_t**>(featurePaths);
common.PathListInfo.Length = 1;
+ if (GetEnvironmentVariableW(L"VEYRA_TEST_NGX_VERBOSE", nullptr, 0)) {
+ common.LoggingInfo.LoggingCallback = runtimeLog;
+ common.LoggingInfo.MinimumLoggingLevel = NVSDK_NGX_LOGGING_LEVEL_ON;
+ common.LoggingInfo.DisableOtherLoggingSinks = true;
+ }
uint32_t sehCode = 0;
const NVSDK_NGX_Result result = CallInitWithProjectId(projectId, NVSDK_NGX_ENGINE_TYPE_CUSTOM,
diff --git a/src/ngx/NvapiArchSpoof.cpp b/src/ngx/NvapiArchSpoof.cpp
index 97508219..fbf5d416 100644
--- a/src/ngx/NvapiArchSpoof.cpp
+++ b/src/ngx/NvapiArchSpoof.cpp
@@ -1,6 +1,7 @@
#include "veyra/ngx/NvapiArchSpoof.h"
#include "veyra/Log.h"
+#include "compat/RestoreMemory.h"
#include <format>
#include <mutex>
@@ -60,18 +61,6 @@ Global& global() {
return value;
}
-bool writeCode(void* target, const uint8_t* bytes, size_t count) {
- DWORD oldProtect = 0;
- if (VirtualProtect(target, count, PAGE_EXECUTE_READWRITE, &oldProtect) == 0) {
- return false;
- }
- std::memcpy(target, bytes, count);
- DWORD ignored = 0;
- VirtualProtect(target, count, oldProtect, &ignored);
- FlushInstructionCache(GetCurrentProcess(), target, count);
- return true;
-}
-
int __cdecl SpoofedGetArchInfo(void* physicalGpu, NvGpuArchInfo* info) {
auto& g = global();
if (g.trampoline == nullptr) {
@@ -155,7 +144,14 @@ bool NvapiArchSpoof::install(HMODULE module, uint32_t reportedArchitecture) {
const uint64_t back = reinterpret_cast<uint64_t>(g.entry + kRelocatedBytes);
std::memcpy(jump + 6, &back, 8);
}
- FlushInstructionCache(GetCurrentProcess(), g.trampoline, kTrampolineBytes);
+ DWORD trampolineProtection = 0;
+ if (!VirtualProtect(g.trampoline, kTrampolineBytes, PAGE_EXECUTE_READ, &trampolineProtection) ||
+ !FlushInstructionCache(GetCurrentProcess(), g.trampoline, kTrampolineBytes)) {
+ VirtualFree(g.trampoline, 0, MEM_RELEASE);
+ g.trampoline = nullptr; g.entry = nullptr;
+ g.detail = L"trampoline executable publication failed";
+ return false;
+ }
// Entry: "jmp [rip+0] <SpoofedGetArchInfo>" (14 bytes, no register touched).
uint8_t patch[kJumpBytes]{};
@@ -164,11 +160,13 @@ bool NvapiArchSpoof::install(HMODULE module, uint32_t reportedArchitecture) {
std::memcpy(patch + 2, &zero, 4);
const uint64_t target = reinterpret_cast<uint64_t>(&SpoofedGetArchInfo);
std::memcpy(patch + 6, &target, 8);
- if (!writeCode(g.entry, patch, kJumpBytes)) {
- g.detail = L"the provider GetArchInfo wrapper page is not writable";
- VirtualFree(g.trampoline, 0, MEM_RELEASE);
- g.trampoline = nullptr;
- g.entry = nullptr;
+ // No provider calls can run before the owning session completes startup.
+ // This 14-byte jump is larger than the atomic gate helper supports.
+ if (!compat::restoreMemory(g.entry, patch, kJumpBytes)) {
+ g.detail = L"provider wrapper publication failed";
+ // An uncertain publication may still reference the trampoline. Session
+ // teardown must restore the entry before releasing this allocation.
+ g.installed = true;
return false;
}
g.reportedArchitecture = reportedArchitecture;
@@ -179,13 +177,14 @@ bool NvapiArchSpoof::install(HMODULE module, uint32_t reportedArchitecture) {
return true;
}
-void NvapiArchSpoof::release() {
+bool NvapiArchSpoof::release() {
auto& g = global();
std::lock_guard lock(g.mutex);
if (!g.installed) {
- return;
+ return true;
}
- const bool restored = writeCode(g.entry, kExpectedPrologue, kRelocatedBytes);
+ const bool restored = compat::restoreMemory(g.entry, kExpectedPrologue, kRelocatedBytes);
+ if (!restored) { log::error("nvapi-spoof", "wrapper restoration failed; retaining trampoline"); return false; }
if (g.trampoline != nullptr) {
VirtualFree(g.trampoline, 0, MEM_RELEASE);
g.trampoline = nullptr;
@@ -194,6 +193,7 @@ void NvapiArchSpoof::release() {
"provider GetArchInfo wrapper restored={} (process memory only)", restored ? 1 : 0));
g.installed = false;
g.entry = nullptr;
+ return true;
}
bool NvapiArchSpoof::installed() {
diff --git a/src/ngx/compat/HDE_LICENSE.txt b/src/ngx/compat/HDE_LICENSE.txt
new file mode 100644
index 00000000..665244c6
--- /dev/null
+++ b/src/ngx/compat/HDE_LICENSE.txt
@@ -0,0 +1,81 @@
+MinHook - The Minimalistic API Hooking Library for x64/x86
+Copyright (C) 2009-2017 Tsuda Kageyu.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
+OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+================================================================================
+Portions of this software are Copyright (c) 2008-2009, Vyacheslav Patkov.
+================================================================================
+Hacker Disassembler Engine 32 C
+Copyright (c) 2008-2009, Vyacheslav Patkov.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
+CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+-------------------------------------------------------------------------------
+Hacker Disassembler Engine 64 C
+Copyright (c) 2008-2009, Vyacheslav Patkov.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
+CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/src/ngx/compat/NgxDiscovery.h b/src/ngx/compat/NgxDiscovery.h
new file mode 100644
index 00000000..94d419fe
--- /dev/null
+++ b/src/ngx/compat/NgxDiscovery.h
@@ -0,0 +1,231 @@
+// Adapted from dashdogy/RTX40MFG-Unlock ampere_backend.cpp, MIT.
+// Commit 33b41835dc39c5d8ab1ef93efb2449be31139c09. Image and decoded
+// discovery only; Veyra owns scoped calls and resources without detours.
+#pragma once
+#include "NgxPatterns.h"
+#include "hde/hde64.h"
+#include <algorithm>
+#include <cstring>
+namespace veyra::ngx::compat {
+using namespace ampere_patterns;
+struct Image
+{
+ HMODULE module{};
+ uintptr_t base{};
+ uint32_t size{};
+ const IMAGE_NT_HEADERS64* nt{};
+ bool Open(HMODULE value) noexcept
+ {
+ module = value; base = reinterpret_cast<uintptr_t>(value);
+ __try
+ {
+ const auto* dos = reinterpret_cast<IMAGE_DOS_HEADER*>(value);
+ if (!dos || dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew <= 0 || dos->e_lfanew > 0x100000) return false;
+ nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(base + dos->e_lfanew);
+ if (nt->Signature != IMAGE_NT_SIGNATURE || nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) return false;
+ size = nt->OptionalHeader.SizeOfImage;
+ const uintptr_t sectionEnd = reinterpret_cast<uintptr_t>(IMAGE_FIRST_SECTION(nt) + nt->FileHeader.NumberOfSections);
+ return size >= 4096 && size < 1024u * 1024u * 1024u && sectionEnd >= base && sectionEnd - base <= size;
+ }
+ __except (EXCEPTION_EXECUTE_HANDLER) { return false; }
+ }
+ bool Contains(uintptr_t address, size_t bytes = 1) const noexcept
+ { return address >= base && address - base < size && bytes <= size - (address - base); }
+ bool Readable(uintptr_t address,size_t bytes) const noexcept
+ {
+ if(!Contains(address,bytes))return false;
+ const auto end=address+bytes;
+ while(address<end){
+ MEMORY_BASIC_INFORMATION m{};
+ if(VirtualQuery(reinterpret_cast<void*>(address),&m,sizeof(m))!=sizeof(m)||m.AllocationBase!=module||
+ m.State!=MEM_COMMIT||(m.Protect&(PAGE_GUARD|PAGE_NOACCESS)))return false;
+ const DWORD p=m.Protect&0xff;
+ if(p!=PAGE_READONLY&&p!=PAGE_READWRITE&&p!=PAGE_WRITECOPY&&p!=PAGE_EXECUTE_READ&&p!=PAGE_EXECUTE_READWRITE&&p!=PAGE_EXECUTE_WRITECOPY)return false;
+ const auto next=reinterpret_cast<uintptr_t>(m.BaseAddress)+m.RegionSize;
+ if(next<=address)return false;
+ address=next;
+ }
+ return true;
+ }
+ bool Executable(uintptr_t address) const noexcept
+ {
+ MEMORY_BASIC_INFORMATION m{};
+ return Contains(address) && VirtualQuery(reinterpret_cast<void*>(address), &m, sizeof(m)) == sizeof(m)
+ && m.AllocationBase == module && m.Type == MEM_IMAGE && m.State == MEM_COMMIT
+ && (m.Protect & (PAGE_GUARD | PAGE_NOACCESS)) == 0
+ && ((m.Protect & 0xff) == PAGE_EXECUTE_READ || (m.Protect & 0xff) == PAGE_EXECUTE);
+ }
+};
+
+// Signature masks permit relocation operands, not opcode or layout changes.
+// Decode the whole window and require every relative call/LEA and branch to
+// belong to the same image. No driver version or fixed RVA grants admission.
+bool DecodedWindow(const Image& image, uintptr_t address, size_t length) noexcept
+{
+ size_t offset = 0;
+ while (offset < length)
+ {
+ hde64s ins{};
+ const unsigned n = hde64_disasm(reinterpret_cast<void*>(address + offset), &ins);
+ if (!n || (ins.flags & F_ERROR) || n > length - offset) return false;
+ const auto* bytes = reinterpret_cast<const uint8_t*>(address + offset);
+ if (ins.opcode == 0xe8)
+ {
+ int32_t displacement = 0; memcpy(&displacement, bytes + n - 4, 4);
+ if (!image.Executable(address + offset + n + displacement)) return false;
+ }
+ if (ins.opcode == 0x8d && ins.modrm_mod == 0 && ins.modrm_rm == 5)
+ {
+ int32_t displacement = 0; memcpy(&displacement, bytes + n - 4, 4);
+ if (!image.Contains(address + offset + n + displacement)) return false;
+ }
+ offset += n;
+ }
+ return offset == length;
+}
+
+uintptr_t FindPattern(const Image& image, const uint8_t* pattern, const uint8_t* mask,
+ size_t length, size_t branchOffset = SIZE_MAX, uint32_t minimum = 0, uint32_t maximum = 0,
+ unsigned* matches = nullptr) noexcept
+{
+ if (matches) *matches = 0;
+ uintptr_t match = 0;
+ const auto* sections = IMAGE_FIRST_SECTION(image.nt);
+ for (unsigned i = 0; i < image.nt->FileHeader.NumberOfSections; ++i)
+ {
+ const auto& s = sections[i];
+ if (!(s.Characteristics & IMAGE_SCN_MEM_EXECUTE) || s.VirtualAddress >= image.size) continue;
+ const uint32_t begin = std::max<uint32_t>(s.VirtualAddress, minimum);
+ const uint32_t end = static_cast<uint32_t>(std::min<uint64_t>(
+ std::min<uint64_t>(image.size, maximum ? maximum : image.size),
+ uint64_t{s.VirtualAddress} + std::max(s.Misc.VirtualSize, s.SizeOfRawData)));
+ if(end<=begin||!image.Readable(image.base+begin,end-begin))continue;
+ for (uint64_t offset = begin; offset + length <= end; ++offset)
+ {
+ const auto* candidate = reinterpret_cast<const uint8_t*>(image.base + offset);
+ bool same = true;
+ for (size_t j = 0; same && j < length; ++j) same = !mask[j] || candidate[j] == pattern[j];
+ if (!same || !DecodedWindow(image, image.base + offset, length)) continue;
+ if (branchOffset != SIZE_MAX)
+ {
+ const int displacement = static_cast<int8_t>(candidate[branchOffset + 1]);
+ if (displacement <= 0 || !image.Executable(image.base + offset + branchOffset + 2 + displacement)) continue;
+ }
+ if (matches) ++*matches;
+ if (match) return 0;
+ match = image.base + offset;
+ }
+ }
+ return match;
+}
+
+bool UnwindRoot(const Image& image, RUNTIME_FUNCTION function, RUNTIME_FUNCTION& root) noexcept
+{
+ for (unsigned depth = 0; depth != 8; ++depth)
+ {
+ const uintptr_t unwind = image.base + function.UnwindData;
+ if (!image.Contains(unwind, 4)) return false;
+ const auto* bytes = reinterpret_cast<const uint8_t*>(unwind);
+ if ((bytes[0] & 7u) != 1u) return false;
+ const unsigned flags = bytes[0] >> 3;
+ if (!(flags & UNW_FLAG_CHAININFO)) { root = function; return true; }
+ if (flags & (UNW_FLAG_EHANDLER | UNW_FLAG_UHANDLER)) return false;
+ const size_t offset = (4u + 2u * bytes[2] + 3u) & ~size_t{3};
+ if (!image.Contains(unwind, offset + sizeof(RUNTIME_FUNCTION))) return false;
+ RUNTIME_FUNCTION parent{};
+ memcpy(&parent, bytes + offset, sizeof(parent));
+ DWORD64 owner = 0;
+ const auto* actual = RtlLookupFunctionEntry(image.base + parent.BeginAddress, &owner, nullptr);
+ if (!actual || owner != image.base
+ || !image.Contains(reinterpret_cast<uintptr_t>(actual), sizeof(*actual))
+ || memcmp(actual, &parent, sizeof(parent))) return false;
+ function = parent;
+ }
+ return false;
+}
+
+bool FunctionBounds(const Image& image, uintptr_t entry, uint32_t& begin, uint32_t& end) noexcept
+{
+ DWORD64 owner = 0;
+ const auto* function = RtlLookupFunctionEntry(entry, &owner, nullptr);
+ if (!function || owner != image.base
+ || !image.Contains(reinterpret_cast<uintptr_t>(function), sizeof(*function))
+ || function->BeginAddress >= function->EndAddress
+ || function->EndAddress > image.size
+ || image.base + function->BeginAddress != entry
+ || function->EndAddress - function->BeginAddress > 0x4000
+ || !image.Executable(entry) || !image.Executable(image.base + function->EndAddress - 1))
+ return false;
+ begin = function->BeginAddress;
+ end = function->EndAddress;
+ RUNTIME_FUNCTION root{};
+ if (!UnwindRoot(image, *function, root) || root.BeginAddress != begin) return false;
+ // MSVC splits one function's unwind coverage when a nonvolatile register
+ // is saved only on one branch. Adjacent entries with an exact chained
+ // unwind parent are continuations, not independent exported functions.
+ for (unsigned fragments = 0; fragments != 32; ++fragments)
+ {
+ owner = 0;
+ const auto* next = RtlLookupFunctionEntry(image.base + end, &owner, nullptr);
+ if (!next || owner != image.base
+ || !image.Contains(reinterpret_cast<uintptr_t>(next), sizeof(*next))
+ || next->BeginAddress != end) return true;
+ RUNTIME_FUNCTION nextRoot{};
+ if (!UnwindRoot(image, *next, nextRoot)) return false;
+ if (memcmp(&root, &nextRoot, sizeof(root))) return true;
+ if (next->EndAddress <= end || next->EndAddress > image.size
+ || next->EndAddress - begin > 0x4000
+ || !image.Executable(image.base + next->EndAddress - 1)) return false;
+ end = next->EndAddress;
+ }
+ return false;
+}
+
+// NGX may outline Create's architecture validation into a helper far from
+// its public export. Inspect only that function and its decoded direct callees;
+// neighboring API implementations and unrelated image-wide matches grant no
+// coverage. Resolve before installing our Create entry detour, then retain the
+// owned addresses for the scoped startup/Create patches.
+uintptr_t FindCreateValidation(const Image& image, uintptr_t create) noexcept
+{
+ uint32_t begin = 0, end = 0;
+ if (!FunctionBounds(image, create, begin, end)) return 0;
+ std::array<uintptr_t, 65> functions{};
+ functions[0] = create;
+ size_t count = 1;
+ for (uintptr_t cursor = create; cursor < image.base + end;)
+ {
+ hde64s ins{};
+ const unsigned length = hde64_disasm(reinterpret_cast<void*>(cursor), &ins);
+ if (!length || (ins.flags & F_ERROR) || length > image.base + end - cursor) return 0;
+ if (ins.opcode == 0xe8)
+ {
+ int32_t displacement = 0;
+ memcpy(&displacement, reinterpret_cast<void*>(cursor + length - 4), sizeof(displacement));
+ const uintptr_t target = cursor + length + displacement;
+ uint32_t childBegin = 0, childEnd = 0;
+ if (FunctionBounds(image, target, childBegin, childEnd)
+ && std::find(functions.begin(), functions.begin() + count, target) == functions.begin() + count)
+ {
+ if (count == functions.size()) return 0;
+ functions[count++] = target;
+ }
+ }
+ cursor += length;
+ }
+ uintptr_t selected = 0;
+ for (size_t i = 0; i < count; ++i)
+ {
+ if (!FunctionBounds(image, functions[i], begin, end)) return 0;
+ unsigned matches = 0;
+ const uintptr_t candidate = FindPattern(image, kAmpereNgxCreateValidationPattern.data(),
+ kAmpereNgxCreateValidationPatternMask.data(), kAmpereNgxCreateValidationPattern.size(),
+ kAmpereNgxCreateValidationBranchOffset, begin, end, &matches);
+ if (matches > 1 || (candidate && selected)) return 0;
+ if (candidate) selected = candidate;
+ }
+ return selected;
+}
+
+
+}
diff --git a/src/ngx/compat/NgxPatterns.h b/src/ngx/compat/NgxPatterns.h
new file mode 100644
index 00000000..8aa30254
--- /dev/null
+++ b/src/ngx/compat/NgxPatterns.h
@@ -0,0 +1,65 @@
+// Adapted from dashdogy/RTX40MFG-Unlock, MIT, commit 33b41835dc39c5d8ab1ef93efb2449be31139c09.
+// Only NGX driver metadata/Create patterns; no wrapper or Streamline patches.
+#pragma once
+#include <array>
+#include <cstdint>
+#include <Windows.h>
+namespace ampere_patterns {
+static constexpr std::array<uint8_t, 59> kAmpereNgxMetadataPattern{
+ 0x41, 0x8B, 0x46, 0x10, 0x41, 0x8B, 0x97, 0x5C,
+ 0x24, 0x00, 0x00, 0x3B, 0xC2, 0x7E, 0x31, 0x89,
+ 0x54, 0x24, 0x28, 0x89, 0x44, 0x24, 0x20, 0x4C,
+ 0x8D, 0x0D, 0x58, 0xC0, 0x06, 0x00, 0x4C, 0x8D,
+ 0x05, 0xB1, 0xBF, 0x06, 0x00, 0xBA, 0xDA, 0x05,
+ 0x00, 0x00, 0x48, 0x8D, 0x0D, 0x9D, 0xB1, 0x06,
+ 0x00, 0xE8, 0xE8, 0xD5, 0x00, 0x00, 0xB8, 0x01,
+ 0x00, 0xD0, 0xBA,
+};
+static constexpr std::array<uint8_t, 59> kAmpereNgxMetadataPatternMask{
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF,
+ 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00,
+ 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00,
+ 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF,
+};
+constexpr size_t kAmpereNgxMetadataBranchOffset = 13;
+static constexpr uint8_t kAmpereNgxMetadataOriginal = 0x7E;
+static constexpr uint8_t kAmpereNgxMetadataReplacement = 0xEB;
+
+// A second independent architecture branch is crossed only around one
+// authorized CreateFeature call, then restored before post-create work.
+static constexpr std::array<uint8_t, 57>
+ kAmpereNgxCreateValidationPattern{
+ 0x8B, 0x84, 0xC6, 0xD0, 0x2E, 0x00, 0x00, 0x39,
+ 0x41, 0x1C, 0x7D, 0x32, 0x4C, 0x8D, 0x0D, 0xD9,
+ 0xD6, 0x04, 0x00, 0x4C, 0x8D, 0x05, 0x72, 0xD6,
+ 0x04, 0x00, 0xBA, 0xD5, 0x02, 0x00, 0x00, 0x48,
+ 0x8D, 0x0D, 0x76, 0xCD, 0x04, 0x00, 0xE8, 0x91,
+ 0x61, 0xFF, 0xFF, 0x90, 0x48, 0x8B, 0xCB, 0xE8,
+ 0x84, 0x2A, 0x00, 0x00, 0xBF, 0x0B, 0x00, 0xD0,
+ 0xBA,
+ };
+static constexpr std::array<uint8_t, 57>
+ kAmpereNgxCreateValidationPatternMask{
+ 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
+ 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
+ 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF,
+ 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
+ 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF,
+ };
+constexpr size_t kAmpereNgxCreateValidationBranchOffset = 10;
+static constexpr uint8_t kAmpereNgxCreateValidationOriginal = 0x7D;
+static constexpr uint8_t kAmpereNgxCreateValidationReplacement = 0xEB;
+// The same validation body is emitted for several NGX entry points. Resolve
+// the D3D12 instance through decoded instructions rooted at the exported
+// CreateFeature entry and its direct callees. Owned unwind entries bound each
+// function; the unchanged full signature must have exactly one match.
+
+
+}
diff --git a/src/ngx/compat/RTX40MFG_LICENSE.txt b/src/ngx/compat/RTX40MFG_LICENSE.txt
new file mode 100644
index 00000000..c17ab9cd
--- /dev/null
+++ b/src/ngx/compat/RTX40MFG_LICENSE.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Michael Robles
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/src/ngx/compat/RestoreMemory.h b/src/ngx/compat/RestoreMemory.h
new file mode 100644
index 00000000..d9c30b54
--- /dev/null
+++ b/src/ngx/compat/RestoreMemory.h
@@ -0,0 +1,34 @@
+#pragma once
+#include "protected_pointer.h"
+#include "veyra/Log.h"
+#include <format>
+#include <atomic>
+
+namespace veyra::ngx::compat {
+inline std::atomic<bool> memoryProtectionUncertain{false};
+// Called only after NGX shutdown. Retain patch records and backing storage
+// whenever restoration cannot be proved, including page protection failures.
+inline bool restoreMemory(void* destination, const void* original, size_t bytes) {
+ if (GetEnvironmentVariableW(L"VEYRA_TEST_PATCH_RESTORE_FAIL", nullptr, 0)) return false;
+ DWORD protection = 0;
+ const auto address = reinterpret_cast<uintptr_t>(destination);
+ if (!protected_pointer::QueryProtection(address, protection, bytes)) { log::error("patch-memory",std::format("query failed address=0x{:X} bytes={} win32={}",address,bytes,GetLastError())); return false; }
+ DWORD oldProtection=0;
+ // Image-backed pages may report EXECUTE_WRITECOPY until the first write
+ // faults in a private page, even after a successful READWRITE request.
+ const bool changed=VirtualProtect(destination,bytes,PAGE_EXECUTE_READWRITE,&oldProtection)!=FALSE;
+ DWORD writable=0;
+ const bool queried=protected_pointer::QueryProtection(address,writable,bytes);
+ if (!changed||!queried||(writable!=PAGE_EXECUTE_READWRITE&&writable!=PAGE_EXECUTE_WRITECOPY)) {
+ if(!protected_pointer::RestoreProtectionWithRetry(destination, bytes, protection, &VirtualProtect))memoryProtectionUncertain=true;
+ log::error("patch-memory",std::format("writable protection failed address=0x{:X} bytes={} protection=0x{:X} win32={}",address,bytes,protection,GetLastError())); return false;
+ }
+ std::memcpy(destination, original, bytes);
+ const bool flushed = FlushInstructionCache(GetCurrentProcess(), destination, bytes) != FALSE;
+ const bool restored = protected_pointer::RestoreProtectionWithRetry(destination, bytes, protection, &VirtualProtect);
+ const bool equal=std::memcmp(destination, original, bytes)==0;
+ if(!flushed||!restored||!equal)memoryProtectionUncertain=true;
+ if(!flushed||!restored||!equal)log::error("patch-memory",std::format("verification failed address=0x{:X} bytes={} protection=0x{:X} flush={} restored={} equal={} win32={}",address,bytes,protection,flushed,restored,equal,GetLastError()));
+ return flushed && restored && equal;
+}
+}
diff --git a/src/ngx/compat/hde/hde64.c b/src/ngx/compat/hde/hde64.c
new file mode 100644
index 00000000..9222148c
--- /dev/null
+++ b/src/ngx/compat/hde/hde64.c
@@ -0,0 +1,337 @@
+/*
+ * Hacker Disassembler Engine 64 C
+ * Copyright (c) 2008-2009, Vyacheslav Patkov.
+ * All rights reserved.
+ *
+ */
+
+#if defined(_M_X64) || defined(__x86_64__)
+
+#include "hde64.h"
+#include "table64.h"
+
+unsigned int hde64_disasm(const void *code, hde64s *hs)
+{
+ uint8_t x, c = 0, *p = (uint8_t *)code, cflags, opcode, pref = 0;
+ uint8_t *ht = hde64_table, m_mod, m_reg, m_rm, disp_size = 0;
+ uint8_t op64 = 0;
+
+ // Avoid using memset to reduce the footprint.
+#ifndef _MSC_VER
+ memset((LPBYTE)hs, 0, sizeof(hde64s));
+#else
+ __stosb((LPBYTE)hs, 0, sizeof(hde64s));
+#endif
+
+ for (x = 16; x; x--)
+ switch (c = *p++) {
+ case 0xf3:
+ hs->p_rep = c;
+ pref |= PRE_F3;
+ break;
+ case 0xf2:
+ hs->p_rep = c;
+ pref |= PRE_F2;
+ break;
+ case 0xf0:
+ hs->p_lock = c;
+ pref |= PRE_LOCK;
+ break;
+ case 0x26: case 0x2e: case 0x36:
+ case 0x3e: case 0x64: case 0x65:
+ hs->p_seg = c;
+ pref |= PRE_SEG;
+ break;
+ case 0x66:
+ hs->p_66 = c;
+ pref |= PRE_66;
+ break;
+ case 0x67:
+ hs->p_67 = c;
+ pref |= PRE_67;
+ break;
+ default:
+ goto pref_done;
+ }
+ pref_done:
+
+ hs->flags = (uint32_t)pref << 23;
+
+ if (!pref)
+ pref |= PRE_NONE;
+
+ if ((c & 0xf0) == 0x40) {
+ hs->flags |= F_PREFIX_REX;
+ if ((hs->rex_w = (c & 0xf) >> 3) && (*p & 0xf8) == 0xb8)
+ op64++;
+ hs->rex_r = (c & 7) >> 2;
+ hs->rex_x = (c & 3) >> 1;
+ hs->rex_b = c & 1;
+ if (((c = *p++) & 0xf0) == 0x40) {
+ opcode = c;
+ goto error_opcode;
+ }
+ }
+
+ if ((hs->opcode = c) == 0x0f) {
+ hs->opcode2 = c = *p++;
+ ht += DELTA_OPCODES;
+ } else if (c >= 0xa0 && c <= 0xa3) {
+ op64++;
+ if (pref & PRE_67)
+ pref |= PRE_66;
+ else
+ pref &= ~PRE_66;
+ }
+
+ opcode = c;
+ cflags = ht[ht[opcode / 4] + (opcode % 4)];
+
+ if (cflags == C_ERROR) {
+ error_opcode:
+ hs->flags |= F_ERROR | F_ERROR_OPCODE;
+ cflags = 0;
+ if ((opcode & -3) == 0x24)
+ cflags++;
+ }
+
+ x = 0;
+ if (cflags & C_GROUP) {
+ uint16_t t;
+ t = *(uint16_t *)(ht + (cflags & 0x7f));
+ cflags = (uint8_t)t;
+ x = (uint8_t)(t >> 8);
+ }
+
+ if (hs->opcode2) {
+ ht = hde64_table + DELTA_PREFIXES;
+ if (ht[ht[opcode / 4] + (opcode % 4)] & pref)
+ hs->flags |= F_ERROR | F_ERROR_OPCODE;
+ }
+
+ if (cflags & C_MODRM) {
+ hs->flags |= F_MODRM;
+ hs->modrm = c = *p++;
+ hs->modrm_mod = m_mod = c >> 6;
+ hs->modrm_rm = m_rm = c & 7;
+ hs->modrm_reg = m_reg = (c & 0x3f) >> 3;
+
+ if (x && ((x << m_reg) & 0x80))
+ hs->flags |= F_ERROR | F_ERROR_OPCODE;
+
+ if (!hs->opcode2 && opcode >= 0xd9 && opcode <= 0xdf) {
+ uint8_t t = opcode - 0xd9;
+ if (m_mod == 3) {
+ ht = hde64_table + DELTA_FPU_MODRM + t*8;
+ t = ht[m_reg] << m_rm;
+ } else {
+ ht = hde64_table + DELTA_FPU_REG;
+ t = ht[t] << m_reg;
+ }
+ if (t & 0x80)
+ hs->flags |= F_ERROR | F_ERROR_OPCODE;
+ }
+
+ if (pref & PRE_LOCK) {
+ if (m_mod == 3) {
+ hs->flags |= F_ERROR | F_ERROR_LOCK;
+ } else {
+ uint8_t *table_end, op = opcode;
+ if (hs->opcode2) {
+ ht = hde64_table + DELTA_OP2_LOCK_OK;
+ table_end = ht + DELTA_OP_ONLY_MEM - DELTA_OP2_LOCK_OK;
+ } else {
+ ht = hde64_table + DELTA_OP_LOCK_OK;
+ table_end = ht + DELTA_OP2_LOCK_OK - DELTA_OP_LOCK_OK;
+ op &= -2;
+ }
+ for (; ht != table_end; ht++)
+ if (*ht++ == op) {
+ if (!((*ht << m_reg) & 0x80))
+ goto no_lock_error;
+ else
+ break;
+ }
+ hs->flags |= F_ERROR | F_ERROR_LOCK;
+ no_lock_error:
+ ;
+ }
+ }
+
+ if (hs->opcode2) {
+ switch (opcode) {
+ case 0x20: case 0x22:
+ m_mod = 3;
+ if (m_reg > 4 || m_reg == 1)
+ goto error_operand;
+ else
+ goto no_error_operand;
+ case 0x21: case 0x23:
+ m_mod = 3;
+ if (m_reg == 4 || m_reg == 5)
+ goto error_operand;
+ else
+ goto no_error_operand;
+ }
+ } else {
+ switch (opcode) {
+ case 0x8c:
+ if (m_reg > 5)
+ goto error_operand;
+ else
+ goto no_error_operand;
+ case 0x8e:
+ if (m_reg == 1 || m_reg > 5)
+ goto error_operand;
+ else
+ goto no_error_operand;
+ }
+ }
+
+ if (m_mod == 3) {
+ uint8_t *table_end;
+ if (hs->opcode2) {
+ ht = hde64_table + DELTA_OP2_ONLY_MEM;
+ table_end = ht + sizeof(hde64_table) - DELTA_OP2_ONLY_MEM;
+ } else {
+ ht = hde64_table + DELTA_OP_ONLY_MEM;
+ table_end = ht + DELTA_OP2_ONLY_MEM - DELTA_OP_ONLY_MEM;
+ }
+ for (; ht != table_end; ht += 2)
+ if (*ht++ == opcode) {
+ if (*ht++ & pref && !((*ht << m_reg) & 0x80))
+ goto error_operand;
+ else
+ break;
+ }
+ goto no_error_operand;
+ } else if (hs->opcode2) {
+ switch (opcode) {
+ case 0x50: case 0xd7: case 0xf7:
+ if (pref & (PRE_NONE | PRE_66))
+ goto error_operand;
+ break;
+ case 0xd6:
+ if (pref & (PRE_F2 | PRE_F3))
+ goto error_operand;
+ break;
+ case 0xc5:
+ goto error_operand;
+ }
+ goto no_error_operand;
+ } else
+ goto no_error_operand;
+
+ error_operand:
+ hs->flags |= F_ERROR | F_ERROR_OPERAND;
+ no_error_operand:
+
+ c = *p++;
+ if (m_reg <= 1) {
+ if (opcode == 0xf6)
+ cflags |= C_IMM8;
+ else if (opcode == 0xf7)
+ cflags |= C_IMM_P66;
+ }
+
+ switch (m_mod) {
+ case 0:
+ if (pref & PRE_67) {
+ if (m_rm == 6)
+ disp_size = 2;
+ } else
+ if (m_rm == 5)
+ disp_size = 4;
+ break;
+ case 1:
+ disp_size = 1;
+ break;
+ case 2:
+ disp_size = 2;
+ if (!(pref & PRE_67))
+ disp_size <<= 1;
+ }
+
+ if (m_mod != 3 && m_rm == 4) {
+ hs->flags |= F_SIB;
+ p++;
+ hs->sib = c;
+ hs->sib_scale = c >> 6;
+ hs->sib_index = (c & 0x3f) >> 3;
+ if ((hs->sib_base = c & 7) == 5 && !(m_mod & 1))
+ disp_size = 4;
+ }
+
+ p--;
+ switch (disp_size) {
+ case 1:
+ hs->flags |= F_DISP8;
+ hs->disp.disp8 = *p;
+ break;
+ case 2:
+ hs->flags |= F_DISP16;
+ hs->disp.disp16 = *(uint16_t *)p;
+ break;
+ case 4:
+ hs->flags |= F_DISP32;
+ hs->disp.disp32 = *(uint32_t *)p;
+ }
+ p += disp_size;
+ } else if (pref & PRE_LOCK)
+ hs->flags |= F_ERROR | F_ERROR_LOCK;
+
+ if (cflags & C_IMM_P66) {
+ if (cflags & C_REL32) {
+ if (pref & PRE_66) {
+ hs->flags |= F_IMM16 | F_RELATIVE;
+ hs->imm.imm16 = *(uint16_t *)p;
+ p += 2;
+ goto disasm_done;
+ }
+ goto rel32_ok;
+ }
+ if (op64) {
+ hs->flags |= F_IMM64;
+ hs->imm.imm64 = *(uint64_t *)p;
+ p += 8;
+ } else if (!(pref & PRE_66)) {
+ hs->flags |= F_IMM32;
+ hs->imm.imm32 = *(uint32_t *)p;
+ p += 4;
+ } else
+ goto imm16_ok;
+ }
+
+
+ if (cflags & C_IMM16) {
+ imm16_ok:
+ hs->flags |= F_IMM16;
+ hs->imm.imm16 = *(uint16_t *)p;
+ p += 2;
+ }
+ if (cflags & C_IMM8) {
+ hs->flags |= F_IMM8;
+ hs->imm.imm8 = *p++;
+ }
+
+ if (cflags & C_REL32) {
+ rel32_ok:
+ hs->flags |= F_IMM32 | F_RELATIVE;
+ hs->imm.imm32 = *(uint32_t *)p;
+ p += 4;
+ } else if (cflags & C_REL8) {
+ hs->flags |= F_IMM8 | F_RELATIVE;
+ hs->imm.imm8 = *p++;
+ }
+
+ disasm_done:
+
+ if ((hs->len = (uint8_t)(p-(uint8_t *)code)) > 15) {
+ hs->flags |= F_ERROR | F_ERROR_LENGTH;
+ hs->len = 15;
+ }
+
+ return (unsigned int)hs->len;
+}
+
+#endif // defined(_M_X64) || defined(__x86_64__)
diff --git a/src/ngx/compat/hde/hde64.h b/src/ngx/compat/hde/hde64.h
new file mode 100644
index 00000000..ecd72811
--- /dev/null
+++ b/src/ngx/compat/hde/hde64.h
@@ -0,0 +1,112 @@
+/*
+ * Hacker Disassembler Engine 64
+ * Copyright (c) 2008-2009, Vyacheslav Patkov.
+ * All rights reserved.
+ *
+ * hde64.h: C/C++ header file
+ *
+ */
+
+#ifndef _HDE64_H_
+#define _HDE64_H_
+
+/* stdint.h - C99 standard header
+ * http://en.wikipedia.org/wiki/stdint.h
+ *
+ * if your compiler doesn't contain "stdint.h" header (for
+ * example, Microsoft Visual C++), you can download file:
+ * http://www.azillionmonkeys.com/qed/pstdint.h
+ * and change next line to:
+ * #include "pstdint.h"
+ */
+#include "pstdint.h"
+
+#define F_MODRM 0x00000001
+#define F_SIB 0x00000002
+#define F_IMM8 0x00000004
+#define F_IMM16 0x00000008
+#define F_IMM32 0x00000010
+#define F_IMM64 0x00000020
+#define F_DISP8 0x00000040
+#define F_DISP16 0x00000080
+#define F_DISP32 0x00000100
+#define F_RELATIVE 0x00000200
+#define F_ERROR 0x00001000
+#define F_ERROR_OPCODE 0x00002000
+#define F_ERROR_LENGTH 0x00004000
+#define F_ERROR_LOCK 0x00008000
+#define F_ERROR_OPERAND 0x00010000
+#define F_PREFIX_REPNZ 0x01000000
+#define F_PREFIX_REPX 0x02000000
+#define F_PREFIX_REP 0x03000000
+#define F_PREFIX_66 0x04000000
+#define F_PREFIX_67 0x08000000
+#define F_PREFIX_LOCK 0x10000000
+#define F_PREFIX_SEG 0x20000000
+#define F_PREFIX_REX 0x40000000
+#define F_PREFIX_ANY 0x7f000000
+
+#define PREFIX_SEGMENT_CS 0x2e
+#define PREFIX_SEGMENT_SS 0x36
+#define PREFIX_SEGMENT_DS 0x3e
+#define PREFIX_SEGMENT_ES 0x26
+#define PREFIX_SEGMENT_FS 0x64
+#define PREFIX_SEGMENT_GS 0x65
+#define PREFIX_LOCK 0xf0
+#define PREFIX_REPNZ 0xf2
+#define PREFIX_REPX 0xf3
+#define PREFIX_OPERAND_SIZE 0x66
+#define PREFIX_ADDRESS_SIZE 0x67
+
+#pragma pack(push,1)
+
+typedef struct {
+ uint8_t len;
+ uint8_t p_rep;
+ uint8_t p_lock;
+ uint8_t p_seg;
+ uint8_t p_66;
+ uint8_t p_67;
+ uint8_t rex;
+ uint8_t rex_w;
+ uint8_t rex_r;
+ uint8_t rex_x;
+ uint8_t rex_b;
+ uint8_t opcode;
+ uint8_t opcode2;
+ uint8_t modrm;
+ uint8_t modrm_mod;
+ uint8_t modrm_reg;
+ uint8_t modrm_rm;
+ uint8_t sib;
+ uint8_t sib_scale;
+ uint8_t sib_index;
+ uint8_t sib_base;
+ union {
+ uint8_t imm8;
+ uint16_t imm16;
+ uint32_t imm32;
+ uint64_t imm64;
+ } imm;
+ union {
+ uint8_t disp8;
+ uint16_t disp16;
+ uint32_t disp32;
+ } disp;
+ uint32_t flags;
+} hde64s;
+
+#pragma pack(pop)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* __cdecl */
+unsigned int hde64_disasm(const void *code, hde64s *hs);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _HDE64_H_ */
diff --git a/src/ngx/compat/hde/pstdint.h b/src/ngx/compat/hde/pstdint.h
new file mode 100644
index 00000000..c9985292
--- /dev/null
+++ b/src/ngx/compat/hde/pstdint.h
@@ -0,0 +1,39 @@
+/*
+ * MinHook - The Minimalistic API Hooking Library for x64/x86
+ * Copyright (C) 2009-2017 Tsuda Kageyu. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#include <windows.h>
+
+// Integer types for HDE.
+typedef INT8 int8_t;
+typedef INT16 int16_t;
+typedef INT32 int32_t;
+typedef INT64 int64_t;
+typedef UINT8 uint8_t;
+typedef UINT16 uint16_t;
+typedef UINT32 uint32_t;
+typedef UINT64 uint64_t;
diff --git a/src/ngx/compat/hde/table64.h b/src/ngx/compat/hde/table64.h
new file mode 100644
index 00000000..144f2907
--- /dev/null
+++ b/src/ngx/compat/hde/table64.h
@@ -0,0 +1,74 @@
+/*
+ * Hacker Disassembler Engine 64 C
+ * Copyright (c) 2008-2009, Vyacheslav Patkov.
+ * All rights reserved.
+ *
+ */
+
+#define C_NONE 0x00
+#define C_MODRM 0x01
+#define C_IMM8 0x02
+#define C_IMM16 0x04
+#define C_IMM_P66 0x10
+#define C_REL8 0x20
+#define C_REL32 0x40
+#define C_GROUP 0x80
+#define C_ERROR 0xff
+
+#define PRE_ANY 0x00
+#define PRE_NONE 0x01
+#define PRE_F2 0x02
+#define PRE_F3 0x04
+#define PRE_66 0x08
+#define PRE_67 0x10
+#define PRE_LOCK 0x20
+#define PRE_SEG 0x40
+#define PRE_ALL 0xff
+
+#define DELTA_OPCODES 0x4a
+#define DELTA_FPU_REG 0xfd
+#define DELTA_FPU_MODRM 0x104
+#define DELTA_PREFIXES 0x13c
+#define DELTA_OP_LOCK_OK 0x1ae
+#define DELTA_OP2_LOCK_OK 0x1c6
+#define DELTA_OP_ONLY_MEM 0x1d8
+#define DELTA_OP2_ONLY_MEM 0x1e7
+
+unsigned char hde64_table[] = {
+ 0xa5,0xaa,0xa5,0xb8,0xa5,0xaa,0xa5,0xaa,0xa5,0xb8,0xa5,0xb8,0xa5,0xb8,0xa5,
+ 0xb8,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xac,0xc0,0xcc,0xc0,0xa1,0xa1,
+ 0xa1,0xa1,0xb1,0xa5,0xa5,0xa6,0xc0,0xc0,0xd7,0xda,0xe0,0xc0,0xe4,0xc0,0xea,
+ 0xea,0xe0,0xe0,0x98,0xc8,0xee,0xf1,0xa5,0xd3,0xa5,0xa5,0xa1,0xea,0x9e,0xc0,
+ 0xc0,0xc2,0xc0,0xe6,0x03,0x7f,0x11,0x7f,0x01,0x7f,0x01,0x3f,0x01,0x01,0xab,
+ 0x8b,0x90,0x64,0x5b,0x5b,0x5b,0x5b,0x5b,0x92,0x5b,0x5b,0x76,0x90,0x92,0x92,
+ 0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x6a,0x73,0x90,
+ 0x5b,0x52,0x52,0x52,0x52,0x5b,0x5b,0x5b,0x5b,0x77,0x7c,0x77,0x85,0x5b,0x5b,
+ 0x70,0x5b,0x7a,0xaf,0x76,0x76,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,
+ 0x5b,0x5b,0x86,0x01,0x03,0x01,0x04,0x03,0xd5,0x03,0xd5,0x03,0xcc,0x01,0xbc,
+ 0x03,0xf0,0x03,0x03,0x04,0x00,0x50,0x50,0x50,0x50,0xff,0x20,0x20,0x20,0x20,
+ 0x01,0x01,0x01,0x01,0xc4,0x02,0x10,0xff,0xff,0xff,0x01,0x00,0x03,0x11,0xff,
+ 0x03,0xc4,0xc6,0xc8,0x02,0x10,0x00,0xff,0xcc,0x01,0x01,0x01,0x00,0x00,0x00,
+ 0x00,0x01,0x01,0x03,0x01,0xff,0xff,0xc0,0xc2,0x10,0x11,0x02,0x03,0x01,0x01,
+ 0x01,0xff,0xff,0xff,0x00,0x00,0x00,0xff,0x00,0x00,0xff,0xff,0xff,0xff,0x10,
+ 0x10,0x10,0x10,0x02,0x10,0x00,0x00,0xc6,0xc8,0x02,0x02,0x02,0x02,0x06,0x00,
+ 0x04,0x00,0x02,0xff,0x00,0xc0,0xc2,0x01,0x01,0x03,0x03,0x03,0xca,0x40,0x00,
+ 0x0a,0x00,0x04,0x00,0x00,0x00,0x00,0x7f,0x00,0x33,0x01,0x00,0x00,0x00,0x00,
+ 0x00,0x00,0xff,0xbf,0xff,0xff,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0xff,0x00,
+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,
+ 0x00,0x00,0x00,0xbf,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7f,0x00,0x00,
+ 0xff,0x40,0x40,0x40,0x40,0x41,0x49,0x40,0x40,0x40,0x40,0x4c,0x42,0x40,0x40,
+ 0x40,0x40,0x40,0x40,0x40,0x40,0x4f,0x44,0x53,0x40,0x40,0x40,0x44,0x57,0x43,
+ 0x5c,0x40,0x60,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,
+ 0x40,0x40,0x64,0x66,0x6e,0x6b,0x40,0x40,0x6a,0x46,0x40,0x40,0x44,0x46,0x40,
+ 0x40,0x5b,0x44,0x40,0x40,0x00,0x00,0x00,0x00,0x06,0x06,0x06,0x06,0x01,0x06,
+ 0x06,0x02,0x06,0x06,0x00,0x06,0x00,0x0a,0x0a,0x00,0x00,0x00,0x02,0x07,0x07,
+ 0x06,0x02,0x0d,0x06,0x06,0x06,0x0e,0x05,0x05,0x02,0x02,0x00,0x00,0x04,0x04,
+ 0x04,0x04,0x05,0x06,0x06,0x06,0x00,0x00,0x00,0x0e,0x00,0x00,0x08,0x00,0x10,
+ 0x00,0x18,0x00,0x20,0x00,0x28,0x00,0x30,0x00,0x80,0x01,0x82,0x01,0x86,0x00,
+ 0xf6,0xcf,0xfe,0x3f,0xab,0x00,0xb0,0x00,0xb1,0x00,0xb3,0x00,0xba,0xf8,0xbb,
+ 0x00,0xc0,0x00,0xc1,0x00,0xc7,0xbf,0x62,0xff,0x00,0x8d,0xff,0x00,0xc4,0xff,
+ 0x00,0xc5,0xff,0x00,0xff,0xff,0xeb,0x01,0xff,0x0e,0x12,0x08,0x00,0x13,0x09,
+ 0x00,0x16,0x08,0x00,0x17,0x09,0x00,0x2b,0x09,0x00,0xae,0xff,0x07,0xb2,0xff,
+ 0x00,0xb4,0xff,0x00,0xb5,0xff,0x00,0xc3,0x01,0x00,0xc7,0xff,0xbf,0xe7,0x08,
+ 0x00,0xf0,0x02,0x00
+};
diff --git a/src/ngx/compat/protected_pointer.h b/src/ngx/compat/protected_pointer.h
new file mode 100644
index 00000000..026e95ff
--- /dev/null
+++ b/src/ngx/compat/protected_pointer.h
@@ -0,0 +1,446 @@
+#pragma once
+// dashdogy/RTX40MFG-Unlock, commit 33b41835dc39c5d8ab1ef93efb2449be31139c09.
+// Unmodified implementation; MIT, see RTX40MFG_LICENSE.txt.
+
+#include <Windows.h>
+
+#include <cstddef>
+#include <cstdint>
+#include <cstring>
+#include <intrin.h>
+
+namespace protected_pointer
+{
+using ProtectMemoryFn = BOOL(WINAPI*)(LPVOID, SIZE_T, DWORD, PDWORD);
+using FlushInstructionCacheFn = BOOL(WINAPI*)(HANDLE, LPCVOID, SIZE_T);
+
+enum class PublishDisposition : uint32_t
+{
+ eNotPublishedRestored = 0,
+ ePublishedRestored = 1,
+ eRolledBackRestored = 2,
+ eIndeterminate = 3,
+};
+
+struct PublishResult
+{
+ PublishDisposition disposition = PublishDisposition::eIndeterminate;
+ bool replacementWasPublished = false;
+};
+
+inline void* ReadPointer(uintptr_t address) noexcept
+{
+ return ReadPointerAcquire(
+ reinterpret_cast<PVOID const volatile*>(address));
+}
+
+inline bool ProtectionMatches(uintptr_t address, DWORD expected,
+ size_t size = 1) noexcept
+{
+ MEMORY_BASIC_INFORMATION memory{};
+ if (!address || size == 0
+ || VirtualQuery(reinterpret_cast<const void*>(address), &memory,
+ sizeof(memory))
+ != sizeof(memory)
+ || memory.State != MEM_COMMIT)
+ {
+ return false;
+ }
+ const uintptr_t regionBegin = reinterpret_cast<uintptr_t>(
+ memory.BaseAddress);
+ if (memory.RegionSize < size || address < regionBegin
+ || address - regionBegin > memory.RegionSize - size)
+ {
+ return false;
+ }
+ constexpr DWORD kProtectionMask = 0xFFu | PAGE_GUARD | PAGE_NOCACHE
+ | PAGE_WRITECOMBINE;
+ return (memory.Protect & kProtectionMask)
+ == (expected & kProtectionMask);
+}
+
+inline bool QueryProtection(uintptr_t address, DWORD& protection,
+ size_t size = 1) noexcept
+{
+ MEMORY_BASIC_INFORMATION memory{};
+ if (!address || size == 0
+ || VirtualQuery(reinterpret_cast<const void*>(address), &memory,
+ sizeof(memory))
+ != sizeof(memory)
+ || memory.State != MEM_COMMIT)
+ {
+ return false;
+ }
+ const uintptr_t regionBegin = reinterpret_cast<uintptr_t>(
+ memory.BaseAddress);
+ if (memory.RegionSize < size || address < regionBegin
+ || address - regionBegin > memory.RegionSize - size)
+ {
+ return false;
+ }
+ protection = memory.Protect;
+ return true;
+}
+
+inline bool SetAndVerifyProtection(void* address, size_t size,
+ DWORD protection, ProtectMemoryFn protectMemory) noexcept
+{
+ DWORD ignored = 0;
+ protectMemory(address, size, protection, &ignored);
+ return ProtectionMatches(
+ reinterpret_cast<uintptr_t>(address), protection, size);
+}
+
+inline bool RestoreProtectionWithRetry(void* address, size_t size,
+ DWORD protection, ProtectMemoryFn protectMemory) noexcept
+{
+ // A failed VirtualProtect is normally non-mutating, but retry once so a
+ // transient injected or system failure cannot leave our temporary RW page
+ // behind. Verification, rather than the API return alone, is authoritative.
+ for (uint32_t attempt = 0; attempt < 2; ++attempt)
+ {
+ if (SetAndVerifyProtection(address, size, protection, protectMemory))
+ return true;
+ }
+ return false;
+}
+
+inline PublishResult ReplaceProtectedPointer(uintptr_t address,
+ uintptr_t expected, uintptr_t replacement,
+ ProtectMemoryFn protectMemory = &VirtualProtect,
+ DWORD temporaryWritableProtection = PAGE_READWRITE) noexcept
+{
+ if (!address || !expected || !replacement || !protectMemory
+ || (temporaryWritableProtection != PAGE_READWRITE
+ && temporaryWritableProtection != PAGE_WRITECOPY)
+ || (address & (alignof(void*) - 1)) != 0)
+ {
+ return {};
+ }
+
+ auto* const destination = reinterpret_cast<void* volatile*>(address);
+ void* const protectionAddress = reinterpret_cast<void*>(address);
+ DWORD oldProtection = 0;
+ if (!QueryProtection(address, oldProtection, sizeof(void*)))
+ return {};
+ if (!SetAndVerifyProtection(protectionAddress, sizeof(void*),
+ temporaryWritableProtection, protectMemory))
+ {
+ // VirtualProtect can mutate the page even when it reports failure.
+ // Best-effort restoration keeps an initial protection failure from
+ // leaving an IAT or immutable table writable. A competing writer may
+ // also have published the exact replacement while the page was
+ // transiently writable, so re-read only after restoring protection;
+ // callers use replacementWasPublished to retain replacement-owned
+ // storage even though this attempt cannot claim publication.
+ const bool restored = RestoreProtectionWithRetry(protectionAddress,
+ sizeof(void*), oldProtection, protectMemory);
+ void* const observed = ReadPointer(address);
+ void* const expectedPointer = reinterpret_cast<void*>(expected);
+ void* const replacementPointer = reinterpret_cast<void*>(replacement);
+ return {restored && observed == expectedPointer
+ ? PublishDisposition::eNotPublishedRestored
+ : PublishDisposition::eIndeterminate,
+ observed == replacementPointer};
+ }
+
+ void* const expectedPointer = reinterpret_cast<void*>(expected);
+ void* const replacementPointer = reinterpret_cast<void*>(replacement);
+ void* const previous = InterlockedCompareExchangePointer(destination,
+ replacementPointer, expectedPointer);
+ if (previous != expectedPointer)
+ {
+ const bool replacementObservedBeforeRestore =
+ previous == replacementPointer;
+ const bool foreignPointerObserved =
+ previous != replacementPointer;
+ const bool restored = RestoreProtectionWithRetry(protectionAddress,
+ sizeof(void*), oldProtection, protectMemory);
+ void* const observed = ReadPointer(address);
+ return {!foreignPointerObserved && restored
+ && observed == expectedPointer
+ ? PublishDisposition::eNotPublishedRestored
+ : PublishDisposition::eIndeterminate,
+ replacementObservedBeforeRestore
+ || observed == replacementPointer};
+ }
+
+ if (SetAndVerifyProtection(protectionAddress, sizeof(void*), oldProtection,
+ protectMemory))
+ {
+ const void* const observed = ReadPointer(address);
+ if (observed == replacementPointer)
+ return {PublishDisposition::ePublishedRestored, true};
+ if (observed == expectedPointer)
+ return {PublishDisposition::eRolledBackRestored, true};
+ return {PublishDisposition::eIndeterminate, true};
+ }
+
+ // The replacement was visible, but the requested protection could not be
+ // verified. VirtualProtect is allowed to have changed the page despite a
+ // failure result, so it is not safe to assume the slot remains writable.
+ // Re-observe both state dimensions before deciding whether to publish,
+ // preserve a third writer, or attempt rollback.
+ void* const observedAfterRestore = ReadPointer(address);
+ if (observedAfterRestore == replacementPointer
+ && ProtectionMatches(address, oldProtection, sizeof(void*)))
+ {
+ return {PublishDisposition::ePublishedRestored, true};
+ }
+ if (observedAfterRestore != replacementPointer)
+ {
+ const bool protectionRestored = RestoreProtectionWithRetry(
+ protectionAddress, sizeof(void*), oldProtection, protectMemory);
+ if (observedAfterRestore == expectedPointer && protectionRestored
+ && ReadPointer(address) == expectedPointer)
+ {
+ return {PublishDisposition::eRolledBackRestored, true};
+ }
+ return {PublishDisposition::eIndeterminate, true};
+ }
+
+ // Never issue the rollback CAS until writable protection is positively
+ // established. If that cannot be proven, leave the already-visible
+ // replacement in place, retry the original protection, and classify the
+ // final exact state without risking a write fault.
+ if (!SetAndVerifyProtection(protectionAddress, sizeof(void*),
+ temporaryWritableProtection, protectMemory))
+ {
+ const bool protectionRestored = RestoreProtectionWithRetry(
+ protectionAddress, sizeof(void*), oldProtection, protectMemory);
+ if (protectionRestored && ReadPointer(address) == replacementPointer)
+ return {PublishDisposition::ePublishedRestored, true};
+ return {PublishDisposition::eIndeterminate, true};
+ }
+
+ // Never free replacement storage after this point: another reader may
+ // have retained the briefly published pointer.
+ void* const rollbackPrevious = InterlockedCompareExchangePointer(
+ destination, expectedPointer, replacementPointer);
+ const bool slotRestored = rollbackPrevious == replacementPointer
+ || rollbackPrevious == expectedPointer;
+ const bool protectionRestored = RestoreProtectionWithRetry(protectionAddress,
+ sizeof(void*), oldProtection, protectMemory);
+ if (slotRestored && protectionRestored
+ && ReadPointer(address) == expectedPointer)
+ {
+ return {PublishDisposition::eRolledBackRestored, true};
+ }
+ return {PublishDisposition::eIndeterminate, true};
+}
+
+inline bool BytesEqual(uintptr_t address, const void* expected,
+ size_t size) noexcept
+{
+ return address && expected && size != 0
+ && std::memcmp(reinterpret_cast<const void*>(address), expected, size)
+ == 0;
+}
+
+inline bool AtomicCompareExchangeBytes(uintptr_t address,
+ const void* expected, const void* replacement, size_t size,
+ unsigned char* observedBytes) noexcept
+{
+ if (!address || !expected || !replacement || !observedBytes
+ || (size != 1 && size != 2 && size != 4 && size != 8)
+ || (address & (size - 1)) != 0)
+ {
+ return false;
+ }
+ if (size == 1)
+ {
+ char expectedValue = 0;
+ char replacementValue = 0;
+ std::memcpy(&expectedValue, expected, 1);
+ std::memcpy(&replacementValue, replacement, 1);
+ const char observed = _InterlockedCompareExchange8(
+ reinterpret_cast<volatile char*>(address), replacementValue,
+ expectedValue);
+ std::memcpy(observedBytes, &observed, 1);
+ return true;
+ }
+ if (size == 2)
+ {
+ short expectedValue = 0;
+ short replacementValue = 0;
+ std::memcpy(&expectedValue, expected, 2);
+ std::memcpy(&replacementValue, replacement, 2);
+ const short observed = _InterlockedCompareExchange16(
+ reinterpret_cast<volatile short*>(address), replacementValue,
+ expectedValue);
+ std::memcpy(observedBytes, &observed, 2);
+ return true;
+ }
+ if (size == 4)
+ {
+ long expectedValue = 0;
+ long replacementValue = 0;
+ std::memcpy(&expectedValue, expected, 4);
+ std::memcpy(&replacementValue, replacement, 4);
+ const long observed = InterlockedCompareExchange(
+ reinterpret_cast<volatile long*>(address), replacementValue,
+ expectedValue);
+ std::memcpy(observedBytes, &observed, 4);
+ return true;
+ }
+ LONG64 expectedValue = 0;
+ LONG64 replacementValue = 0;
+ std::memcpy(&expectedValue, expected, 8);
+ std::memcpy(&replacementValue, replacement, 8);
+ const LONG64 observed = InterlockedCompareExchange64(
+ reinterpret_cast<volatile LONG64*>(address), replacementValue,
+ expectedValue);
+ std::memcpy(observedBytes, &observed, 8);
+ return true;
+}
+
+inline PublishResult ReplaceProtectedBytes(uintptr_t address,
+ const void* expected, const void* replacement, size_t size,
+ DWORD finalProtection = PAGE_EXECUTE_READ,
+ ProtectMemoryFn protectMemory = &VirtualProtect,
+ FlushInstructionCacheFn flushInstructionCache = &FlushInstructionCache,
+ DWORD temporaryWritableProtection = PAGE_EXECUTE_READWRITE)
+ noexcept
+{
+ if (!address || !expected || !replacement
+ || (size != 1 && size != 2 && size != 4 && size != 8)
+ || (address & (size - 1)) != 0 || !protectMemory
+ || !flushInstructionCache
+ || (temporaryWritableProtection != PAGE_EXECUTE_READWRITE
+ && temporaryWritableProtection != PAGE_EXECUTE_WRITECOPY))
+ return {};
+
+ void* const destination = reinterpret_cast<void*>(address);
+ DWORD observedProtection = 0;
+ if (!QueryProtection(address, observedProtection, size))
+ return {};
+
+ // Executable mutations are trusted only when the page was already in the
+ // exact canonical non-writable state. Best-effort repair of a pre-existing
+ // writable page is useful containment, but its bytes remain indeterminate
+ // for this attempt and must never authorize publication.
+ if (!ProtectionMatches(address, finalProtection, size))
+ {
+ RestoreProtectionWithRetry(destination, size, finalProtection,
+ protectMemory);
+ return {PublishDisposition::eIndeterminate,
+ BytesEqual(address, replacement, size)};
+ }
+ if (BytesEqual(address, replacement, size))
+ return {PublishDisposition::ePublishedRestored, true};
+ if (!BytesEqual(address, expected, size))
+ return {PublishDisposition::eIndeterminate, false};
+
+ if (!SetAndVerifyProtection(destination, size, temporaryWritableProtection,
+ protectMemory))
+ {
+ const bool restored = RestoreProtectionWithRetry(destination, size,
+ finalProtection, protectMemory);
+ const bool expectedObserved = BytesEqual(address, expected, size);
+ const bool replacementObserved = BytesEqual(
+ address, replacement, size);
+ if (replacementObserved)
+ flushInstructionCache(GetCurrentProcess(), destination, size);
+ return {restored && expectedObserved
+ ? PublishDisposition::eNotPublishedRestored
+ : PublishDisposition::eIndeterminate,
+ replacementObserved};
+ }
+
+ // Revalidate after making the page writable. A debugger or another
+ // diagnostic writer must not be overwritten merely because the earlier
+ // read matched.
+ if (!BytesEqual(address, expected, size))
+ {
+ const bool replacementObserved =
+ BytesEqual(address, replacement, size);
+ if (replacementObserved)
+ flushInstructionCache(GetCurrentProcess(), destination, size);
+ const bool restored = RestoreProtectionWithRetry(destination, size,
+ finalProtection, protectMemory);
+ (void)restored;
+ // A positively observed foreign/replacement value cannot be laundered
+ // into a clean non-publication merely because another writer restores
+ // the expected bytes before the final read.
+ return {PublishDisposition::eIndeterminate, replacementObserved};
+ }
+
+ unsigned char observed[8]{};
+ if (!AtomicCompareExchangeBytes(address, expected, replacement, size,
+ observed))
+ {
+ const bool restored = RestoreProtectionWithRetry(destination, size,
+ finalProtection, protectMemory);
+ return {restored && BytesEqual(address, expected, size)
+ ? PublishDisposition::eNotPublishedRestored
+ : PublishDisposition::eIndeterminate,
+ false};
+ }
+ if (std::memcmp(observed, expected, size) != 0)
+ {
+ const bool replacementAlreadyVisible =
+ std::memcmp(observed, replacement, size) == 0;
+ if (replacementAlreadyVisible)
+ {
+ // A competing writer, rather than this CAS, published these
+ // bytes. Flush them for containment, but never claim ownership:
+ // otherwise an unrelated debugger/patcher could be laundered
+ // into a certified executable mutation on the next scan.
+ flushInstructionCache(GetCurrentProcess(), destination, size);
+ }
+ const bool restored = RestoreProtectionWithRetry(destination, size,
+ finalProtection, protectMemory);
+ (void)restored;
+ return {PublishDisposition::eIndeterminate,
+ replacementAlreadyVisible};
+ }
+ const bool replacementFlushed = flushInstructionCache(
+ GetCurrentProcess(), destination, size) != FALSE;
+ if (replacementFlushed
+ && RestoreProtectionWithRetry(destination, size, finalProtection,
+ protectMemory)
+ && BytesEqual(address, replacement, size))
+ {
+ return {PublishDisposition::ePublishedRestored, true};
+ }
+
+ // The replacement was visible but the final protection could not be
+ // certified. Re-establish writable access before rollback; a failed
+ // VirtualProtect may already have made the page read-only.
+ if (!SetAndVerifyProtection(destination, size, temporaryWritableProtection,
+ protectMemory))
+ {
+ const bool restored = RestoreProtectionWithRetry(destination, size,
+ finalProtection, protectMemory);
+ if (replacementFlushed && restored
+ && BytesEqual(address, replacement, size))
+ return {PublishDisposition::ePublishedRestored, true};
+ return {PublishDisposition::eIndeterminate, true};
+ }
+
+ if (BytesEqual(address, replacement, size))
+ {
+ unsigned char rollbackObserved[8]{};
+ if (!AtomicCompareExchangeBytes(address, replacement, expected, size,
+ rollbackObserved)
+ || std::memcmp(rollbackObserved, replacement, size) != 0)
+ {
+ RestoreProtectionWithRetry(destination, size, finalProtection,
+ protectMemory);
+ return {PublishDisposition::eIndeterminate, true};
+ }
+ if (flushInstructionCache(GetCurrentProcess(), destination, size)
+ == FALSE)
+ {
+ RestoreProtectionWithRetry(destination, size, finalProtection,
+ protectMemory);
+ return {PublishDisposition::eIndeterminate, true};
+ }
+ }
+ const bool restored = RestoreProtectionWithRetry(destination, size,
+ finalProtection, protectMemory);
+ if (restored && BytesEqual(address, expected, size))
+ return {PublishDisposition::eRolledBackRestored, true};
+ return {PublishDisposition::eIndeterminate, true};
+}
+}
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index 4d9b8459..26d51701 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -22,6 +22,7 @@
#include "veyra/gfx/CommandSlotRing.h"
#include "veyra/gfx/D3D12DeviceContext.h"
#include "veyra/ngx/DlssFgBackend.h"
+#include "veyra/ngx/FgCompatibilitySession.h"
#include "veyra/ngx/AdaMfgUnlock.h"
#include "veyra/ngx/AmpereMfgUnlock.h"
#include "veyra/ngx/NvapiArchSpoof.h"
@@ -252,6 +253,14 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)
{
failedBackend_=engine::FailedBackend::Infrastructure;
if(!desc.protection.validate().empty())return false;
+ if(desc.compatibilityPreflight&&!desc.compatibilityPreflight(desc,context_)){
+ failedBackend_=engine::FailedBackend::Fg;
+ veyra::log::error("graph","FG compatibility preflight failed; see fg-probe log");return false;
+ }
+ if(desc.fgMotionProbe){
+ const auto d=desc.fgMotionProbe->GetDesc();ComPtr<ID3D12Device> device;
+ if(!desc.enableFg||desc.noFeatures||desc.noNgx||d.Dimension!=D3D12_RESOURCE_DIMENSION_TEXTURE2D||d.Width!=desc.workWidth||d.Height!=desc.workHeight||d.Format!=DXGI_FORMAT_R16G16_FLOAT||d.DepthOrArraySize!=1||d.MipLevels!=1||d.SampleDesc.Count!=1||(d.Flags&D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)||FAILED(desc.fgMotionProbe->GetDevice(IID_PPV_ARGS(&device)))||device.Get()!=context_.device())return false;
+ }
if(desc.srMotionProbe){
const auto d=desc.srMotionProbe->GetDesc();ComPtr<ID3D12Device> device;
if(!desc.enableSr||desc.noFeatures||desc.noNgx||d.Dimension!=D3D12_RESOURCE_DIMENSION_TEXTURE2D||d.Width!=desc.workWidth||d.Height!=desc.workHeight||d.Format!=DXGI_FORMAT_R16G16_FLOAT||d.DepthOrArraySize!=1||d.MipLevels!=1||d.SampleDesc.Count!=1||(d.Flags&D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)||FAILED(desc.srMotionProbe->GetDevice(IID_PPV_ARGS(&device)))||device.Get()!=context_.device()){
@@ -642,11 +651,7 @@ void EnhanceGraph::applyAdaMfgUnlock()
return;
}
const auto modulePath = std::filesystem::path(desc_.runtimeAbsPath) / L"nvngx_dlssg.dll";
- HMODULE module = GetModuleHandleW(L"nvngx_dlssg.dll");
- if (module == nullptr) {
- module = LoadLibraryExW(modulePath.c_str(), nullptr,
- LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32);
- }
+HMODULE module = fgCompatibility_ ? fgCompatibility_->provider() : nullptr;
if (module == nullptr) {
veyra::log::warn("ada-mfg", std::format("DLSS-G runtime could not be opened for the unlock (path={} win32={})",
modulePath.string(), GetLastError()));
@@ -693,22 +698,16 @@ void EnhanceGraph::prepareAmpereFgSpoof()
}
const auto modulePath = std::filesystem::path(desc_.runtimeAbsPath) / L"nvngx_dlssg.dll";
- HMODULE module = GetModuleHandleW(L"nvngx_dlssg.dll");
- if (module == nullptr) {
- module = LoadLibraryExW(modulePath.c_str(), nullptr,
- LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32);
- }
+HMODULE module = fgCompatibility_ ? fgCompatibility_->provider() : nullptr;
if (module == nullptr) {
veyra::log::warn("ampere-mfg", std::format("DLSS-G runtime could not be preloaded for the architecture spoof (path={} win32={})",
modulePath.string(), GetLastError()));
return;
}
- // Ampere default: tell the provider it runs on Blackwell (0x1B0). That is
- // what makes its frame-generation availability gate pass; the sm_86 kernel
- // rewrite is what makes the programs actually run. Ada/Blackwell never reach
- // this function. VEYRA_TEST_NVAPI_SPOOF_ARCH overrides the reported id (e.g.
- // 0x190 for Ada, 0x170 to disable the trick), 0 refuses the spoof entirely.
- uint32_t spoofArchitecture = ngx::NvapiArchSpoof::kArchBlackwell;
+ // Preserve real architecture for DL4RT's hardware-specific network choice.
+ // Upstream changes capability policy independently of the NVAPI query.
+ // Architecture substitution remains available only for diagnostic tests.
+ uint32_t spoofArchitecture = 0;
{
wchar_t overrideText[16]{};
if (GetEnvironmentVariableW(L"VEYRA_TEST_NVAPI_SPOOF_ARCH", overrideText, 16) > 0) {
@@ -716,6 +715,7 @@ void EnhanceGraph::prepareAmpereFgSpoof()
}
}
if (spoofArchitecture == 0) {
+ veyra::log::info("ampere-mfg", "preserving real NVAPI architecture; applying scoped compatibility policy only");
return;
}
ampereSpoofed_ = ngx::NvapiArchSpoof::install(module, spoofArchitecture);
@@ -732,8 +732,7 @@ void EnhanceGraph::applyAmpereMfgUnlock()
// Hard architecture gate: only RTX 30 (Ampere GA10x) takes this path. Ada
// keeps its own unlock and Blackwell keeps its native multi-frame path.
// VEYRA_TEST_FORCE_AMPERE_UNLOCK exists so the patch itself can be checked
- // on a non-Ampere host (does rewriting all 69 fatbins leave the runtime
- // functional?); it never run in a product session.
+ // on a non-Ampere host; it is not enabled in a product session.
wchar_t forced[2]{};
const bool forceOnAnyAdapter=GetEnvironmentVariableW(L"VEYRA_TEST_FORCE_AMPERE_UNLOCK",forced,2)>0;
if (!forceOnAnyAdapter&&!ngx::AmpereMfgUnlock::adapterIsAmpere(adapter.vendorId, adapter.deviceId)) {
@@ -745,11 +744,7 @@ void EnhanceGraph::applyAmpereMfgUnlock()
return;
}
const auto modulePath = std::filesystem::path(desc_.runtimeAbsPath) / L"nvngx_dlssg.dll";
- HMODULE module = GetModuleHandleW(L"nvngx_dlssg.dll");
- if (module == nullptr) {
- module = LoadLibraryExW(modulePath.c_str(), nullptr,
- LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32);
- }
+HMODULE module = fgCompatibility_ ? fgCompatibility_->provider() : nullptr;
if (module == nullptr) {
veyra::log::warn("ampere-mfg", std::format("DLSS-G runtime could not be opened for the RTX 30 unlock (path={} win32={})",
modulePath.string(), GetLastError()));
@@ -777,8 +772,8 @@ void EnhanceGraph::applyAmpereMfgUnlock()
// the kernel rewrite runs here. Without the spoof the old retarget is kept.
const auto spoofState = ngx::NvapiArchSpoof::snapshot();
const bool spoofed = ampereSpoofed_ && spoofState.installed;
- const auto state = ngx::AmpereMfgUnlock::apply(module, !spoofed);
- veyra::log::info("ampere-mfg", std::format("adapter deviceId=0x{:04X} unlock applied={} spoofed={} reportedArch=0x{:X} runs={} slots={} fatbins={} lea={} gates={} ({})",
+ const auto state = ngx::AmpereMfgUnlock::apply(module, !spoofed, adapter.luid);
+ veyra::log::info("ampere-mfg", std::format("adapter deviceId=0x{:04X} unlock applied={} spoofed={} reportedArch=0x{:X} runs={} slots={} inventoryFatbins={} inventoryLea={} gates={} ({})",
adapter.deviceId, state.applied ? 1 : 0,
spoofed ? 1 : 0, spoofState.reportedArchitecture, state.slotRuns,
state.slotPointers,
@@ -856,14 +851,36 @@ bool EnhanceGraph::initNgxFeatures()
return false;
}
- // RTX 30 needs the NVAPI architecture spoof in place before the provider is
- // initialized below. No-op on Ada/Blackwell and when FG is off.
- prepareAmpereFgSpoof();
+ // Publish the programs before Init: the provider can register/cache CUDA
+ // programs and capabilities during Init, before GetCapabilityParameters.
+ if(!ngx::FgCompatibilitySession::processHealthy()){
+ failedBackend_=engine::FailedBackend::NgxCore;
+ log::error("graph","compatibility rollback was not verified; restart required before NGX initialization");
+ return false;
+ }
+ if (fgEnabled_ && desc_.frameGenerationBackend==engine::FrameGenerationBackend::Dlss &&
+ ngx::FgCompatibilitySession::requested(context_.adapter().vendorId,context_.adapter().deviceId)) {
+ failedBackend_=engine::FailedBackend::Fg;
+ fgCompatibility_=std::make_unique<ngx::FgCompatibilitySession>();
+ if(!fgCompatibility_->open(context_.device(),context_.adapter().vendorId,context_.adapter().deviceId,desc_.runtimeAbsPath))return false;
+ prepareAmpereFgSpoof();
+ applyAdaMfgUnlock();
+ applyAmpereMfgUnlock();
+ if(!fgCompatibility_->prepareDriver(desc_.runtimeAbsPath,projectId.c_str(),engineVersion.c_str()))return false;
+ std::array<ID3D12Resource*,2> real={videoFrame_[0].Get(),videoFrame_[1].Get()};
+ std::array<ID3D12Resource*,kGeneratedPoolSlots> generated{};
+ for(size_t i=0;i<generated.size();++i)generated[i]=genFrame_[i].Get();
+ if(!fgCompatibility_->bindResources(real,generated))return false;
+ }
+ failedBackend_=engine::FailedBackend::NgxCore;
coreHost_ = std::make_unique<ngx::NgxCoreHost>();
Status st = Status::Ok;
- if (!coreHost_->initialize(context_.device(), desc_.runtimeAbsPath.c_str(),
- projectId.c_str(), engineVersion.c_str(), st)) {
+ if(fgCompatibility_&&!fgCompatibility_->beginInitialization())return false;
+ const bool initialized=coreHost_->initialize(context_.device(), desc_.runtimeAbsPath.c_str(),
+ projectId.c_str(), engineVersion.c_str(), st);
+ const bool initRestored=!fgCompatibility_||fgCompatibility_->endInitialization(initialized);
+ if (!initialized || !initRestored) {
return false;
}
@@ -871,42 +888,20 @@ bool EnhanceGraph::initNgxFeatures()
fgMultiFrameMax_ = 0;
if (fgEnabled_ && desc_.frameGenerationBackend==engine::FrameGenerationBackend::Dlss) {
failedBackend_=engine::FailedBackend::Fg;
- // RTX 40 series would report only 2X here; open the arch gate in the mapped
- // DLSS-G runtime first so the capability query below sees multi-frame. On
- // every other architecture this is a no-op.
- applyAdaMfgUnlock();
- // RTX 30 has no sm_86 program in the provider at all; the Ampere unlock
- // rebuilds every fatbin and re-targets the arch gates before the query.
- applyAmpereMfgUnlock();
fgBackend_ = std::make_unique<ngx::DlssFgBackend>();
+ fgBackend_->setCompatibility(fgCompatibility_.get());
ngx::DlssFgBackend::Capability fgCaps{};
const bool fgAvailable = fgBackend_->queryCapability(*coreHost_, fgCaps, st);
if (!fgAvailable) {
- if (ngx::AmpereMfgUnlock::applied()) {
- // The unlock rewrites the provider's programs, but the runtime's own
- // availability gate still refuses sm_86. A real RTX 3060 (field log
- // 2026-09-17) showed that forcing the capability here only moves the
- // failure to CreateFeature (0xBAD0000B UnableToInitializeFeature)
- // and then tears the whole frame-generation stage down with a
- // generic error. Fail closed with the actual reason instead. If a
- // 30-series configuration is ever shown to work, the controlled
- // retry belongs behind an explicit, verified capability path - not
- // behind an assumption.
- veyra::log::error("ampere-mfg", std::format(
- "runtime reported FG unavailable (MultiFrameCountMax={}); the sm_86 unlock is applied but this driver/runtime combination does not enable frame generation - failing closed instead of forcing CreateFeature",
- fgCaps.multiFrameCountMax));
- return false;
- } else {
- veyra::log::error("graph", "FG unavailable; fail closed");
- return false;
- }
+ veyra::log::error("graph", "FG capability startup failed; see native results and compatibility stage above");
+ return false;
}
// Publish the capability before validating the request so a rejected
// multiplier still teaches the caller what this GPU supports.
fgCapsAvailable_ = fgCaps.available;
fgMultiFrameMax_ = fgCaps.multiFrameCountMax;
if (ngx::AdaMfgUnlock::applied() && fgMultiFrameMax_ <= 1) {
- veyra::log::warn("ada-mfg", std::format("unlock is installed but the runtime still reports maxGeneratedFrames={}; the active DLSS-G is not the audited local build", fgMultiFrameMax_));
+ veyra::log::warn("ada-mfg", std::format("provider patch installed, but startup maximum remains {}; inspect provider generation and capability query", fgMultiFrameMax_));
}
// Test-only capability override: lets the Ada (40-series) ceiling and the
// capability-driven UI/recovery paths be exercised on a 50-series host
@@ -1051,7 +1046,7 @@ bool EnhanceGraph::initNgxFeatures()
bool warmOk = true;
for(uint32_t sub=1;sub<=fe.multiFrameCount;++sub){
fe.multiFrameIndex=sub;
- warmOk=fgBackend_->evaluate(wlist,ngxParams_,fe,st)&&warmOk;
+ if (!fgBackend_->evaluate(wlist,ngxParams_,fe,st)) { warmOk=false; break; }
D3D12_RESOURCE_BARRIER u{};u.Type=D3D12_RESOURCE_BARRIER_TYPE_UAV;u.UAV.pResource=fe.outputInterpolated;wlist->ResourceBarrier(1,&u);
}
if(!warmOk){failedBackend_=engine::FailedBackend::Fg;return false;}
@@ -1306,6 +1301,12 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
}
uint32_t slot = 0;
if (uploadFences_[parity] && !context_.waitForFenceValue(uploadFences_[parity])) return false;
+ // Presentation returns the shared output to COMMON before this parity
+ // can be written again. Direct graph callers also need the GPU dependency.
+ if(presentationFences_[parity]){
+ const HRESULT hr=context_.directQueue()->Wait(presentationFences_[parity].Get(),presentationValues_[parity]);
+ if(FAILED(hr)){veyra::log::error("graph",std::format("presentation handoff wait hr=0x{:X}",unsigned(hr)));return false;}
+ }
hardwareInputFrames_[parity].reset();
if(frame->format==AV_PIX_FMT_D3D12||frame->format==AV_PIX_FMT_D3D11){
auto* retained=av_frame_clone(frame);
@@ -1831,9 +1832,9 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
for(uint32_t sub=1;sub<desc_.fgMultiplier;++sub){
const uint32_t generatedSlot=parity+(sub-1)*2;
auto* flist=ring_.acquireNext(slot,st); if(!flist)return false;
- auto* motion=haveFlow?baseFlow_.Get():nrZeroMotion_.Get();
+ auto* motion=desc_.fgMotionProbe?desc_.fgMotionProbe:(haveFlow?baseFlow_.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);
+ if(!desc_.fgMotionProbe)tracker_.transition(flist,motion,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
tracker_.transition(flist,depthTex_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
tracker_.transition(flist,genFrame_[generatedSlot].Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
// One status resource for the whole input-frame pair, just like the
@@ -1850,8 +1851,8 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
fe.multiFrameCount=desc_.fgMultiplier-1;fe.multiFrameIndex=sub;
fe.frameId=realFrameIndex_+1;
// 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;
+ fe.mvecScaleX=(haveFlow||desc_.fgMotionProbe)?-1.0f/static_cast<float>(workW_):1.0f;
+ fe.mvecScaleY=(haveFlow||desc_.fgMotionProbe)?-1.0f/static_cast<float>(workH_):1.0f;
if(sub==1)gpuTimer_.mark(flist,GpuStage::FgBatch);
const auto timingStage=static_cast<GpuStage>(unsigned(GpuStage::Fg1)+sub-1);gpuTimer_.mark(flist,timingStage);
if(!fgBackend_->evaluate(flist,ngxParams_,fe,st)){failedBackend_=engine::FailedBackend::Fg;return false;}
@@ -1998,7 +1999,12 @@ ID3D12Resource* EnhanceGraph::generatedFrameResource(uint32_t slot) const
void EnhanceGraph::shutdown()
{
if (!initialized_ && !nrAdapter_ && !nvof_ && !srcRgba_) return;
+ for(unsigned i=0;i<2;++i)if(presentationFences_[i]){
+ const HRESULT hr=context_.directQueue()->Wait(presentationFences_[i].Get(),presentationValues_[i]);
+ if(FAILED(hr))veyra::log::error("graph",std::format("presentation teardown wait hr=0x{:X}",unsigned(hr)));
+ }
(void)ring_.drainQueue();(void)ring_.discardRecording();
+ presentationFences_={};presentationValues_={};
for(auto& input:hardwareInputFrames_)input.reset();
Status st = Status::Ok;
if (nv12Ctx_ != nullptr) { sws_freeContext(nv12Ctx_); nv12Ctx_ = nullptr; }
@@ -2046,9 +2052,8 @@ void EnhanceGraph::shutdown()
if (coreHost_) coreHost_->shutdown();
// Restore the DLSS-G runtime image only after the NGX core released the
// feature (the unlock is process memory only; the file on disk is untouched).
- ngx::AdaMfgUnlock::release();
- ngx::AmpereMfgUnlock::release();
- ngx::NvapiArchSpoof::release();
+ fgCompatibility_.reset();
+ ampereSpoofed_=false;
// Staged explicit release (scope-end destructors then have nothing left).
decPass_ = ComputePass{};
diff --git a/src/sink/CaptureAudioSession.cpp b/src/sink/CaptureAudioSession.cpp
index 77802a29..ee63b4cb 100644
--- a/src/sink/CaptureAudioSession.cpp
+++ b/src/sink/CaptureAudioSession.cpp
@@ -52,7 +52,7 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
headPts=pcmTimeline.at(double(pcmHead)).value_or(headPts);
pcmTimeline.discardBefore(pcmHead);queueChanged();
}
- void fail(const wchar_t* reason){std::lock_guard lock(mutex);state.available=false;state.running=false;state.skewMs.reset();state.error=reason;}
+ void fail(const wchar_t* reason){std::lock_guard lock(mutex);state.available=false;state.running=false;state.outputRecovering=false;state.skewMs.reset();state.error=reason;}
size_t pull(float* dst,size_t frames,double* pts)override{
std::lock_guard lock(mutex);
const size_t take=std::min(frames,pcm.size()/layout.channels);
@@ -112,11 +112,14 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
};
auto recoverEndpoint=[&]{
const auto error=renderer.lastError();renderer.shutdown();endpointReady=false;retryAt=hostTime()+5000000;
+ if(injectEndpointLoss&&GetEnvironmentVariableW(L"VEYRA_TEST_CAPTURE_AUDIO_LONG_OUTAGE",nullptr,0)>0)
+ retryAt=hostTime()+40000000;
clearPcm();swr_close(swr);if(swr_init(swr)<0){fail(L"音频重采样重置失败");return false;}
if(!clearCorrection())return false;
endpointEventReady=false;
std::lock_guard lock(mutex);input.clear();inputBytes=convertingBytes=0;pendingReset=false;haveVideo=false;
state.available=false;state.running=false;state.skewMs.reset();state.endpointBufferedMs=0;
+ state.outputRecovering=true;
state.error=L"音频输出断开,正在重连("+std::to_wstring(unsigned(error))+L")";queueChanged();return true;
};
while(!stop){
@@ -132,7 +135,7 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
if(!renderer.start(layout,20.0)){if(!recoverEndpoint())break;continue;}
endpointReady=true;lastUnderruns=renderer.underruns();
lastUnderrunFrames=renderer.underrunFrames();lastSilenceFrames=renderer.silenceFrames();starvationSince=0;
- {std::lock_guard lock(mutex);state.error.clear();state.inputChannels=layout.channels;state.inputChannelMask=layout.mask;const auto output=renderer.outputFormat();state.outputChannels=output.channels;state.outputChannelMask=output.mask;pendingReset=true;}
+ {std::lock_guard lock(mutex);state.error.clear();state.outputRecovering=false;state.inputChannels=layout.channels;state.inputChannelMask=layout.mask;const auto output=renderer.outputFormat();state.outputChannels=output.channels;state.outputChannelMask=output.mask;pendingReset=true;}
}
renderer.setGain(gain);
// Wait before collecting callbacks, so PCM arriving during the
@@ -413,13 +416,16 @@ void CaptureAudioSession::stop(){p_->stop=true;p_->wake.notify_all();if(p_->thre
bool CaptureAudioSession::push(const void* data,size_t bytes,double pts,bool discontinuity){
auto& p=*p_;if(!data||!p.format.nBlockAlign||bytes%p.format.nBlockAlign||bytes>p.format.nAvgBytesPerSec/2||!std::isfinite(pts))return false;if(!bytes)return true;
std::lock_guard lock(p.mutex);
- if(p.stop||!p.state.error.empty())return true;
- p.recording.raw(data,bytes);
- if(discontinuity){p.input.clear();p.inputBytes=0;p.pendingReset=true;p.haveVideo=false;}
+ if(p.stop||(!p.state.error.empty()&&!p.state.outputRecovering))return true;
const auto arrival=hostTime();
p.state.inputIntervalMs=p.state.inputBlocks&&!discontinuity?double(arrival-p.lastArrival)/10000:0;
p.state.inputBlockMs=1000.0*bytes/p.format.nAvgBytesPerSec;++p.state.inputBlocks;
p.lastArrival=arrival;
+ // A lost output endpoint does not mean the capture device stopped sending.
+ // Keep its liveness visible without accumulating stale PCM for replay.
+ if(p.state.outputRecovering)return true;
+ p.recording.raw(data,bytes);
+ if(discontinuity){p.input.clear();p.inputBytes=0;p.pendingReset=true;p.haveVideo=false;}
if(!p.haveIngress||discontinuity){p.ingressClock.reset();p.haveIngress=true;}
p.ingressMapping=p.ingressClock.observe(double(p.lastArrival)/10000,pts);
const double blockMs=1000.0*bytes/p.format.nAvgBytesPerSec;
diff --git a/src/sink/MfVideoEncoder.cpp b/src/sink/MfVideoEncoder.cpp
index 6b49fabe..21b18ec3 100644
--- a/src/sink/MfVideoEncoder.cpp
+++ b/src/sink/MfVideoEncoder.cpp
@@ -143,6 +143,7 @@ public:
bool finish() override;
void close() override;
EncoderBackend backend() const override {return EncoderBackend::MediaFoundation;}
+ std::wstring lastError() const override {return error_;}
std::wstring describe() const override {
return hevc_?std::format(L"系统硬件编码 HEVC({})",friendly_):std::format(L"系统硬件编码 H.264({})",friendly_);
}
@@ -173,6 +174,8 @@ private:
ComPtr<IMFMediaType> inputType_,outputType_;
std::vector<uint8_t> extradata_;
std::wstring friendly_;
+ std::wstring error_;
+ bool check(HRESULT hr,const wchar_t* stage){if(SUCCEEDED(hr))return true;error_=std::format(L"{} HRESULT=0x{:08X}",stage,unsigned(hr));log::error("mf-encoder",std::string(error_.begin(),error_.end()));return false;}
bool hevc_=false;
uint32_t bitrateMbps_=0;
unsigned fpsNum_=1,fpsDen_=1;
@@ -195,20 +198,24 @@ bool MfVideoEncoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& rin
hevc_=config.hevc;bitrateMbps_=config.bitrateMbps;
fpsNum_=std::max(1u,config.fpsNum);fpsDen_=std::max(1u,config.fpsDen);
width_=graph.workWidth();height_=graph.workHeight();
+ error_=L"Media Foundation startup failed; see worker log";
if(graph.hdrOutput()){
// The MFT path is 8-bit 4:2:0 only; producing an SDR file from an HDR
// source without telling the user would be a silent quality lie.
log::error("mf-encoder","HDR export requires NVENC (HEVC Main10); Media Foundation path refused");
+ error_=L"HDR 10bit 不支持此系统编码路径(仅 8bit NV12)";
return false;
}
if(width_<16||height_<16||(width_&1)||(height_&1)){
log::error("mf-encoder",std::format("unsupported extent {}x{} for NV12",width_,height_));
+ error_=std::format(L"Unsupported NV12 extent {}x{}",width_,height_);
return false;
}
if(!acquireMediaFoundation())return false;
mfAcquired_=true;
std::vector<MftCandidate> candidates;std::wstring detail;
if(!listHardwareMfts(hevc_,config.adapterVendorId,candidates,detail)){
+ error_=detail;
log::error("mf-encoder",std::format("no hardware MFT: {}",std::string(detail.begin(),detail.end())));
return false;
}
@@ -219,7 +226,7 @@ bool MfVideoEncoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& rin
events_.Reset();codecApi_.Reset();inputType_.Reset();outputType_.Reset();extradata_.clear();
async_=false;needInput_=false;haveOutput_=false;marker_=false;drainingDone_=false;draining_=false;sampleSent_=false;
ComPtr<IMFTransform> transform;
- if(FAILED(candidate.activate->ActivateObject(IID_PPV_ARGS(&transform)))||!transform){
+ if(!check(candidate.activate->ActivateObject(IID_PPV_ARGS(&transform)),L"ActivateObject")||!transform){
log::warn("mf-encoder",std::format("activate failed for {}",std::string(candidate.name.begin(),candidate.name.end())));
continue;
}
@@ -237,6 +244,7 @@ bool MfVideoEncoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& rin
if(FAILED(transform_->QueryInterface(IID_PPV_ARGS(&codecApi_)))){
log::warn("mf-encoder","no ICodecAPI on this MFT; bitrate settings are unavailable");
}
+ error_=L"MFT type/header negotiation failed";
if(applyRateControl()&&setupTypes()&&readExtradata()){
// ~2 s GOP: the first sample and every GOP boundary are forced,
// which is what makes vendor MFTs emit their first output
@@ -254,18 +262,20 @@ bool MfVideoEncoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& rin
log::error("mf-encoder",std::format("no hardware MFT accepted the contract ({} candidates)",candidates.size()));
return false;
}
- if(FAILED(transform_->GetOutputStreamInfo(outputId_,&outputInfo_)))return false;
+ if(!check(transform_->GetOutputStreamInfo(outputId_,&outputInfo_),L"GetOutputStreamInfo"))return false;
outputProvidesSamples_=(outputInfo_.dwFlags&(MFT_OUTPUT_STREAM_PROVIDES_SAMPLES|MFT_OUTPUT_STREAM_CAN_PROVIDE_SAMPLES))!=0;
// Same NV12 conversion the NVENC path uses; the result is read back because
// MFTs take system-memory NV12 (no shared D3D12 texture contract).
std::vector<uint8_t> shader;
- if(!convert_.loadShader("RgbToNv12.dxil",shader)||!convert_.create(ctx.device(),shader,10,1,2))return false;
- for(unsigned i=0;i<8;++i)makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),graph.outputFormat(),cpuHandleOf(convert_,i));
+ error_=L"RgbToNv12 shader load/create failed";
+ if(!convert_.loadShader("RgbToNv12.dxil",shader)||!convert_.create(ctx.device(),shader,kOutputPoolSlots+2,1,2))return false;
+ for(unsigned i=0;i<kOutputPoolSlots;++i)makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),graph.outputFormat(),cpuHandleOf(convert_,i));
+ error_=L"NV12 conversion/readback allocation failed";
y_=makeTexture(ctx.device(),width_,height_,DXGI_FORMAT_R8_UNORM,true);
uv_=makeTexture(ctx.device(),width_/2,height_/2,DXGI_FORMAT_R8G8_UNORM,true);
if(!y_||!uv_)return false;
- makeUav(ctx.device(),y_.Get(),DXGI_FORMAT_R8_UNORM,cpuHandleOf(convert_,8));
- makeUav(ctx.device(),uv_.Get(),DXGI_FORMAT_R8G8_UNORM,cpuHandleOf(convert_,9));
+ makeUav(ctx.device(),y_.Get(),DXGI_FORMAT_R8_UNORM,cpuHandleOf(convert_,kOutputPoolSlots));
+ makeUav(ctx.device(),uv_.Get(),DXGI_FORMAT_R8G8_UNORM,cpuHandleOf(convert_,kOutputPoolSlots+1));
auto makeReadback=[&](uint32_t rows,uint32_t rowBytes,ComPtr<ID3D12Resource>& out,UINT& pitch){
pitch=alignUp(rowBytes,256);
D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;
@@ -276,10 +286,11 @@ bool MfVideoEncoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& rin
if(!makeReadback(height_,width_,yRead_,yPitch_)||!makeReadback(height_/2,width_,uvRead_,uvPitch_))return false;
packed_.resize(size_t(width_)*height_+size_t(width_)*(height_/2));
fenceEvent_=CreateEventW(nullptr,FALSE,FALSE,nullptr);
- if(!fenceEvent_)return false;
- if(FAILED(transform_->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH,0)))return false;
- transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING,0);
- transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM,0);
+ if(!fenceEvent_){error_=std::format(L"CreateEvent win32={}",GetLastError());return false;}
+ if(!check(transform_->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH,0),L"Flush"))return false;
+ if(!check(transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING,0),L"BeginStreaming"))return false;
+ if(!check(transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM,0),L"StartOfStream"))return false;
+ error_.clear();
return true;
}
@@ -521,6 +532,7 @@ bool MfVideoEncoder::drainOutputs(bool waitForOutput){
}
bool MfVideoEncoder::convertToNv12(unsigned frameSlot,bool generated){
+ if(frameSlot>=(generated?kGeneratedPoolSlots:2)){error_=L"Encoder frame slot out of range";return false;}
Status status=Status::Ok;
uint32_t slot=0;
auto* list=ring_->acquireNext(slot,status);
@@ -533,7 +545,7 @@ bool MfVideoEncoder::convertToNv12(unsigned frameSlot,bool generated){
// Foundation encoder must dither a graded frame exactly like the NVENC path
// so preview/export stay consistent.
const float dims[8]={std::bit_cast<float>(width_),std::bit_cast<float>(height_),0,std::bit_cast<float>(graph_?graph_->outputDitherStep():0.0f),0,0,0,0};
- convert_.bind(list,dims,gpuHandleOf(convert_,frameSlot+(generated?2:0)).ptr,gpuHandleOf(convert_,8).ptr);
+ convert_.bind(list,dims,gpuHandleOf(convert_,frameSlot+(generated?2:0)).ptr,gpuHandleOf(convert_,kOutputPoolSlots).ptr);
list->Dispatch((width_+15)/16,(height_+15)/16,1);
states_.uavBarrier(list,y_.Get());
states_.uavBarrier(list,uv_.Get());
diff --git a/src/sink/NvencD3D12Encoder.cpp b/src/sink/NvencD3D12Encoder.cpp
index 36a461a3..8b377951 100644
--- a/src/sink/NvencD3D12Encoder.cpp
+++ b/src/sink/NvencD3D12Encoder.cpp
@@ -8,6 +8,9 @@
#include <format>
#include <algorithm>
namespace veyra::sink {
+// Use a complete, pinned ABI. Lowering only open.apiVersion does not make
+// newer structure layouts compatible with an older driver.
+static_assert(NVENCAPI_MAJOR_VERSION==13&&NVENCAPI_MINOR_VERSION==0,"NVENC requires the audited 13.0 ABI headers");
using namespace veyra::pipeline;
struct NvencD3D12Encoder::Impl {
HMODULE dll=nullptr;void* encoder=nullptr;NV_ENCODE_API_FUNCTION_LIST api{};
@@ -15,12 +18,14 @@ struct NvencD3D12Encoder::Impl {
bool hdr=false;bool hevc=false;NV_ENC_BUFFER_FORMAT inputFormat=NV_ENC_BUFFER_FORMAT_NV12;
unsigned w=0,h=0;uint64_t submitted=0,completed=0;
uint32_t bitrateMbps=0;
+ std::wstring error;
+ bool fail(std::wstring message){error=std::move(message);veyra::log::error("nvenc",std::string(error.begin(),error.end()));return false;}
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 check(NVENCSTATUS code,const char* op){const char* detail=code!=NV_ENC_SUCCESS&&encoder&&api.nvEncGetLastErrorString?api.nvEncGetLastErrorString(encoder):"";if(!detail)detail="";veyra::log::info("nvenc",std::format("{} status={} detail={}",op,int(code),detail));if(code!=NV_ENC_SUCCESS){const auto text=std::format("{} status={} {}",op,int(code),detail);error.assign(text.begin(),text.end());}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;}
@@ -34,6 +39,7 @@ struct NvencD3D12Encoder::Impl {
NvencD3D12Encoder::NvencD3D12Encoder():p_(std::make_unique<Impl>()){}
NvencD3D12Encoder::~NvencD3D12Encoder(){close();}
std::vector<uint8_t> NvencD3D12Encoder::headers()const{return p_->sequence;}
+std::wstring NvencD3D12Encoder::lastError()const{return p_->error;}
std::wstring NvencD3D12Encoder::describe()const{
return p_->hevc?L"NVIDIA NVENC HEVC (D3D12)":L"NVIDIA NVENC H.264 (D3D12)";
}
@@ -41,56 +47,39 @@ bool NvencD3D12Encoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
const bool hevc=config.hevc;const unsigned fpsNum=config.fpsNum,fpsDen=config.fpsDen;
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);
p.hevc=hevc;p.bitrateMbps=config.bitrateMbps;
+ p.error=L"NVENC initialization incomplete";
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;
+ p.dll=LoadLibraryExW(dllPath.c_str(),nullptr,LOAD_LIBRARY_SEARCH_SYSTEM32);if(!p.dll)return p.fail(std::format(L"LoadLibrary nvEncodeAPI64.dll win32={}",GetLastError()));
+ using MaxVersion=NVENCSTATUS(NVENCAPI*)(uint32_t*);
+ auto maxVersion=reinterpret_cast<MaxVersion>(GetProcAddress(p.dll,"NvEncodeAPIGetMaxSupportedVersion"));
+ uint32_t supported=0;
+ if(maxVersion)p.check(maxVersion(&supported),"GetMaxSupportedVersion");
+ log::info("nvenc",std::format("DLL={} driverApi={}.{} compiledAbi={}.{} codec={} extent={}x{} fps={}/{}",std::string(dllPath.begin(),dllPath.end()),supported>>4,supported&15,NVENCAPI_MAJOR_VERSION,NVENCAPI_MINOR_VERSION,hevc?"HEVC":"H264",p.w,p.h,fpsNum,fpsDen));
+ // Version/capability queries are diagnostics. The real API calls decide
+ // whether the driver can open and initialize this exact encoder request.
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;
+ if(!create)return p.fail(L"NvEncodeAPICreateInstance export missing");
+ p.api.version=NV_ENCODE_API_FUNCTION_LIST_VER;if(!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;
- // Some systems carry an older nvEncodeAPI64.dll (System32 copy from a
- // mixed driver/tool install) which rejects the compiled 13.1 declaration
- // with NV_ENC_ERR_INVALID_VERSION (status 15) - observed on a user RTX
- // 5060 where every export died here. Older API versions are fully
- // sufficient for our usage (H.264/HEVC, D3D12, low latency), so retry
- // downwards before giving up.
- // Test-only: pretend the compiled declaration was refused, so the fallback
- // ladder below still gets exercised on a healthy driver. Never set by the UI.
- // 1 = skip the first open only (exercises the ladder), 2 = refuse every
- // attempt (exercises the export's Media Foundation fallback). Test-only.
+ // Test injection goes through the same error handling as the real status.
wchar_t forcedText[8]{};GetEnvironmentVariableW(L"VEYRA_TEST_NVENC_FIRST_OPEN_FAILS",forcedText,8);
const int forcedMode=_wtoi(forcedText);
- const bool forcedMiss=forcedMode>0;
- const bool forcedMissAll=forcedMode>=2;
- if(forcedMiss)veyra::log::warn("nvenc","test-only: skipping the first OpenD3D12Session so the apiVersion ladder runs");
- if(forcedMiss||!p.check(p.api.nvEncOpenEncodeSessionEx(&open,&p.encoder),"OpenD3D12Session")) {
- const uint32_t fallbackVersions[]={NVENCAPI_MAJOR_VERSION,13u,12u,11u};
- bool opened=false;uint32_t accepted=0;
- for(const uint32_t major:fallbackVersions){
- if(!forcedMiss&&major==NVENCAPI_MAJOR_VERSION)continue; // already refused above
- if(forcedMissAll){
- log::info("nvenc",std::format("test-only: refusing apiVersion={}.0 as well",major));
- continue;
- }
- open.apiVersion=major;
- const auto result=p.api.nvEncOpenEncodeSessionEx(&open,&p.encoder);
- log::info("nvenc",std::format("OpenD3D12Session retry apiVersion={}.0 status={}",major,unsigned(result)));
- if(result==NV_ENC_SUCCESS){opened=true;accepted=major;break;}
- }
- if(!opened)return false;
- log::info("nvenc",std::format("OpenD3D12Session accepted apiVersion={}.0 (compiled {}.0 was refused)",accepted,NVENCAPI_MAJOR_VERSION));
- }
- p.hdr=graph.hdrOutput();if(p.hdr&&!hevc){veyra::log::error("nvenc","HDR export requires HEVC Main10");return false;}
+ if(forcedMode>0)log::warn("nvenc","test-only: inject OpenD3D12Session failure");
+ const auto opened=forcedMode==1?NV_ENC_ERR_INVALID_VERSION:forcedMode>=2?NV_ENC_ERR_UNSUPPORTED_DEVICE:p.api.nvEncOpenEncodeSessionEx(&open,&p.encoder);
+ if(!p.check(opened,"OpenD3D12Session"))return false;
+ p.hdr=graph.hdrOutput();if(p.hdr&&!hevc)return p.fail(L"HDR export requires HEVC Main10");
p.inputFormat=p.hdr?NV_ENC_BUFFER_FORMAT_YUV420_10BIT:NV_ENC_BUFFER_FORMAT_NV12;
const GUID codec=hevc?NV_ENC_CODEC_HEVC_GUID:NV_ENC_CODEC_H264_GUID;
int maxWidth=0,maxHeight=0;
NV_ENC_CAPS_PARAM caps{};caps.version=NV_ENC_CAPS_PARAM_VER;caps.capsToQuery=NV_ENC_CAPS_WIDTH_MAX;
- if(!p.check(p.api.nvEncGetEncodeCaps(p.encoder,codec,&caps,&maxWidth),"WidthMax"))return false;
+ p.check(p.api.nvEncGetEncodeCaps(p.encoder,codec,&caps,&maxWidth),"WidthMax");
caps.capsToQuery=NV_ENC_CAPS_HEIGHT_MAX;
- if(!p.check(p.api.nvEncGetEncodeCaps(p.encoder,codec,&caps,&maxHeight),"HeightMax"))return false;
+ p.check(p.api.nvEncGetEncodeCaps(p.encoder,codec,&caps,&maxHeight),"HeightMax");
veyra::log::info("nvenc",std::format("codec={} requested={}x{} maximum={}x{}",hevc?"HEVC":"H264",p.w,p.h,maxWidth,maxHeight));
- if(maxWidth<=0||maxHeight<=0||p.w>unsigned(maxWidth)||p.h>unsigned(maxHeight)||(p.w&1)||(p.h&1)){
- veyra::log::error("nvenc","requested dimensions unsupported by selected codec/NV12 input");return false;
+ if((p.w&1)||(p.h&1)){
+ return p.fail(std::format(L"NV12 plane allocation requires even dimensions: {}x{}",p.w,p.h));
}
- if(p.hdr){int supported=0;caps.capsToQuery=NV_ENC_CAPS_SUPPORT_10BIT_ENCODE;if(!p.check(p.api.nvEncGetEncodeCaps(p.encoder,codec,&caps,&supported),"10bit support")||!supported)return false;}
+ if(p.hdr){int supported=0;caps.capsToQuery=NV_ENC_CAPS_SUPPORT_10BIT_ENCODE;p.check(p.api.nvEncGetEncodeCaps(p.encoder,codec,&caps,&supported),"10bit support");}
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.enableLookahead=0;
@@ -127,24 +116,31 @@ bool NvencD3D12Encoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
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;
+ const HRESULT fenceResult=ctx.device()->CreateFence(0,D3D12_FENCE_FLAG_NONE,IID_PPV_ARGS(&p.fence));
+ if(FAILED(fenceResult))return p.fail(std::format(L"CreateFence HRESULT=0x{:08X}",unsigned(fenceResult)));
+ p.event=CreateEventW(nullptr,FALSE,FALSE,nullptr);if(!p.event)return p.fail(std::format(L"CreateEvent win32={}",GetLastError()));
+ p.error=L"NV12/P010 plane allocation failed";
p.y=makeTexture(ctx.device(),p.w,p.h,p.hdr?DXGI_FORMAT_R16_UNORM:DXGI_FORMAT_R8_UNORM,true);p.uv=makeTexture(ctx.device(),p.w/2,p.h/2,p.hdr?DXGI_FORMAT_R16G16_UNORM: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,10,1,2))return false;
- for(unsigned i=0;i<8;++i)makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),graph.outputFormat(),cpuHandleOf(p.convert,i));
- makeUav(ctx.device(),p.y.Get(),p.hdr?DXGI_FORMAT_R16_UNORM:DXGI_FORMAT_R8_UNORM,cpuHandleOf(p.convert,8));makeUav(ctx.device(),p.uv.Get(),p.hdr?DXGI_FORMAT_R16G16_UNORM:DXGI_FORMAT_R8G8_UNORM,cpuHandleOf(p.convert,9));
+ p.error=L"RgbToNv12 shader load/create failed";
+ std::vector<uint8_t> cs;if(!p.convert.loadShader("RgbToNv12.dxil",cs)||!p.convert.create(ctx.device(),cs,kOutputPoolSlots+2,1,2))return false;
+ for(unsigned i=0;i<kOutputPoolSlots;++i)makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),graph.outputFormat(),cpuHandleOf(p.convert,i));
+ makeUav(ctx.device(),p.y.Get(),p.hdr?DXGI_FORMAT_R16_UNORM:DXGI_FORMAT_R8_UNORM,cpuHandleOf(p.convert,kOutputPoolSlots));makeUav(ctx.device(),p.uv.Get(),p.hdr?DXGI_FORMAT_R16G16_UNORM:DXGI_FORMAT_R8G8_UNORM,cpuHandleOf(p.convert,kOutputPoolSlots+1));
for(auto& s:p.slots){
+ p.error=L"NVENC input/output slot allocation failed";
s.input=makeTexture(ctx.device(),p.w,p.h,p.hdr?DXGI_FORMAT_P010: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;
+ const HRESULT resourceResult=ctx.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&s.output));
+ if(FAILED(resourceResult))return p.fail(std::format(L"CreateBitstreamResource HRESULT=0x{:08X}",unsigned(resourceResult)));
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:p.inputFormat;r.bufferUsage=output?NV_ENC_OUTPUT_BITSTREAM:NV_ENC_INPUT_IMAGE;
if(!p.check(p.api.nvEncRegisterResource(p.encoder,&r),output?"RegisterOutput":p.hdr?"RegisterP010":"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;
+ }p.error.clear();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;
+ if(frameSlot>=(generated?kGeneratedPoolSlots:2))return p.fail(L"Encoder frame slot out of range");
Status st=Status::Ok;uint32_t slot=0;auto* list=p.ring->acquireNext(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);
@@ -152,7 +148,7 @@ bool NvencD3D12Encoder::encode(unsigned frameSlot,bool generated,int64_t pts){au
// banding at the 8-bit (or 10-bit HDR) conversion; ungraded exports keep the
// exact legacy bytes because the graph reports a zero step.
const float dither=p.graph?p.graph->outputDitherStep():0.0f;
- const float dims[8]={std::bit_cast<float>(p.w),std::bit_cast<float>(p.h),std::bit_cast<float>(p.hdr?(p.graph->hdr10Output()?2u:1u):0u),std::bit_cast<float>(dither),0,0,0,0};p.convert.bind(list,dims,gpuHandleOf(p.convert,frameSlot+(generated?2:0)).ptr,gpuHandleOf(p.convert,8).ptr);list->Dispatch((p.w+15)/16,(p.h+15)/16,1);
+ const float dims[8]={std::bit_cast<float>(p.w),std::bit_cast<float>(p.h),std::bit_cast<float>(p.hdr?(p.graph->hdr10Output()?2u:1u):0u),std::bit_cast<float>(dither),0,0,0,0};p.convert.bind(list,dims,gpuHandleOf(p.convert,frameSlot+(generated?2:0)).ptr,gpuHandleOf(p.convert,kOutputPoolSlots).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;
diff --git a/src/sink/VideoEncoderFactory.cpp b/src/sink/VideoEncoderFactory.cpp
index 7c404d96..1b7717d3 100644
--- a/src/sink/VideoEncoderFactory.cpp
+++ b/src/sink/VideoEncoderFactory.cpp
@@ -28,12 +28,14 @@ std::unique_ptr<VideoEncoder> openVideoEncoder(gfx::D3D12DeviceContext& ctx,gfx:
// fallback encoder can be exercised without non-NVIDIA hardware. Never set
// by the product UI.
const bool forceMediaFoundation=GetEnvironmentVariableW(L"VEYRA_TEST_FORCE_MF_ENCODER",nullptr,0)>0;
+ std::wstring nvencError;
if(nvidia&&!forceMediaFoundation){
auto nvenc=std::make_unique<NvencD3D12Encoder>();
if(nvenc->open(ctx,ring,graph,request,writer)){
log::info("export",std::format("encoder selected={}",std::string(encoderBackendName(nvenc->backend()))));
return nvenc;
}
+ nvencError=nvenc->lastError();
// A refused NVENC session (mixed/old nvEncodeAPI64.dll, codec the GPU
// cannot encode) must not cost the user the whole export while the OS
// exposes a hardware MFT for the same codec.
@@ -44,8 +46,8 @@ std::unique_ptr<VideoEncoder> openVideoEncoder(gfx::D3D12DeviceContext& ctx,gfx:
log::info("export",std::format("encoder selected={}",std::string(encoderBackendName(mf->backend()))));
return mf;
}
- detail=nvidia?L"NVIDIA NVENC 与系统硬件编码器都无法初始化;请更新显卡驱动后重试"
- :L"当前显卡没有可用的硬件编码器(系统未提供 H.264/HEVC 编码 MFT);请更新显卡驱动后重试";
+ detail=nvencError.empty()?std::format(L"系统编码器初始化失败:{}",mf->lastError())
+ :std::format(L"编码器初始化失败;NVENC:{};系统编码器:{}",nvencError,mf->lastError());
return nullptr;
}
} // namespace veyra::sink
diff --git a/src/sink/WasapiAudioSink.cpp b/src/sink/WasapiAudioSink.cpp
index b3130af3..3eea2dda 100644
--- a/src/sink/WasapiAudioSink.cpp
+++ b/src/sink/WasapiAudioSink.cpp
@@ -34,23 +34,47 @@ bool AudioPipeline::open(const std::wstring& path)
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;
+ tracks_.clear();
+ for(unsigned i=0;i<fmt_->nb_streams;++i){
+ const auto* stream=fmt_->streams[i];const auto* p=stream->codecpar;
+ if(p->codec_type!=AVMEDIA_TYPE_AUDIO)continue;
+ const auto* language=av_dict_get(stream->metadata,"language",nullptr,0);
+ const auto* title=av_dict_get(stream->metadata,"title",nullptr,0);
+ tracks_.push_back({int(i),language?language->value:"",title?title->value:"",avcodec_get_name(p->codec_id),unsigned(p->ch_layout.nb_channels)});
+ }
const AVCodec* codec = nullptr;
const int si = av_find_best_stream(fmt_, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0);
if (si < 0 || codec == nullptr) {
veyra::log::info("audio", "no audio stream in source");
return false;
}
- streamIndex_ = si;
- codecCtx_ = avcodec_alloc_context3(codec);
- if (avcodec_parameters_to_context(codecCtx_, fmt_->streams[si]->codecpar) < 0) return false;
- if (avcodec_open2(codecCtx_, codec, nullptr) < 0) return false;
- stream_ = fmt_->streams[si];
- const auto& layout=codecCtx_->ch_layout;
- if(layout.order==AV_CHANNEL_ORDER_NATIVE&&layout.u.mask<=UINT32_MAX)pcmFormat_={unsigned(layout.nb_channels),uint32_t(layout.u.mask)};
- else if(layout.nb_channels==1)pcmFormat_={1,SPEAKER_FRONT_CENTER};
- else if(layout.nb_channels==2)pcmFormat_={};
- else {log::error("audio","Unsupported or unspecified multichannel speaker layout");return false;}
- if(!pcmFormat_.valid())return false;
+ return selectTrack(si);
+}
+
+bool AudioPipeline::selectTrack(int si)
+{
+ if(thread_.joinable()||!fmt_||si<0||unsigned(si)>=fmt_->nb_streams)return false;
+ const auto* parameters=fmt_->streams[si]->codecpar;
+ if(parameters->codec_type!=AVMEDIA_TYPE_AUDIO)return false;
+ const auto* codec=avcodec_find_decoder(parameters->codec_id);
+ if(!codec)return false;
+ auto* candidate=avcodec_alloc_context3(codec);
+ if(!candidate)return false;
+ int result=avcodec_parameters_to_context(candidate,parameters);
+ if(result>=0)result=avcodec_open2(candidate,codec,nullptr);
+ AudioFormat format;
+ const auto& layout=candidate->ch_layout;
+ if(layout.order==AV_CHANNEL_ORDER_NATIVE&&layout.u.mask<=UINT32_MAX)format={unsigned(layout.nb_channels),uint32_t(layout.u.mask)};
+ else if(layout.nb_channels==1)format={1,SPEAKER_FRONT_CENTER};
+ else if(layout.nb_channels!=2)result=AVERROR(EINVAL);
+ if(result<0||!format.valid()){
+ log::error("audio-track",std::format("decoder rejected stream={} code={}",si,result));
+ avcodec_free_context(&candidate);return false;
+ }
+ avcodec_free_context(&codecCtx_);codecCtx_=candidate;streamIndex_=si;stream_=fmt_->streams[si];pcmFormat_=format;
+ if(swr_)swr_free(&swr_);
+ av_packet_unref(packet_);havePacket_=demuxEof_=drainSent_=false;decodedEof_=false;
+ {std::lock_guard lock(mutex_);ring_.clear();segments_.clear();ringFrames_=0;}
log::info("audio-format",std::format("file input channels={} mask=0x{:X}; preserve to renderer",pcmFormat_.channels,pcmFormat_.mask));
veyra::log::info("audio", std::format("audio stream idx={} codec={} rate={}",
si, codec->name, codecCtx_->sample_rate));
@@ -586,7 +610,7 @@ void AudioRenderer::setPaused(bool value)
if(checked(value ? client_->Stop() : client_->Start(),"Pause/resume")){pausedEndpoint_=value;liveGap_.reset();}
}
-void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint)
+void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint, double initialMs)
{
const auto t0 = std::chrono::steady_clock::now();
bool endpointReady = renderer && (!ownEndpoint || renderer->start(pcmFormat_));
@@ -610,14 +634,22 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint)
log::warn("audio-recovery",std::format("endpoint unavailable hr=0x{:08X} holdPtsMs={:.3f}",unsigned(endpointError_.load()),recoveryTargetMs));
};
auto rewind = [&](double target) {
+ const auto seekBegin=std::chrono::steady_clock::now();
{
std::lock_guard lock(mutex_);
ring_.clear();ringFrames_=0;segments_.clear();
if(havePacket_){av_packet_unref(packet_);havePacket_=false;}
avcodec_flush_buffers(codecCtx_);
if(swr_)swr_free(&swr_);
- const int64_t tbTarget=static_cast<int64_t>(target*stream_->time_base.den/1000/stream_->time_base.num);
- const int result=avformat_seek_file(fmt_,streamIndex_,INT64_MIN,tbTarget,INT64_MAX,0);
+ // Matroska commonly indexes only video keyframes. Seeking an audio
+ // stream can use its sparse, previously observed packet index and
+ // decode minutes of audio. Seek the container's video index, then
+ // trim decoded PCM to the exact requested audio timestamp.
+ const int video=av_find_best_stream(fmt_,AVMEDIA_TYPE_VIDEO,-1,-1,nullptr,0);
+ const int seekStream=video>=0?video:streamIndex_;
+ const auto tb=fmt_->streams[seekStream]->time_base;
+ const int64_t tbTarget=av_rescale_q(int64_t(target*1000),{1,1000000},tb);
+ const int result=av_seek_frame(fmt_,seekStream,tbTarget,AVSEEK_FLAG_BACKWARD);
if(result<0){log::error("audio",std::format("seek failed code={}",result));clockExhausted_=false;return false;}
demuxEof_=drainSent_=false;decodedEof_=false;
nextPtsMs_=target;discardUntilPtsMs_=target;
@@ -625,16 +657,13 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint)
decodeBlock();
discardUntilPtsMs_=-1;
clockExhausted_=decodedEof_&&headPtsMs()<0;
+ log::info("audio-seek",std::format("targetMs={:.3f} firstPtsMs={:.3f} totalMs={:.3f}",target,headPtsMs(),std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-seekBegin).count()));
return true;
};
if(renderer&&ownEndpoint&&!endpointReady)recovering(renderer->lastError());
// Initial prefill (open case).
- {
- std::unique_lock<std::mutex> lock(mutex_);
- seekRequested_ = false;
- discardUntilPtsMs_ = -1.0;
- }
- decodeBlock();
+ if(initialMs>=0){if(!rewind(initialMs))recovering(E_FAIL);}
+ else decodeBlock();
{
std::unique_lock<std::mutex> lock(mutex_);
if (segments_.empty()) {
@@ -700,7 +729,11 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint)
if (seekOk&&endpointReady && !clockExhausted_) {
pauseApplied=shouldPause();
if (!renderer->startAnchored(*this,pauseApplied)) recovering(renderer->lastError());
+ // A seek can interrupt the first prefill before it clears
+ // startup recovery. Publish the newly anchored endpoint.
+ else endpointRecovering_=false;
}
+ if(seekOk&&endpointReady&&clockExhausted_)endpointRecovering_=false;
{
std::lock_guard<std::mutex> l2(mutex_);
discardUntilPtsMs_ = -1.0;
@@ -758,10 +791,12 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint)
if(renderer&&ownEndpoint)renderer->shutdown();
}
-void AudioPipeline::startThread(AudioRenderer* renderer, bool ownEndpoint)
+void AudioPipeline::startThread(AudioRenderer* renderer, bool ownEndpoint, double initialMs)
{
+ if(thread_.joinable())return;
+ stopFlag_=false;seekRequested_=false;seekDone_=true;discardUntilPtsMs_=-1;
endpointRecovering_=renderer&&ownEndpoint;endpointError_=S_OK;endpointRecoveries_=0;clockExhausted_=false;
- thread_ = std::thread(&AudioPipeline::runOnAudioThread, this, renderer, ownEndpoint);
+ thread_ = std::thread(&AudioPipeline::runOnAudioThread, this, renderer, ownEndpoint, initialMs);
}
} // namespace veyra::sink
diff --git a/tests/integration/AudioTimelineTests.cpp b/tests/integration/AudioTimelineTests.cpp
index 2544d896..efc92cbf 100644
--- a/tests/integration/AudioTimelineTests.cpp
+++ b/tests/integration/AudioTimelineTests.cpp
@@ -49,6 +49,25 @@ void decode(const std::filesystem::path& file) {
check(pipe.overruns()==0, "bounded PCM ring did not overflow");
pipe.stopThread();
}
+int startupSeek(const std::filesystem::path& dir) {
+ const auto file=dir/"startup-seek.wav";fixture(file,48000,4000);
+ for(unsigned attempt=0;attempt<3;++attempt){
+ AudioPipeline pipe;AudioRenderer renderer;renderer.setGain(0);
+ check(pipe.open(file.wstring()),"open startup seek fixture");
+ pipe.holdForVideo();pipe.startThread(&renderer,true);
+ // Interrupt the initial prefill while the owned WASAPI endpoint opens.
+ const double target=pipe.requestSeek(1000);
+ check(std::abs(target-1000)<.05&&renderer.started(),"startup seek anchors actual PCM");
+ check(!pipe.endpointRecovering(),"successful startup seek clears endpoint recovery");
+ const double held=renderer.mediaTimeMs();std::this_thread::sleep_for(40ms);
+ check(std::abs(held-1000)<.1&&std::abs(renderer.mediaTimeMs()-held)<.1,"startup seek remains held for first video");
+ pipe.videoPresented(1042);
+ check(until([&]{return renderer.mediaTimeMs()>1100;}),"first video releases startup seek audio");
+ check(pipe.overruns()==0,"startup seek keeps bounded PCM");
+ pipe.stopThread();
+ }
+ return failures?1:0;
+}
int jitter(const std::filesystem::path& dir) {
const auto file=dir/"video-jitter.wav";fixture(file,48000,6000);
// Alternating 0/5ms completion jitter around 30fps. Real/generated frames
@@ -112,8 +131,9 @@ int underrate(const std::filesystem::path& dir) {
}
}
int wmain(int argc, wchar_t** argv) {
- if (argc!=2&&!(argc==3&&(wcscmp(argv[2],L"--jitter")==0||wcscmp(argv[2],L"--underrate")==0))) return 2;
+ if (argc!=2&&!(argc==3&&(wcscmp(argv[2],L"--jitter")==0||wcscmp(argv[2],L"--underrate")==0||wcscmp(argv[2],L"--startup-seek")==0))) return 2;
const std::filesystem::path dir=argv[1]; std::filesystem::create_directories(dir);
+ if(argc==3&&wcscmp(argv[2],L"--startup-seek")==0)return startupSeek(dir);
if(argc==3&&wcscmp(argv[2],L"--underrate")==0)return underrate(dir);
if(argc==3)return jitter(dir);
for(uint32_t rate:{48000u,44100u}) { const auto file=dir/(std::to_string(rate)+".wav"); fixture(file,rate); decode(file); }
diff --git a/tests/integration/AudioTrackOutputTests.cpp b/tests/integration/AudioTrackOutputTests.cpp
new file mode 100644
index 00000000..800470d5
--- /dev/null
+++ b/tests/integration/AudioTrackOutputTests.cpp
@@ -0,0 +1,69 @@
+#include "veyra/engine/ExportJobManager.h"
+#include "veyra/engine/FgCompatibilityProbe.h"
+#include "veyra/sink/WasapiAudioSink.h"
+#include <chrono>
+#include <filesystem>
+#include <iostream>
+#include <thread>
+#include <vector>
+
+using namespace veyra::engine;
+using Clock=std::chrono::steady_clock;
+
+// Fixture: video plus 440 Hz Spanish and 880 Hz English mono tracks.
+bool verifyPcm(veyra::sink::AudioPipeline& audio,int stream,double frequency){
+ if(!audio.selectTrack(stream))return false;
+ audio.setPaused(true);audio.startThread(nullptr,false,1000);
+ const auto deadline=Clock::now()+std::chrono::seconds(10);
+ while(audio.bufferedMs()<500&&Clock::now()<deadline)std::this_thread::sleep_for(std::chrono::milliseconds(5));
+ audio.stopThread();
+ const auto channels=audio.pcmFormat().channels;
+ if(!channels||audio.bufferedMs()<500)return false;
+ std::vector<float> pcm(24000*channels);double pts=-1;
+ const size_t frames=audio.pull(pcm.data(),24000,&pts);
+ unsigned crossings=0;double energy=0;
+ for(size_t i=0;i<frames;++i){const float value=pcm[i*channels];energy+=value*value;if(i&&value>=0&&pcm[(i-1)*channels]<0)++crossings;}
+ const double measured=double(crossings)*48000/frames;
+ const bool ok=frames==24000&&std::abs(pts-1000)<30&&energy/frames>.001&&std::abs(measured-frequency)<5;
+ std::cout<<(ok?"PASS ":"FAIL ")<<"stream="<<stream<<" Hz="<<measured<<" ptsMs="<<pts<<" frames="<<frames<<std::endl;
+ return ok;
+}
+bool verifyExport(const std::filesystem::path& output){
+ veyra::sink::AudioPipeline audio;
+ return audio.open(output.wstring())&&audio.tracks().size()==1&&audio.tracks()[0].language=="eng"&&verifyPcm(audio,audio.tracks()[0].streamIndex,880);
+}
+int wmain(int argc,wchar_t** argv){
+ wchar_t executable[32768]{};GetModuleFileNameW(nullptr,executable,32768);setFgCompatibilityProbeExecutable(executable);
+ CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ if(argc==3&&std::wstring_view(argv[1])==L"--export-worker")return runExportWorker(reinterpret_cast<HANDLE>(_wcstoui64(argv[2],nullptr,10)));
+ if(argc!=3)return 2;
+ std::filesystem::create_directories(argv[2]);
+ veyra::Logger::instance().openFile((std::filesystem::path(argv[2])/L"audio-tracks.log").wstring());
+ veyra::Logger::instance().setConsoleEnabled(false);
+ veyra::sink::AudioPipeline audio;
+ if(!audio.open(argv[1])||audio.tracks().size()!=2)return 1;
+ const auto tracks=audio.tracks();
+ if(tracks[0].language!="spa"||tracks[1].language!="eng")return 1;
+ for(unsigned index:{0,1,0,1})if(!verifyPcm(audio,tracks[index].streamIndex,index?880:440))return 1;
+ if(audio.selectTrack(99999)||audio.selectedTrack()!=tracks[1].streamIndex)return 1;
+ EnhancementSettings settings;settings.nr=settings.sr=false;settings.multiplier=1;
+ const auto workerOutput=std::filesystem::path(argv[2])/L"english-worker.mkv";
+ {
+ ExportJobManager manager;
+ if(!manager.start(argv[1],workerOutput.wstring(),settings,false,0,tracks[1].streamIndex))return 1;
+ const auto deadline=Clock::now()+std::chrono::seconds(90);
+ ExportJobSnapshot state;
+ do{state=manager.poll();if(!state.active())break;std::this_thread::sleep_for(std::chrono::milliseconds(10));}while(Clock::now()<deadline);
+ std::wcout<<L"worker state="<<int(state.state)<<L" encoded="<<state.encoded<<L" log="<<state.workerLog<<std::endl;
+ if(state.state!=ExportState::Succeeded||!verifyExport(workerOutput))return 1;
+ }
+ const auto legacyOutput=std::filesystem::path(argv[2])/L"english-controller.mkv";
+ {
+ EngineController engine;auto options=PlayerOptions::from(settings);options.audioStreamIndex=tracks[1].streamIndex;
+ engine.startExport(argv[1],legacyOutput.wstring(),options,false);
+ const auto deadline=Clock::now()+std::chrono::seconds(90);
+ while(!engine.idle()&&Clock::now()<deadline)std::this_thread::sleep_for(std::chrono::milliseconds(10));
+ if(!engine.idle()||engine.snapshot().failed||!verifyExport(legacyOutput))return 1;
+ }
+ CoUninitialize();return 0;
+}
diff --git a/tests/integration/CaptureAudioTests.cpp b/tests/integration/CaptureAudioTests.cpp
index f7230b0e..9a9f2a0f 100644
--- a/tests/integration/CaptureAudioTests.cpp
+++ b/tests/integration/CaptureAudioTests.cpp
@@ -1,5 +1,6 @@
#include "veyra/sink/CaptureAudioSession.h"
#include "veyra/sink/AudioFormat.h"
+#include "veyra/source/AudioInputRecovery.h"
#include <chrono>
#include <thread>
#include <iostream>
@@ -20,7 +21,9 @@ int main(int argc,char** argv){
else std::this_thread::sleep_until(due);
}
} pacer;
- const bool endpointTest=argc>=2&&std::string_view(argv[1])=="--endpoint-loss";
+ const bool longOutage=argc>=2&&std::string_view(argv[1])=="--long-endpoint-loss";
+ const bool endpointTest=longOutage||(argc>=2&&std::string_view(argv[1])=="--endpoint-loss");
+ if(longOutage)SetEnvironmentVariableW(L"VEYRA_TEST_CAPTURE_AUDIO_LONG_OUTAGE",L"1");
const bool slowStart=argc>=2&&std::string_view(argv[1])=="--slow-start";
const bool jitterTest=slowStart||(argc>=2&&std::string_view(argv[1])=="--jitter");
const bool transientTest=argc>=2&&std::string_view(argv[1])=="--transient";
@@ -143,19 +146,33 @@ int main(int argc,char** argv){
std::cout<<(pass?"PASS ":"FAIL ")<<"120s capture clock speed="<<speed<<" p95SkewMs="<<p95<<" missing="<<missing<<" resets="<<state.resets<<" highWaterMs="<<state.bufferHighWaterMs<<'\n';return pass?0:1;
}
double sum=0;unsigned count=0;bool bounded=true,sawReconnecting=false;
- for(unsigned i=0;i<(endpointTest?350u:160u);++i){
+ veyra::source::AudioInputRecovery inputRecovery;inputRecovery.reset(GetTickCount64());
+ unsigned falseInputRecoveries=0,callbacksDuringOutage=0;
+ const unsigned blocks=longOutage?650u:endpointTest?350u:160u;
+ for(unsigned i=0;i<blocks;++i){
const auto due=start+std::chrono::milliseconds(i*10);pacer.until(due);
const auto time=std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;
if(!audio.push(pcm.data(),pcm.size()*2,i*10.0,i==0))return 3;
if(i>=8)present(i*10.0-80,time,80);
const auto s=audio.snapshot();bounded&=s.bufferedMs<=520;
sawReconnecting|=!s.error.empty();
- if(i>(endpointTest?240u:70u)&&s.running&&s.skewMs){sum+=std::abs(*s.skewMs);++count;}
+ if(!s.error.empty())++callbacksDuringOutage;
+ if(inputRecovery.due(s.inputBlocks,GetTickCount64()))++falseInputRecoveries;
+ if(i>(longOutage?540u:endpointTest?240u:70u)&&s.running&&s.skewMs){sum+=std::abs(*s.skewMs);++count;}
}
const auto state=audio.snapshot();
std::cout<<"capture_audio meanAbsSkewMs="<<(count?sum/count:-1)<<" samples="<<count<<" compensationMs="<<state.compensationMs<<" queueMs="<<state.bufferedMs<<" resets="<<state.resets<<" overflows="<<state.overflows<<" underruns="<<state.underruns<<'\n';
bool ok=count>=60&&sum/count<25&&state.compensationMs>=65&&state.compensationMs<=95&&bounded&&state.overflows==0;
- if(endpointTest){ok=ok&&sawReconnecting&&state.error.empty()&&state.endpointRetries>=2&&state.running;audio.stop();std::cout<<(ok?"PASS ":"FAIL ")<<"owned WASAPI endpoint recovered without reopening capture retries="<<state.endpointRetries<<'\n';return ok?0:1;}
+ if(endpointTest){
+ ok=ok&&sawReconnecting&&state.error.empty()&&state.endpointRetries>=2&&state.running;
+ const auto lastProgress=GetTickCount64();
+ inputRecovery.due(state.inputBlocks,lastProgress);
+ const bool actualInputLossDetected=inputRecovery.due(state.inputBlocks,lastProgress+3001);
+ if(longOutage)ok=ok&&falseInputRecoveries==0&&callbacksDuringOutage>=350&&state.inputBlocks==blocks&&actualInputLossDetected;
+ audio.stop();std::cout<<(ok?"PASS ":"FAIL ")<<"owned WASAPI endpoint recovered without reopening capture retries="<<state.endpointRetries
+ <<" falseInputRecoveries="<<falseInputRecoveries<<" callbacksDuringOutage="<<callbacksDuringOutage<<" inputBlocks="<<state.inputBlocks
+ <<" actualInputLossDetected="<<actualInputLossDetected<<'\n';return ok?0:1;
+ }
std::cout<<(ok?"PASS":"FAIL")<<" synthetic capture PTS with 80ms video delay; real WASAPI, no physical capture\n";
unsigned sequence=160;
auto phase=[&](unsigned mode,int offset,double delay,double expectedComp,double expectedSkew,double commonInputMs=0,double maxSkewError=28){
diff --git a/tests/integration/CaptureSourceTests.cpp b/tests/integration/CaptureSourceTests.cpp
index 5cca1721..c2224621 100644
--- a/tests/integration/CaptureSourceTests.cpp
+++ b/tests/integration/CaptureSourceTests.cpp
@@ -20,9 +20,20 @@ int wmain(int argc,wchar_t** argv){
CoUninitialize();return videos.empty()?1:0;
}
const bool wasapiTest=argc==3&&wcscmp(argv[1],L"--wasapi")==0;
+ const bool outageTest=argc==2&&wcscmp(argv[1],L"--output-outage")==0;
if(argc!=2&&!wasapiTest){printf("Specify capture:device:format:audio or --wasapi <explicit endpoint ID>; real hardware required\n");return 2;}
CoInitializeEx(nullptr,COINIT_MULTITHREADED);
veyra::source::CaptureCardSource source;veyra::source::SourceOpenDesc d;d.path=argv[1];
+ if(outageTest){
+ const auto videos=veyra::source::CaptureCardSource::deviceDetails();
+ const auto audios=veyra::source::CaptureCardSource::deviceDetails(true);
+ const auto video=std::find_if(videos.begin(),videos.end(),[](const auto& v){return v.name==L"USB3 Video";});
+ const auto audio=std::find_if(audios.begin(),audios.end(),[](const auto& a){return !a.wasapi&&a.name.find(L"USB3 Digital Audio")!=std::wstring::npos;});
+ if(video==videos.end()||audio==audios.end()){printf("FAIL explicit physical USB3 A/V fixture unavailable\n");return 3;}
+ d.path=veyra::source::CaptureCardSource::makeCapturePath(unsigned(video-videos.begin()),*video,0,unsigned(audio-audios.begin()),&*audio);
+ SetEnvironmentVariableW(L"VEYRA_TEST_CAPTURE_AUDIO_ENDPOINT_LOSS",L"1");
+ SetEnvironmentVariableW(L"VEYRA_TEST_CAPTURE_AUDIO_LONG_OUTAGE",L"1");
+ }
if(wasapiTest){
const auto videos=veyra::source::CaptureCardSource::deviceDetails();
const auto video=std::find_if(videos.begin(),videos.end(),[](const auto& v){return v.name==L"USB3 Video";});
@@ -46,6 +57,27 @@ int wmain(int argc,wchar_t** argv){
auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(2);
auto readFrame=[&](){while(std::chrono::steady_clock::now()<deadline){auto r=source.read(packet,&frame);if(r==veyra::source::SourceReadStatus::Frame){if(wasapiTest)source.videoPresented(packet.pts.toDouble()*1000,std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count()/100,packet.arrivalHost100ns);return true;}if(r==veyra::source::SourceReadStatus::Error)return false;}return false;};
if(!readFrame()){printf("FAIL first frame\n");return 5;}
+ if(outageTest){
+ const auto until=std::chrono::steady_clock::now()+std::chrono::seconds(7);
+ auto last=std::chrono::steady_clock::now();double maxGapMs=0;
+ unsigned frames=0;bool sawOutage=false;uint64_t firstBlocks=0,lastBlocks=0;
+ bool monotonic=true;
+ while(std::chrono::steady_clock::now()<until){
+ source.recoverAudio(0,2,0);
+ deadline=until;if(!readFrame())break;
+ const auto now=std::chrono::steady_clock::now();
+ maxGapMs=std::max(maxGapMs,std::chrono::duration<double,std::milli>(now-last).count());last=now;++frames;
+ const auto s=source.audioState();
+ if(s.outputRecovering){sawOutage=true;if(!firstBlocks)firstBlocks=s.inputBlocks;}
+ monotonic&=s.inputBlocks>=lastBlocks;lastBlocks=s.inputBlocks;
+ }
+ const auto s=source.audioState();
+ check(sawOutage&&s.running&&!s.outputRecovering&&s.error.empty()&&s.endpointRetries>=2,"owned output outage recovers on physical audio input");
+ check(monotonic&&firstBlocks&&s.inputBlocks>firstBlocks+350,"input continues without graph/audio-session restart");
+ check(frames>=350&&maxGapMs<150,"physical video stays continuous through output outage");
+ printf("PHYSICAL_OUTAGE frames=%u maxReadGapMs=%.3f inputBlocks=%llu endpointRetries=%llu monotonic=%d\n",frames,maxGapMs,s.inputBlocks,s.endpointRetries,monotonic);
+ source.close();CoUninitialize();return failures?1:0;
+ }
const auto initialPts=packet.pts.toDouble();const auto initialReceived=source.metrics().received;
const int rowBytes=av_image_get_linesize(AVPixelFormat(frame->format),frame->width,0);
std::vector<unsigned char> row(frame->data[0],frame->data[0]+rowBytes);
diff --git a/tests/integration/ExportFramePoolTests.cpp b/tests/integration/ExportFramePoolTests.cpp
new file mode 100644
index 00000000..646f6071
--- /dev/null
+++ b/tests/integration/ExportFramePoolTests.cpp
@@ -0,0 +1,73 @@
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/sink/VideoEncoder.h"
+#include <filesystem>
+#include <fstream>
+#include <iostream>
+#include <cmath>
+extern "C" {
+#include <libavformat/avformat.h>
+#include <libavcodec/avcodec.h>
+}
+
+int main(int argc,char** argv){
+ using namespace veyra;
+ if(argc<2)return 2;
+ CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;pipeline::EnhanceGraph graph(ctx,ring);
+ Status status=Status::Ok;gfx::DeviceContextDesc device;device.enableDebugLayer=true;
+ bool ok=ctx.initialize(device,status)&&ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,status);
+ pipeline::EnhanceGraphDesc desc;desc.sourceWidth=desc.workWidth=640;desc.sourceHeight=desc.workHeight=360;
+ desc.enableNr=desc.enableSr=false;desc.enableFg=true;desc.fgMultiplier=6;desc.rgbInput=true;
+ desc.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();
+ ok=ok&&graph.initialize(desc)&&graph.createViews();
+ std::ofstream file(std::filesystem::path(argv[1]),std::ios::binary);
+ sink::EncoderConfig config;config.fpsNum=60;config.fpsDen=1;config.hevc=argc>2;
+ std::wstring detail;std::unique_ptr<sink::VideoEncoder> encoder;
+ if(ok)encoder=sink::openVideoEncoder(ctx,ring,graph,config,[&](const uint8_t* data,size_t size,int64_t,bool){file.write(reinterpret_cast<const char*>(data),size);return bool(file);},detail);
+ ok=ok&&bool(encoder)&&bool(file);
+ if(!ok)std::wcerr<<detail<<'\n';
+ if(ok){const auto headers=encoder->headers();file.write(reinterpret_cast<const char*>(headers.data()),headers.size());}
+ auto upload=ok?pipeline::makeUploadBuffer(ctx.device(),640*360*4):nullptr;
+ ok=ok&&bool(upload);
+ for(unsigned i=0;ok&&i<pipeline::kOutputPoolSlots;++i){
+ void* data=nullptr;ok=SUCCEEDED(upload->Map(0,nullptr,&data));if(!ok)break;
+ const uint8_t gray=uint8_t(20+i*18);
+ auto* pixels=static_cast<uint8_t*>(data);
+ for(size_t n=0;n<640*360;++n){pixels[n*4]=pixels[n*4+1]=pixels[n*4+2]=gray;pixels[n*4+3]=255;}
+ upload->Unmap(0,nullptr);
+ auto* target=i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2);
+ unsigned slot=0;auto* list=ring.acquireNext(slot,status);if(!list||!target){ok=false;break;}
+ D3D12_RESOURCE_BARRIER b{};b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
+ b.Transition={target,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_DEST};list->ResourceBarrier(1,&b);
+ D3D12_TEXTURE_COPY_LOCATION src{},dst{};src.pResource=upload.Get();src.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
+ src.PlacedFootprint.Footprint={DXGI_FORMAT_R8G8B8A8_UNORM,640,360,1,640*4};dst.pResource=target;
+ list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(1,&b);
+ ok=ring.submitAndSignal(slot)&&ring.waitIdle()&&encoder->encode(i<2?i:i-2,i>=2,i)&&ring.waitIdle();
+ }
+ if(encoder){ok=encoder->finish()&&ok;encoder->close();encoder.reset();}file.close();
+ ring.drainQueue();graph.shutdown();ring.shutdown();ctx.shutdown();
+ AVFormatContext* format=nullptr;AVCodecContext* decoder=nullptr;AVPacket* packet=av_packet_alloc();AVFrame* frame=av_frame_alloc();
+ unsigned decoded=0;
+ if(ok)ok=avformat_open_input(&format,argv[1],nullptr,nullptr)>=0&&avformat_find_stream_info(format,nullptr)>=0;
+ int video=-1;
+ if(ok){video=av_find_best_stream(format,AVMEDIA_TYPE_VIDEO,-1,-1,nullptr,0);ok=video>=0;}
+ if(ok){auto* parameters=format->streams[video]->codecpar;decoder=avcodec_alloc_context3(avcodec_find_decoder(parameters->codec_id));ok=decoder&&avcodec_parameters_to_context(decoder,parameters)>=0&&avcodec_open2(decoder,decoder->codec,nullptr)>=0;}
+ auto receive=[&]{
+ int result=0;
+ while((result=avcodec_receive_frame(decoder,frame))>=0){
+ const double expected=16+(20+decoded*18)*219.0/255;
+ double sum=0;for(unsigned y=20;y<340;++y)for(unsigned x=20;x<620;++x)sum+=frame->data[0][size_t(y)*frame->linesize[0]+x];
+ const double mean=sum/(320*600);
+ std::cout<<"slot="<<decoded<<" expectedY="<<expected<<" decodedY="<<mean<<'\n';
+ ok=ok&&decoded<pipeline::kOutputPoolSlots&&std::abs(mean-expected)<3;++decoded;av_frame_unref(frame);
+ }
+ if(result!=AVERROR(EAGAIN)&&result!=AVERROR_EOF)ok=false;
+ };
+ while(ok&&av_read_frame(format,packet)>=0){if(packet->stream_index==video){ok=avcodec_send_packet(decoder,packet)>=0;if(ok)receive();}av_packet_unref(packet);}
+ if(ok){ok=avcodec_send_packet(decoder,nullptr)>=0;if(ok)receive();}
+ ok=ok&&decoded==pipeline::kOutputPoolSlots;
+ std::cout<<"EXPORT_POOL decoded="<<decoded<<" passed="<<ok<<'\n';
+ av_frame_free(&frame);av_packet_free(&packet);avcodec_free_context(&decoder);avformat_close_input(&format);CoUninitialize();return ok?0:1;
+}
diff --git a/tests/integration/ExportTimingTests.ps1 b/tests/integration/ExportTimingTests.ps1
new file mode 100644
index 00000000..74a08329
--- /dev/null
+++ b/tests/integration/ExportTimingTests.ps1
@@ -0,0 +1,77 @@
+param(
+ [Parameter(Mandatory=$true)][string]$BuildDirectory,
+ [Parameter(Mandatory=$true)][string]$OutputDirectory
+)
+$ErrorActionPreference='Stop'
+$exe=Join-Path (Resolve-Path $BuildDirectory).Path 'veyra.exe'
+$directory=[IO.Path]::GetFullPath($OutputDirectory)
+New-Item -ItemType Directory -Path $directory -ErrorAction Stop | Out-Null
+$fixture=Join-Path $directory 'irregular.mkv'
+# Change cadence halfway through. The old CFR preflight rejected this file.
+& ffmpeg -hide_banner -loglevel error -f lavfi -i 'testsrc2=size=640x360:rate=30:duration=2' -f lavfi -i 'sine=frequency=880:sample_rate=48000:duration=3' -vf "setpts='if(lt(N,30),N/(30*TB),(1+(N-30)/15)/TB)'" -fps_mode passthrough -c:v libx264 -preset veryfast -bf 0 -c:a ac3 $fixture
+if($LASTEXITCODE){throw 'Fixture generation failed'}
+function Probe([string]$path,[string]$selector,[string]$entries,[string]$show){
+ $json=& ffprobe -v error -select_streams $selector $show -show_entries $entries -of json $path
+ if($LASTEXITCODE){throw "ffprobe failed: $path"}
+ return ($json -join "`n" | ConvertFrom-Json)
+}
+function RunExport([string]$name,[string[]]$flags,[int]$expectedExit=0){
+ $destination=Join-Path $directory "$name.mp4"
+ $arguments=@($fixture,'--no-nr','--no-sr','--no-fg','--export-out',$destination)+$flags
+ $quoted=@($arguments | ForEach-Object {'"'+$_+'"'})
+ $logName=$name.Replace('/','-')
+ $process=Start-Process -FilePath $exe -ArgumentList $quoted -PassThru -WindowStyle Hidden -RedirectStandardOutput "$directory/$logName.stdout.log" -RedirectStandardError "$directory/$logName.stderr.log"
+ $null=$process.Handle
+ if(!$process.WaitForExit(120000)){Stop-Process -Id $process.Id -Force;throw "$name timed out"}
+ $process.Refresh()
+ if($process.ExitCode -ne $expectedExit){throw "$name exit=$($process.ExitCode) expected=$expectedExit"}
+ return $destination
+}
+$source=(Probe $fixture 'v:0' 'frame=best_effort_timestamp_time' '-show_frames').frames
+if($source.Count -ne 60){throw 'Unexpected source frame count'}
+$results=@()
+foreach($case in @(
+ @{name='irregular-h264';multiplier=1;flags=@()},
+ @{name='irregular-hevc-6x';multiplier=6;flags=@('--hevc','--fg-multiplier','6')},
+ @{name='irregular-mf';multiplier=1;flags=@();forceMf=$true},
+ @{name='irregular-nvenc-fallback';multiplier=1;flags=@();failNvenc=$true}
+)){
+ try {
+ if($case.forceMf){$env:VEYRA_TEST_FORCE_MF_ENCODER='1'}
+ if($case.failNvenc){$env:VEYRA_TEST_NVENC_FIRST_OPEN_FAILS='1'}
+ $output=RunExport $case.name $case.flags
+ } finally {
+ Remove-Item Env:VEYRA_TEST_FORCE_MF_ENCODER,Env:VEYRA_TEST_NVENC_FIRST_OPEN_FAILS -ErrorAction SilentlyContinue
+ }
+ $packets=(Probe $output 'v:0' 'packet=pts_time,duration_time' '-show_packets').packets
+ if($packets.Count -ne $source.Count*$case.multiplier){throw "$($case.name): frame count mismatch"}
+ $maxError=0.0
+ for($i=0;$i -lt $source.Count;$i++){
+ $timestampError=[math]::Abs([double]$packets[$i*$case.multiplier].pts_time-([double]$source[$i].best_effort_timestamp_time-[double]$source[0].best_effort_timestamp_time))
+ $maxError=[math]::Max($timestampError,$maxError)
+ if($timestampError -gt 0.000002){throw "$($case.name): source timestamp shifted by $timestampError seconds"}
+ if($i+1 -lt $source.Count){
+ $start=[double]$packets[$i*$case.multiplier].pts_time
+ $end=[double]$packets[($i+1)*$case.multiplier].pts_time
+ for($j=1;$j -lt $case.multiplier;$j++){
+ $expected=$start+($end-$start)*$j/$case.multiplier
+ if([math]::Abs([double]$packets[$i*$case.multiplier+$j].pts_time-$expected) -gt 0.000002){throw 'Generated timestamp misplaced'}
+ }
+ }
+ }
+ for($i=0;$i+1 -lt $packets.Count;$i++){
+ $end=[double]$packets[$i].pts_time+[double]$packets[$i].duration_time
+ if([math]::Abs($end-[double]$packets[$i+1].pts_time) -gt 0.000002){throw 'Noncontiguous sample duration'}
+ }
+ $audio=(Probe $output 'a:0' 'stream=codec_name,duration' '-show_streams').streams
+ if($audio.Count -ne 1 -or $audio[0].codec_name -ne 'ac3' -or [double]$audio[0].duration -lt 2.9){throw 'Audio timeline lost'}
+ # Independent development check only; the product no longer reopens output.
+ & ffmpeg -v error -xerror -i $output -f null -
+ if($LASTEXITCODE){throw 'Output decode failed'}
+ $results+=@{case=$case.name;frames=$packets.Count;maxTimestampErrorSeconds=$maxError;audioSeconds=$audio[0].duration;passed=$true}
+ Write-Output "PASS $($case.name): $($packets.Count) frames, source timestamps and audio preserved"
+}
+$failedOutput=RunExport 'missing-directory/write-error' @() 1
+if(Test-Path -LiteralPath $failedOutput){throw 'Write failure reported success'}
+$results | ConvertTo-Json -Depth 4 | Set-Content "$directory/result.json" -Encoding utf8
+Write-Output 'PASS real output I/O failure remains a failure'
diff --git a/tests/integration/ExportWorkerFailureTests.cpp b/tests/integration/ExportWorkerFailureTests.cpp
new file mode 100644
index 00000000..c2bdb994
--- /dev/null
+++ b/tests/integration/ExportWorkerFailureTests.cpp
@@ -0,0 +1,64 @@
+#include "veyra/engine/ExportJobManager.h"
+#include "veyra/engine/FgCompatibilityProbe.h"
+#include <chrono>
+#include <filesystem>
+#include <iostream>
+#include <thread>
+
+int wmain(int argc,wchar_t** argv){
+ using namespace veyra::engine;
+ wchar_t executable[32768]{};
+ if(!GetModuleFileNameW(nullptr,executable,32768))return 1;
+ setFgCompatibilityProbeExecutable(executable);
+ if(argc==3&&std::wstring_view(argv[1])==L"--export-worker"){
+ const HRESULT com=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ const int result=runExportWorker(reinterpret_cast<HANDLE>(_wcstoui64(argv[2],nullptr,10)));
+ if(SUCCEEDED(com))CoUninitialize();
+ return result;
+ }
+ if(argc==3&&std::wstring_view(argv[1])==L"--fg-compat-probe")
+ return runFgCompatibilityProbe(reinterpret_cast<HANDLE>(_wcstoui64(argv[2],nullptr,10)));
+ if(argc!=4)return 2;
+ const std::wstring mode=argv[1];
+ const bool encoder=mode==L"encoder",cancel=mode==L"cancel";
+ if(encoder)SetEnvironmentVariableW(L"VEYRA_TEST_NVENC_FIRST_OPEN_FAILS",L"1");
+ else{
+ SetEnvironmentVariableW(L"VEYRA_TEST_FORCE_AMPERE_UNLOCK",L"1");
+ SetEnvironmentVariableW(cancel?L"VEYRA_TEST_FG_PROBE_HANG":L"VEYRA_TEST_FG_PROBE_FAIL",L"1");
+ }
+ CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ bool ok=false;
+ {
+ ExportJobManager manager;
+ EnhancementSettings settings;settings.nr=settings.sr=false;settings.multiplier=encoder?1:6;
+ if(!manager.start(argv[2],argv[3],settings,true,12))return 1;
+ const auto start=std::chrono::steady_clock::now();
+ ExportJobSnapshot snapshot;
+ bool requestedCancel=false;
+ while(std::chrono::steady_clock::now()-start<std::chrono::seconds(20)){
+ snapshot=manager.poll();
+ if(!snapshot.active())break;
+ if(cancel&&!requestedCancel&&std::chrono::steady_clock::now()-start>std::chrono::milliseconds(500)){
+ manager.cancel();requestedCancel=true;
+ }
+ std::this_thread::sleep_for(std::chrono::milliseconds(10));
+ }
+ // Poll the process exit as well as its shared terminal state, so the
+ // assertion covers the final error and appended worker log location.
+ while(std::chrono::steady_clock::now()-start<std::chrono::seconds(25)){
+ snapshot=manager.poll();
+ if(snapshot.state==ExportState::Succeeded)break;
+ if(cancel&&snapshot.state==ExportState::Cancelled)break;
+ if(!cancel&&snapshot.message.find(snapshot.workerLog)!=std::wstring::npos)break;
+ std::this_thread::sleep_for(std::chrono::milliseconds(10));
+ }
+ ok=snapshot.workerPid&&std::filesystem::exists(snapshot.workerLog);
+ if(cancel)ok=ok&&requestedCancel&&snapshot.state==ExportState::Cancelled&&!std::filesystem::exists(argv[3]);
+ else if(encoder){
+ ok=ok&&snapshot.state==ExportState::Failed&&snapshot.encoded==0&&snapshot.message.find(snapshot.workerLog)!=std::wstring::npos;
+ ok=ok&&!std::filesystem::exists(argv[3])&&snapshot.message.find(L"OpenD3D12Session")!=std::wstring::npos&&snapshot.message.find(L"15")!=std::wstring::npos&&snapshot.message.find(L"HDR")!=std::wstring::npos;
+ }else ok=ok&&snapshot.state==ExportState::Succeeded&&snapshot.sourceFrames==12&&snapshot.encoded==72&&std::filesystem::exists(argv[3]); // Probe refusal must not block actual FG initialization.
+ std::wcout<<L"WORKER mode="<<mode<<L" state="<<int(snapshot.state)<<L" encoded="<<snapshot.encoded<<L" passed="<<ok<<L" message="<<snapshot.message<<L'\n';
+ }
+ CoUninitialize();return ok?0:1;
+}
diff --git a/tests/integration/FgLifecycleTests.cpp b/tests/integration/FgLifecycleTests.cpp
new file mode 100644
index 00000000..aa2159b2
--- /dev/null
+++ b/tests/integration/FgLifecycleTests.cpp
@@ -0,0 +1,69 @@
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/ngx/FgCompatibilitySession.h"
+#include <filesystem>
+#include <iostream>
+#include <string_view>
+extern "C" {
+#include <libavutil/frame.h>
+#include <libavutil/pixfmt.h>
+}
+
+int main(int argc,char** argv) {
+ using namespace veyra;
+ CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;pipeline::EnhanceGraph graph(ctx,ring);
+ Status status=Status::Ok;gfx::DeviceContextDesc device;
+ bool ok=ctx.initialize(device,status)&&ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,status);
+ pipeline::EnhanceGraphDesc desc;desc.sourceWidth=desc.workWidth=640;
+ desc.enableNr=desc.enableSr=false;desc.enableFg=true;desc.rgbInput=true;
+ desc.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();
+ const bool initFailure=argc>1&&std::string_view(argv[1])=="init-failure";
+ if(ok&&initFailure){
+ desc.sourceHeight=desc.workHeight=360;
+ SetEnvironmentVariableW(L"VEYRA_TEST_NGX_INIT_FAILURE",L"1");
+ const bool rejected=!graph.initialize(desc);
+ SetEnvironmentVariableW(L"VEYRA_TEST_NGX_INIT_FAILURE",nullptr);
+ graph.shutdown();
+ ok=rejected&&ngx::FgCompatibilitySession::processHealthy();
+ std::cout<<"INIT failure-restores-session="<<ok<<'\n';
+ }
+ unsigned iteration=0;
+ for(unsigned multiplier:{6u,2u,5u,3u,4u,6u}) {
+ if(!ok)break;
+ desc.fgMultiplier=multiplier;desc.sourceHeight=desc.workHeight=360+8*(iteration++%2);
+ ok=graph.initialize(desc)&&graph.createViews();
+ AVFrame* frame=av_frame_alloc();if(!frame){ok=false;break;}
+ frame->format=AV_PIX_FMT_RGBA;frame->width=int(desc.workWidth);frame->height=int(desc.workHeight);frame->color_range=AVCOL_RANGE_JPEG;
+ ok=ok&&av_frame_get_buffer(frame,32)>=0;
+ unsigned generated=0;
+ for(unsigned i=0;ok&&i<4;++i){
+ for(unsigned y=0;y<desc.workHeight;++y)for(unsigned x=0;x<desc.workWidth;++x){
+ auto* p=frame->data[0]+size_t(y)*frame->linesize[0]+x*4;
+ p[0]=p[1]=p[2]=uint8_t(24+(((x+i*8)/32+y/32)%2)*180);p[3]=255;
+ }
+ pipeline::EnhanceGraph::FrameOutputs output;
+ const bool reset=i==0||i==2;
+ ok=graph.process(frame,i*20.0,reset,output)&&ring.waitIdle()&&graph.resolveGeneration(output);
+ unsigned count=0;
+ for(unsigned j=0;ok&&j<output.batch.count;++j){
+ const auto& f=output.batch.frames[j];
+ if(f.kind==pipeline::FrameKind::Generated){++count;ok=f.validity==pipeline::GenerationValidity::Valid&&f.lease&&f.lease->slot<pipeline::kGeneratedPoolSlots;}
+ }
+ ok=ok&&count==(reset?0:multiplier-1);generated+=count;
+ }
+ av_frame_free(&frame);ok=ring.drainQueue()&&ok;
+ if(argc>1&&!initFailure)SetEnvironmentVariableW(L"VEYRA_TEST_PATCH_RESTORE_FAIL",L"1");
+ graph.shutdown();
+ if(argc>1&&!initFailure){
+ SetEnvironmentVariableW(L"VEYRA_TEST_PATCH_RESTORE_FAIL",nullptr);
+ const bool rejected=!ngx::FgCompatibilitySession::processHealthy()&&!graph.initialize(desc);
+ std::cout<<"ROLLBACK failure-retains-storage-and-rejects-reinit="<<rejected<<'\n';
+ ok=ok&&rejected;break;
+ }
+ ok=ok&&ngx::FgCompatibilitySession::processHealthy();
+ std::cout<<"LIFECYCLE multiplier="<<multiplier<<" generated="<<generated<<" reset-and-shutdown="<<ok<<'\n';
+ }
+ graph.shutdown();ring.shutdown();ctx.shutdown();CoUninitialize();return ok?0:1;
+}
diff --git a/tests/integration/FgPresentationTests.cpp b/tests/integration/FgPresentationTests.cpp
new file mode 100644
index 00000000..c6e1c169
--- /dev/null
+++ b/tests/integration/FgPresentationTests.cpp
@@ -0,0 +1,111 @@
+#include "veyra/engine/VideoPresenter.h"
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/sink/ImageExportSink.h"
+#include <d3d12sdklayers.h>
+#include <filesystem>
+#include <iostream>
+#include <thread>
+extern "C" {
+#include <libavutil/frame.h>
+#include <libavutil/pixfmt.h>
+}
+
+int wmain(int argc,wchar_t** argv){
+ using namespace veyra;
+ if(argc!=2||FAILED(CoInitializeEx(nullptr,COINIT_MULTITHREADED)))return 2;
+ std::filesystem::create_directories(argv[1]);
+ HWND window=CreateWindowExW(0,L"STATIC",L"FG presentation regression",WS_POPUP,0,0,640,360,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status=Status::Ok;
+ gfx::DeviceContextDesc device;device.enableDebugLayer=true;
+ bool ok=window&&ctx.initialize(device,status)&&ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,status);
+ Microsoft::WRL::ComPtr<ID3D12InfoQueue> info;
+ if(ok)ok=SUCCEEDED(ctx.device()->QueryInterface(IID_PPV_ARGS(&info)));
+ pipeline::EnhanceGraph graph(ctx,ring);engine::VideoPresenter presenter;
+ AVFrame* frame=av_frame_alloc();
+ if(frame){frame->format=AV_PIX_FMT_RGBA;frame->width=640;frame->height=360;frame->color_range=AVCOL_RANGE_JPEG;frame->color_trc=AVCOL_TRC_IEC61966_2_1;}
+ ok=ok&&frame&&av_frame_get_buffer(frame,32)>=0;
+ unsigned cycle=0;
+ for(unsigned multiplier:{4u,6u,4u}){
+ if(!ok)break;
+ ++cycle;
+ pipeline::EnhanceGraphDesc desc;desc.sourceWidth=desc.workWidth=640;desc.sourceHeight=desc.workHeight=360;
+ desc.enableNr=desc.enableSr=false;desc.enableFg=desc.rgbInput=true;desc.fgMultiplier=multiplier;
+ desc.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();
+ ok=graph.initialize(desc)&&presenter.open(ctx,window,graph)&&graph.createViews();
+ if(ok&&cycle==1){
+ // A producer allocator stall must not be reported as private
+ // presentation-ring service. Release the GPU wait from the CPU.
+ Microsoft::WRL::ComPtr<ID3D12Fence> blocker;
+ ok=SUCCEEDED(ctx.device()->CreateFence(0,D3D12_FENCE_FLAG_NONE,IID_PPV_ARGS(&blocker)));
+ unsigned slot=0;
+ if(ok)ok=ring.acquireNext(slot,status)!=nullptr;
+ if(ok)ok=SUCCEEDED(ctx.directQueue()->Wait(blocker.Get(),1));
+ if(ok){
+ const auto sharedBefore=ring.cpuWaitMilliseconds(),presentBefore=presenter.cpuWaitMilliseconds(ring);
+ HRESULT released=E_FAIL;
+ std::jthread release([&]{Sleep(40);released=blocker->Signal(1);});
+ ok=ring.submitAndSignal(slot)&&ring.acquire(slot,status)!=nullptr;
+ release.join();ok=SUCCEEDED(released)&&ring.discardRecording()&&ok;
+ const auto sharedWait=ring.cpuWaitMilliseconds()-sharedBefore;
+ const auto presentWait=presenter.cpuWaitMilliseconds(ring)-presentBefore;
+ ok=ok&&sharedWait>=20&&presentWait==0;
+ std::cout<<"WAIT_ACCOUNTING sharedMs="<<sharedWait<<" privateMs="<<presentWait<<" pass="<<ok<<std::endl;
+ }
+ }
+ Microsoft::WRL::ComPtr<ID3D12Fence> consumer;
+ if(ok)ok=SUCCEEDED(ctx.device()->CreateFence(0,D3D12_FENCE_FLAG_NONE,IID_PPV_ARGS(&consumer)));
+ if(ok){
+ graph.presentationSubmitted(0,consumer.Get(),1);
+ ok=!graph.nextFrameSlotAvailable();
+ ok=SUCCEEDED(consumer->Signal(1))&&ok&&graph.nextFrameSlotAvailable();
+ }
+ unsigned generated=0;int maxError=0;
+ for(unsigned i=0;ok&&i<40;++i){
+ if(i==8||i==24){
+ SetWindowPos(window,nullptr,0,0,i==8?320:640,i==8?180:360,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
+ Sleep(110);
+ }
+ for(unsigned y=0;y<360;++y)for(unsigned x=0;x<640;++x){
+ auto* p=frame->data[0]+size_t(y)*frame->linesize[0]+x*4;
+ p[0]=p[1]=p[2]=uint8_t(24+(((x+i*8)/32+y/32)%2)*180);p[3]=255;
+ }
+ pipeline::EnhanceGraph::FrameOutputs out;
+ ok=graph.process(frame,i*20.0,i==0||i==4,out,i+1)&&ring.waitIdle()&&graph.resolveGeneration(out);
+ for(unsigned j=0;ok&&j<out.batch.count;++j){
+ const auto& item=out.batch.frames[j];const bool interpolated=item.kind==pipeline::FrameKind::Generated;
+ if(interpolated&&item.validity!=pipeline::GenerationValidity::Valid){ok=false;break;}
+ ok=presenter.present(ctx,ring,graph,item.lease->slot,interpolated,false,0,false,.5f,item.identity);
+ sink::RgbaImage shown;
+ // First verify exact pixels; then exercise queued GPU reads,
+ // resize and parity reuse without a readback draining each blit.
+ if(i<8){
+ sink::RgbaImage expected;
+ ok=ok&&presenter.readPresentedFrameForTest(ctx,ring,shown)&&sink::readRgba8(ctx,ring,item.lease->texture.Get(),expected);
+ ok=ok&&shown.width==expected.width&&shown.height==expected.height&&shown.pixels.size()==expected.pixels.size();
+ if(ok){
+ for(size_t p=0;p<shown.pixels.size();++p)if(p%4!=3)maxError=std::max(maxError,std::abs(int(shown.pixels[p])-int(expected.pixels[p])));
+ ok=maxError<=2;
+ }
+ }
+ if(interpolated){
+ ++generated;
+ if(generated==1&&ok)ok=sink::saveImage((std::filesystem::path(argv[1])/(std::to_wstring(cycle)+L"-"+std::to_wstring(multiplier)+L"x-generated.png")).wstring(),shown);
+ }
+ }
+ }
+ ok=ok&&generated==38*(multiplier-1);
+ // Also exercise producer teardown first: it must cover consumer GPU reads.
+ graph.shutdown();presenter.close();
+ std::cout<<"PRESENTATION multiplier="<<multiplier<<" generated="<<generated<<" maxPixelError="<<maxError<<" pass="<<ok<<std::endl;
+ }
+ graph.shutdown();presenter.close();ring.drainQueue();
+ unsigned errors=0;
+ if(info)for(UINT64 i=0;i<info->GetNumStoredMessagesAllowedByRetrievalFilter();++i){
+ SIZE_T bytes=0;info->GetMessage(i,nullptr,&bytes);std::vector<uint8_t> data(bytes);
+ auto* message=reinterpret_cast<D3D12_MESSAGE*>(data.data());
+ if(SUCCEEDED(info->GetMessage(i,message,&bytes))&&message->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;std::cerr<<message->pDescription<<'\n';}
+ }
+ std::cout<<"D3D12 errors="<<errors<<std::endl;
+ av_frame_free(&frame);ring.shutdown();ctx.shutdown();DestroyWindow(window);CoUninitialize();return ok&&!errors?0:1;
+}
diff --git a/tests/integration/FgSettingsTests.cpp b/tests/integration/FgSettingsTests.cpp
new file mode 100644
index 00000000..6cac402e
--- /dev/null
+++ b/tests/integration/FgSettingsTests.cpp
@@ -0,0 +1,98 @@
+#include "veyra/engine/EngineController.h"
+#include "veyra/engine/FgCompatibilityProbe.h"
+#include "veyra/Log.h"
+#include <chrono>
+#include <filesystem>
+#include <iostream>
+#include <thread>
+
+int wmain(int argc,wchar_t** argv) {
+ using namespace veyra::engine;
+ using namespace std::chrono_literals;
+ wchar_t executable[32768]{};
+ if(!GetModuleFileNameW(nullptr,executable,32768))return 2;
+ setFgCompatibilityProbeExecutable(executable);
+ if(argc==3&&std::wstring_view(argv[1])==L"--fg-compat-probe")
+ return runFgCompatibilityProbe(reinterpret_cast<HANDLE>(_wcstoui64(argv[2],nullptr,10)));
+ if(argc!=3&&argc!=4)return 2;
+ const bool probeFailure=argc==4&&std::wstring_view(argv[3])==L"probe-failure";
+ if(argc==4&&!probeFailure)return 2;
+ const HRESULT com=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ if(FAILED(com))return 2;
+ std::filesystem::create_directories(argv[2]);
+ veyra::Logger::instance().openFile((std::filesystem::path(argv[2])/L"engine.log").wstring());
+ veyra::Logger::instance().setConsoleEnabled(false);
+ HWND window=CreateWindowExW(0,L"STATIC",L"FG settings test",WS_POPUP,0,0,960,540,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
+ if(!window){CoUninitialize();return 2;}
+ int failures=0;
+ {
+ EngineController engine;
+ engine.setVolume(0,true);
+ auto wait=[&](auto predicate,int seconds=30,bool allowFailed=false){
+ const auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(seconds);
+ while(std::chrono::steady_clock::now()<deadline){
+ MSG msg;while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}
+ const auto s=engine.snapshot();
+ if(s.failed&&!allowFailed)return false;
+ if(predicate(s))return true;
+ std::this_thread::sleep_for(10ms);
+ }
+ return false;
+ };
+ auto check=[&](bool ok,const char* label){
+ const auto s=engine.snapshot();
+ std::cout<<(ok?"PASS ":"FAIL ")<<label<<" desired="<<s.desired.multiplier
+ <<" applied="<<s.applied.multiplier<<" frames="<<s.frames<<" generated="<<s.generated
+ <<" cap="<<s.fgMultiFrameMax<<" failed="<<s.failed<<std::endl;
+ if(!ok)std::wcerr<<s.status<<L" / "<<s.backendWarning<<std::endl;
+ failures+=!ok;return ok;
+ };
+ engine.open(window,argv[1],{});
+ check(wait([](const auto& s){return s.frames>=12&&!s.fgActive&&s.generated==0;}),"plain playback");
+ if(probeFailure&&!failures){
+ const auto before=engine.snapshot();
+ auto settings=before.desired;
+ settings.nr=settings.sr=false;
+ settings.frameGenerationBackend=FrameGenerationBackend::Dlss;
+ settings.multiplier=6;
+ const auto started=std::chrono::steady_clock::now();
+ check(engine.requestSettings(settings),"request failing provider");
+ check(wait([&](const auto& s){return !s.applying&&!s.fgActive&&!s.backendWarning.empty()&&
+ s.applied.multiplier==1&&s.frames>=before.frames+12&&s.generated==before.generated;},15),
+ "failed probe restores advancing playback within 15 seconds");
+ std::cout<<"Probe recovery elapsedMs="<<std::chrono::duration_cast<std::chrono::milliseconds>(
+ std::chrono::steady_clock::now()-started).count()<<std::endl;
+ }
+ for(const unsigned multiplier:{2u,6u,1u,6u}){
+ if(probeFailure)break;
+ if(failures)break;
+ const auto beforeSwitch=engine.snapshot();
+ auto settings=beforeSwitch.desired;
+ settings.nr=settings.sr=false;
+ settings.frameGenerationBackend=FrameGenerationBackend::Dlss;
+ settings.multiplier=multiplier;
+ if(!check(engine.requestSettings(settings),"request multiplier"))break;
+ const auto revision=engine.snapshot().desired.revision;
+ if(!check(wait([&](const auto& s){return !s.applying&&s.applied.revision==revision&&
+ s.applied.multiplier==multiplier&&s.fgActive==(multiplier>1)&&s.frames>=beforeSwitch.frames+12&&
+ (multiplier==1||(s.generated>=beforeSwitch.generated+10&&s.fgMultiFrameMax>=int(multiplier)-1));},70),"requested multiplier produces new output"))break;
+ if(multiplier!=6)continue;
+ engine.pause(true);
+ check(wait([](const auto& s){return s.transport==TransportState::Paused;}),"pause");
+ const auto before=engine.snapshot();
+ engine.seek(before.position+2.0);
+ const auto request=engine.snapshot().seekRequested;
+ if(!check(wait([&](const auto& s){return s.seekPresented>=request;}),"paused seek presents requested frame"))break;
+ engine.pause(false);
+ const auto generated=engine.snapshot().generated;
+ check(wait([&](const auto& s){return s.transport==TransportState::Playing&&s.fgActive&&
+ s.applied.multiplier==6&&s.generated>generated+10;}),"6X resumes after history reset");
+ }
+ engine.stop();
+ check(wait([&](const auto&){return engine.idle();},20,true),"engine drains and stops");
+ }
+ DestroyWindow(window);
+ CoUninitialize();
+ std::cout<<"This test checks settings, output counts and lifecycle; not target-card support or interpolation quality.\n";
+ return failures?1:0;
+}
diff --git a/tests/integration/FgSustainedTests.cpp b/tests/integration/FgSustainedTests.cpp
new file mode 100644
index 00000000..d57f267d
--- /dev/null
+++ b/tests/integration/FgSustainedTests.cpp
@@ -0,0 +1,87 @@
+#include "veyra/engine/EngineController.h"
+#include "veyra/engine/FgCompatibilityProbe.h"
+#include "veyra/Log.h"
+#include <chrono>
+#include <filesystem>
+#include <iostream>
+#include <thread>
+
+int wmain(int argc,wchar_t** argv){
+ using namespace veyra::engine;
+ using Clock=std::chrono::steady_clock;
+ wchar_t executable[32768]{};
+ GetModuleFileNameW(nullptr,executable,32768);
+ setFgCompatibilityProbeExecutable(executable);
+ if(argc==3&&std::wstring_view(argv[1])==L"--fg-compat-probe")
+ return runFgCompatibilityProbe(reinterpret_cast<HANDLE>(_wcstoui64(argv[2],nullptr,10)));
+ if(argc!=7&&argc!=8)return 2; // source, log directory, multiplier, admission, seconds, effects, optional minimum target ratio
+ const unsigned multiplier=_wtoi(argv[3]);
+ const int seconds=_wtoi(argv[5]);
+ const double minimumRatio=argc==8?_wtof(argv[7]):0;
+ if((multiplier!=4&&multiplier!=6)||seconds<30||seconds>240)return 2;
+ if(FAILED(CoInitializeEx(nullptr,COINIT_MULTITHREADED)))return 2;
+ std::filesystem::create_directories(argv[2]);
+ veyra::Logger::instance().openFile((std::filesystem::path(argv[2])/L"engine.log").wstring());
+ veyra::Logger::instance().setConsoleEnabled(false);
+ RECT rect{0,0,2191,1187};AdjustWindowRect(&rect,WS_OVERLAPPEDWINDOW,FALSE);
+ HWND window=CreateWindowExW(0,L"STATIC",L"DLSS sustained regression",WS_OVERLAPPEDWINDOW,
+ 0,0,rect.right-rect.left,rect.bottom-rect.top,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
+ if(!window){CoUninitialize();return 2;}
+ ShowWindow(window,SW_SHOWNOACTIVATE);
+ bool ok=true;
+ {
+ EngineController engine;engine.setVolume(0,true);
+ EnhancementSettings settings;settings.multiplier=multiplier;
+ const std::wstring_view effects=argv[6];
+ settings.nr=effects==L"on"||effects==L"nr";
+ settings.sr=effects==L"on"||effects==L"sr";
+ auto options=PlayerOptions::from(settings);
+ const std::wstring source=argv[1];
+ options.captureReplayForTest=!source.starts_with(L"capture:")&&!source.starts_with(L"capture2:");
+ options.captureReplayDisableFgAdmissionForTest=std::wstring_view(argv[4])==L"off";
+ engine.open(window,source,options);
+ const auto opened=Clock::now();auto started=Clock::time_point{};
+ int reported=-1;bool stalled=false,cleared=false;
+ uint64_t beforeRecovery=0;double recoveredRate=0;unsigned recoveredSamples=0;
+ while(Clock::now()-opened<std::chrono::seconds(seconds+35)){
+ MSG msg;while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}
+ const auto s=engine.snapshot();
+ if(s.failed){std::wcerr<<s.status<<L" / "<<s.backendWarning<<std::endl;ok=false;break;}
+ if(started==Clock::time_point{}&&s.frames>=10)started=Clock::now();
+ if(started!=Clock::time_point{}){
+ const auto elapsed=int(std::chrono::duration_cast<std::chrono::seconds>(Clock::now()-started).count());
+ if(elapsed>=seconds)break;
+ if(elapsed>=15&&!stalled){SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",L"55");stalled=true;}
+ if(elapsed>=17&&!cleared){SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",nullptr);cleared=true;beforeRecovery=s.generated;}
+ if(elapsed!=reported){
+ reported=elapsed;const auto& f=s.metrics.flow;const auto& c=f.counters;
+ std::cout<<"t="<<elapsed<<" multiplier="<<s.applied.multiplier<<" frames="<<s.frames<<" generated="<<s.generated
+ <<" sourceFps="<<f.sourceCompletedFps<<" submitFps="<<f.presentSubmitFps<<" validFps="<<f.validGeneratedFps
+ <<" limited="<<s.fgBudgetLimited<<" skipped="<<c.fgSkippedBeforeEval<<" expired="<<c.generatedExpiredAfterEval
+ <<" presentMs="<<s.presentCpuP95Ms<<" slotMs="<<f.slotWaitPerFrameMs.value_or(-1);
+ for(const auto stage:{veyra::diagnostics::GpuStage::Nr,veyra::diagnostics::GpuStage::Sr,veyra::diagnostics::GpuStage::Flow,veyra::diagnostics::GpuStage::FgBatch})
+ std::cout<<" gpu"<<int(stage)<<"="<<f.gpuTiming[size_t(stage)].p95.value_or(-1);
+ std::cout<<std::endl;
+ if(elapsed>=22){recoveredRate+=f.presentSubmitFps;++recoveredSamples;}
+ }
+ }
+ std::this_thread::sleep_for(std::chrono::milliseconds(5));
+ }
+ SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",nullptr);
+ const auto s=engine.snapshot();
+ ok=ok&&cleared&&s.fgActive&&s.applied.multiplier==multiplier&&s.generated>beforeRecovery+100;
+ const double mean=recoveredSamples?recoveredRate/recoveredSamples:0;
+ const bool throughput=minimumRatio<=0||(recoveredSamples&&mean>=s.nominalSourceFps*multiplier*minimumRatio);
+ std::cout<<"SUSTAINED lifecycle="<<ok<<" recoveredMeanSubmitFps="<<mean
+ <<" minimumTargetRatio="<<minimumRatio<<" throughput="<<throughput
+ <<" nominalTarget="<<s.nominalSourceFps*multiplier<<" frames="<<s.frames<<" generated="<<s.generated<<std::endl;
+ ok=ok&&throughput;
+ engine.stop();
+ const auto stopping=Clock::now();
+ while(!engine.idle()&&Clock::now()-stopping<std::chrono::seconds(15))std::this_thread::sleep_for(std::chrono::milliseconds(10));
+ ok=ok&&engine.idle();
+ }
+ DestroyWindow(window);CoUninitialize();
+ std::cout<<"Submission rates are not scanout rates. Lifecycle recovery does not assert target throughput or image quality.\n";
+ return ok?0:1;
+}
diff --git a/tests/integration/PlayerShellTests.ps1 b/tests/integration/PlayerShellTests.ps1
new file mode 100644
index 00000000..aba49636
--- /dev/null
+++ b/tests/integration/PlayerShellTests.ps1
@@ -0,0 +1,117 @@
+param(
+ [Parameter(Mandatory=$true)][string]$BuildDirectory,
+ [Parameter(Mandatory=$true)][string]$Media,
+ [string]$Root=(Get-Location).Path
+)
+$ErrorActionPreference='Stop'
+$Root=(Resolve-Path -LiteralPath $Root).Path
+$BuildDirectory=(Resolve-Path -LiteralPath $BuildDirectory).Path
+$Media=(Resolve-Path -LiteralPath $Media).Path
+$sandbox=Join-Path $Root ('out/tests/player-shell-'+[guid]::NewGuid().ToString('N'))
+New-Item -ItemType Directory -Path "$sandbox/runtime_local","$sandbox/logs" | Out-Null
+Copy-Item -LiteralPath "$BuildDirectory/veyra.exe" -Destination $sandbox
+Get-ChildItem -LiteralPath $BuildDirectory -Filter '*.dll' | Copy-Item -Destination $sandbox
+foreach($component in 'nvidia','intel','amd'){
+ New-Item -ItemType Junction -Path "$sandbox/runtime_local/$component" -Target "$Root/runtime_local/$component" | Out-Null
+}
+New-Item -ItemType Junction -Path "$sandbox/shaders" -Target "$BuildDirectory/shaders" | Out-Null
+Add-Type -TypeDefinition @'
+using System;
+using System.Text;
+using System.Runtime.InteropServices;
+public static class ShellTestNative {
+ public delegate bool EnumProc(IntPtr window,IntPtr context);
+ [DllImport("user32.dll")] public static extern bool EnumWindows(EnumProc callback,IntPtr context);
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window,out uint process);
+ [DllImport("user32.dll",CharSet=CharSet.Unicode)] public static extern int GetClassName(IntPtr window,StringBuilder name,int size);
+ [DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window,int id);
+ [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr window,int command);
+ [DllImport("user32.dll")] public static extern IntPtr SendMessageW(IntPtr window,uint message,IntPtr wp,IntPtr lp);
+ [DllImport("user32.dll")] public static extern bool PostMessageW(IntPtr window,uint message,IntPtr wp,IntPtr lp);
+ public static IntPtr Find(uint process,string cls){
+ IntPtr result=IntPtr.Zero;
+ EnumWindows((window,context)=>{uint p;GetWindowThreadProcessId(window,out p);var name=new StringBuilder(256);GetClassName(window,name,256);if(p==process&&name.ToString()==cls){result=window;return false;}return true;},IntPtr.Zero);
+ return result;
+ }
+}
+'@
+function Wait-Condition([scriptblock]$Condition,[string]$Label){
+ $deadline=[DateTime]::UtcNow.AddSeconds(25)
+ do{if(& $Condition){return};Start-Sleep -Milliseconds 25}while([DateTime]::UtcNow -lt $deadline)
+ throw "Timeout: $Label"
+}
+function Post($Window,$Message,$Wparam,$Lparam=0){[void][ShellTestNative]::PostMessageW($Window,$Message,[intptr]$Wparam,[intptr]$Lparam)}
+function Send($Window,$Message,$Wparam=0,$Lparam=0){[ShellTestNative]::SendMessageW($Window,$Message,[intptr]$Wparam,[intptr]$Lparam).ToInt64()}
+$script:app=$null
+$oldLog=$env:VEYRA_LOG_FILE
+function Start-Player([string]$Arguments,[string]$Label){
+ $script:log=Join-Path $sandbox "logs/$Label.log"
+ $env:VEYRA_LOG_FILE=$script:log
+ if($Arguments){$script:app=Start-Process -FilePath "$sandbox/veyra.exe" -ArgumentList $Arguments -WindowStyle Hidden -PassThru}
+ else{$script:app=Start-Process -FilePath "$sandbox/veyra.exe" -WindowStyle Hidden -PassThru}
+ Wait-Condition { [ShellTestNative]::Find($script:app.Id,'VeyraApp') -ne [intptr]::Zero } 'main window'
+ $script:window=[ShellTestNative]::Find($script:app.Id,'VeyraApp')
+ # The popup contract requires a visible anchor; show only this test window.
+ [void][ShellTestNative]::ShowWindow($script:window,5)
+}
+function Close-Player {
+ Post $script:window 0x10 0
+ if(!$script:app.WaitForExit(25000)){throw 'Normal close timed out'}
+ if($script:app.ExitCode -ne 0){throw "Player exit $($script:app.ExitCode)"}
+ $script:app=$null
+}
+function Log-Matches([string]$Pattern){(Test-Path -LiteralPath $script:log) -and (Select-String -LiteralPath $script:log -Pattern $Pattern -Quiet)}
+function Select-Popup([int]$Row,[int]$Count=0){
+ Wait-Condition { [ShellTestNative]::Find($script:app.Id,'VeyraGlassSelector') -ne [intptr]::Zero } 'selector'
+ $popup=[ShellTestNative]::Find($script:app.Id,'VeyraGlassSelector')
+ $list=[ShellTestNative]::GetDlgItem($popup,1)
+ if($Count -and (Send $list 0x18B) -ne $Count){throw "Wrong popup count, expected $Count"}
+ [void](Send $list 0x186 $Row)
+ Post $list 0x100 13
+ Wait-Condition { [ShellTestNative]::Find($script:app.Id,'VeyraGlassSelector') -ne $popup } 'selector accepted'
+}
+try{
+ Start-Player '--nr-community' 'preferences-first'
+ [void](Send $window 0x802C 200 1)
+ [void](Send $window 0x802C 201 1)
+ [void](Send $window 0x111 224)
+ Close-Player
+ $preset=Get-Content -LiteralPath "$sandbox/runtime_local/last-applied.v1" -Raw
+ if($preset -notmatch '"Last applied" 1 1 1 '){throw 'NR/SR preferences missing'}
+ Start-Player '' 'preferences-restart'
+ if((Send ([ShellTestNative]::GetDlgItem($window,105)) 0xF0) -ne 1){throw 'NR not restored'}
+ if((Send ([ShellTestNative]::GetDlgItem($window,106)) 0xF0) -ne 1){throw 'SR not restored'}
+ Close-Player
+ if((Get-Content -LiteralPath "$sandbox/runtime_local/last-applied.v1" -Raw) -ne $preset){throw 'Restart changed saved settings'}
+ Start-Player '' 'preferences-bypass'
+ [void](Send $window 0x111 221)
+ Close-Player
+ if((Get-Content -LiteralPath "$sandbox/runtime_local/last-applied.v1" -Raw) -ne $preset){throw 'Master bypass erased configured effects'}
+ if((Get-Content -LiteralPath "$sandbox/runtime_local/ui-preferences.v1" -Raw).Trim() -notmatch ' 0$'){throw 'Master bypass not saved'}
+ Write-Output 'PASS normal GUI close/restart preserves NR, SR, runtime choice and bypass draft'
+ Start-Player ('"'+$Media+'"') 'playback'
+ Wait-Condition {Log-Matches 'playback display/system request acquired'} 'playing power guard'
+ [void](Send $window 0x111 120)
+ [void](Send $window 0x112 0xF140)
+ [void](Send $window 0x111 102)
+ Wait-Condition {Log-Matches 'playback display/system request released'} 'pause power release'
+ [void](Send $window 0x111 102)
+ Wait-Condition {((Select-String -LiteralPath $log -Pattern 'playback display/system request acquired').Count -ge 2)} 'resume power guard'
+ [void](Send $window 0x111 120)
+ Wait-Condition {Log-Matches 'single-pass complete tracks=32'} 'subtitle scan'
+ Post $window 0x111 225 ([ShellTestNative]::GetDlgItem($window,225))
+ Select-Popup 1
+ Select-Popup 32 33
+ Wait-Condition {Log-Matches 'selected secondary=false track=31 stream=49 enabled=true'} 'last subtitle selected'
+ Post $window 0x111 225 ([ShellTestNative]::GetDlgItem($window,225))
+ Select-Popup 0
+ Select-Popup 0 17
+ Wait-Condition {Log-Matches 'audio-track.*requested=1 selected=1 changed=true'} 'first audio selected'
+ Close-Player
+ if((Select-String -LiteralPath $log -Pattern 'playback display/system request released').Count -lt 2){throw 'Close did not release power guard'}
+ Write-Output 'PASS normal GUI 32nd subtitle and audio selection, fullscreen, pause/resume/close power lifecycle'
+ Write-Output "Evidence: $sandbox"
+}finally{
+ $env:VEYRA_LOG_FILE=$oldLog
+ if($script:app -and !$script:app.HasExited){Post $script:window 0x10 0;[void]$script:app.WaitForExit(25000)}
+}
diff --git a/tests/integration/PlayerTracksTests.cpp b/tests/integration/PlayerTracksTests.cpp
new file mode 100644
index 00000000..18d35891
--- /dev/null
+++ b/tests/integration/PlayerTracksTests.cpp
@@ -0,0 +1,72 @@
+#include "veyra/engine/EngineController.h"
+#include "veyra/Log.h"
+#include <chrono>
+#include <filesystem>
+#include <iostream>
+#include <thread>
+
+int wmain(int argc,wchar_t** argv){
+ using namespace veyra::engine;
+ using Clock=std::chrono::steady_clock;
+ if(argc<3)return 2;
+ CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ std::filesystem::create_directories(argv[2]);
+ veyra::Logger::instance().openFile((std::filesystem::path(argv[2])/L"engine.log").wstring());
+ veyra::Logger::instance().setConsoleEnabled(false);
+ RECT windowRect{0,0,1155,741};AdjustWindowRect(&windowRect,WS_OVERLAPPEDWINDOW,FALSE);
+ HWND window=CreateWindowExW(0,L"STATIC",L"Player track regression",WS_OVERLAPPEDWINDOW,0,0,windowRect.right-windowRect.left,windowRect.bottom-windowRect.top,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
+ ShowWindow(window,SW_SHOWNOACTIVATE);
+ int failures=0;
+ {
+ EngineController engine;engine.setVolume(0,true);
+ auto wait=[&](auto predicate,int seconds=25){
+ const auto deadline=Clock::now()+std::chrono::seconds(seconds);
+ while(Clock::now()<deadline){
+ MSG msg;while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}
+ const auto state=engine.snapshot();if(state.failed)return false;if(predicate(state))return true;
+ std::this_thread::sleep_for(std::chrono::milliseconds(5));
+ }return false;
+ };
+ auto check=[&](bool ok,const char* label){const auto s=engine.snapshot();std::cout<<(ok?"PASS ":"FAIL ")<<label<<" frames="<<s.frames<<" generated="<<s.generated<<" position="<<s.position<<" audio="<<s.selectedAudioTrack<<std::endl;if(!ok)std::wcerr<<s.status<<L" / "<<s.backendWarning<<std::endl;failures+=!ok;return ok;};
+ const bool liveAmd=argc>3&&std::wstring_view(argv[3])==L"xess-live-amd";
+ PlayerOptions options;options.captureReplayForTest=liveAmd;
+ if(liveAmd)options.settings.opticalFlowBackend=OpticalFlowBackend::AmdFidelityFx;
+ const auto opened=Clock::now();engine.open(window,argv[1],options);
+ check(wait([](const auto& s){return s.frames>0;}),"first frame");
+ std::cout<<"openMs="<<std::chrono::duration<double,std::milli>(Clock::now()-opened).count()<<std::endl;
+ if(argc>3&&(std::wstring_view(argv[3])==L"xess"||liveAmd)){
+ for(const bool nrFirst:{true,false,true,false}){
+ if(failures)break;
+ auto change=[&](bool nr,bool xess){auto s=engine.snapshot();auto settings=s.desired;settings.nr=nr;settings.multiplier=xess?2:1;settings.frameGenerationBackend=FrameGenerationBackend::XeSS;
+ engine.requestSettings(settings);const auto revision=engine.snapshot().desired.revision;
+ return check(wait([&](const auto& v){return !v.applying&&v.applied.revision==revision&&v.nrActive==nr&&v.applied.multiplier==settings.multiplier&&v.frames>=s.frames+30&&(!xess||v.generated>=s.generated+10);},40),nr?(xess?"NR+XeSS output":"NR output"):(xess?"XeSS output":"plain output"));};
+ if(!change(false,false)||!change(nrFirst,!nrFirst)||!change(true,true)||!change(false,false))break;
+ }
+ }else{
+ check(wait([](const auto& s){return !s.audioTracks.empty();}),"enumerate audio tracks");
+ const auto initial=engine.snapshot();
+ check(!engine.selectAudioTrack(initial.sessionId+1,initial.selectedAudioTrack),"reject stale session");
+ check(!engine.selectAudioTrack(initial.sessionId,99999),"reject invalid stream");
+ for(const bool paused:{false,true}){
+ engine.pause(paused);
+ for(const auto& track:initial.audioTracks){
+ if(failures)break;
+ const auto before=engine.snapshot();
+ if(track.streamIndex==before.selectedAudioTrack)continue;
+ const auto start=Clock::now();
+ check(engine.selectAudioTrack(before.sessionId,track.streamIndex),"request audio track");
+ check(wait([&](const auto& s){return s.selectedAudioTrack==track.streamIndex&&s.seekPresented>=s.seekRequested&&s.seekRequested>before.seekRequested&&s.transport==(paused?TransportState::Paused:TransportState::Playing)&&s.audioInputChannels==track.channels;}),"switch preserves transport and layout");
+ const auto after=engine.snapshot();check(std::abs(after.position-before.position)<3,"switch preserves position");
+ std::cout<<"switchMs="<<std::chrono::duration<double,std::milli>(Clock::now()-start).count()<<std::endl;
+ }
+ }
+ for(double target:{30.0,1200.0,90.0}){
+ if(failures)break;const auto start=Clock::now();engine.seek(target);const auto id=engine.snapshot().seekRequested;
+ check(wait([&](const auto& s){return s.seekPresented>=id;}),"seek presents target");
+ std::cout<<"seekMs="<<std::chrono::duration<double,std::milli>(Clock::now()-start).count()<<std::endl;
+ }
+ }
+ engine.stop();check(wait([&](const auto&){return engine.idle();}),"stop");
+ }
+ DestroyWindow(window);CoUninitialize();return failures?1:0;
+}
diff --git a/tests/integration/PopupSelectorTests.cpp b/tests/integration/PopupSelectorTests.cpp
index d4cc76f8..53c77f5d 100644
--- a/tests/integration/PopupSelectorTests.cpp
+++ b/tests/integration/PopupSelectorTests.cpp
@@ -36,11 +36,11 @@ try{
next=CreateWindowExW(0,L"BUTTON",L"next",WS_CHILD|WS_VISIBLE|WS_TABSTOP,20,100,100,32,owner,HMENU(11),wc.hInstance,nullptr);
// First ShowWindow consumes the runner's STARTUPINFO SW_HIDE.
ShowWindow(owner,SW_HIDE);ShowWindow(owner,SW_SHOW);SetForegroundWindow(owner);SetActiveWindow(owner);
- for(int i=0;i<24;++i){auto label=L"Option "+std::to_wstring(i);SendMessageW(combo,CB_ADDSTRING,0,LPARAM(label.c_str()));}SendMessageW(combo,CB_SETCURSEL,4,0);SetFocus(combo);notifications.clear();steps=0;SetTimer(owner,1,20,nullptr);
+ for(int i=0;i<33;++i){auto label=L"Option "+std::to_wstring(i);SendMessageW(combo,CB_ADDSTRING,0,LPARAM(label.c_str()));}SendMessageW(combo,CB_SETCURSEL,4,0);SetFocus(combo);notifications.clear();steps=0;SetTimer(owner,1,20,nullptr);
SendMessageW(combo,CB_SHOWDROPDOWN,TRUE,0);if(IsWindow(owner))KillTimer(owner,1);require(action==8||action==12?steps==0:steps>0&&steps<=10,"bounded popup closed including synchronous cancellation");require(!veyra::ui::popupSelectorOpen()&&!veyra::ui::activeSelector,"popup releases all active state");
if(action>=9&&action<=12){require(!IsWindow(combo),"destroyed combo stays destroyed");if(action==10||action==12)require(!IsWindow(owner),"destroyed owner stays destroyed");if(IsWindow(owner))DestroyWindow(owner);std::cout<<"PASS popup case "<<action<<"\n";continue;}
require(!SendMessageW(combo,CB_GETDROPPEDSTATE,0,0),"collapse reports closed");require(notified(CBN_DROPDOWN)&&notified(CBN_CLOSEUP),"native dropdown lifecycle notifications");
- if(action==0||action==5){require(SendMessageW(combo,CB_GETCURSEL,0,0)==(action==0?5:23),"arrow/end commits selected option including scrolled items");require(notified(CBN_SELCHANGE)&&notified(CBN_SELENDOK),"commit notifies owning panel");}
+ if(action==0||action==5){require(SendMessageW(combo,CB_GETCURSEL,0,0)==(action==0?5:32),"arrow/end commits selected option including scrolled items");require(notified(CBN_SELCHANGE)&&notified(CBN_SELENDOK),"commit notifies owning panel");}
else{require(notified(CBN_SELENDCANCEL)&&!notified(CBN_SELCHANGE),"cancel never submits a setting");if(action!=4)require(SendMessageW(combo,CB_GETCURSEL,0,0)==4,"cancel keeps original selection");}
if(action==3)require(GetFocus()==next,"Tab advances to next control");
if(action==13)require(GetFocus()==previous,"Shift+Tab returns to previous control");
diff --git a/tests/integration/RepairFgTests.cpp b/tests/integration/RepairFgTests.cpp
index d1b8547a..678050f1 100644
--- a/tests/integration/RepairFgTests.cpp
+++ b/tests/integration/RepairFgTests.cpp
@@ -13,7 +13,36 @@ extern "C" {
}
namespace {
uint64_t hash(const veyra::sink::RgbaImage& im){uint64_t v=14695981039346656037ull;for(auto b:im.pixels){v^=b;v*=1099511628211ull;}return v;}
+double latticeValue(unsigned x,unsigned y){
+ uint32_t value=x*0x9e3779b9u+y*0x85ebca6bu;
+ value^=value>>16;value*=0x7feb352du;value^=value>>15;
+ return 32.0+double(value%193);
+}
+uint8_t detailedPlane(unsigned x,unsigned y,unsigned frame){
+ // A translated, nonperiodic bilinear texture avoids the sine fixture's
+ // repeated low-frequency structure without changing the position gate.
+ const unsigned local=x+256-frame*16;
+ const unsigned cellX=local/8,cellY=y/8;
+ const double tx=double(local%8)/8,ty=double(y%8)/8;
+ const double a=latticeValue(cellX,cellY)*(1-tx)+latticeValue(cellX+1,cellY)*tx;
+ const double b=latticeValue(cellX,cellY+1)*(1-tx)+latticeValue(cellX+1,cellY+1)*tx;
+ return uint8_t(std::lround(a*(1-ty)+b*ty));
+}
double center(const veyra::sink::RgbaImage& im){double total=0,sum=0;for(unsigned y=300;y<780;++y)for(unsigned x=0;x<im.width;++x){const auto v=im.pixels[(size_t(y)*im.width+x)*4];if(v>160){total+=1;sum+=x;}}return total?sum/total:-1;}
+double translation(const veyra::sink::RgbaImage& previous,const veyra::sink::RgbaImage& generated){
+ double best=1e30,shift=0;
+ for(unsigned quarter=0;quarter<=64;++quarter){
+ const double dx=quarter*0.25;double error=0;
+ for(unsigned y=200;y<880;y+=8)for(unsigned x=300;x<1620;x+=8){
+ const double sample=x-dx;const unsigned left=unsigned(sample);const double fraction=sample-left;
+ const size_t offset=(size_t(y)*previous.width+left)*4;
+ const double expected=previous.pixels[offset]*(1-fraction)+previous.pixels[offset+4]*fraction;
+ const double delta=expected-generated.pixels[(size_t(y)*generated.width+x)*4];error+=delta*delta;
+ }
+ if(error<best){best=error;shift=dx;}
+ }
+ return shift;
+}
}
int main(int argc,char** argv){
using namespace veyra;CoInitializeEx(nullptr,COINIT_MULTITHREADED);
@@ -21,31 +50,57 @@ int main(int argc,char** argv){
Status st=Status::Ok;gfx::DeviceContextDesc dd;dd.commandSlotCount=6;bool ok=ctx.initialize(dd,st)&&ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,st);
pipeline::EnhanceGraphDesc gd;gd.sourceWidth=gd.workWidth=1920;gd.sourceHeight=gd.workHeight=1080;gd.enableNr=false;gd.enableSr=false;gd.enableFg=true;gd.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();
const std::string mode=argc>1?argv[1]:"off";
+ gd.rgbInput=mode.find("-rgb")!=std::string::npos;
gd.enableNr=mode!="off";gd.enableNvofStandalone=gd.enableNr;
if(mode.starts_with("dis"))gd.opticalFlowBackend=engine::OpticalFlowBackend::GpuDis;
if(mode=="flowP")gd.flowQuality=engine::FlowQuality::Performance;
if(mode=="flowQ")gd.flowQuality=engine::FlowQuality::Quality;
if(mode=="dis-sr"){gd.workWidth=3840;gd.workHeight=2160;gd.nrWidth=1920;gd.nrHeight=1080;gd.enableSr=true;gd.videoSrQuality=2;}
if(mode=="sr"){gd.workWidth=3840;gd.workHeight=2160;gd.nrWidth=1920;gd.nrHeight=1080;gd.enableSr=true;}
- if(mode=="mfg3"||mode=="mfg4"){gd.fgMultiplier=mode=="mfg3"?3:4;gd.enableNr=false;gd.enableNvofStandalone=false;}
+ const bool textured=mode.ends_with("-textured");
+ const bool exact=mode.find("-exact")!=std::string::npos;
+ const bool globalMotion=mode.find("-pan")!=std::string::npos;
+ const bool planar=mode.find("-planar")!=std::string::npos;
+ const bool detailed=mode.find("-detail")!=std::string::npos;
+ const uint16_t motionBits=mode.find("-reverse")!=std::string::npos?0x4c00:mode.find("-zero")!=std::string::npos?0:0xcc00;
+ pipeline::ComPtr<ID3D12Resource> motion,upload;
+ if(ok&&exact){motion=pipeline::makeTexture(ctx.device(),1920,1080,DXGI_FORMAT_R16G16_FLOAT,false);upload=pipeline::makeUploadBuffer(ctx.device(),1920ull*1080*4);ok=motion&&upload;gd.fgMotionProbe=motion.Get();}
+ if(mode.starts_with("mfg")&&mode.size()>=4&&mode[3]>='2'&&mode[3]<='6'){gd.fgMultiplier=uint32_t(mode[3]-'0');gd.enableNr=false;gd.enableNvofStandalone=false;}
if(ok)ok=graph.initialize(gd)&&graph.createViews();
AVFrame* f=av_frame_alloc();f->format=AV_PIX_FMT_RGBA;f->width=1920;f->height=1080;f->color_range=AVCOL_RANGE_JPEG;ok=ok&&av_frame_get_buffer(f,32)>=0;
sink::RgbaImage previous;unsigned generated=0,valid=0;pipeline::FrameBatch retained;
for(unsigned i=0;ok&&i<12;++i){
- for(int y=0;y<1080;++y)for(int x=0;x<1920;++x){auto* p=f->data[0]+size_t(y)*f->linesize[0]+x*4;const bool square=x>=240+int(i)*16&&x<880+int(i)*16&&y>=220&&y<860;p[0]=p[1]=p[2]=square?240:20;p[3]=255;}
+ if(exact){
+ void* data=nullptr;if(FAILED(upload->Map(0,nullptr,&data))){ok=false;break;}
+ for(unsigned y=0;y<1080;++y)for(unsigned x=0;x<1920;++x){auto* p=static_cast<uint16_t*>(data)+(size_t(y)*1920+x)*2;const bool square=x>=240+i*16&&x<880+i*16&&y>=220&&y<860;p[0]=i&&(square||globalMotion||planar)?motionBits:0;p[1]=0;}
+ upload->Unmap(0,nullptr);unsigned slot=0;auto* list=ring.acquireNext(slot,st);if(!list){ok=false;break;}
+ D3D12_RESOURCE_BARRIER b{};b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;b.Transition={motion.Get(),D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,i?D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE:D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_DEST};list->ResourceBarrier(1,&b);
+ D3D12_TEXTURE_COPY_LOCATION dst{},src{};dst.pResource=motion.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;src.pResource=upload.Get();src.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;src.PlacedFootprint.Footprint={DXGI_FORMAT_R16G16_FLOAT,1920,1080,1,1920*4};list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);b.Transition.StateBefore=D3D12_RESOURCE_STATE_COPY_DEST;b.Transition.StateAfter=D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;list->ResourceBarrier(1,&b);
+ if(!ring.submitAndSignal(slot)||!ring.drainQueue()){ok=false;break;}
+ }
+ for(int y=0;y<1080;++y)for(int x=0;x<1920;++x){auto* p=f->data[0]+size_t(y)*f->linesize[0]+x*4;const int local=x-int(i)*16;const bool square=local>=240&&local<880&&y>=220&&y<860;const int texture=textured?((local*13+y*7)^((local/8)*19+(y/8)*23))&31:0;p[0]=p[1]=p[2]=square?240-texture:20;p[3]=255;}
+ if(planar)for(int y=0;y<1080;++y)for(int x=0;x<1920;++x){
+ auto* p=f->data[0]+size_t(y)*f->linesize[0]+x*4;const double local=x-int(i)*16;
+ p[0]=p[1]=p[2]=uint8_t(std::lround(128+45*std::sin(local*0.07)+35*std::sin(local*0.031+y*0.06)+25*std::sin(y*0.031)));p[3]=255;
+ if(detailed)p[0]=p[1]=p[2]=detailedPlane(unsigned(x),unsigned(y),i);
+ }
pipeline::EnhanceGraph::FrameOutputs out;if(!graph.process(f,i*20.0,i==0,out)){ok=false;break;}
sink::RgbaImage real,g;if(!sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),real)){ok=false;break;}
if(!ring.waitIdle()||!graph.resolveGeneration(out)){ok=false;break;}
uint64_t previousGeneratedHash=0;
for(uint32_t j=0;j<out.batch.count;++j){const auto& item=out.batch.frames[j];if(item.kind!=pipeline::FrameKind::Generated)continue;
++generated;if(!sink::readRgba8(ctx,ring,graph.generatedFrameResource(item.lease->slot),g)){ok=false;break;}
+ if(i==8&&exact)sink::saveImage((std::filesystem::path(VEYRA_PROJECT_ROOT)/"out/logs"/("post140-exact-"+std::to_string(item.subframe)+".png")).wstring(),g);
const double t=double(item.subframe)/gd.fgMultiplier;
double blendResidual=0;for(size_t k=0;k<g.pixels.size();k+=4)blendResidual+=std::abs(double(g.pixels[k])-(double(previous.pixels[k])*(1-t)+real.pixels[k]*t));blendResidual/=g.width*g.height;
const double expected=center(previous)*(1-t)+center(real)*t;
- const bool good=item.validity==pipeline::GenerationValidity::Valid&&hash(g)!=hash(previous)&&hash(g)!=hash(real)&&hash(g)!=previousGeneratedHash&&blendResidual>0.1&&std::abs(center(g)-expected)<=3.0&&std::abs(item.pts100ns/10000.0-((i-1+t)*20.0))<=0.0001;
+ const double displacement=planar?translation(previous,g):0;
+ const bool position=planar?std::abs(displacement-16*t)<=1.0:std::abs(center(g)-expected)<=3.0;
+ const bool good=item.validity==pipeline::GenerationValidity::Valid&&hash(g)!=hash(previous)&&hash(g)!=hash(real)&&hash(g)!=previousGeneratedHash&&blendResidual>0.1&&position&&std::abs(item.pts100ns/10000.0-((i-1+t)*20.0))<=0.0001;
valid+=good;
previousGeneratedHash=hash(g);
std::cout<<"CONTENT frame="<<i<<" subframe="<<item.subframe<<" pts="<<item.pts100ns<<" previousHash="<<hash(previous)<<" realHash="<<hash(real)<<" generatedHash="<<hash(g)<<" expectedCenter="<<expected<<" actualCenter="<<center(g)<<" blendResidual="<<blendResidual<<" valid="<<good<<std::endl;
+ if(planar)std::cout<<"TRANSLATION expected="<<16*t<<" observed="<<displacement<<std::endl;
}
previous=std::move(real);
if(i==10)retained=out.batch;
diff --git a/tests/integration/SchedulingChainTests.cpp b/tests/integration/SchedulingChainTests.cpp
new file mode 100644
index 00000000..d5abbff7
--- /dev/null
+++ b/tests/integration/SchedulingChainTests.cpp
@@ -0,0 +1,86 @@
+#include "veyra/engine/EngineController.h"
+#include "veyra/engine/VideoExportJob.h"
+#include "veyra/Log.h"
+#include <chrono>
+#include <cmath>
+#include <filesystem>
+#include <iostream>
+#include <thread>
+
+int wmain(int argc,wchar_t** argv){
+ using namespace veyra::engine;
+ using Clock=std::chrono::steady_clock;
+ if(argc!=4)return 2; // media, output directory, playback/xess/export
+ if(FAILED(CoInitializeEx(nullptr,COINIT_MULTITHREADED)))return 2;
+ const std::filesystem::path directory=argv[2];
+ std::filesystem::create_directories(directory);
+ veyra::Logger::instance().openFile((directory/L"engine.log").wstring());
+ veyra::Logger::instance().setConsoleEnabled(false);
+ int failures=0;
+ auto check=[&](bool ok,const char* label){std::cout<<(ok?"PASS ":"FAIL ")<<label<<std::endl;failures+=!ok;};
+ if(std::wstring_view(argv[3])==L"export"){
+ for(unsigned stopAfter:{1u,3u,5u,0u}){
+ std::atomic<bool> cancel=false;unsigned boundaries=0;uint64_t sources=0,encoded=0;
+ const auto output=directory/(L"export-"+std::to_wstring(stopAfter)+L".mp4");
+ const bool ok=exportVideo(argv[1],output.wstring(),{},false,cancel,
+ [](double,const std::wstring&){},12,
+ [&]{if(stopAfter&&boundaries++>=stopAfter){cancel=true;return false;}return true;},
+ [&](const ExportCounts& c){sources=c.source;encoded=c.encoded;});
+ std::cout<<"stopAfter="<<stopAfter<<" sources="<<sources<<" encoded="<<encoded<<std::endl;
+ check(stopAfter?(!ok&&cancel&&sources==stopAfter&&!std::filesystem::exists(output)&&std::filesystem::exists(output.wstring()+L".partial")):(ok&&sources==12&&encoded==12&&std::filesystem::exists(output)),stopAfter?"cancel with encoder frames pending":"export following cancellations");
+ }
+ }else{
+ HWND window=CreateWindowExW(0,L"STATIC",L"Scheduling regression",WS_OVERLAPPEDWINDOW,
+ 0,0,960,600,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
+ if(!window){CoUninitialize();return 2;}
+ ShowWindow(window,SW_SHOWNOACTIVATE);
+ {
+ EngineController engine;engine.setVolume(0,true);
+ auto pump=[] {MSG m;while(PeekMessageW(&m,nullptr,0,0,PM_REMOVE)){TranslateMessage(&m);DispatchMessageW(&m);}};
+ auto wait=[&](auto predicate,int milliseconds=10000){
+ const auto end=Clock::now()+std::chrono::milliseconds(milliseconds);
+ while(Clock::now()<end){pump();const auto s=engine.snapshot();if(s.failed)return false;if(predicate(s))return true;std::this_thread::sleep_for(std::chrono::milliseconds(5));}return false;
+ };
+ auto delay=[&](int milliseconds){const auto end=Clock::now()+std::chrono::milliseconds(milliseconds);while(Clock::now()<end){pump();std::this_thread::sleep_for(std::chrono::milliseconds(5));}};
+ const bool xess=std::wstring_view(argv[3])==L"xess";
+ EnhancementSettings settings;
+ if(xess){settings.multiplier=2;settings.frameGenerationBackend=FrameGenerationBackend::XeSS;}
+ engine.open(window,argv[1],PlayerOptions::from(settings));
+ check(wait([](const auto& s){return s.frames>=10;}),"first frames");
+ check(engine.snapshot().audioTracks.empty(),"fixture has no audio clock");
+ auto interval=[&](int milliseconds,const char* label){
+ const auto before=engine.snapshot();const auto start=Clock::now();delay(milliseconds);
+ const auto after=engine.snapshot();const double wall=std::chrono::duration<double>(Clock::now()-start).count();
+ const double speed=(after.position-before.position)/wall;
+ std::cout<<label<<" wall="<<wall<<" media="<<after.position-before.position<<" speed="<<speed<<" skipped="<<after.previewSkipped<<" lateMs="<<after.lateMs<<std::endl;
+ check(!after.failed&&speed>.80&&speed<1.20,label);
+ return after;
+ };
+ SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",L"60");
+ const auto overloaded=interval(3000,"silent overload keeps wall-clock pace");
+ check(overloaded.previewSkipped>0,"expired source opportunities skipped");
+ if(xess){
+ check(wait([](const auto& s){return s.xessGenerationSuppressed;},5000),"XeSS suppresses sustained overload");
+ SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",L"10");
+ const auto before=engine.snapshot();
+ interval(5000,"XeSS moderate-load pace");
+ const auto after=engine.snapshot();
+ std::cout<<"XeSS suppressed="<<after.xessGenerationSuppressed<<" generatedDelta="<<after.generated-before.generated<<std::endl;
+ check(!after.xessGenerationSuppressed&&after.generated>before.generated+30,"XeSS resumes at sustainable load");
+ }
+ SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",nullptr);
+ interval(2000,"recovery pace");
+ engine.pause(true);check(wait([](const auto& s){return s.transport==TransportState::Paused;}),"pause");
+ delay(200);const auto paused=engine.snapshot();delay(400);
+ check(std::abs(engine.snapshot().position-paused.position)<.05,"paused position stable");
+ engine.seek(12);const auto seekId=engine.snapshot().seekRequested;
+ check(wait([&](const auto& s){return s.seekPresented>=seekId&&std::abs(s.position-12)<.15;}),"paused seek");
+ delay(300);engine.pause(false);
+ check(wait([](const auto& s){return s.transport==TransportState::Playing&&s.position>12.1;}),"resume");
+ interval(2000,"resumed pace");
+ engine.stop();check(wait([&](const auto&){return engine.idle();}),"stop");
+ }
+ DestroyWindow(window);
+ }
+ CoUninitialize();return failures?1:0;
+}
diff --git a/tests/integration/SubtitleLoadingTests.cpp b/tests/integration/SubtitleLoadingTests.cpp
new file mode 100644
index 00000000..c5ca0e86
--- /dev/null
+++ b/tests/integration/SubtitleLoadingTests.cpp
@@ -0,0 +1,77 @@
+#include "veyra/engine/Subtitles.h"
+#include <chrono>
+#include <iostream>
+#include <thread>
+
+int wmain(int argc,wchar_t** argv){
+ using namespace veyra::engine;
+ using Clock=std::chrono::steady_clock;
+ if(argc<2){std::cerr<<"Pass a media file with text subtitle tracks\n";return 2;}
+ const auto start=Clock::now();
+ SubtitleLoader loader;
+ loader.request(argv[1]);
+ const auto cancelled=loader.request(L"");
+ auto await=[&](uint64_t id){
+ const auto deadline=Clock::now()+std::chrono::seconds(20);
+ while(Clock::now()<deadline){
+ if(auto result=loader.poll()){
+ if(result->generation!=id)throw std::runtime_error("stale generation published");
+ if(result->complete)return *result;
+ }
+ std::this_thread::sleep_for(std::chrono::milliseconds(5));
+ }
+ throw std::runtime_error("subtitle loading timeout");
+ };
+ try{
+ if(!await(cancelled).tracks.empty())return 1;
+ const auto interrupted=loader.request(argv[1]);
+ const auto metadataDeadline=Clock::now()+std::chrono::seconds(20);
+ bool metadataSeen=false;
+ while(Clock::now()<metadataDeadline){
+ if(auto metadata=loader.poll()){
+ if(metadata->generation!=interrupted||metadata->complete)return 1;
+ metadataSeen=true;break;
+ }
+ std::this_thread::sleep_for(std::chrono::milliseconds(5));
+ }
+ if(!metadataSeen)return 1;
+ const auto cancelStart=Clock::now();
+ if(!await(loader.request(L"")).tracks.empty())return 1;
+ const double cancelMs=std::chrono::duration<double,std::milli>(Clock::now()-cancelStart).count();
+ std::cout<<"mid-scan cancellation ms="<<cancelMs<<'\n';
+ if(cancelMs>2000)return 1;
+ const auto id=loader.request(argv[1]);
+ bool partialCues=false;
+ SubtitleLoader::Result result;
+ const auto completeDeadline=Clock::now()+std::chrono::seconds(20);
+ while(Clock::now()<completeDeadline){
+ if(auto update=loader.poll()){
+ if(update->generation!=id)return 1;
+ if(!update->complete)for(const auto& track:update->tracks)partialCues|=!track.cues.empty();
+ if(update->complete){result=std::move(*update);break;}
+ }
+ std::this_thread::sleep_for(std::chrono::milliseconds(5));
+ }
+ std::cout<<"progressive cues="<<partialCues<<'\n';
+ if(!result.complete||(argc>2&&!partialCues))return 1;
+ size_t usable=0,cues=0;
+ for(const auto& track:result.tracks){
+ usable+=track.usable();cues+=track.cues.size();
+ if(track.starts.size()!=track.cues.size())return 1;
+ double previous=-1e30;
+ for(const auto& cue:track.cues){
+ if(cue.begin<previous||cue.end<=cue.begin)return 1;
+ previous=cue.begin;
+ }
+ if(track.usable()&&textAt(track,(track.cues.front().begin+track.cues.front().end)/2).empty())return 1;
+ }
+ std::cout<<"tracks="<<result.tracks.size()<<" usable="<<usable<<" cues="<<cues
+ <<" elapsedMs="<<std::chrono::duration<double,std::milli>(Clock::now()-start).count()<<'\n';
+ if(!usable||(argc>2&&usable!=size_t(std::wcstoul(argv[2],nullptr,10))))return 1;
+ std::stop_source stop;stop.request_stop();
+ if(!loadEmbeddedSubtitleTracks(argv[1],stop.get_token()).empty())return 1;
+ // Destroy with work pending: cancellation must not wait for an entire scan.
+ loader.request(argv[1]);
+ }catch(const std::exception& e){std::cerr<<e.what()<<'\n';return 1;}
+ return 0;
+}
diff --git a/tests/unit/LiveGpuSchedulerTests.cpp b/tests/unit/LiveGpuSchedulerTests.cpp
index 69b5e418..cedd4a81 100644
--- a/tests/unit/LiveGpuSchedulerTests.cpp
+++ b/tests/unit/LiveGpuSchedulerTests.cpp
@@ -38,20 +38,36 @@ int main(){
check(!scheduler.push([](int64_t){return Scheduler::Step{State::Complete};},[]{}),"failed scheduler rejects new work");
veyra::engine::TimingWindow timing;for(unsigned i=0;i<100;++i)timing.add(i);check(timing.p95()==94,"percentile order statistic");timing.clear();timing.add(6);check(timing.p95()==6,"reset removes old timing window");
veyra::engine::FgRecoveryBudget budget;
+ {
+ using Window=veyra::engine::TimingWindow;
+ const Window::Clock::time_point start{};
+ Window present{std::chrono::seconds(1)};
+ present.add(80,start);
+ check(present.p95(start)==80,"temporary Present stall is visible to admission");
+ check(!budget.admit(10000000,10200000,0,present.p95(start)),"stall limits FG admission");
+ check(present.p95(start+std::chrono::seconds(1))==0,"Present stall expires without successful FG or new samples");
+ present.add(2,start+std::chrono::seconds(1));
+ check(budget.admit(20000000,20200000,0,present.p95(start+std::chrono::seconds(1))),"admission recovers after expired Present stall");
+ present.clear();check(present.p95(start+std::chrono::seconds(1))==0,"new metrics window clears admission samples");
+ budget.reset();
+ }
budget.fgCost(3,10000000);budget.complete(31,true,false,10000000);
+ check(budget.processingAllowance(10000000,166667)==166667,"live processing allowance is bounded to one source interval");
check(budget.predicted(10000000)&&std::abs(*budget.predicted(10000000)-31)<.001,"base and FG cost do not double count additional generation");
check(!budget.admit(10000000,10100000,0,0),"insufficient pair deadline enters limited state");
- check(!budget.admit(10100000,10600000,0,0),"recovery does not oscillate every input frame");
- check(budget.admit(12600000,13100000,0,0)&&budget.recovering(),"bounded recovery admits first warmup opportunity");
- check(budget.admit(12900000,13400000,0,0)&&!budget.recovering(),"second consecutive opportunity exits recovery and can produce a frame");
+ check(budget.admit(10100000,10600000,0,0)&&budget.recovering(),"fresh deadline admits warmup without a fixed cooldown");
+ check(budget.admit(10266667,10766667,0,0)&&!budget.recovering(),"second consecutive source pair exits recovery");
budget.complete(200,true,true,13000000);
check(*budget.predicted(13000000)<32,"expensive reset warmup does not poison steady cost");
budget.complete(10,false,false,24000000);
+ check(budget.processingAllowance(24000000,166667)==100000,"live deadline includes measured enhancement before interpolation cadence");
check(*budget.predicted(24000000)<14,"old slow completion expires even when no FG succeeds");
check(!budget.admit(24000000,23800000,0,0),"recovery never admits an already expired deadline");
budget.reset();check(!budget.predicted(25000000),"settings revision reset clears prior backend costs");
+ check(budget.processingAllowance(25000000,166667)==0,"unknown GPU work cannot invent a processing allowance");
budget.fgCost(20,25000000);budget.complete(12,true,false,25000000,3);
check(budget.predicted(25000000)==29,"subtract same-frame FG time instead of another frame's higher percentile");
+ check(!budget.admit(25000000,25050000,100,0),"long CPU stall cannot discount FG that has not been submitted");
budget.complete(std::nullopt,true,false,36000000);
check(!budget.predicted(36000000),"missing GPU timing cannot retain a stale CPU polling cost");
check(!budget.admit(36000000,35800000,0,0),"unknown cost still rejects expired presentation deadlines");
diff --git a/tests/unit/RepairContractTests.cpp b/tests/unit/RepairContractTests.cpp
index cb239de8..22efe843 100644
--- a/tests/unit/RepairContractTests.cpp
+++ b/tests/unit/RepairContractTests.cpp
@@ -75,6 +75,12 @@ int main(){
auto& last=gpu.gpu[size_t(diagnostics::GpuStage::FgBatch)];last={diagnostics::SampleState::Measured,3,10000,13000,1000000};
gpu.gpu[size_t(diagnostics::GpuStage::Blit)]={diagnostics::SampleState::Measured,2,100000,102000,1000000};
check(diagnostics::graphExecutionSpanMs(gpu)==12,"GPU budget excludes delayed presentation and CPU completion observation");
+ for(unsigned sub=1;sub<=5;++sub){
+ const auto stage=static_cast<diagnostics::GpuStage>(unsigned(diagnostics::GpuStage::Fg1)+sub-1);
+ gpu.gpu[size_t(stage)]={diagnostics::SampleState::Measured,1,3000+sub*1000,4000+sub*1000,1000000};
+ }
+ check(last.begin==10000&&last.end==13000&&gpu.gpu[size_t(diagnostics::GpuStage::Blit)].begin==100000,
+ "6X subframe timestamps cannot overwrite batch or presentation timestamps");
last.frequency=1000;check(!diagnostics::graphExecutionSpanMs(gpu),"unrelated GPU clocks cannot form a processing envelope");
}
const auto logPath=std::filesystem::temp_directory_path()/(L"veyra-log-reopen-"+std::to_wstring(GetCurrentProcessId())+L".log");
@@ -261,6 +267,14 @@ int main(){
check(pipeline::FrameBatch::interpolate(0,200000,1,3)==66667&&pipeline::FrameBatch::interpolate(0,200000,2,3)==133333,"rational 3X PTS within tick");
pipeline::FrameBatch b;b.identity={1,2,3};pipeline::BatchFrame f;f.identity=b.identity;f.pts100ns=1;b.append(f);f.identity.settingsRevision=3;
bool rejected=false;try{b.append(f);}catch(...){rejected=true;}check(rejected,"reject mixed settingsRevision");
+ for(uint32_t multiplier=2;multiplier<=pipeline::FrameBatch::Capacity;++multiplier){
+ pipeline::FrameBatch batch;batch.identity={7,9,11};batch.a100ns=0;batch.b100ns=1000000;
+ for(uint32_t j=1;j<multiplier;++j){pipeline::BatchFrame item;item.identity=batch.identity;item.kind=pipeline::FrameKind::Generated;item.subframe=j;item.pts100ns=pipeline::FrameBatch::interpolate(0,1000000,j,multiplier);batch.append(item);}
+ pipeline::BatchFrame real;real.identity=batch.identity;real.pts100ns=1000000;batch.append(real);
+ check(batch.count==multiplier&&batch.frames[batch.count-1].kind==pipeline::FrameKind::Real,"2-6X batch retains every generated position and final real frame");
+ if(multiplier==pipeline::FrameBatch::Capacity){real.pts100ns++;bool overflow=false;try{batch.append(real);}catch(const std::invalid_argument&){overflow=true;}check(overflow,"full 6X batch rejects seventh frame before writing");
+ batch.count=UINT32_MAX;overflow=false;try{batch.append(real);}catch(const std::invalid_argument&){overflow=true;}check(overflow,"corrupt batch count rejects before indexing previous frame");}
+ }
diagnostics::FrameMetrics m;check(!m.displayFps&& !m.gpu[0].milliseconds,"unknown display/GPU is not zero");
diagnostics::DiagnosticHistory h;diagnostics::DiagnosticEvent e;e.fingerprint="same";for(int i=0;i<100;++i)h.add(e);
check(h.size()==1&&h.events()[0].occurrenceCount==100,"merge repeated error");
diff --git a/tests/unit/UiContractTests.cpp b/tests/unit/UiContractTests.cpp
index 1f5f758e..4944d653 100644
--- a/tests/unit/UiContractTests.cpp
+++ b/tests/unit/UiContractTests.cpp
@@ -75,6 +75,8 @@ int wmain(int argc,wchar_t** argv){try{
// and inspector 4 - the audio page, one of the five rail tabs - failed the
// range check. Both silently reset window size, volume and subtitle style.
{ui::UiPreferences audio;audio.volume=.9f;audio.muted=true;audio.inspector=4;audio.inspectorWidth=380;audio.width=1600;audio.height=900;require(prefs.save(audio,nullptr),"audio-page preferences save");ui::UiPreferenceStore reload(dir);const auto back=reload.load();require(std::abs(back.volume-.9f)<1e-6&&back.inspector==4&&back.inspectorWidth==380&&back.width==1600,"audio page and geometry survive the version 3 round trip");}
- auto setting=loaded.startup({});before.revision=setting.revision;require(setting==before,"all confirmed parameters round trip");auto path=dir/"ui-preferences.v1";{std::ofstream bad(path);bad<<"UNKNOWN 9 invalid";}ui::UiPreferenceStore damaged(dir);damaged.load();require(!damaged.save(p,nullptr),"corrupt preference cannot be overwritten");std::ifstream f(path);std::string data((std::istreambuf_iterator<char>(f)),{});require(data=="UNKNOWN 9 invalid","corrupt original preserved");}
+ auto setting=loaded.startup({});before.revision=setting.revision;require(setting==before,"all confirmed parameters round trip");
+ for(int enabled:{0,1}){p.enhancementEnabled=enabled;before.nr=true;before.nrRuntime=engine::NrRuntime::Community;require(prefs.save(p,&before),"master and runtime save");ui::UiPreferenceStore restart(dir);require(restart.load().enhancementEnabled==enabled,"master state survives restart");auto restoredSettings=restart.startup({});require(restoredSettings.nr&&restoredSettings.nrRuntime==before.nrRuntime,"bypassed effects and runtime survive restart");}
+ auto path=dir/"ui-preferences.v1";{std::ofstream bad(path);bad<<"UNKNOWN 9 invalid";}ui::UiPreferenceStore damaged(dir);damaged.load();require(!damaged.save(p,nullptr),"corrupt preference cannot be overwritten");std::ifstream f(path);std::string data((std::istreambuf_iterator<char>(f)),{});require(data=="UNKNOWN 9 invalid","corrupt original preserved");}
std::cout<<"PASS: mode/bypass, 384 layout cases at four DPI scales, actual PCM gain/mute, confirmed settings persistence/corruption\n";return 0;
}catch(const std::exception& e){std::cerr<<"FAIL: "<<e.what()<<'\n';return 1;}}
diff --git a/tools/fg_harness/fg_test.cpp b/tools/fg_harness/fg_test.cpp
index 2055748e..feab7c65 100644
--- a/tools/fg_harness/fg_test.cpp
+++ b/tools/fg_harness/fg_test.cpp
@@ -360,6 +360,85 @@ void copyUploadToTexture(ID3D12GraphicsCommandList* list, ID3D12Resource* dst,
} // namespace
+// Diagnostic readback only: isolate the NGX backend from graph scheduling,
+// pool ownership, source conversion and optical-flow estimation.
+static bool runPlanarSix(veyra::gfx::CommandSlotRing& ring,
+ veyra::ngx::NgxCoreHost& core, NVSDK_NGX_Parameter* params, GpuTextures& t)
+{
+ veyra::Status status = veyra::Status::Ok;
+ veyra::ngx::DlssFgBackend fg;
+ auto* list = ring.acquire(0, status);
+ veyra::ngx::DlssFgBackend::CreateDesc create{kWidth,kHeight,kWidth,kHeight,DXGI_FORMAT_R8G8B8A8_UNORM,false};
+ if (!list || !fg.create(core,list,params,create,status) || !ring.submitAndSignal(0) || !ring.waitIdle()) return false;
+ std::vector<uint8_t> previous(kRowPitch*kHeight), current(previous.size());
+ unsigned generated=0, accurate=0, distinct=0;
+ bool ok=true;
+ for (unsigned frame=0; ok && frame<12; ++frame) {
+ for(unsigned y=0;y<kHeight;++y)for(unsigned x=0;x<kWidth;++x){
+ const double local=double(x)-frame*16;
+ auto* p=current.data()+size_t(y)*kRowPitch+x*4;
+ p[0]=p[1]=p[2]=uint8_t(std::lround(128+45*std::sin(local*0.07)+35*std::sin(local*0.031+y*0.06)+25*std::sin(y*0.031)));p[3]=255;
+ auto* mv=reinterpret_cast<uint16_t*>(t.mappedMvec+size_t(y)*kRowPitch+x*4);
+ mv[0]=frame?floatToHalf(16.0f):0;mv[1]=0;
+ }
+ std::memcpy(t.mappedColor,current.data(),current.size());
+ uint64_t previousHash=0;
+ for(unsigned sub=1;ok&&sub<=5;++sub){
+ list=ring.acquire(0,status);if(!list){ok=false;break;}
+ if(sub==1){
+ copyUploadToTexture(list,t.backbuffer.Get(),t.uploadColor.Get(),DXGI_FORMAT_R8G8B8A8_UNORM,kWidth,kHeight);
+ copyUploadToTexture(list,t.mvecs.Get(),t.uploadMvec.Get(),DXGI_FORMAT_R16G16_FLOAT,kWidth,kHeight);
+ copyUploadToTexture(list,t.depth.Get(),t.uploadDepth.Get(),DXGI_FORMAT_R32_FLOAT,kWidth,kHeight);
+ }
+ ID3D12Resource* resources[]={t.backbuffer.Get(),t.depth.Get(),t.mvecs.Get(),t.outInterp.Get(),t.disableFlag.Get()};
+ D3D12_RESOURCE_BARRIER barriers[5]{};
+ for(unsigned j=0;j<5;++j){barriers[j].Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;barriers[j].Transition={resources[j],D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,D3D12_RESOURCE_STATE_COMMON,j<3?D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE:D3D12_RESOURCE_STATE_UNORDERED_ACCESS};}
+ list->ResourceBarrier(5,barriers);
+ veyra::ngx::DlssFgBackend::EvalDesc evaluate{};
+ evaluate.backbuffer=t.backbuffer.Get();evaluate.depth=t.depth.Get();evaluate.mvecs=t.mvecs.Get();
+ evaluate.outputInterpolated=t.outInterp.Get();evaluate.outputDisableInterpolation=t.disableFlag.Get();
+ evaluate.reset=frame==0;evaluate.frameId=frame+1;evaluate.multiFrameCount=5;evaluate.multiFrameIndex=sub;
+ evaluate.mvecScaleX=1.0f/kWidth;evaluate.mvecScaleY=1.0f/kHeight;
+ ok=fg.evaluate(list,params,evaluate,status);
+ for(unsigned j=0;j<5;++j){barriers[j].Transition.StateBefore=barriers[j].Transition.StateAfter;barriers[j].Transition.StateAfter=j<3?D3D12_RESOURCE_STATE_COMMON:D3D12_RESOURCE_STATE_COPY_SOURCE;}
+ list->ResourceBarrier(5,barriers);
+ D3D12_TEXTURE_COPY_LOCATION dst{},src{};
+ dst.pResource=t.readbackInterp.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
+ dst.PlacedFootprint.Footprint={DXGI_FORMAT_R8G8B8A8_UNORM,kWidth,kHeight,1,UINT(kRowPitch)};
+ src.pResource=t.outInterp.Get();src.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);list->CopyBufferRegion(t.readbackFlag.Get(),0,t.disableFlag.Get(),0,4);
+ for(unsigned j=3;j<5;++j){barriers[j].Transition.StateBefore=D3D12_RESOURCE_STATE_COPY_SOURCE;barriers[j].Transition.StateAfter=D3D12_RESOURCE_STATE_COMMON;}
+ list->ResourceBarrier(2,barriers+3);
+ ok=ring.submitAndSignal(0)&&ring.waitIdle()&&ok;if(!ok)break;
+ if(!frame)continue;
+ uint8_t* pixels=nullptr;uint8_t* flag=nullptr;
+ if(FAILED(t.readbackInterp->Map(0,nullptr,reinterpret_cast<void**>(&pixels)))){ok=false;break;}
+ if(FAILED(t.readbackFlag->Map(0,nullptr,reinterpret_cast<void**>(&flag)))){t.readbackInterp->Unmap(0,nullptr);ok=false;break;}
+ double best=1e30,shift=0;
+ for(unsigned quarter=0;quarter<=64;++quarter){
+ const double dx=quarter*0.25;double error=0;
+ for(unsigned y=200;y<880;y+=8)for(unsigned x=300;x<1620;x+=8){
+ const double sample=x-dx;const unsigned left=unsigned(sample);const double fraction=sample-left;
+ const size_t offset=size_t(y)*kRowPitch+left*4;
+ const double expected=previous[offset]*(1-fraction)+previous[offset+4]*fraction;
+ const double delta=expected-pixels[size_t(y)*kRowPitch+x*4];error+=delta*delta;
+ }
+ if(error<best){best=error;shift=dx;}
+ }
+ const uint64_t hash=fnv1a64(pixels,current.size());
+ const bool unique=hash!=previousHash&&hash!=fnv1a64(previous.data(),previous.size())&&hash!=fnv1a64(current.data(),current.size());
+ const bool position=std::abs(shift-16.0*sub/6)<=1.0;
+ ++generated;distinct+=unique;accurate+=position&&unique&&!*flag;previousHash=hash;
+ log::info("fg-planar6",std::format("frame={} sub={} expected={:.3f} observed={:.3f} distinct={} disabled={} positionPass={}",frame,sub,16.0*sub/6,shift,unique,unsigned(*flag),position));
+ t.readbackInterp->Unmap(0,nullptr);t.readbackFlag->Unmap(0,nullptr);
+ }
+ previous=current;
+ }
+ const bool drained=ring.drainQueue();fg.release();
+ log::info("fg-planar6",std::format("directNGX=true generated={} distinct={} contentValid={} graphUsed=false",generated,distinct,accurate));
+ return ok&&drained&&generated==55&&accurate==55;
+}
+
// Runs one DLSSG phase (translation or cut) for a given mvec convention.
// The FG feature must already be created; textures must be initialized.
static PhaseResult runPhase(
@@ -758,6 +837,12 @@ int runFgTest(const FgTestArgs& args)
coreHost.shutdown(); ring.shutdown(); context.shutdown(); return 9;
}
+ if(args.planarSix){
+ const bool passed=caps.multiFrameCountMax>=5&&runPlanarSix(ring,coreHost,params,textures);
+ coreHost.destroyParameters(params);coreHost.shutdown();ring.shutdown();context.shutdown();
+ return passed?0:1;
+ }
+
// CPU truth: real-frame centroids for both phases.
std::vector<Centroid> realCentroids(kRealFrames);
{
diff --git a/tools/fg_harness/fg_test.h b/tools/fg_harness/fg_test.h
index 611d68a4..741f5a1d 100644
--- a/tools/fg_harness/fg_test.h
+++ b/tools/fg_harness/fg_test.h
@@ -17,6 +17,7 @@ struct FgTestArgs {
std::wstring jsonFile;
std::wstring captureDir;
bool capabilityOnly = false; // --fg-cap: query + honest JSON, no create
+ bool planarSix = false; // Direct NGX diagnostic; no player/EnhanceGraph.
};
// Runs the full FG truth test and writes JSON to args.jsonFile.
diff --git a/tools/fg_harness/main.cpp b/tools/fg_harness/main.cpp
index ecdb573a..0afc71de 100644
--- a/tools/fg_harness/main.cpp
+++ b/tools/fg_harness/main.cpp
@@ -19,7 +19,7 @@ namespace {
void printUsage()
{
std::fprintf(stderr,
- "usage: veyra_fg_harness --fg-cap | --fg-test | --audio-test\n"
+ "usage: veyra_fg_harness --fg-cap | --fg-test | --fg-planar6 | --audio-test\n"
" [--runtime-dir DIR] [--run-id ID] [--log-file FILE] [--json-file FILE]\n"
" [--capture-dir DIR]\n");
}
@@ -31,6 +31,7 @@ int main(int argc, char** argv)
using namespace veyra::harness;
bool doCap = false, doFgTest = false, doAudio = false;
+ bool planarSix = false;
std::wstring runtimeDir;
std::string runId = "fg-harness";
std::wstring logFile, jsonFile, captureDir;
@@ -39,6 +40,7 @@ int main(int argc, char** argv)
const std::string arg = argv[i];
if (arg == "--fg-cap") doCap = true;
else if (arg == "--fg-test") doFgTest = true;
+ else if (arg == "--fg-planar6") { doFgTest = true; planarSix = true; }
else if (arg == "--audio-test") doAudio = true;
else if (arg == "--run-id" && i + 1 < argc) runId = argv[++i];
else if (arg == "--runtime-dir" && i + 1 < argc) {
@@ -81,6 +83,7 @@ int main(int argc, char** argv)
args.runId = runId;
args.jsonFile = jsonFile;
args.captureDir = captureDir;
+ args.planarSix = planarSix;
return runFgTest(args);
}
AudioTestArgs args{};