Separate the SDK and Qt sample build projects

Compared with f612cfd:

- Move the capture SDK, private IOCTL wrapper, and optional preview helper under GVFG_SDK with an independent top-level CMake project and version source.

- Move the Qt preview application into GVFG_Qt_Sample and consume prebuilt SDK DLLs and compiler-specific import libraries through imported CMake targets instead of compiling SDK sources as subdirectories.

- Resolve Qt Creator configuration-specific SDK build directories automatically, copy the three runtime DLLs beside the sample executable, and keep missing MSVC or MinGW artifacts as explicit configure errors.

- Update Release and Debug packaging scripts to read SDK and sample outputs separately, and update the repository build instructions for the two-project workflow.

- Preserve the pre-existing uncommitted device display-name suffix change outside this commit.

Validation: independent MSVC SDK configure/build and independent Qt MSVC sample configure/build passed; the sample build graph contains no SDK implementation sources; git diff --check passed. No MinGW link, runtime launch, capture, audio playback, or hardware validation was run.
This commit is contained in:
Mark.lin
2026-09-11 13:28:56 +08:00
parent f612cfd11b
commit cae4a04612
39 changed files with 205 additions and 113 deletions
@@ -0,0 +1,48 @@
project(gvfg_preview LANGUAGES CXX)
add_library(gvfg_preview SHARED
include/gvfg_preview.h
../../sdk/gvfg/src/gpu/d3d_conversion_pipeline.cpp
../../sdk/gvfg/src/gpu/d3d_conversion_pipeline.h
src/gvfg_preview.cpp
)
set_target_properties(gvfg_preview PROPERTIES
AUTOMOC OFF
AUTOUIC OFF
AUTORCC OFF
)
target_include_directories(gvfg_preview
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/include
PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src
${CMAKE_CURRENT_SOURCE_DIR}/../../sdk/gvfg/src/gpu
)
target_compile_definitions(gvfg_preview PRIVATE
GVFG_PREVIEW_BUILD
GVFG_INTERNAL_DIAGNOSTICS=$<IF:$<CONFIG:Debug>,1,0>
)
target_link_libraries(gvfg_preview
PRIVATE
user32
dxgi
d3d11
D3DCompiler
)
if (MSVC)
target_compile_options(gvfg_preview PRIVATE /utf-8 /EHsc)
endif()
install(TARGETS gvfg_preview
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
)
install(FILES include/gvfg_preview.h
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
@@ -0,0 +1,30 @@
# Preview GPU path
The preview worker now runs:
1. Execute the upload slot's command list (the SDK frame was already released by the caller).
2. Convert packed YUY2/Y210 into a full-resolution FP16 target.
3. Sample that FP16 target directly into the 8-bit or 10-bit swapchain, preserving aspect ratio.
4. Present(0, 0). DXGI handles presentation waits; no application retry loop.
Compared with the previous preview, this removes one full-frame FP16 CopyResource per image. The 8-bit path also removes an intermediate BGRA8 draw and quantizes only at the swapchain. FP16 precision and the requested swapchain bit depth remain; no capture-frame decimation was added. Scaled 8-bit output may differ slightly because rounding now occurs after scaling instead of before it.
Each of the four upload slots owns its SRV; the worker no longer creates an SRV for every preview frame. YUY2/Y210 shaders use one packed texture load per output pixel. The old ProcAmp settings were fixed at neutral, so unused neighbor sharpness reads and neutral color adjustments were removed; BT.709 coefficients, packing, Y210 word shifts and odd-tail chroma behavior remain. Constant-buffer data updates only when source dimensions change, but its binding is restored each draw.
Preview-only resource initialization allocates only the FP16 conversion target, omitting scene, BGRA8 export, RGB10 export and NV12 planes. Export conversion still uses the default full resource path; no public capture or buffer API signature changed. Export shaders are not compiled for preview-only initialization.
Swapchain resize/release unbinds the render target before releasing local references. Preview configuration/resource changes and drawing share the D3D mutex. No GPU mutex is held while subsequently acquiring the renderer mutex in the worker completion path.
## Validation boundary
Source checks only in this change: no application/shader build, GPU timing or hardware playback test. These changes remove identifiable work but do not establish a GPU utilization reduction or identify the reported 10-bit startup failure.
User validation reported after the source change: GPU utilization decreased by approximately 15%. This is a user-reported observation, not an agent-run benchmark; baseline/final readings and whether the difference is relative or in percentage points were not specified. Resolution of the 10-bit startup failure was not reported.
Build the preview DLL with the changed shared pipeline source. If distributing the SDK GPU buffer converter, rebuild that DLL too because it shares the shader source. Keep the APP and preview DLL from the same delivery-statistics API revision.
On the target Ryzen 7 7700 system, compare identical resolution/FPS/window size and input formats before/after. Check 8-bit and 10-bit colors (including gradients), resize/fullscreen, repeated Start/Stop, Present skip counts and GPU engine utilization. Also verify public BGRA8/RGB10A2/NV12 buffer conversion if shipping its rebuilt DLL. Capture HRESULT details if 10-bit still fails; do not infer insufficient GPU capacity solely from utilization.
Expected preview pacing skips and audio queue evictions remain internal counters and are not logged. Preview/render failures, frame-ID anomalies, audio write failures, and delivery-accounting mismatches are logged as errors, aggregated at most once per five seconds. Mutex/drain/join waits service synchronous Windows sent messages without dispatching queued application input. Blocking Present still has no application timeout; device hangs and window transitions require hardware validation.
Preview queue policy: three pending/upload-reserved slots plus one presenting slot. Consume in enqueue order, keep frames within a 50 ms queue-age limit, and skip incoming frames only when capacity is full. Expired queued frames are counted in the existing replaced field (APP label: expired). This is not a 50 ms bound on blocking Present or physical scanout.
@@ -0,0 +1,165 @@
#pragma once
/*
* Optional GVFG preview helper API.
*
* Standalone preview helper. Applications provide the frame buffer, pixel
* format, and row stride explicitly; gvfg_preview.dll does not depend on
* gvfg.dll.
*/
#include <stdint.h>
#ifdef _WIN32
#ifdef GVFG_PREVIEW_BUILD
#define GVFG_PREVIEW_API __declspec(dllexport)
#else
#define GVFG_PREVIEW_API __declspec(dllimport)
#endif
#else
#define GVFG_PREVIEW_API
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef enum
{
GVFG_PREVIEW_OK = 0,
GVFG_PREVIEW_EINVAL = -1,
GVFG_PREVIEW_ESTATE = -2,
GVFG_PREVIEW_ENOTSUP = -3,
GVFG_PREVIEW_ERENDER = -4
} gvfg_preview_status_t;
typedef struct gvfg_preview_handle_t *gvfg_preview_handle;
typedef enum
{
GVFG_PREVIEW_PIXFMT_Y210 = 2,
GVFG_PREVIEW_PIXFMT_YUY2 = 3
} gvfg_preview_pixel_format_t;
typedef struct
{
const void *data;
uint64_t data_size;
int width;
int height;
int pixel_format; /* gvfg_preview_pixel_format_t */
int bit_depth;
int row_bytes;
uint64_t frame_id;
} gvfg_preview_frame_t;
typedef struct
{
int active;
int width;
int height;
int bit_depth;
char pixel_format[32];
char adapter_name[160];
int adapter_index;
} gvfg_preview_info_t;
/*
* Preview presentation statistics.
*
* present_fps counts only frames accepted by DXGI Present, not physical
* scanout. The rate uses successful presents from the most recent five
* seconds. Pending preview replacements are excluded from this rate.
*/
typedef struct
{
double present_fps;
uint64_t presented_frames;
uint64_t skipped_presents;
} gvfg_preview_stats_t;
/* Lifetime counters (until shutdown); configure/clear do not reset them.
* submitted = presented + replaced + busy + failed + cancelled + in_flight.
* Presented means DXGI accepted Present, not proof of physical scanout.
* Failed render API calls are counted by the caller, not in submitted.
*/
typedef struct
{
uint64_t submitted;
uint64_t presented;
uint64_t replaced; /* Queued frames discarded after the 50 ms age limit. */
uint64_t busy;
uint64_t failed;
uint64_t cancelled;
uint64_t in_flight;
uint64_t last_presented_id;
uint64_t present_busy;
uint64_t slots_busy;
uint64_t last_busy_id;
} gvfg_preview_delivery_stats_t;
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_get_delivery_stats(
gvfg_preview_handle handle, gvfg_preview_delivery_stats_t *out_stats);
/* Call after stopping submissions. Wait at most timeout_ms for queued work.
* Returns ESTATE if work remains; does not discard or reset counters. */
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_wait_idle(
gvfg_preview_handle handle, uint32_t timeout_ms);
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_create(
gvfg_preview_handle *out_handle);
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_destroy(
gvfg_preview_handle handle);
/*
* Attach a native window handle for preview output.
*
* On Windows, native_window_handle is an HWND.
*/
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_attach_window(
gvfg_preview_handle handle,
void *native_window_handle);
/* Pre-create GPU resources before the first captured frame is held. */
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_prepare(
gvfg_preview_handle handle,
int width,
int height,
int bit_depth);
/*
* Upload one frame to an internal GPU slot and queue it for preview.
*
* The frame memory remains owned by the caller and must remain valid until
* this function returns. GPU conversion and Present continue on the internal
* preview worker. Up to three pending frames are retained in FIFO order.
* Frames waiting longer than 50 ms are discarded; if the queue is full,
* the incoming frame is skipped. No SDK frame is retained for queueing.
* The age limit excludes time spent rendering or waiting inside Present.
*/
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_render_frame(
gvfg_preview_handle handle,
const gvfg_preview_frame_t *frame);
/* Replace the last presented frame with a solid black frame. */
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_clear(
gvfg_preview_handle handle);
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_get_info(
gvfg_preview_handle handle,
gvfg_preview_info_t *out_info);
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_get_stats(
gvfg_preview_handle handle,
gvfg_preview_stats_t *out_stats);
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_shutdown(
gvfg_preview_handle handle);
GVFG_PREVIEW_API const char *gvfg_preview_strerror(
gvfg_preview_status_t status);
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,884 @@
#include "gvfg_preview.h"
#include "d3d_conversion_pipeline.h"
#include <d3d11_4.h>
#include <dxgi1_2.h>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstring>
#include <deque>
#include <cstdio>
#include <array>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <thread>
#include <windows.h>
#include <wrl/client.h>
using Microsoft::WRL::ComPtr;
namespace
{
constexpr size_t kMaxPendingFrames = 3;
constexpr size_t kUploadSlotCount = kMaxPendingFrames + 1;
constexpr auto kMaxQueueAge = std::chrono::milliseconds(50);
// Blocking DXGI calls may send synchronous messages to the HWND owner.
// Service only sent messages while waiting; do not dispatch queued input,
// timers or application callbacks into Start/Stop recursively.
void serviceWindowMessages()
{
MsgWaitForMultipleObjectsEx(0, nullptr, 1, QS_SENDMESSAGE, MWMO_INPUTAVAILABLE);
MSG message{};
PeekMessageW(&message, nullptr, 0, 0, PM_NOREMOVE | PM_QS_SENDMESSAGE);
}
std::unique_lock<std::mutex> lockWithWindowMessages(std::mutex &mutex)
{
std::unique_lock<std::mutex> lock(mutex, std::defer_lock);
while (!lock.try_lock())
serviceWindowMessages();
return lock;
}
}
class PreviewRenderer
{
public:
PreviewRenderer() = default;
~PreviewRenderer() { shutdown(); }
bool configure(void *hwnd)
{
auto lock = lockWithWindowMessages(mutex_);
auto d3dLock = lockWithWindowMessages(d3dMutex_);
resetPresentStats();
hwnd_ = hwnd;
configured_ = hwnd_ != nullptr;
if (configured_ && ensureDevice())
{
if (!pipeline_)
pipeline_ = std::make_unique<gvfg::internal::D3DPreviewPipeline>();
pipeline_->initialize(d3d_->device.Get(), d3d_->context.Get());
gvfg::internal::gvfg_render_preview_desc_t desc{};
desc.hwnd = hwnd_;
desc.enable_preview = configured_ ? 1 : 0;
desc.swapchain_10bit = gvfg::internal::GVFG_RENDER_PREVIEW_BITDEPTH_AUTO;
pipeline_->configurePreview(desc);
}
else if (pipeline_)
{
gvfg::internal::gvfg_render_preview_desc_t desc{};
desc.hwnd = hwnd_;
desc.enable_preview = 0;
desc.swapchain_10bit = gvfg::internal::GVFG_RENDER_PREVIEW_BITDEPTH_AUTO;
pipeline_->configurePreview(desc);
}
return configured_;
}
bool render(const gvfg_preview_frame_t &frame)
{
auto lock = lockWithWindowMessages(mutex_);
if (!configured_ || !hwnd_ || !frame.data || frame.width <= 0 || frame.height <= 0)
return false;
int sourceBitDepth = frame.bit_depth > 0 ? frame.bit_depth : 8;
if (frame.pixel_format == GVFG_PREVIEW_PIXFMT_Y210)
sourceBitDepth = 10;
if (!ensureDevice() || !ensureWorkerLocked() ||
!ensureUploadSlotsLocked(frame.width, frame.height, frame.pixel_format))
return false;
discardExpiredLocked();
size_t pending = 0;
for (const auto &slot : slots_)
if (slot.state == SlotState::Pending || slot.state == SlotState::Uploading)
++pending;
size_t slotIndex = slots_.size();
for (size_t i = 0; i < slots_.size(); ++i)
if (pending < kMaxPendingFrames && slots_[i].state == SlotState::Free)
{ slotIndex = i; break; }
if (slotIndex == slots_.size())
{
++skippedSubmits_;
++delivery_.submitted;
++delivery_.busy;
++delivery_.slots_busy;
delivery_.last_busy_id = frame.frame_id;
return true;
}
UploadSlot &slot = slots_[slotIndex];
slot.state = SlotState::Uploading;
slot.generation = clearGeneration_.load(std::memory_order_acquire);
ID3D11DeviceContext *deferred = slot.deferred.Get();
ID3D11Texture2D *texture = slot.texture.Get();
lock.unlock();
D3D11_MAPPED_SUBRESOURCE mapped{};
if (FAILED(deferred->Map(texture, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped)))
{
lock.lock(); slot.state = SlotState::Free; return false;
}
const size_t rowBytes = frame.pixel_format == GVFG_PREVIEW_PIXFMT_Y210
? static_cast<size_t>(frame.width) * 4u
: static_cast<size_t>((frame.width + 1) / 2) * 4u;
if (mapped.RowPitch == rowBytes && static_cast<size_t>(frame.row_bytes) == rowBytes)
{
std::memcpy(mapped.pData, frame.data, rowBytes * static_cast<size_t>(frame.height));
}
else
{
for (int row = 0; row < frame.height; ++row)
std::memcpy(static_cast<uint8_t *>(mapped.pData) + static_cast<size_t>(row) * mapped.RowPitch,
static_cast<const uint8_t *>(frame.data) + static_cast<size_t>(row) * frame.row_bytes,
rowBytes);
}
deferred->Unmap(texture, 0);
ComPtr<ID3D11CommandList> commands;
if (FAILED(deferred->FinishCommandList(FALSE, &commands)))
{
lock.lock(); slot.state = SlotState::Free; return false;
}
lock.lock();
++delivery_.submitted;
slot.commands = commands;
slot.width = frame.width;
slot.height = frame.height;
slot.bitDepth = sourceBitDepth;
slot.pixelFormat = frame.pixel_format;
slot.frameId = frame.frame_id;
slot.queuedAt = std::chrono::steady_clock::now();
slot.queueOrder = ++queueOrder_;
slot.state = SlotState::Pending;
workerCv_.notify_one();
return true;
}
bool prepare(int width, int height, int sourceBitDepth)
{
auto lock = lockWithWindowMessages(mutex_);
if (!configured_ || !hwnd_ || width <= 0 || height <= 0)
return false;
return ensureDevice() &&
ensurePipeline(width, height, sourceBitDepth > 0 ? sourceBitDepth : 8);
}
bool clear()
{
clearGeneration_.fetch_add(1, std::memory_order_acq_rel);
{
auto lock = lockWithWindowMessages(mutex_);
if (!configured_ || !pipeline_)
return false;
for (UploadSlot &slot : slots_)
{
if (slot.state == SlotState::Pending)
{
++delivery_.cancelled;
slot.commands.Reset();
slot.state = SlotState::Free;
}
}
}
auto d3dLock = lockWithWindowMessages(d3dMutex_);
const bool cleared = pipeline_->clear_preview_black();
if (cleared)
clearActiveInfo();
return cleared;
}
void shutdown()
{
{
auto lock = lockWithWindowMessages(mutex_);
workerStopping_ = true;
workerCv_.notify_all();
}
if (worker_.joinable())
{
while (WaitForSingleObject(worker_.native_handle(), 0) == WAIT_TIMEOUT)
serviceWindowMessages();
worker_.join();
}
auto lock = lockWithWindowMessages(mutex_);
if (pipeline_)
pipeline_->release_preview_swapchain();
for (UploadSlot &slot : slots_)
slot = UploadSlot{};
pipeline_.reset();
d3d_.reset();
configured_ = false;
hwnd_ = nullptr;
workerStarted_ = false;
workerStopping_ = false;
uploadWidth_ = 0;
uploadHeight_ = 0;
uploadPixelFormat_ = -1;
clearActiveInfo();
resetPresentStats();
delivery_ = {};
}
bool active() const
{
return active_.load(std::memory_order_relaxed);
}
int width() const
{
return width_.load(std::memory_order_relaxed);
}
int height() const
{
return height_.load(std::memory_order_relaxed);
}
int bitDepth() const
{
return bitDepth_.load(std::memory_order_relaxed);
}
const char *pixelFormat() const
{
return swapchain10Bit_.load(std::memory_order_relaxed) ? "RGB10A2" : "BGRA8";
}
const char *adapterName() const
{
return adapterName_;
}
int adapterIndex() const
{
return adapterIndex_;
}
void getStats(gvfg_preview_stats_t &stats) const
{
auto lock = lockWithWindowMessages(mutex_);
stats.presented_frames = presentedFrames_;
stats.skipped_presents = skippedPresents_ + skippedSubmits_;
stats.present_fps = active_.load(std::memory_order_relaxed)
? calculatePresentFps(std::chrono::steady_clock::now())
: 0.0;
}
void getDeliveryStats(gvfg_preview_delivery_stats_t &stats) const
{
auto lock = lockWithWindowMessages(mutex_);
stats = delivery_;
stats.in_flight = stats.submitted - stats.presented - stats.replaced -
stats.busy - stats.failed - stats.cancelled;
}
bool waitIdle(uint32_t timeoutMs)
{
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
for (;;)
{
std::unique_lock<std::mutex> lock(mutex_, std::try_to_lock);
bool idle = lock.owns_lock();
if (idle)
{
for (const auto &slot : slots_)
if (slot.state != SlotState::Free)
idle = false;
}
if (idle)
return true;
if (lock.owns_lock())
lock.unlock();
if (std::chrono::steady_clock::now() >= deadline)
return false;
serviceWindowMessages();
}
}
private:
enum class SlotState { Free, Uploading, Pending, Presenting };
struct UploadSlot
{
ComPtr<ID3D11DeviceContext> deferred;
ComPtr<ID3D11Texture2D> texture;
ComPtr<ID3D11ShaderResourceView> view;
ComPtr<ID3D11CommandList> commands;
SlotState state = SlotState::Free;
int width = 0;
int height = 0;
int bitDepth = 0;
int pixelFormat = -1;
uint64_t frameId = 0;
uint64_t generation = 0;
std::chrono::steady_clock::time_point queuedAt{};
uint64_t queueOrder = 0;
};
void discardExpiredLocked()
{
const auto now = std::chrono::steady_clock::now();
for (auto &slot : slots_)
if (slot.state == SlotState::Pending && now - slot.queuedAt > kMaxQueueAge)
{
slot.commands.Reset();
slot.state = SlotState::Free;
++skippedSubmits_;
++delivery_.replaced; // Retired queued frame: expired, not latest-frame replacement.
}
}
struct D3DState
{
ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> context;
};
void clearActiveInfo()
{
width_.store(0, std::memory_order_relaxed);
height_.store(0, std::memory_order_relaxed);
bitDepth_.store(0, std::memory_order_relaxed);
swapchain10Bit_.store(false, std::memory_order_relaxed);
active_.store(false, std::memory_order_relaxed);
}
using PresentClock = std::chrono::steady_clock;
void resetPresentStats()
{
presentTimes_.clear();
presentedFrames_ = 0;
skippedPresents_ = 0;
skippedSubmits_ = 0;
}
void recordPresentResult(gvfg::internal::gvfg_preview_present_result_t result)
{
if (result == gvfg::internal::GVFG_PREVIEW_PRESENT_SKIPPED)
{
++skippedPresents_;
return;
}
if (result != gvfg::internal::GVFG_PREVIEW_PRESENTED)
return;
++presentedFrames_;
const PresentClock::time_point now = PresentClock::now();
presentTimes_.push_back(now);
const auto windowStart = now - std::chrono::seconds(5);
while (presentTimes_.size() > 2 && presentTimes_.front() < windowStart)
presentTimes_.pop_front();
}
double calculatePresentFps(PresentClock::time_point now) const
{
if (presentTimes_.size() < 2 ||
now - presentTimes_.back() > std::chrono::seconds(1))
return 0.0;
const double elapsed =
std::chrono::duration<double>(presentTimes_.back() - presentTimes_.front()).count();
if (elapsed < 2.0)
return 0.0;
return static_cast<double>(presentTimes_.size() - 1) / elapsed;
}
static bool sameLuid(const LUID &a, const LUID &b)
{
return a.LowPart == b.LowPart && a.HighPart == b.HighPart;
}
static int dxgiAdapterIndexForLuid(const LUID &luid)
{
ComPtr<IDXGIFactory1> factory;
if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) || !factory)
return -1;
for (UINT i = 0;; ++i)
{
ComPtr<IDXGIAdapter1> adapter;
const HRESULT hr = factory->EnumAdapters1(i, &adapter);
if (hr == DXGI_ERROR_NOT_FOUND)
break;
if (FAILED(hr) || !adapter)
continue;
DXGI_ADAPTER_DESC1 desc{};
if (SUCCEEDED(adapter->GetDesc1(&desc)) && sameLuid(desc.AdapterLuid, luid))
return static_cast<int>(i);
}
return -1;
}
void updateAdapterInfo(ID3D11Device *device)
{
adapterName_[0] = '\0';
adapterIndex_ = -1;
if (!device)
return;
ComPtr<IDXGIDevice> dxgiDevice;
if (FAILED(device->QueryInterface(IID_PPV_ARGS(&dxgiDevice))) || !dxgiDevice)
return;
ComPtr<IDXGIAdapter> adapter;
if (FAILED(dxgiDevice->GetAdapter(&adapter)) || !adapter)
return;
DXGI_ADAPTER_DESC desc{};
if (FAILED(adapter->GetDesc(&desc)))
return;
WideCharToMultiByte(CP_UTF8, 0, desc.Description, -1,
adapterName_, static_cast<int>(sizeof(adapterName_)), nullptr, nullptr);
adapterIndex_ = dxgiAdapterIndexForLuid(desc.AdapterLuid);
}
bool ensureDevice()
{
if (d3d_ && d3d_->device && d3d_->context)
return true;
auto state = std::make_unique<D3DState>();
UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
#ifdef _DEBUG
flags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0};
D3D_FEATURE_LEVEL got{};
HRESULT hr = D3D11CreateDevice(nullptr,
D3D_DRIVER_TYPE_HARDWARE,
nullptr,
flags,
levels,
_countof(levels),
D3D11_SDK_VERSION,
&state->device,
&got,
&state->context);
#ifdef _DEBUG
if (FAILED(hr))
{
flags &= ~D3D11_CREATE_DEVICE_DEBUG;
hr = D3D11CreateDevice(nullptr,
D3D_DRIVER_TYPE_HARDWARE,
nullptr,
flags,
levels,
_countof(levels),
D3D11_SDK_VERSION,
&state->device,
&got,
&state->context);
}
#endif
if (FAILED(hr) || !state->device || !state->context)
return false;
ComPtr<ID3D11Multithread> mt;
if (SUCCEEDED(state->device.As(&mt)) && mt)
mt->SetMultithreadProtected(TRUE);
updateAdapterInfo(state->device.Get());
d3d_ = std::move(state);
return true;
}
bool ensureWorkerLocked()
{
if (workerStarted_)
return true;
workerStopping_ = false;
try
{
worker_ = std::thread(&PreviewRenderer::workerLoop, this);
workerStarted_ = true;
}
catch (...)
{
return false;
}
return true;
}
bool ensureUploadSlotsLocked(int width, int height, int pixelFormat)
{
if (uploadWidth_ == width && uploadHeight_ == height &&
uploadPixelFormat_ == pixelFormat && slots_[0].texture)
return true;
for (const UploadSlot &slot : slots_)
if (slot.state == SlotState::Uploading || slot.state == SlotState::Presenting)
return false;
const DXGI_FORMAT format = pixelFormat == GVFG_PREVIEW_PIXFMT_Y210
? DXGI_FORMAT_R16G16B16A16_UINT
: DXGI_FORMAT_R8G8B8A8_UINT;
const UINT textureWidth = static_cast<UINT>((width + 1) / 2);
std::array<UploadSlot, kUploadSlotCount> replacement{};
for (UploadSlot &slot : replacement)
{
if (FAILED(d3d_->device->CreateDeferredContext(0, &slot.deferred)))
return false;
D3D11_TEXTURE2D_DESC desc{};
desc.Width = textureWidth;
desc.Height = static_cast<UINT>(height);
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = format;
desc.SampleDesc.Count = 1;
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
if (FAILED(d3d_->device->CreateTexture2D(&desc, nullptr, &slot.texture)))
return false;
if (FAILED(d3d_->device->CreateShaderResourceView(slot.texture.Get(), nullptr, &slot.view)))
return false;
}
for (const UploadSlot &slot : slots_)
if (slot.state == SlotState::Pending)
++delivery_.cancelled;
slots_ = std::move(replacement);
uploadWidth_ = width;
uploadHeight_ = height;
uploadPixelFormat_ = pixelFormat;
return true;
}
void workerLoop()
{
for (;;)
{
size_t selected = slots_.size();
UploadSlot work;
{
auto lock = lockWithWindowMessages(mutex_);
workerCv_.wait(lock, [this] {
if (workerStopping_)
return true;
for (const UploadSlot &slot : slots_)
if (slot.state == SlotState::Pending)
return true;
return false;
});
if (workerStopping_)
break;
discardExpiredLocked();
for (size_t i = 0; i < slots_.size(); ++i)
if (slots_[i].state == SlotState::Pending &&
(selected == slots_.size() || slots_[i].queueOrder < slots_[selected].queueOrder))
selected = i;
if (selected == slots_.size())
continue;
slots_[selected].state = SlotState::Presenting;
work = slots_[selected];
}
bool ready = false;
{
auto lock = lockWithWindowMessages(mutex_);
ready = configured_ && !workerStopping_ &&
ensurePipeline(work.width, work.height, work.bitDepth);
}
bool rendered = false;
bool expired = false;
gvfg::internal::gvfg_preview_present_result_t presentResult =
gvfg::internal::GVFG_PREVIEW_PRESENT_FAILED;
if (ready)
{
auto d3dLock = lockWithWindowMessages(d3dMutex_);
if (work.generation == clearGeneration_.load(std::memory_order_acquire))
{
expired = std::chrono::steady_clock::now() - work.queuedAt > kMaxQueueAge;
if (!expired)
{
d3d_->context->ExecuteCommandList(work.commands.Get(), FALSE);
const gvfg::internal::gvfg_render_pixfmt_t renderFmt =
work.pixelFormat == GVFG_PREVIEW_PIXFMT_Y210
? gvfg::internal::GVFG_RENDER_FMT_Y210
: gvfg::internal::GVFG_RENDER_FMT_YUY2;
rendered = pipeline_->render_texture_to_fp16(work.texture.Get(), renderFmt,
work.width, work.height, work.view.Get());
if (rendered)
presentResult = pipeline_->present_preview(work.width, work.height);
}
}
}
{
auto lock = lockWithWindowMessages(mutex_);
if (expired)
{
++skippedSubmits_;
++delivery_.replaced;
}
else if (ready && rendered &&
presentResult != gvfg::internal::GVFG_PREVIEW_PRESENT_FAILED)
{
recordPresentResult(presentResult);
if (presentResult == gvfg::internal::GVFG_PREVIEW_PRESENT_SKIPPED)
{
++delivery_.busy;
++delivery_.present_busy;
delivery_.last_busy_id = work.frameId;
}
else
{
++delivery_.presented;
delivery_.last_presented_id = work.frameId;
}
width_.store(work.width, std::memory_order_relaxed);
height_.store(work.height, std::memory_order_relaxed);
bitDepth_.store(work.bitDepth, std::memory_order_relaxed);
swapchain10Bit_.store(pipeline_->preview_swapchain_10bit(), std::memory_order_relaxed);
active_.store(true, std::memory_order_relaxed);
}
else
{
if (work.generation != clearGeneration_.load(std::memory_order_acquire))
++delivery_.cancelled;
else
++delivery_.failed;
clearActiveInfo();
}
slots_[selected].commands.Reset();
slots_[selected].state = SlotState::Free;
workerCv_.notify_all();
}
}
}
bool ensurePipeline(int width, int height, int sourceBitDepth)
{
auto d3dLock = lockWithWindowMessages(d3dMutex_);
if (!pipeline_)
pipeline_ = std::make_unique<gvfg::internal::D3DPreviewPipeline>();
if (!pipeline_->initialize(d3d_->device.Get(), d3d_->context.Get()))
return false;
gvfg::internal::gvfg_render_preview_desc_t desc{};
desc.hwnd = hwnd_;
desc.enable_preview = configured_ ? 1 : 0;
desc.swapchain_10bit = gvfg::internal::GVFG_RENDER_PREVIEW_BITDEPTH_AUTO;
pipeline_->configurePreview(desc);
pipeline_->set_source_bit_depth(sourceBitDepth > 0 ? sourceBitDepth : 8);
const bool ready = pipeline_->ensure_rt_and_pipeline(width, height, true) &&
pipeline_->ensure_preview_swapchain(width, height);
return ready;
}
mutable std::mutex mutex_;
std::mutex d3dMutex_;
std::atomic<uint64_t> clearGeneration_{0};
void *hwnd_ = nullptr;
bool configured_ = false;
std::atomic<int> width_{0};
std::atomic<int> height_{0};
std::atomic<int> bitDepth_{0};
std::atomic<bool> swapchain10Bit_{false};
std::atomic<bool> active_{false};
char adapterName_[160] = {};
int adapterIndex_ = -1;
std::deque<PresentClock::time_point> presentTimes_;
uint64_t presentedFrames_ = 0;
uint64_t skippedPresents_ = 0;
uint64_t skippedSubmits_ = 0;
gvfg_preview_delivery_stats_t delivery_{};
uint64_t queueOrder_ = 0;
std::array<UploadSlot, kUploadSlotCount> slots_{};
std::thread worker_;
std::condition_variable workerCv_;
bool workerStarted_ = false;
bool workerStopping_ = false;
int uploadWidth_ = 0;
int uploadHeight_ = 0;
int uploadPixelFormat_ = -1;
std::unique_ptr<D3DState> d3d_;
std::unique_ptr<gvfg::internal::D3DPreviewPipeline> pipeline_;
};
struct gvfg_preview_handle_t
{
PreviewRenderer renderer;
};
namespace
{
void copy_cstr(char *dst, size_t dstSize, const char *src)
{
if (!dst || dstSize == 0)
return;
dst[0] = '\0';
if (src)
strncpy_s(dst, dstSize, src, _TRUNCATE);
}
}
extern "C"
{
gvfg_preview_status_t gvfg_preview_create(gvfg_preview_handle *out_handle)
{
if (!out_handle)
return GVFG_PREVIEW_EINVAL;
*out_handle = nullptr;
auto handle = std::make_unique<gvfg_preview_handle_t>();
*out_handle = handle.release();
return GVFG_PREVIEW_OK;
}
gvfg_preview_status_t gvfg_preview_destroy(gvfg_preview_handle handle)
{
if (!handle)
return GVFG_PREVIEW_OK;
delete handle;
return GVFG_PREVIEW_OK;
}
gvfg_preview_status_t gvfg_preview_attach_window(gvfg_preview_handle handle,
void *native_window_handle)
{
if (!handle)
return GVFG_PREVIEW_EINVAL;
if (!native_window_handle)
{
handle->renderer.shutdown();
return GVFG_PREVIEW_EINVAL;
}
return handle->renderer.configure(native_window_handle) ? GVFG_PREVIEW_OK : GVFG_PREVIEW_ESTATE;
}
gvfg_preview_status_t gvfg_preview_prepare(gvfg_preview_handle handle,
int width,
int height,
int bit_depth)
{
if (!handle || width <= 0 || height <= 0)
return GVFG_PREVIEW_EINVAL;
return handle->renderer.prepare(width, height, bit_depth)
? GVFG_PREVIEW_OK
: GVFG_PREVIEW_ERENDER;
}
gvfg_preview_status_t gvfg_preview_render_frame(gvfg_preview_handle handle,
const gvfg_preview_frame_t *frame)
{
if (!handle || !frame)
return GVFG_PREVIEW_EINVAL;
if (!frame->data ||
frame->width <= 0 ||
frame->height <= 0 ||
frame->row_bytes <= 0)
return GVFG_PREVIEW_EINVAL;
uint64_t minimumRowBytes = 0;
switch (frame->pixel_format)
{
case GVFG_PREVIEW_PIXFMT_YUY2:
minimumRowBytes = static_cast<uint64_t>(frame->width) * 2u;
break;
case GVFG_PREVIEW_PIXFMT_Y210:
minimumRowBytes = static_cast<uint64_t>(frame->width) * 4u;
break;
default:
return GVFG_PREVIEW_ENOTSUP;
}
const uint64_t rowBytes = static_cast<uint64_t>(frame->row_bytes);
if (rowBytes < minimumRowBytes ||
rowBytes > UINT64_MAX / static_cast<uint64_t>(frame->height) ||
frame->data_size < rowBytes * static_cast<uint64_t>(frame->height))
return GVFG_PREVIEW_EINVAL;
return handle->renderer.render(*frame) ? GVFG_PREVIEW_OK : GVFG_PREVIEW_ERENDER;
}
gvfg_preview_status_t gvfg_preview_clear(gvfg_preview_handle handle)
{
if (!handle)
return GVFG_PREVIEW_EINVAL;
return handle->renderer.clear() ? GVFG_PREVIEW_OK : GVFG_PREVIEW_ERENDER;
}
gvfg_preview_status_t gvfg_preview_get_info(gvfg_preview_handle handle,
gvfg_preview_info_t *out_info)
{
if (!handle || !out_info)
return GVFG_PREVIEW_EINVAL;
std::memset(out_info, 0, sizeof(*out_info));
out_info->active = handle->renderer.active() ? 1 : 0;
out_info->width = handle->renderer.width();
out_info->height = handle->renderer.height();
out_info->bit_depth = handle->renderer.bitDepth();
copy_cstr(out_info->pixel_format,
sizeof(out_info->pixel_format),
handle->renderer.pixelFormat());
copy_cstr(out_info->adapter_name,
sizeof(out_info->adapter_name),
handle->renderer.adapterName());
out_info->adapter_index = handle->renderer.adapterIndex();
return GVFG_PREVIEW_OK;
}
gvfg_preview_status_t gvfg_preview_get_stats(gvfg_preview_handle handle,
gvfg_preview_stats_t *out_stats)
{
if (!handle || !out_stats)
return GVFG_PREVIEW_EINVAL;
gvfg_preview_stats_t stats{};
handle->renderer.getStats(stats);
*out_stats = stats;
return GVFG_PREVIEW_OK;
}
gvfg_preview_status_t gvfg_preview_get_delivery_stats(
gvfg_preview_handle handle, gvfg_preview_delivery_stats_t *out_stats)
{
if (!handle || !out_stats)
return GVFG_PREVIEW_EINVAL;
handle->renderer.getDeliveryStats(*out_stats);
return GVFG_PREVIEW_OK;
}
gvfg_preview_status_t gvfg_preview_wait_idle(gvfg_preview_handle handle, uint32_t timeout_ms)
{
if (!handle)
return GVFG_PREVIEW_EINVAL;
return handle->renderer.waitIdle(timeout_ms) ? GVFG_PREVIEW_OK : GVFG_PREVIEW_ESTATE;
}
gvfg_preview_status_t gvfg_preview_shutdown(gvfg_preview_handle handle)
{
if (!handle)
return GVFG_PREVIEW_EINVAL;
handle->renderer.shutdown();
return GVFG_PREVIEW_OK;
}
const char *gvfg_preview_strerror(gvfg_preview_status_t status)
{
switch (status)
{
case GVFG_PREVIEW_OK:
return "OK";
case GVFG_PREVIEW_EINVAL:
return "Invalid argument";
case GVFG_PREVIEW_ESTATE:
return "Invalid state";
case GVFG_PREVIEW_ENOTSUP:
return "Unsupported frame format";
case GVFG_PREVIEW_ERENDER:
return "Render failed";
default:
return "Unknown";
}
}
}