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

VFG mixed tiers and a GPU shot-change test per input pair

Veyra Goal Agent58dc1235566c
diff --git a/CMakeLists.txt b/CMakeLists.txt
index d46841c3..c74a6c8d 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -297,6 +297,8 @@ veyra_add_compute_shader(veyra_shader_nr_temporal NrTemporal)
# Stage-5 output stabiliser (anti-flicker, default off).
veyra_add_compute_shader(veyra_shader_nr_hold NrHold)
veyra_add_compute_shader(veyra_shader_flow_adapt FlowAdapt)
+# VfgShotChange: per-pair shot-change test for VFG (replaces the SDK's automatic one).
+veyra_add_compute_shader(veyra_shader_vfg_shot_change VfgShotChange)
veyra_add_compute_shader(veyra_shader_rgb_nv12 RgbToNv12)
# ---------------------------------------------------------------------------
@@ -554,7 +556,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
# veyra_sources: product input sources (Playbook R3/R7). MediaFileSource
# composes veyra_media; no second decode implementation exists.
- add_dependencies(veyra_pipeline veyra_shader_nr_downsample veyra_shader_nr_residual veyra_shader_nr_temporal veyra_shader_nr_hold veyra_shader_flow_adapt)
+ add_dependencies(veyra_pipeline veyra_shader_nr_downsample veyra_shader_nr_residual veyra_shader_nr_temporal veyra_shader_nr_hold veyra_shader_flow_adapt veyra_shader_vfg_shot_change)
add_library(veyra_sources STATIC
src/source/NativeCaptureSink.cpp
src/source/MediaFileSource.cpp
diff --git a/i18n/catalog.json b/i18n/catalog.json
index fbbfe5ec..024a53a7 100644
--- a/i18n/catalog.json
+++ b/i18n/catalog.json
@@ -15114,6 +15114,41 @@
"zh-TW": "螢幕 %1 Hz 最多顯示約 %2X",
"en": "A %1 Hz display shows at most about %2X",
"ja": "%1 Hz の画面で表示できるのは最大約 %2X"
+ },
+ {
+ "zh": "高+中",
+ "src": "qml/NodePage.qml",
+ "zh-TW": "高+中",
+ "en": "High+Medium",
+ "ja": "高+中"
+ },
+ {
+ "zh": "高+低",
+ "src": "qml/NodePage.qml",
+ "zh-TW": "高+低",
+ "en": "High+Low",
+ "ja": "高+低"
+ },
+ {
+ "zh": "中+低",
+ "src": "qml/NodePage.qml",
+ "zh-TW": "中+低",
+ "en": "Medium+Low",
+ "ja": "中+低"
+ },
+ {
+ "zh": "高质量更耗时;混合档:每对原帧的中间帧用前一档,其余用后一档",
+ "src": "qml/NodePage.qml",
+ "zh-TW": "高品質更耗時;混合檔:每對原始影格的中間影格用前一檔,其餘用後一檔",
+ "en": "Higher quality takes longer. Mixed tiers: the middle frame of each source pair uses the first model, the others the second.",
+ "ja": "高品質ほど時間がかかります。混合:各元フレーム間の中央の 1 枚に前者、残りに後者を使います。"
+ },
+ {
+ "zh": "VFG 中间帧约 %1 ms、其余每张约 %2 ms,当前负载约可稳定 %3X",
+ "src": "src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "VFG 中間影格約 %1 ms、其餘每張約 %2 ms,目前負載約可穩定 %3X",
+ "en": "VFG takes about %1 ms for the middle frame and %2 ms for each other frame; about %3X holds at the current load",
+ "ja": "VFG は中央の 1 枚が約 %1 ms、その他は 1 枚あたり約 %2 ms、現在の負荷で安定するのは約 %3X"
}
]
}
diff --git a/include/veyra/engine/EnhancementSettings.h b/include/veyra/engine/EnhancementSettings.h
index 7016e9ee..8b205b39 100644
--- a/include/veyra/engine/EnhancementSettings.h
+++ b/include/veyra/engine/EnhancementSettings.h
@@ -47,6 +47,19 @@ constexpr bool presentSinkFrameGeneration(FrameGenerationBackend backend) {
// exposes 2/3/4/6 and MFG buyers pick from those; 1 = generation off.
inline constexpr uint32_t kFgMultiplierChoices[]={1,2,3,4,6};
inline constexpr uint32_t kVfgMultiplierChoices[]={1,2,3,4,5,6,7,8};
+// VFG quality: 0-2 run one NvVFX model (Low/Medium/High) for every subframe.
+// 3-5 are mixed tiers (3 High+Medium, 4 High+Low, 5 Medium+Low): one subframe
+// per source pair, the one nearest the middle where interpolation is hardest,
+// uses the first model; the others, closer to a real frame, use the second.
+// Every subframe is a full VFG inference (the SDK shares nothing between
+// them), so a pair costs one first-model run plus N-2 second-model runs.
+inline constexpr uint32_t kVfgQualityCount=6;
+constexpr bool vfgMixedQuality(uint32_t quality){return quality>=3&&quality<kVfgQualityCount;}
+constexpr uint32_t vfgPrimaryMode(uint32_t quality){return quality<3?quality:quality==5?1u:2u;}
+constexpr uint32_t vfgSecondaryMode(uint32_t quality){return quality==3?1u:quality==4||quality==5?0u:vfgPrimaryMode(quality);}
+// The subframe of a multiplier-M group that uses the first model: t=1/2 for
+// even M, the one just after the middle for odd M (2X: its only subframe).
+constexpr uint32_t vfgPrimarySubframe(uint32_t multiplier){return (multiplier+1)/2;}
inline constexpr size_t kFgMultiplierChoiceCount=sizeof(kFgMultiplierChoices)/sizeof(kFgMultiplierChoices[0]);
// Export bitrate presets in Mbps; index 0 keeps the encoder's constant-quality
// default. Labels are the UI strings for the same order.
@@ -303,7 +316,8 @@ struct EnhancementSettings {
uint32_t videoSrQuality=0; // 0 DLSS SR; 1–4 RTX Video SR
uint32_t multiplier=1;
FrameGenerationBackend frameGenerationBackend=FrameGenerationBackend::Dlss;
- uint32_t vfgQuality=1; // NvVFX Mode: Low=0, Medium=1 (default), High=2
+ // NvVFX Mode: Low=0, Medium=1 (default), High=2; mixed tiers 3-5, see vfgPrimaryMode().
+ uint32_t vfgQuality=1;
// Export target bitrate in Mbps; 0 keeps the encoder's constant-quality
// default (NVENC CONSTQP / MFT quality mode). Only the export job consumes
// it: preview never re-encodes.
@@ -461,7 +475,7 @@ struct EnhancementSettings {
}
if(nr&&nrLayerCount&&!activeNrLayerCount())return "enabled NR stack has no active layer";
if(frameGenerationBackend<FrameGenerationBackend::Dlss||frameGenerationBackend>FrameGenerationBackend::Vfg)return "invalid frame generation backend";
- if(vfgQuality>2)return "invalid VFG quality";
+ if(vfgQuality>=kVfgQualityCount)return "invalid VFG quality";
// The XeSS provider reports its own generated-frame ceiling at session
// start; the engine clamps/rejects above it, so validation only guards
// the absolute API range here.
diff --git a/include/veyra/pipeline/VfgBackend.h b/include/veyra/pipeline/VfgBackend.h
index d9475534..c363c0c7 100644
--- a/include/veyra/pipeline/VfgBackend.h
+++ b/include/veyra/pipeline/VfgBackend.h
@@ -17,6 +17,8 @@ public:
VfgBackend& operator=(const VfgBackend&)=delete;
static std::wstring runtimeDirectory(const std::wstring& runtimeRoot);
static bool runtimeAvailable(const std::wstring& runtimeRoot);
+ // quality 0-5 as engine::EnhancementSettings::vfgQuality; a mixed tier
+ // loads a second effect with the second model on the same CUDA stream.
bool initialize(gfx::D3D12DeviceContext&,const std::wstring& runtimeRoot,
unsigned width,unsigned height,DXGI_FORMAT,unsigned multiplier,unsigned quality,
bool asynchronousSubmission=false);
@@ -24,7 +26,11 @@ public:
// Caller transitions encoded texture to COPY_SOURCE and back to COMMON.
// Submit this list before generate(). Normal frames never CPU-wait here;
// teardown and exceptional SDK rejection drain work before releasing it.
- bool capture(ID3D12GraphicsCommandList*,ID3D12Resource*,unsigned parity);
+ // The same list also runs the GPU shot-change test of this pair against
+ // the other parity's input (comparePrevious=false when the pair has no
+ // valid A, e.g. after a reset); copyOutput() of the pair's subframes is
+ // predicated on its result and shows the current input on a cut.
+ bool capture(ID3D12GraphicsCommandList*,ID3D12Resource*,unsigned parity,bool comparePrevious=true);
// Signals an OWNED producer fence and queues a GPU wait before copyOutput.
// Preview offloads the serial CUDA wait/run/signal to a bounded worker;
// synchronous/export callers retain the immediate SDK rejection verdict.
@@ -33,6 +39,11 @@ public:
// proof that the SDK accepted the generated frame.
SubmissionState submissionState(unsigned slot) const;
bool copyOutput(ID3D12GraphicsCommandList*,ID3D12Resource*,unsigned slot);
+ // Test diagnostics only: the shot-change result buffer (null when the SDK's
+ // automatic detection is used instead). Between captures it is in
+ // D3D12_RESOURCE_STATE_PREDICATION; uint32 layout: cut flag per parity at
+ // 0/2, last SAD/histogram/compare per parity at 4/8, cut count at 12.
+ ID3D12Resource* shotChangeResultsForTest() const;
void shutdown();
private:
struct Impl;
diff --git a/qml/Veyra/NodePage.qml b/qml/Veyra/NodePage.qml
index 1ccb02ea..3ea8df43 100644
--- a/qml/Veyra/NodePage.qml
+++ b/qml/Veyra/NodePage.qml
@@ -1519,10 +1519,10 @@ VPage {
VRow {
label: qsTr("VFG 质量")
visible: veyra.fgBackendName === "vfg"
- hint: qsTr("高质量需要更多处理时间")
+ hint: qsTr("高质量更耗时;混合档:每对原帧的中间帧用前一档,其余用后一档")
VSelect {
objectName: "node-vfg-quality"
- options: [{id:"0",label:qsTr("低")},{id:"1",label:qsTr("中")},{id:"2",label:qsTr("高")}]
+ options: [{id:"0",label:qsTr("低")},{id:"1",label:qsTr("中")},{id:"2",label:qsTr("高")},{id:"3",label:qsTr("高+中")},{id:"4",label:qsTr("高+低")},{id:"5",label:qsTr("中+低")}]
value: options[veyra.vfgQuality].label
onPicked: id => veyra.vfgQuality = Number(id)
}
diff --git a/qml/Veyra/ProPage.qml b/qml/Veyra/ProPage.qml
index 2e2d31a1..f26b4a01 100644
--- a/qml/Veyra/ProPage.qml
+++ b/qml/Veyra/ProPage.qml
@@ -1685,10 +1685,10 @@ VPage {
VRow {
label: qsTr("VFG 质量")
visible: veyra.fgBackendName === "vfg"
- hint: qsTr("高质量需要更多处理时间")
+ hint: qsTr("高质量更耗时;混合档:每对原帧的中间帧用前一档,其余用后一档")
VSelect {
objectName: "list-vfg-quality"
- options: [{id:"0",label:qsTr("低")},{id:"1",label:qsTr("中")},{id:"2",label:qsTr("高")}]
+ options: [{id:"0",label:qsTr("低")},{id:"1",label:qsTr("中")},{id:"2",label:qsTr("高")},{id:"3",label:qsTr("高+中")},{id:"4",label:qsTr("高+低")},{id:"5",label:qsTr("中+低")}]
value: options[veyra.vfgQuality].label
onPicked: id => veyra.vfgQuality = Number(id)
}
diff --git a/shaders/VfgShotChange.hlsl b/shaders/VfgShotChange.hlsl
new file mode 100644
index 00000000..0db9d32c
--- /dev/null
+++ b/shaders/VfgShotChange.hlsl
@@ -0,0 +1,97 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// Shot-change test for one VFG input pair (VfgBackend). It replaces the SDK's
+// AutomaticShotChangeDetection, which synchronised the CPU with every Run and
+// was evaluated again for every subframe of the same pair.
+//
+// Same measures and thresholds as core::SceneCadenceAnalyzer on the CPU path:
+// 64x36 luma samples, 256-bin histogram distance (L1 / 2) and normalised SAD;
+// a flash (large SAD, near-identical histogram) is not a cut. The samples come
+// from the encoded A/B buffers VFG itself reads, so every source kind (capture,
+// software and hardware decode, streaming) is covered without a CPU readback.
+//
+// flags[parity] (64-bit, offset parity*8) = 1 when the pair crosses a cut; the
+// subframe copies of that pair are predicated on it and show B instead.
+
+cbuffer Constants : register(b0)
+{
+ uint width;
+ uint height;
+ uint pitch; // bytes per row of both buffers
+ uint tenBit; // 1: R10G10B10A2, 0: R8G8B8A8
+ uint parity;
+ uint compare; // 0 when the pair has no valid A (reset): never a cut
+ float cutSad; // SceneCadenceAnalyzer::Config::sceneCutSadThreshold
+ float cutHistogram;
+ float replacementSad;
+ float replacementHistogram;
+ float flashSad;
+ float flashHistogram;
+};
+
+ByteAddressBuffer previousFrame : register(t0);
+ByteAddressBuffer currentFrame : register(t1);
+RWByteAddressBuffer flags : register(u0);
+
+static const uint kColumns = 64;
+static const uint kRows = 36;
+static const uint kSamples = kColumns * kRows;
+
+groupshared uint histogramPrevious[256];
+groupshared uint histogramCurrent[256];
+groupshared uint sadSum;
+groupshared uint histogramL1;
+
+// Integer luma weights of the CPU sampler (packedIngressLuma): 8-bit
+// (54R+183G+19B+128)>>8, 10-bit min(255,(54R+183G+19B+512)>>10).
+uint lumaAt(ByteAddressBuffer frame, uint x, uint y)
+{
+ const uint word = frame.Load(y * pitch + x * 4);
+ if (tenBit != 0) {
+ const uint r = word & 1023u, g = (word >> 10) & 1023u, b = (word >> 20) & 1023u;
+ return min(255u, (54u * r + 183u * g + 19u * b + 512u) >> 10);
+ }
+ const uint r = word & 255u, g = (word >> 8) & 255u, b = (word >> 16) & 255u;
+ return (54u * r + 183u * g + 19u * b + 128u) >> 8;
+}
+
+[numthreads(256, 1, 1)]
+void main(uint index : SV_GroupIndex)
+{
+ histogramPrevious[index] = 0;
+ histogramCurrent[index] = 0;
+ if (index == 0) {
+ sadSum = 0;
+ histogramL1 = 0;
+ }
+ GroupMemoryBarrierWithGroupSync();
+ if (compare != 0) {
+ for (uint i = index; i < kSamples; i += 256) {
+ const uint x = (i % kColumns) * width / kColumns;
+ const uint y = (i / kColumns) * height / kRows;
+ const uint a = lumaAt(previousFrame, x, y);
+ const uint b = lumaAt(currentFrame, x, y);
+ InterlockedAdd(histogramPrevious[a], 1);
+ InterlockedAdd(histogramCurrent[b], 1);
+ InterlockedAdd(sadSum, a > b ? a - b : b - a);
+ }
+ }
+ GroupMemoryBarrierWithGroupSync();
+ const uint p = histogramPrevious[index], c = histogramCurrent[index];
+ InterlockedAdd(histogramL1, p > c ? p - c : c - p);
+ GroupMemoryBarrierWithGroupSync();
+ if (index == 0) {
+ const float sad = float(sadSum) / (255.0 * kSamples);
+ const float histogram = float(histogramL1) / (2.0 * kSamples);
+ const bool flash = sad > flashSad && histogram < flashHistogram;
+ const bool cut = compare != 0 && !flash &&
+ ((sad > cutSad && histogram > cutHistogram) ||
+ (sad > replacementSad && histogram > replacementHistogram));
+ flags.Store2(parity * 8, uint2(cut ? 1u : 0u, 0u));
+ // Diagnostics for tests: last scores per parity and a running cut count.
+ flags.Store3(16 + parity * 16, uint3(asuint(sad), asuint(histogram), compare));
+ if (cut) {
+ uint previousCount;
+ flags.InterlockedAdd(48, 1, previousCount);
+ }
+ }
+}
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index 7778161f..6d2d0d31 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -2874,7 +2874,9 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
// therefore includes actual cross-queue work, not CPU wall time.
if(runFg){gpuTimer_.mark(list,GpuStage::FgBatch);gpuTimer_.mark(list,GpuStage::Fg1);}
tracker_.transition(list,videoFrame_[parity].Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);
- if(!vfgBackend_->capture(list,videoFrame_[parity].Get(),parity)){failedBackend_=engine::FailedBackend::Fg;return false;}
+ // The same list tests A/B for a shot change on the GPU (VfgBackend);
+ // a reset pair has no valid A and is bypassed by ShotChange instead.
+ if(!vfgBackend_->capture(list,videoFrame_[parity].Get(),parity,!resetFg)){failedBackend_=engine::FailedBackend::Fg;return false;}
tracker_.transition(list,videoFrame_[parity].Get(),D3D12_RESOURCE_STATE_COMMON);
}
if(!runFg)gpuTimer_.resolve(list);
diff --git a/src/pipeline/VfgBackend.cpp b/src/pipeline/VfgBackend.cpp
index 532c9250..d14c9380 100644
--- a/src/pipeline/VfgBackend.cpp
+++ b/src/pipeline/VfgBackend.cpp
@@ -1,5 +1,8 @@
#include "veyra/pipeline/VfgBackend.h"
#include "veyra/pipeline/FrameBatch.h"
+#include "veyra/pipeline/GpuPassUtils.h"
+#include "veyra/core/SceneCadenceAnalyzer.h"
+#include "veyra/engine/EnhancementSettings.h"
#include "veyra/gfx/D3D12DeviceContext.h"
#include "veyra/Log.h"
#include <Windows.h>
@@ -9,6 +12,7 @@
#include <cmath>
#include <atomic>
#include <condition_variable>
+#include <cstring>
#include <deque>
#include <filesystem>
#include <format>
@@ -23,6 +27,11 @@ namespace veyra::pipeline {
namespace {
namespace fs=std::filesystem;
constexpr unsigned kOutputs=2*(FrameBatch::Capacity-1);
+constexpr unsigned kShotChangeConstants=12; // VfgShotChange.hlsl cbuffer
+constexpr UINT64 kShotChangeBytes=256; // flags, scores and a cut count
+void transition(D3D12_RESOURCE_BARRIER& barrier,ID3D12Resource* resource,D3D12_RESOURCE_STATES from,D3D12_RESOURCE_STATES to){
+ barrier={};barrier.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;barrier.Transition={resource,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,from,to};
+}
constexpr DWORD kDllFlags=LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_SYSTEM32|LOAD_LIBRARY_SEARCH_USER_DIRS;
bool regularFile(const fs::path& path){std::error_code error;return fs::is_regular_file(path,error);}
HMODULE load(const fs::path& path){
@@ -106,16 +115,31 @@ struct VfgBackend::Impl {
CUexternalSemaphore inputSemaphore=nullptr,outputSemaphore=nullptr;
CUcontext cudaContext=nullptr;CUstream stream=nullptr;CUdevice device=0;
bool retained=false;
- void* effect=nullptr;
+ // [0] runs every subframe, or only the middle one of a mixed tier; [1]
+ // (mixed tiers only) the others. Both share the stream, so their CUDA work
+ // stays serial and the producer/completion fences are unchanged.
+ struct Effect {void* handle=nullptr;unsigned mode=1;uint64_t boundPair=0;unsigned boundMultiplier=0;};
+ std::array<Effect,2> effects{};
+ bool mixed=false;
std::vector<HMODULE> libraries;
D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{};
uint64_t bytes=0,signalValue=0;
unsigned width=0,height=0,maxMultiplier=2;
DXGI_FORMAT format=DXGI_FORMAT_UNKNOWN;
bool ready=false;
- uint64_t inputRevision=0,boundInputRevision=0;
- unsigned boundParity=2,boundMultiplier=0;
- bool boundReset=false;
+ // pairSerial advances when a new A/B pair starts; each effect rebinds its
+ // inputs once per pair (boundPair), whichever subframe reaches it first.
+ uint64_t inputRevision=0,pairSerial=0,lastRevision=0;
+ unsigned lastParity=2;
+ bool lastReset=false;
+ // GPU shot-change test (shaders/VfgShotChange.hlsl) instead of the SDK's
+ // AutomaticShotChangeDetection; VEYRA_TEST_VFG_AUTO_SHOT_CHANGE=1 restores
+ // the SDK detection (and skips this test) for same-EXE A/B runs.
+ bool gpuShotChange=false;
+ Microsoft::WRL::ComPtr<ID3D12RootSignature> cutRoot;
+ Microsoft::WRL::ComPtr<ID3D12PipelineState> cutPso;
+ Microsoft::WRL::ComPtr<ID3D12Resource> cutResults;
+ D3D12_RESOURCE_STATES cutState=D3D12_RESOURCE_STATE_COMMON;
struct Job {unsigned parity,sub,multiplier;bool reset;uint64_t revision,value;};
std::array<std::atomic<SubmissionState>,kOutputs> states{};
std::atomic<bool> failed=false;
@@ -157,16 +181,16 @@ struct VfgBackend::Impl {
// next one resolves; a full ring skips profiling and marks a gap.
static constexpr unsigned kProfileJobs=32;
std::array<CUevent,2*kProfileJobs> events{};
- std::array<unsigned,kProfileJobs> profiledSub{};std::array<bool,kProfileJobs> profiledAfterGap{};
+ std::array<unsigned,kProfileJobs> profiledSub{};std::array<bool,kProfileJobs> profiledAfterGap{},profiledSecond{};
uint64_t profileHead=0,profileTail=0;
- std::array<double,3> gpuSum{},gpuMax{};std::array<unsigned,3> gpuSamples{};
+ std::array<double,4> gpuSum{},gpuMax{};std::array<unsigned,4> gpuSamples{};
std::chrono::steady_clock::time_point nextGpuLog{};
void resolveGpu(){
while(profileTail<profileHead){
const unsigned slot=unsigned(profileTail%kProfileJobs);
if(cuEventQueryFn(events[2*slot+1])!=CUDA_SUCCESS)return;
float ms=0;
- if(cuEventElapsedTimeFn(&ms,events[2*slot],events[2*slot+1])==CUDA_SUCCESS)gpuSample(0,ms);
+ if(cuEventElapsedTimeFn(&ms,events[2*slot],events[2*slot+1])==CUDA_SUCCESS)gpuSample(profiledSecond[slot]?3:0,ms);
if(!profiledAfterGap[slot]){
const unsigned previous=unsigned((profileTail-1)%kProfileJobs);
if(cuEventElapsedTimeFn(&ms,events[2*previous+1],events[2*slot])==CUDA_SUCCESS)gpuSample(profiledSub[slot]>1?1:2,ms);
@@ -180,7 +204,8 @@ struct VfgBackend::Impl {
}
void logGpu(){
if(!profileGpu||std::chrono::steady_clock::now()<nextGpuLog)return;
- static constexpr std::array<const char*,3> names={"run","handoffIdle","pairIdle"};
+ // "run": the first (or only) model; "runSecond": a mixed tier's second model.
+ static constexpr std::array<const char*,4> names={"run","handoffIdle","pairIdle","runSecond"};
std::string message;
for(unsigned i=0;i<names.size();++i)message+=std::format(" {}MeanMs={:.4f} {}MaxMs={:.4f} {}Calls={}",names[i],gpuSamples[i]?gpuSum[i]/gpuSamples[i]:0,names[i],gpuMax[i],names[i],gpuSamples[i]);
log::info("vfg-gpu",message+" (CUDA events on the SDK stream; test profile)");
@@ -231,6 +256,58 @@ struct VfgBackend::Impl {
if(!cv(imageInit(buffer.image,width,height,int(footprint.Footprint.RowPitch),reinterpret_cast<void*>(buffer.pointer),pixelFormat,componentType,layout,1),"NvCVImage_Init"))return false;
return true;
}
+ // Root signature: 12 constants (b0), the previous/current input buffers as
+ // raw root SRVs (t0/t1) and the result buffer as a raw root UAV (u0). The
+ // shared inputs are plain byte buffers, so no descriptor heap is involved.
+ bool createShotChangeTest(){
+ std::vector<uint8_t> cs;if(!loadShaderBytes("VfgShotChange.dxil",cs))return false;
+ D3D12_ROOT_PARAMETER1 parameters[4]{};
+ parameters[0].ParameterType=D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;parameters[0].Constants.Num32BitValues=kShotChangeConstants;
+ parameters[1].ParameterType=D3D12_ROOT_PARAMETER_TYPE_SRV;parameters[1].Descriptor.ShaderRegister=0;
+ parameters[2].ParameterType=D3D12_ROOT_PARAMETER_TYPE_SRV;parameters[2].Descriptor.ShaderRegister=1;
+ parameters[3].ParameterType=D3D12_ROOT_PARAMETER_TYPE_UAV;parameters[3].Descriptor.ShaderRegister=0;
+ for(auto& parameter:parameters)parameter.ShaderVisibility=D3D12_SHADER_VISIBILITY_ALL;
+ D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{};desc.Version=D3D_ROOT_SIGNATURE_VERSION_1_1;
+ desc.Desc_1_1.NumParameters=4;desc.Desc_1_1.pParameters=parameters;
+ Microsoft::WRL::ComPtr<ID3DBlob> blob,error;
+ if(!hr(D3D12SerializeVersionedRootSignature(&desc,&blob,&error),"serialize shot-change root signature")||
+ !hr(context->device()->CreateRootSignature(0,blob->GetBufferPointer(),blob->GetBufferSize(),IID_PPV_ARGS(&cutRoot)),"CreateRootSignature shot change"))return false;
+ D3D12_COMPUTE_PIPELINE_STATE_DESC pipeline{};pipeline.pRootSignature=cutRoot.Get();pipeline.CS={cs.data(),cs.size()};
+ if(!hr(context->device()->CreateComputePipelineState(&pipeline,IID_PPV_ARGS(&cutPso)),"CreateComputePipelineState shot change"))return false;
+ D3D12_HEAP_PROPERTIES heap{};heap.Type=D3D12_HEAP_TYPE_DEFAULT;
+ D3D12_RESOURCE_DESC buffer{};buffer.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;buffer.Width=kShotChangeBytes;buffer.Height=1;
+ buffer.DepthOrArraySize=1;buffer.MipLevels=1;buffer.SampleDesc.Count=1;buffer.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ buffer.Flags=D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
+ if(!hr(context->device()->CreateCommittedResource(&heap,D3D12_HEAP_FLAG_NONE,&buffer,D3D12_RESOURCE_STATE_COMMON,nullptr,IID_PPV_ARGS(&cutResults)),
+ "Create shot-change results"))return false;
+ cutState=D3D12_RESOURCE_STATE_COMMON;return true;
+ }
+ // Runs after the pair's current input was copied (COPY_DEST); leaves both
+ // inputs in COMMON for CUDA and the result in PREDICATION for copyOutput().
+ void recordShotChangeTest(ID3D12GraphicsCommandList* list,unsigned parity,bool compare){
+ auto* current=inputs[parity].resource.Get();auto* previous=inputs[1-parity].resource.Get();
+ std::array<D3D12_RESOURCE_BARRIER,3> barriers{};
+ transition(barriers[0],current,D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ transition(barriers[1],previous,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ transition(barriers[2],cutResults.Get(),cutState,D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ list->ResourceBarrier(UINT(barriers.size()),barriers.data());
+ // Same thresholds as the CPU scene analysis (core::SceneCadenceAnalyzer).
+ const core::SceneCadenceAnalyzer::Config scene{};
+ const std::array<float,6> thresholds={float(scene.sceneCutSadThreshold),float(scene.sceneCutHistogramThreshold),
+ float(scene.replacementSadThreshold),float(scene.replacementHistogramThreshold),float(scene.flashSadThreshold),float(scene.flashHistogramThreshold)};
+ std::array<uint32_t,kShotChangeConstants> constants={width,height,footprint.Footprint.RowPitch,format==DXGI_FORMAT_R10G10B10A2_UNORM?1u:0u,parity,compare?1u:0u};
+ std::memcpy(constants.data()+6,thresholds.data(),sizeof(thresholds));
+ list->SetComputeRootSignature(cutRoot.Get());list->SetPipelineState(cutPso.Get());
+ list->SetComputeRoot32BitConstants(0,kShotChangeConstants,constants.data(),0);
+ list->SetComputeRootShaderResourceView(1,previous->GetGPUVirtualAddress());
+ list->SetComputeRootShaderResourceView(2,current->GetGPUVirtualAddress());
+ list->SetComputeRootUnorderedAccessView(3,cutResults->GetGPUVirtualAddress());
+ list->Dispatch(1,1,1);
+ transition(barriers[0],current,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,D3D12_RESOURCE_STATE_COMMON);
+ transition(barriers[1],previous,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,D3D12_RESOURCE_STATE_COMMON);
+ transition(barriers[2],cutResults.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_STATE_PREDICATION);
+ list->ResourceBarrier(UINT(barriers.size()),barriers.data());cutState=D3D12_RESOURCE_STATE_PREDICATION;
+ }
void releaseBuffer(Buffer& buffer){
if(buffer.image){imageDestroy(buffer.image);buffer.image=nullptr;}
if(buffer.pointer){cu(cuMemFreeFn(buffer.pointer),"cuMemFree external mapping");buffer.pointer=0;}
@@ -254,25 +331,30 @@ struct VfgBackend::Impl {
// every subframe instead starts a new pair inside the SDK. Keep the
// same pair bound while selecting its remaining intermediate frames.
// capture() revisions also handle callers that start at another index.
- if(ok&&(sub==1||revision!=boundInputRevision||parity!=boundParity||reset!=boundReset)){
- ok=cv(cpuCall(3,[&]{return setImage(effect,"SrcImage0",inputs[reset?parity:1-parity].image);}),"SetImage previous")&&
- cv(cpuCall(4,[&]{return setImage(effect,"SrcImage1",inputs[parity].image);}),"SetImage current")&&
- cv(cpuCall(6,[&]{return setU32(effect,"ShotChange",reset?1u:0u);}),"SetU32 ShotChange");
- if(ok){boundInputRevision=revision;boundParity=parity;boundReset=reset;}
+ if(sub==1||revision!=lastRevision||parity!=lastParity||reset!=lastReset){
+ ++pairSerial;lastRevision=revision;lastParity=parity;lastReset=reset;
}
- if(ok&&boundMultiplier!=multiplier){
- ok=cv(cpuCall(7,[&]{return setU32(effect,"FrameMultiplier",multiplier);}),"SetU32 FrameMultiplier");
- if(ok)boundMultiplier=multiplier;
+ const bool second=mixed&&sub!=engine::vfgPrimarySubframe(multiplier);
+ auto& e=effects[second?1:0];
+ if(ok&&e.boundPair!=pairSerial){
+ ok=cv(cpuCall(3,[&]{return setImage(e.handle,"SrcImage0",inputs[reset?parity:1-parity].image);}),"SetImage previous")&&
+ cv(cpuCall(4,[&]{return setImage(e.handle,"SrcImage1",inputs[parity].image);}),"SetImage current")&&
+ cv(cpuCall(6,[&]{return setU32(e.handle,"ShotChange",reset?1u:0u);}),"SetU32 ShotChange");
+ if(ok)e.boundPair=pairSerial;
}
- ok=ok&&cv(cpuCall(5,[&]{return setImage(effect,"DstImage0",outputs[parity+2*(sub-1)].image);}),"SetImage output")&&
- cv(cpuCall(8,[&]{return setU32(effect,"FrameIndex",sub);}),"SetU32 FrameIndex");
+ if(ok&&e.boundMultiplier!=multiplier){
+ ok=cv(cpuCall(7,[&]{return setU32(e.handle,"FrameMultiplier",multiplier);}),"SetU32 FrameMultiplier");
+ if(ok)e.boundMultiplier=multiplier;
+ }
+ ok=ok&&cv(cpuCall(5,[&]{return setImage(e.handle,"DstImage0",outputs[parity+2*(sub-1)].image);}),"SetImage output")&&
+ cv(cpuCall(8,[&]{return setU32(e.handle,"FrameIndex",sub);}),"SetU32 FrameIndex");
if(ok){
if(rejectRun&&++runCount==rejectRun){log::warn("vfg","injected VFG Run rejection (test hook)");ok=false;}
- else ok=cv(cpuCall(9,[&]{return run(effect,1);}),"NvVFX_Run async");
+ else ok=cv(cpuCall(9,[&]{return run(e.handle,1);}),"NvVFX_Run async");
}
if(profiling){
if(ok&&cu(cuEventRecordFn(events[2*profileSlot+1],stream),"profile cuEventRecord")){
- profiledSub[profileSlot]=sub;profiledAfterGap[profileSlot]=profileGap;profileGap=false;++profileHead;
+ profiledSub[profileSlot]=sub;profiledSecond[profileSlot]=second;profiledAfterGap[profileSlot]=profileGap;profileGap=false;++profileHead;
}else profileGap=true;
}
// Publish rejection before releasing the consumer. Its GPU copy still
@@ -352,11 +434,14 @@ bool VfgBackend::initialize(gfx::D3D12DeviceContext& context,const std::wstring&
shutdown();
#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
auto& p=*impl_;
- if(context.adapter().vendorId!=0x10DE||!runtimeAvailable(root)||!width||!height||multiplier<2||multiplier>FrameBatch::Capacity||quality>2||
+ if(context.adapter().vendorId!=0x10DE||!runtimeAvailable(root)||!width||!height||multiplier<2||multiplier>FrameBatch::Capacity||quality>=engine::kVfgQualityCount||
(format!=DXGI_FORMAT_R8G8B8A8_UNORM&&format!=DXGI_FORMAT_R10G10B10A2_UNORM)){
log::error("vfg","unsupported adapter/runtime/dimensions/multiplier/quality/encoding");return false;
}
p.context=&context;p.width=width;p.height=height;p.format=format;p.maxMultiplier=multiplier;
+ p.mixed=engine::vfgMixedQuality(quality);
+ p.effects[0].mode=engine::vfgPrimaryMode(quality);p.effects[1].mode=engine::vfgSecondaryMode(quality);
+ p.gpuShotChange=GetEnvironmentVariableW(L"VEYRA_TEST_VFG_AUTO_SHOT_CHANGE",nullptr,0)==0;
p.profileCpu=GetEnvironmentVariableW(L"VEYRA_TEST_VFG_CPU_PROFILE",nullptr,0)>0;
wchar_t reject[16]{};
const auto rejectLength=GetEnvironmentVariableW(L"VEYRA_TEST_VFG_REJECT_RUN",reject,16);
@@ -413,7 +498,10 @@ bool VfgBackend::initialize(gfx::D3D12DeviceContext& context,const std::wstring&
BIND_IMAGE(imageInit,"NvCVImage_Init");BIND_IMAGE(fromD3D,"NvCVImage_FromD3DFormat");BIND_IMAGE(errorString,"NvCV_GetErrorStringFromCode");
#undef BIND_IMAGE
unsigned version=0;if(!p.cv(p.getVersion(&version),"NvVFX_GetVersion"))return false;
- log::info("vfg",std::format("SDK version=0x{:08X} LUID={} compute={}.{} size={}x{} multiplier={} quality={} async=1",version,context.adapter().luidString,major,minor,width,height,multiplier,quality));
+ log::info("vfg",std::format("SDK version=0x{:08X} LUID={} compute={}.{} size={}x{} multiplier={} quality={} models={}{} shotChange={} async=1",
+ version,context.adapter().luidString,major,minor,width,height,multiplier,quality,p.effects[0].mode,
+ p.mixed?std::format("+{} (middle subframe {} / others {})",p.effects[1].mode,p.effects[0].mode,p.effects[1].mode):std::string(),
+ p.gpuShotChange?"gpu-pair-test":"sdk-automatic"));
D3D12_RESOURCE_DESC texture{};texture.Dimension=D3D12_RESOURCE_DIMENSION_TEXTURE2D;texture.Width=width;texture.Height=height;texture.DepthOrArraySize=1;texture.MipLevels=1;texture.Format=format;texture.SampleDesc.Count=1;
UINT rows=0;uint64_t rowBytes=0,total=0;context.device()->GetCopyableFootprints(&texture,0,1,0,&p.footprint,&rows,&rowBytes,&total);
p.bytes=uint64_t(p.footprint.Footprint.RowPitch)*height;
@@ -431,14 +519,23 @@ bool VfgBackend::initialize(gfx::D3D12DeviceContext& context,const std::wstring&
if(!hr(context.device()->CreateFence(0,D3D12_FENCE_FLAG_SHARED,IID_PPV_ARGS(&p.producer)),"CreateFence producer")||
!hr(context.device()->CreateFence(0,D3D12_FENCE_FLAG_SHARED,IID_PPV_ARGS(&p.completion)),"CreateFence completion")||
!p.importFence(p.producer.Get(),p.inputSemaphore)||!p.importFence(p.completion.Get(),p.outputSemaphore))return false;
- if(!p.cv(p.create("VideoFrameGeneration",&p.effect),"NvVFX_CreateEffect")||
- !p.cv(p.setStream(p.effect,"CudaStream",p.stream),"SetCudaStream")||
- !p.cv(p.setU32(p.effect,"InputWidth",width),"InputWidth")||!p.cv(p.setU32(p.effect,"InputHeight",height),"InputHeight")||
- !p.cv(p.setU32(p.effect,"Mode",quality),"Mode")||!p.cv(p.setU32(p.effect,"AutomaticShotChangeDetectionEnabled",1),"AutomaticShotChangeDetectionEnabled")||
- !p.cv(p.setImage(p.effect,"SrcImage0",p.inputs[0].image),"initial previous")||!p.cv(p.setImage(p.effect,"SrcImage1",p.inputs[1].image),"initial current")||
- !p.cv(p.loadEffect(p.effect),"NvVFX_Load")||!p.cv(p.setImage(p.effect,"DstImage0",p.outputs[0].image),"initial output")||
- !p.cv(p.setU32(p.effect,"FrameMultiplier",multiplier),"initial multiplier"))return false;
- p.boundMultiplier=multiplier;
+ // With the GPU pair test the SDK's own detection is off: it made every
+ // NvVFX_Run wait on the GPU (measured 2026-10-11: host 3.5 ms -> 0.13 ms per
+ // 4K Run) and repeated per subframe (+0.2 ms GPU each).
+ const unsigned automaticShotChange=p.gpuShotChange?0u:1u;
+ const unsigned effectCount=p.mixed?2u:1u;
+ for(unsigned i=0;i<effectCount;++i){
+ auto& e=p.effects[i];
+ if(!p.cv(p.create("VideoFrameGeneration",&e.handle),"NvVFX_CreateEffect")||
+ !p.cv(p.setStream(e.handle,"CudaStream",p.stream),"SetCudaStream")||
+ !p.cv(p.setU32(e.handle,"InputWidth",width),"InputWidth")||!p.cv(p.setU32(e.handle,"InputHeight",height),"InputHeight")||
+ !p.cv(p.setU32(e.handle,"Mode",e.mode),"Mode")||!p.cv(p.setU32(e.handle,"AutomaticShotChangeDetectionEnabled",automaticShotChange),"AutomaticShotChangeDetectionEnabled")||
+ !p.cv(p.setImage(e.handle,"SrcImage0",p.inputs[0].image),"initial previous")||!p.cv(p.setImage(e.handle,"SrcImage1",p.inputs[1].image),"initial current")||
+ !p.cv(p.loadEffect(e.handle),i?"NvVFX_Load second model":"NvVFX_Load")||!p.cv(p.setImage(e.handle,"DstImage0",p.outputs[0].image),"initial output")||
+ !p.cv(p.setU32(e.handle,"FrameMultiplier",multiplier),"initial multiplier"))return false;
+ e.boundMultiplier=multiplier;
+ }
+ if(p.gpuShotChange&&!p.createShotChangeTest())return false;
p.asynchronous=asynchronousSubmission;
if(p.asynchronous){
try{p.worker=std::thread([&p]{p.work();});}
@@ -458,7 +555,7 @@ bool VfgBackend::created()const{
return false;
#endif
}
-bool VfgBackend::capture(ID3D12GraphicsCommandList* list,ID3D12Resource* texture,unsigned parity){
+bool VfgBackend::capture(ID3D12GraphicsCommandList* list,ID3D12Resource* texture,unsigned parity,bool comparePrevious){
#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
auto& p=*impl_;if(!p.ready||p.failed.load()||!list||!texture||parity>1)return false;
const auto desc=texture->GetDesc();if(desc.Width!=p.width||desc.Height!=p.height||desc.Format!=p.format)return false;
@@ -468,9 +565,11 @@ bool VfgBackend::capture(ID3D12GraphicsCommandList* list,ID3D12Resource* texture
D3D12_TEXTURE_COPY_LOCATION src{};src.pResource=texture;src.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
D3D12_TEXTURE_COPY_LOCATION dst{};dst.pResource=buffer;dst.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;dst.PlacedFootprint=p.footprint;
list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);
- std::swap(barrier.Transition.StateBefore,barrier.Transition.StateAfter);list->ResourceBarrier(1,&barrier);++p.inputRevision;return true;
+ if(p.gpuShotChange)p.recordShotChangeTest(list,parity,comparePrevious);
+ else{std::swap(barrier.Transition.StateBefore,barrier.Transition.StateAfter);list->ResourceBarrier(1,&barrier);}
+ ++p.inputRevision;return true;
#else
- (void)list;(void)texture;(void)parity;return false;
+ (void)list;(void)texture;(void)parity;(void)comparePrevious;return false;
#endif
}
bool VfgBackend::generate(unsigned parity,unsigned sub,unsigned multiplier,bool reset){
@@ -493,16 +592,46 @@ bool VfgBackend::copyOutput(ID3D12GraphicsCommandList* list,ID3D12Resource* text
auto& p=*impl_;if(!p.ready||!list||!texture||slot>=2*(p.maxMultiplier-1))return false;
const auto desc=texture->GetDesc();if(desc.Width!=p.width||desc.Height!=p.height||desc.Format!=p.format)return false;
auto* buffer=p.outputs[slot].resource.Get();
- D3D12_RESOURCE_BARRIER barrier{};barrier.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;barrier.Transition={buffer,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_SOURCE};
- list->ResourceBarrier(1,&barrier);
D3D12_TEXTURE_COPY_LOCATION src{};src.pResource=buffer;src.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;src.PlacedFootprint=p.footprint;
D3D12_TEXTURE_COPY_LOCATION dst{};dst.pResource=texture;dst.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ if(!p.gpuShotChange){
+ D3D12_RESOURCE_BARRIER barrier{};transition(barrier,buffer,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_SOURCE);
+ list->ResourceBarrier(1,&barrier);
+ list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);
+ std::swap(barrier.Transition.StateBefore,barrier.Transition.StateAfter);list->ResourceBarrier(1,&barrier);return true;
+ }
+ // On a cut every subframe of the pair shows the current input B, as the
+ // SDK's own detection did. The GPU picks the copy source by predication on
+ // the pair test result: no readback, no CPU wait, no extra pass.
+ auto* current=p.inputs[slot%2].resource.Get();
+ std::array<D3D12_RESOURCE_BARRIER,3> barriers{};UINT count=2;
+ transition(barriers[0],buffer,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_SOURCE);
+ transition(barriers[1],current,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_SOURCE);
+ if(p.cutState!=D3D12_RESOURCE_STATE_PREDICATION){
+ transition(barriers[2],p.cutResults.Get(),p.cutState,D3D12_RESOURCE_STATE_PREDICATION);count=3;p.cutState=D3D12_RESOURCE_STATE_PREDICATION;
+ }
+ list->ResourceBarrier(count,barriers.data());
+ const UINT64 flag=(slot%2)*8;
+ list->SetPredication(p.cutResults.Get(),flag,D3D12_PREDICATION_OP_NOT_EQUAL_ZERO); // skipped on a cut
list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);
- std::swap(barrier.Transition.StateBefore,barrier.Transition.StateAfter);list->ResourceBarrier(1,&barrier);return true;
+ src.pResource=current;
+ list->SetPredication(p.cutResults.Get(),flag,D3D12_PREDICATION_OP_EQUAL_ZERO); // skipped unless a cut
+ list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);
+ list->SetPredication(nullptr,0,D3D12_PREDICATION_OP_EQUAL_ZERO);
+ transition(barriers[0],buffer,D3D12_RESOURCE_STATE_COPY_SOURCE,D3D12_RESOURCE_STATE_COMMON);
+ transition(barriers[1],current,D3D12_RESOURCE_STATE_COPY_SOURCE,D3D12_RESOURCE_STATE_COMMON);
+ list->ResourceBarrier(2,barriers.data());return true;
#else
(void)list;(void)texture;(void)slot;return false;
#endif
}
+ID3D12Resource* VfgBackend::shotChangeResultsForTest()const{
+#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
+ return impl_->gpuShotChange?impl_->cutResults.Get():nullptr;
+#else
+ return nullptr;
+#endif
+}
void VfgBackend::shutdown(){
#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
auto& p=*impl_;p.ready=false;p.stopWorker();
@@ -512,7 +641,7 @@ void VfgBackend::shutdown(){
// This is teardown, not per-frame synchronization. The graph owner
// drains its direct queue before destroying shared staging buffers.
if(p.stream)p.cu(p.cuStreamSynchronizeFn(p.stream),"teardown cuStreamSynchronize");
- if(p.effect){p.destroy(p.effect);p.effect=nullptr;log::info("vfg","NvVFX_DestroyEffect completed (void API)");}
+ for(auto& e:p.effects)if(e.handle){p.destroy(e.handle);e.handle=nullptr;log::info("vfg","NvVFX_DestroyEffect completed (void API)");}
for(auto& b:p.outputs)p.releaseBuffer(b);for(auto& b:p.inputs)p.releaseBuffer(b);
for(auto event:p.events)if(event)p.cu(p.cuEventDestroyFn(event),"cuEventDestroy profile");
if(p.outputSemaphore)p.cu(p.cuDestroyExternalSemaphoreFn(p.outputSemaphore),"destroy output semaphore");
diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cpp
index 495e210d..7337ad1c 100644
--- a/src/ui/QmlPlayerBridge.cpp
+++ b/src/ui/QmlPlayerBridge.cpp
@@ -1807,7 +1807,7 @@ QVariantList QmlPlayerBridge::fgMultiplierChoices() const {
int QmlPlayerBridge::vfgQuality()const{return int(settings().vfgQuality);}
void QmlPlayerBridge::setVfgQuality(int value){
- if(value<0||value>2)return;auto s=settings();if(s.vfgQuality==uint32_t(value))return;
+ if(value<0||uint32_t(value)>=engine::kVfgQualityCount)return;auto s=settings();if(s.vfgQuality==uint32_t(value))return;
s.vfgQuality=uint32_t(value);
if(!impl_->commit(s)){emit notice(tr("VFG 质量设置未被接受,原设置保留"),true);return;}
emit settingsChanged();emit chainChanged();
@@ -6318,10 +6318,21 @@ void QmlPlayerBridge::updateRunStatus() {
const auto perRun = f.gpuTiming[size_t(diagnostics::GpuStage::Fg1)].p95;
const auto batch = f.gpuTiming[size_t(diagnostics::GpuStage::FgBatch)].p95;
const auto whole = f.enhancementProcessing.p95;
- if (s.fgBudgetLimited && source > 1 && perRun && *perRun > 0 && batch && whole) {
- const double base = std::max(0.0, *whole - *batch);
- const int fits = std::clamp(1 + int(std::floor((1000.0 / source - base) / *perRun)), 1, int(s.applied.multiplier));
- if (fits < int(s.applied.multiplier)) detail << tr("VFG 每张约 %1 ms,当前负载约可稳定 %2X").arg(*perRun, 0, 'f', 1).arg(fits);
+ // A mixed tier runs its first model once per pair (the middle
+ // subframe) and the second model for the others; Fg1 is then a
+ // second-model subframe whenever the group has more than one.
+ const bool mixed = engine::vfgMixedQuality(s.applied.vfgQuality) && s.applied.multiplier > 2;
+ const auto middleStage = diagnostics::GpuStage(unsigned(diagnostics::GpuStage::Fg1) + engine::vfgPrimarySubframe(s.applied.multiplier) - 1);
+ const auto middle = mixed ? f.gpuTiming[size_t(middleStage)].p95 : perRun;
+ if (s.fgBudgetLimited && source > 1 && perRun && *perRun > 0 && middle && *middle > 0 && batch && whole) {
+ const double base = std::max(0.0, *whole - *batch), budget = 1000.0 / source - base;
+ // generated = 1 middle + k others; fits = generated + the real frame.
+ const int generated = budget < *middle ? 0 : 1 + int(std::floor((budget - *middle) / *perRun));
+ const int fits = std::clamp(1 + generated, 1, int(s.applied.multiplier));
+ if (fits < int(s.applied.multiplier)) {
+ if (mixed) detail << tr("VFG 中间帧约 %1 ms、其余每张约 %2 ms,当前负载约可稳定 %3X").arg(*middle, 0, 'f', 1).arg(*perRun, 0, 'f', 1).arg(fits);
+ else detail << tr("VFG 每张约 %1 ms,当前负载约可稳定 %2X").arg(*perRun, 0, 'f', 1).arg(fits);
+ }
}
double refresh = 0;
for (auto* window : QGuiApplication::topLevelWindows())
diff --git a/tests/integration/VfgGpuTests.cpp b/tests/integration/VfgGpuTests.cpp
index eb81887b..87b29836 100644
--- a/tests/integration/VfgGpuTests.cpp
+++ b/tests/integration/VfgGpuTests.cpp
@@ -2,6 +2,7 @@
// Product-library VFG test. Pixel readback and final CPU waits are diagnostic
// only; production uses the same GPU handoff and leased textures without them.
#include "veyra/pipeline/VfgBackend.h"
+#include "veyra/engine/EnhancementSettings.h"
#include "veyra/pipeline/GpuPassUtils.h"
#include "veyra/gfx/D3D12DeviceContext.h"
#include "veyra/gfx/CommandSlotRing.h"
@@ -42,7 +43,7 @@ int wmain(int argc,wchar_t** argv){
const auto desc=textures[0]->GetDesc();D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};UINT rows=0;uint64_t rowBytes=0,total=0;
ctx.device()->GetCopyableFootprints(&desc,0,1,0,&fp,&rows,&rowBytes,&total);
const uint64_t bytes=uint64_t(fp.Footprint.RowPitch)*h;
- auto upload=pipeline::makeUploadBuffer(ctx.device(),bytes*2);auto readback=makeReadback(ctx.device(),bytes*7);if(!upload||!readback)return 2;
+ auto upload=pipeline::makeUploadBuffer(ctx.device(),bytes*3);auto readback=makeReadback(ctx.device(),bytes*7);if(!upload||!readback)return 2;
void* mapped=nullptr;if(FAILED(upload->Map(0,nullptr,&mapped)))return 2;
std::array<double,2> inputCentroid{};
for(unsigned p=0;p<2;++p){double sum=0,weighted=0;
@@ -55,8 +56,24 @@ int wmain(int argc,wchar_t** argv){
else{const uint32_t packed=(r*1023/255)|((g*1023/255)<<10)|((b*1023/255)<<20)|(3u<<30);std::memcpy(pixel,&packed,4);}
}inputCentroid[p]=weighted/sum;
}
+ // Frame 2: an unrelated bright checkerboard, i.e. a hard cut after either frame.
+ for(unsigned y=0;y<h;++y)for(unsigned x=0;x<w;++x){
+ const unsigned v=((x/64)+(y/64))%2?220:60;auto* pixel=static_cast<uint8_t*>(mapped)+2*bytes+y*fp.Footprint.RowPitch+x*4;
+ if(format==DXGI_FORMAT_R8G8B8A8_UNORM){pixel[0]=uint8_t(v);pixel[1]=uint8_t(255-v);pixel[2]=uint8_t(v);pixel[3]=255;}
+ else{const uint32_t packed=(v*1023/255)|(((255-v)*1023/255)<<10)|((v*1023/255)<<20)|(3u<<30);std::memcpy(pixel,&packed,4);}
+ }
+ auto cutTexture=pipeline::makeTexture(ctx.device(),w,h,format,false);if(!cutTexture)return 2;
+ auto results=makeReadback(ctx.device(),256);if(!results)return 2;
+ {uint32_t slot=0;auto* l=ring.acquireNext(slot,st);if(!l)return 2;
+ transition(l,cutTexture.Get(),D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_DEST);
+ D3D12_TEXTURE_COPY_LOCATION src{};src.pResource=upload.Get();src.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;src.PlacedFootprint=fp;src.PlacedFootprint.Offset=2*bytes;
+ D3D12_TEXTURE_COPY_LOCATION dst{};dst.pResource=cutTexture.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ l->CopyTextureRegion(&dst,0,0,0,&src,nullptr);transition(l,cutTexture.Get(),D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_COMMON);
+ if(!ring.submitAndSignal(slot))return 2;}
+ // Hashes of every single-model subframe: a mixed tier must reproduce them exactly.
+ std::array<std::array<std::array<uint64_t,7>,9>,engine::kVfgQualityCount> modelHashes{};
// Keep mapping for readback comparisons; upload memory is immutable.
- for(unsigned quality=0;quality<3;++quality){
+ for(unsigned quality=0;quality<engine::kVfgQualityCount;++quality){
pipeline::VfgBackend vfg;
if(!vfg.initialize(ctx,argv[1],w,h,format,8,quality,asynchronous)){std::puts("FAIL native VFG initialization");return 3;}
for(unsigned p=0;p<2;++p){uint32_t slot=0;auto* l=ring.acquireNext(slot,st);if(!l)return 2;
@@ -65,7 +82,7 @@ int wmain(int argc,wchar_t** argv){
D3D12_TEXTURE_COPY_LOCATION dst{};dst.pResource=textures[p].Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
l->CopyTextureRegion(&dst,0,0,0,&src,nullptr);
transition(l,textures[p].Get(),D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_COPY_SOURCE);
- check(vfg.capture(l,textures[p].Get(),p),"capture encoded GPU frame");
+ check(vfg.capture(l,textures[p].Get(),p,p!=0),"capture encoded GPU frame");
transition(l,textures[p].Get(),D3D12_RESOURCE_STATE_COPY_SOURCE,D3D12_RESOURCE_STATE_COMMON);
if(!ring.submitAndSignal(slot))return 2;
}
@@ -97,12 +114,16 @@ int wmain(int argc,wchar_t** argv){
const double value=red>40?red-16:0;sum+=value;weight+=value*x;
}
const auto center=sum?weight/sum:-1;std::printf("%.3f,",center);hashes.insert(hash);
- orderedHashes[sub-1]=hash;
+ orderedHashes[sub-1]=hash;modelHashes[quality][multiplier][sub-1]=hash;
check(center>previous-1&&center>inputCentroid[0]-1&&center<inputCentroid[1]+1,"intermediate red block advances between A/B");previous=center;
}
std::printf(" distinct=%zu hashes=",hashes.size());
for(unsigned sub=1;sub<multiplier;++sub)std::printf("%016llx,",static_cast<unsigned long long>(orderedHashes[sub-1]));
std::puts("");check(hashes.size()==multiplier-1,"all generated subframes distinct");
+ if(engine::vfgMixedQuality(quality))for(unsigned sub=1;sub<multiplier;++sub){
+ const unsigned model=sub==engine::vfgPrimarySubframe(multiplier)?engine::vfgPrimaryMode(quality):engine::vfgSecondaryMode(quality);
+ check(orderedHashes[sub-1]==modelHashes[model][multiplier][sub-1],"mixed tier subframe equals the single-model output of its model");
+ }
D3D12_RANGE written{0,0};readback->Unmap(0,&written);
}
// Manual cut must not reuse the previous input; clear ShotChange on
@@ -213,6 +234,56 @@ int wmain(int argc,wchar_t** argv){
std::printf("VFG_EDGE format=%u quality=%u centers=",unsigned(format),quality);for(double center:centers)std::printf("%.3f,",center);std::puts("");
readback->Unmap(0,&written);
check(!vfg.generate(1,8,8,false)&&!vfg.generate(2,1,2,false)&&!vfg.generate(0,1,9,false),"invalid slot/multiplier rejected");
+ // Hard cut A -> checkerboard with ShotChange unset: every subframe must
+ // show B (GPU pair test + predicated copy, or the SDK's own detection
+ // under VEYRA_TEST_VFG_AUTO_SHOT_CHANGE=1). Then cut back, and a normal
+ // pair must interpolate again (the predicate is per pair).
+ const auto capturePair=[&](ID3D12Resource* a,ID3D12Resource* b){
+ for(unsigned p=0;p<2;++p){auto* l=ring.acquireNext(slot,st);if(!l)return false;auto* texture=p?b:a;
+ transition(l,texture,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_SOURCE);
+ if(!vfg.capture(l,texture,p,true))return false;
+ transition(l,texture,D3D12_RESOURCE_STATE_COPY_SOURCE,D3D12_RESOURCE_STATE_COMMON);
+ if(!ring.submitAndSignal(slot))return false;}
+ return true;
+ };
+ const auto cutCount=[&]()->int{
+ auto* buffer=vfg.shotChangeResultsForTest();if(!buffer)return -1;
+ auto* l=ring.acquireNext(slot,st);if(!l)return -2;
+ transition(l,buffer,D3D12_RESOURCE_STATE_PREDICATION,D3D12_RESOURCE_STATE_COPY_SOURCE);l->CopyBufferRegion(results.Get(),0,buffer,0,256);
+ transition(l,buffer,D3D12_RESOURCE_STATE_COPY_SOURCE,D3D12_RESOURCE_STATE_PREDICATION);
+ if(!ring.submitAndSignal(slot)||!ring.waitIdle())return -2;
+ void* data=nullptr;D3D12_RANGE all{0,256};if(FAILED(results->Map(0,&all,&data)))return -2;
+ const auto* words=static_cast<const uint32_t*>(data);const int count=int(words[12]);
+ float sad=0,histogram=0;std::memcpy(&sad,words+8,4);std::memcpy(&histogram,words+9,4);
+ std::printf("VFG_SHOT_CHANGE parity1 flag=%u sad=%.4f histogram=%.4f cuts=%d\n",words[2],sad,histogram,count);
+ results->Unmap(0,&written);return count;
+ };
+ check(capturePair(textures[0].Get(),cutTexture.Get()),"capture cut pair");
+ for(unsigned sub=1;sub<4;++sub)check(consume(sub,sub-1),"cut pair subframes queued");
+ check(ring.waitIdle(),"cut pair completion");
+ range={0,size_t(bytes*3)};if(FAILED(readback->Map(0,&range,&pixels)))return 2;
+ unsigned cutError=0;for(unsigned sub=0;sub<3;++sub)for(unsigned y=0;y<h;++y)for(unsigned x=0;x<w*4;++x){
+ const auto a=static_cast<uint8_t*>(pixels)[sub*bytes+y*fp.Footprint.RowPitch+x];const auto b=static_cast<uint8_t*>(mapped)[2*bytes+y*fp.Footprint.RowPitch+x];
+ cutError=std::max(cutError,unsigned(std::abs(int(a)-int(b))));}
+ readback->Unmap(0,&written);std::printf("VFG_CUT format=%u quality=%u maxByteError=%u\n",unsigned(format),quality,cutError);
+ check(cutError<=2,"undeclared cut shows the current input in every subframe");
+ const int afterCut=cutCount();if(afterCut!=-1)check(afterCut==1,"GPU pair test found exactly the one cut");
+ check(capturePair(cutTexture.Get(),textures[1].Get())&&capturePair(textures[0].Get(),textures[1].Get()),"cut back, then a normal pair");
+ for(unsigned sub=1;sub<4;++sub)check(consume(sub,sub-1),"normal pair after cut queued");
+ check(ring.waitIdle(),"normal pair after cut completion");
+ range={0,size_t(bytes*3)};if(FAILED(readback->Map(0,&range,&pixels)))return 2;
+ for(unsigned sub=0;sub<3;++sub){double sum=0,weight=0;
+ for(unsigned y=0;y<h;++y)for(unsigned x=0;x<w;++x){
+ const auto* pixel=static_cast<uint8_t*>(pixels)+sub*bytes+y*fp.Footprint.RowPitch+x*4;
+ unsigned red=pixel[0];if(format!=DXGI_FORMAT_R8G8B8A8_UNORM){uint32_t packed=0;std::memcpy(&packed,pixel,4);red=(packed&1023)*255/1023;}
+ const double v=red>40?red-16:0;sum+=v;weight+=v*x;}
+ const double center=sum?weight/sum:-1;
+ check(center>inputCentroid[0]+1&&center<inputCentroid[1]-1,"normal pair after a cut is interpolated again");
+ }
+ readback->Unmap(0,&written);
+ // Pair tests that crossed a cut: into the checkerboard and out of it.
+ // Every other capture (identical or shifted frames) must stay unflagged.
+ const int afterReturn=cutCount();if(afterReturn!=-1)check(afterReturn==2,"cut back counted; normal pairs never flagged");
vfg.shutdown();
}
D3D12_RANGE written{0,0};upload->Unmap(0,&written);
diff --git a/tests/unit/VfgSettingsTests.cpp b/tests/unit/VfgSettingsTests.cpp
index b2d06c6b..462fa97d 100644
--- a/tests/unit/VfgSettingsTests.cpp
+++ b/tests/unit/VfgSettingsTests.cpp
@@ -45,7 +45,12 @@ int wmain(int argc,wchar_t** argv){
PresetStore legacyReader(root/L"legacy.txt");check(legacyReader.load()&&legacyReader.entries()[0].settings.vfgQuality==1,"old presets default to Medium");
const auto original=bytes(root/L"legacy.txt");
PresetStore store(root/L"settings.txt");check(store.load(),"new store");
- for(unsigned quality=0;quality<3;++quality)for(unsigned m=2;m<=8;++m){
+ // Mixed tiers: the middle subframe runs the first model, the others the second.
+ check(!vfgMixedQuality(0)&&!vfgMixedQuality(2)&&vfgMixedQuality(3)&&vfgMixedQuality(5)&&!vfgMixedQuality(6),"mixed VFG tiers are 3-5");
+ check(vfgPrimaryMode(3)==2&&vfgSecondaryMode(3)==1&&vfgPrimaryMode(4)==2&&vfgSecondaryMode(4)==0&&vfgPrimaryMode(5)==1&&vfgSecondaryMode(5)==0,"High+Medium, High+Low, Medium+Low");
+ for(unsigned q=0;q<3;++q)check(vfgPrimaryMode(q)==q&&vfgSecondaryMode(q)==q,"single-model tiers keep their mode");
+ check(vfgPrimarySubframe(2)==1&&vfgPrimarySubframe(3)==2&&vfgPrimarySubframe(4)==2&&vfgPrimarySubframe(5)==3&&vfgPrimarySubframe(6)==3&&vfgPrimarySubframe(7)==4&&vfgPrimarySubframe(8)==4,"first model on the middle subframe");
+ for(unsigned quality=0;quality<kVfgQualityCount;++quality)for(unsigned m=2;m<=8;++m){
EnhancementSettings s;s.frameGenerationBackend=FrameGenerationBackend::Vfg;s.multiplier=m;s.vfgQuality=quality;
check(s.validate().empty(),"VFG legal multiplier/quality");
const auto name=std::to_wstring(m)+L"x-q"+std::to_wstring(quality);
@@ -57,7 +62,7 @@ int wmain(int argc,wchar_t** argv){
check(reloaded.load()&&reloaded.entries().size()==1&&reloaded.entries()[0]==*e,"library restores full VFG state");
auto applied=legacy;PresetLibrary::apply(*e,applied);
check(applied.multiplier==m&&applied.frameGenerationBackend==FrameGenerationBackend::Vfg&&applied.vfgQuality==quality,"preset applies multiplier backend quality");
- e->contents=presetContentMask(PresetContent::Color);applied=s;applied.vfgQuality=(quality+1)%3;
+ e->contents=presetContentMask(PresetContent::Color);applied=s;applied.vfgQuality=(quality+1)%kVfgQualityCount;
const auto kept=applied.vfgQuality;PresetLibrary::apply(*e,applied);
check(applied.frameGenerationBackend==FrameGenerationBackend::Vfg&&applied.multiplier==m&&applied.vfgQuality==kept,"partial color preset preserves VFG");
auto session=std::make_unique<ChainSession>(ChainSession::initial(s));check(session->select(ChainMode::Node),"VFG node mode initializes");
@@ -68,7 +73,7 @@ int wmain(int argc,wchar_t** argv){
const auto sessionPath=root/(name+L".session");ChainSessionStore sessionWriter(sessionPath);
check(sessionWriter.save(*session),"session atomic save");ChainSessionStore sessionReader(sessionPath);
check(sessionReader.load(*restored)&&*session==*restored,"session restart finds VFG suffix");
- auto bad=s;bad.multiplier=9;check(!bad.validate().empty(),"reject VFG 9X");bad=s;bad.vfgQuality=3;check(!bad.validate().empty(),"reject unknown quality");
+ auto bad=s;bad.multiplier=9;check(!bad.validate().empty(),"reject VFG 9X");bad=s;bad.vfgQuality=kVfgQualityCount;check(!bad.validate().empty(),"reject unknown quality");
bad=s;bad.frameGenerationBackend=FrameGenerationBackend::Dlss;if(m>6)check(!bad.validate().empty(),"DLSS ceiling remains 6X");
veyra::pipeline::FrameBatch batch;batch.identity={1,2,3};batch.a100ns=10000000;batch.b100ns=10333333;
for(unsigned j=1;j<m;++j){veyra::pipeline::BatchFrame f;f.identity=batch.identity;f.subframe=j;f.pts100ns=batch.interpolate(batch.a100ns,batch.b100ns,j,m);f.kind=veyra::pipeline::FrameKind::Generated;batch.append(f);}
@@ -76,8 +81,8 @@ int wmain(int argc,wchar_t** argv){
check(batch.count==m&&batch.frames[m-1].pts100ns==batch.b100ns,"2..8 ordered PTS with every source frame");
if(m==8){bool rejected=false;try{real.pts100ns++;batch.append(real);}catch(const std::invalid_argument&){rejected=true;}check(rejected&&batch.count==8,"8X batch rejects ninth frame");}
}
- PresetStore restoredStore(root/L"settings.txt");check(restoredStore.load()&&restoredStore.entries().size()==21,"all VFG settings restored");
- for(const auto& e:restoredStore.entries())check(e.settings.frameGenerationBackend==FrameGenerationBackend::Vfg&&e.settings.vfgQuality<3&&e.settings.multiplier>=2&&e.settings.multiplier<=8,"stored VFG values legal");
+ PresetStore restoredStore(root/L"settings.txt");check(restoredStore.load()&&restoredStore.entries().size()==7*kVfgQualityCount,"all VFG settings restored");
+ for(const auto& e:restoredStore.entries())check(e.settings.frameGenerationBackend==FrameGenerationBackend::Vfg&&e.settings.vfgQuality<kVfgQualityCount&&e.settings.multiplier>=2&&e.settings.multiplier<=8,"stored VFG values legal");
check(bytes(root/L"legacy.txt")==original,"legacy file unchanged");
std::cout<<"VFG settings "<<checks<<" checks, "<<failures<<" failures\n";return failures?1:0;
}