Optimize GVFG GPU preview and clarify delivery diagnostics

- Render preview directly from the FP16 conversion target into the selected
  8-bit or 10-bit swapchain, removing the full-frame scene copy and the
  intermediate BGRA8 preview pass without capture-frame decimation.
- Simplify neutral YUY2/Y210 shaders to one packed texture load per pixel;
  preserve BT.709 conversion, 10-bit unpacking and odd-width chroma handling.
- Cache shader resource views per upload slot and update constant-buffer
  contents only when source dimensions change.
- Allocate only preview resources and skip export-only shader compilation
  for preview; retain the full BGRA8/RGB10A2/NV12 buffer conversion path.
- Unbind render targets before swapchain resize/release and serialize preview
  configuration and resource changes with GPU rendering.
- Bound startup Present retries and retry presentation without redrawing;
  retain actual skipped-frame counts when presentation remains busy.
- Add preview delivery counters for presented, replaced, busy, failed,
  cancelled and pending frames, including busy source and affected frame ID.
- Fix an uncounted pending-frame replacement and drain pending preview work
  at Stop and before a new run to keep per-run accounting separate.
- Track application audio delivery, dropped duration, read/write stalls and
  frame-ID anomalies while retaining the original 10-block audio queue.
- Stop the channel on audio write failure or two seconds of zero-write
  progress; distinguish cancelled data from runtime drops.
- Keep the existing compact UI; aggregate delivery issue logs at most once
  per five seconds and emit a stop summary with accounting errors only.
- Document diagnostic interpretation, GPU changes and validation boundaries.

Validation:
- User testing reported approximately 15% lower GPU utilization after the
  optimization. Baseline/final readings and relative versus percentage-point
  interpretation were not supplied; no independent benchmark was performed.
- Static source checks and git diff --check passed. No application or shader
  build was performed by the agent; 10-bit startup resolution and long-run
  zero-loss behavior have not been confirmed.
- Rebuild the preview DLL with its matching APP; the SDK GPU buffer converter
  also shares the modified shader source. Capture APIs and driver are unchanged.
This commit is contained in:
Mark.lin
2026-09-04 16:02:33 +08:00
parent 2b62a85912
commit 29b449fc6e
8 changed files with 499 additions and 183 deletions
+26
View File
@@ -0,0 +1,26 @@
# 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. Startup retries repeat only Present, not the draw.
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 three 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.
@@ -78,6 +78,34 @@ typedef struct
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;
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);
+109 -11
View File
@@ -29,7 +29,9 @@ public:
bool configure(void *hwnd)
{
std::lock_guard<std::mutex> lock(mutex_);
std::lock_guard<std::mutex> d3dLock(d3dMutex_);
resetPresentStats();
startupPresentRetries_ = 8;
hwnd_ = hwnd;
configured_ = hwnd_ != nullptr;
if (configured_ && ensureDevice())
@@ -42,8 +44,6 @@ public:
desc.enable_preview = configured_ ? 1 : 0;
desc.swapchain_10bit = gvfg::internal::GVFG_RENDER_PREVIEW_BITDEPTH_AUTO;
pipeline_->configurePreview(desc);
if (!pipeline_->create_shaders_and_states())
return false;
}
else if (pipeline_)
{
@@ -78,6 +78,10 @@ public:
if (slotIndex == slots_.size())
{
++skippedSubmits_;
++delivery_.submitted;
++delivery_.busy;
++delivery_.slots_busy;
delivery_.last_busy_id = frame.frame_id;
return true;
}
@@ -86,6 +90,7 @@ public:
{
slot.commands.Reset();
++skippedSubmits_;
++delivery_.replaced;
}
slot.state = SlotState::Uploading;
ID3D11DeviceContext *deferred = slot.deferred.Get();
@@ -121,7 +126,13 @@ public:
lock.lock();
for (UploadSlot &other : slots_)
if (&other != &slot && other.state == SlotState::Pending)
{
other.commands.Reset();
other.state = SlotState::Free;
++skippedSubmits_;
++delivery_.replaced;
}
++delivery_.submitted;
slot.commands = commands;
slot.width = frame.width;
slot.height = frame.height;
@@ -154,6 +165,7 @@ public:
{
if (slot.state == SlotState::Pending)
{
++delivery_.cancelled;
slot.commands.Reset();
slot.state = SlotState::Free;
}
@@ -193,6 +205,7 @@ public:
uploadPixelFormat_ = -1;
clearActiveInfo();
resetPresentStats();
delivery_ = {};
}
bool active() const
@@ -240,6 +253,25 @@ public:
: 0.0;
}
void getDeliveryStats(gvfg_preview_delivery_stats_t &stats) const
{
std::lock_guard<std::mutex> lock(mutex_);
stats = delivery_;
stats.in_flight = stats.submitted - stats.presented - stats.replaced -
stats.busy - stats.failed - stats.cancelled;
}
bool waitIdle(uint32_t timeoutMs)
{
std::unique_lock<std::mutex> lock(mutex_);
return workerCv_.wait_for(lock, std::chrono::milliseconds(timeoutMs), [this] {
for (const auto &slot : slots_)
if (slot.state != SlotState::Free)
return false;
return true;
});
}
private:
enum class SlotState { Free, Uploading, Pending, Presenting };
@@ -247,6 +279,7 @@ private:
{
ComPtr<ID3D11DeviceContext> deferred;
ComPtr<ID3D11Texture2D> texture;
ComPtr<ID3D11ShaderResourceView> view;
ComPtr<ID3D11CommandList> commands;
SlotState state = SlotState::Free;
int width = 0;
@@ -462,7 +495,12 @@ private:
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;
@@ -498,20 +536,25 @@ private:
slots_[i].commands.Reset();
slots_[i].state = SlotState::Free;
++skippedSubmits_;
++delivery_.replaced;
}
slots_[selected].state = SlotState::Presenting;
work = slots_[selected];
}
bool ready = false;
unsigned startupRetries = 0;
{
std::lock_guard<std::mutex> lock(mutex_);
ready = configured_ && !workerStopping_ &&
ensurePipeline(work.width, work.height, work.bitDepth);
if (ready)
{
startupRetries = startupPresentRetries_;
startupPresentRetries_ = 0;
}
}
bool rendered = false;
bool copied = false;
bool blitted = false;
gvfg::internal::gvfg_preview_present_result_t presentResult =
gvfg::internal::GVFG_PREVIEW_PRESENT_FAILED;
if (ready)
@@ -525,20 +568,49 @@ private:
? 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);
copied = rendered && pipeline_->copy_fp16_to_scene();
blitted = copied && (pipeline_->preview_swapchain_10bit() ||
pipeline_->blit_fp16_to_rgba8(work.width, work.height));
if (blitted)
work.width, work.height, work.view.Get());
if (rendered)
{
presentResult = pipeline_->present_preview(work.width, work.height);
const auto retryDeadline = std::chrono::steady_clock::now() +
std::chrono::milliseconds(16);
// Retry the same uploaded image only on the first presentation
// after attach. Keep normal playback non-blocking. These waits
// run on the preview worker, never while holding an SDK frame.
while (presentResult == gvfg::internal::GVFG_PREVIEW_PRESENT_SKIPPED &&
startupRetries > 0 && std::chrono::steady_clock::now() < retryDeadline)
{
--startupRetries;
std::this_thread::sleep_for(std::chrono::milliseconds(2));
if (work.generation != clearGeneration_.load(std::memory_order_acquire))
{
presentResult = gvfg::internal::GVFG_PREVIEW_PRESENT_FAILED;
break;
}
if (std::chrono::steady_clock::now() >= retryDeadline)
break;
presentResult = pipeline_->retry_preview_present();
}
}
}
}
{
std::lock_guard<std::mutex> lock(mutex_);
if (ready && rendered && copied && blitted &&
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);
@@ -546,15 +618,23 @@ private:
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)
{
std::lock_guard<std::mutex> d3dLock(d3dMutex_);
if (!pipeline_)
pipeline_ = std::make_unique<gvfg::internal::D3DPreviewPipeline>();
@@ -567,7 +647,7 @@ private:
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) &&
const bool ready = pipeline_->ensure_rt_and_pipeline(width, height, true) &&
pipeline_->ensure_preview_swapchain(width, height);
return ready;
}
@@ -588,6 +668,8 @@ private:
uint64_t presentedFrames_ = 0;
uint64_t skippedPresents_ = 0;
uint64_t skippedSubmits_ = 0;
gvfg_preview_delivery_stats_t delivery_{};
unsigned startupPresentRetries_ = 0; // Protected by mutex_; rearmed on attach.
std::array<UploadSlot, 3> slots_{};
std::thread worker_;
std::condition_variable workerCv_;
@@ -734,6 +816,22 @@ extern "C"
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)
@@ -0,0 +1,24 @@
# 關鍵交付 Log
畫面保留原本狀態,不顯示完整交付統計,也不增加設定控制。正常運行不定期列印診斷快照。
- `Video issue`:預覽累計丟棄與原因。`replaced` 是舊影像被替換,`busy` 是無空槽/DXGI 忙碌跳過,`failed` 是提交或渲染失敗。
- busy 發生時附上 `present`/`slots` 分類累計數與 `last_frame_id`,可確認忙碌來源。
- `Audio issue`:累計丟棄區塊/毫秒數、最長寫入停滯、最長收音間隔,以及最近丟棄 ID/時間。
- 序號缺口、倒退/重複、音訊失敗位元組僅在有異常時附上。
- 異常最多每 5 秒彙整一次;累計數不漏計,最近 ID 不代表列出每個遺失區塊。Stop 會補記尚未輸出的異常。
- Stop 留一行 `Summary`。資料去向核對正常時不另外印訊息,只有不一致才印 `ERROR delivery accounting mismatch`。正常停止清掉的待處理資料不算運行丟失。
## 拿到 Log 後怎麼處理
Video 若以 replaced/busy 為主,查預覽/GPU 負載;failed 則查提交和渲染錯誤。APP 持續讀取並釋放每張影像,沒有新增預覽降頻行為。
啟動/重新 attach 預覽後,第一次呈現若 DXGI 回報忙碌,預覽執行緒會保留同一張已上傳的影像,每次等待 2 ms 再試,最多 8 次,且到達 16 ms 重試期限後不再發起重試(排程或呼叫本身可能使實際時間超過期限)。只有最終仍忙碌才計一次 preview drop;成功不算丟棄。平常呈現不重試,不清掉既有計數。等待不持有 SDK frame,但仍可能讓後續預覽影像被替換,替換照常計數。
Audio 保留原本最多 10 個 PCM 區塊的播放佇列(`kMaxQueuedAudioFrames`);滿時丟掉最舊區塊,再加入新區塊。毫秒數只用來表示實際丟失的音訊長度,不控制容量。若偶發丟棄,先根據 Log 的寫入停滯/收音間隔查原因,再決定是否需要調整;最長收音間隔包含正常區塊間隔,不能直接當成丟失時間。
播放 write 失敗,或持續回傳 0、兩秒沒有進展,會記錄原因並停止通道;檢查音效裝置後重新 Start。此檢查無法中斷本身永不返回的 write 呼叫。
統計從 APP 成功取得 SDK frame 開始。SDK ID 連續不能證明更上游沒有丟失;DXGI 接受 Present 不代表實體螢幕已顯示,QAudioSink 接受 PCM 也不代表已實際發聲。已丟掉的原始資料無法靠這些處理補回。
擷取 API/驅動不修改。新版 APP 需配套的新版 gvfg_preview.dll。後續 GPU 優化修改了共用的轉換原始碼;若要發佈包含該優化的 SDK GPU buffer converter,也需重建其 DLL。尚待 build、播放/預覽異常測試與硬體長測;靜態檢查不能證明零丟失。
+188 -9
View File
@@ -163,7 +163,6 @@ MainWindow::MainWindow(QWidget *parent)
: QWidget(parent), ui_(new Ui::MainWindow)
{
ui_->setupUi(this);
#if GVFG_INTERNAL_DIAGNOSTICS
setWindowTitle(QStringLiteral("GVFG Internal Diagnostic - SDK v%1")
.arg(QString::fromLatin1(gvfg_get_version())));
@@ -547,6 +546,11 @@ void MainWindow::startCapture(int channelIndex)
appendLog(QStringLiteral("FPGA signal before stream start"));
#endif
if (gvfg_preview_wait_idle(channel.previewHandle, 2000) != GVFG_PREVIEW_OK)
{
appendLog(QStringLiteral("CH%1 Preview still busy from previous run; retry Start after it completes.").arg(channelIndex));
return;
}
st = gvfg_start_channel(handle_, channelIndex);
if (st != GVFG_OK)
{
@@ -570,9 +574,23 @@ void MainWindow::startCapture(int channelIndex)
channel.audioFrames.store(0, std::memory_order_relaxed);
channel.audioBytes.store(0, std::memory_order_relaxed);
channel.audioQueueDrops.store(0, std::memory_order_relaxed);
channel.videoReceived = 0; channel.videoSubmitted = 0; channel.videoFailed = 0;
channel.videoIdGaps = 0; channel.videoIdResets = 0;
channel.videoLastId = 0;
channel.lastLoggedVideoIssues = channel.lastLoggedAudioIssues = 0;
channel.lastDeliveryLogMs = 0;
channel.previewBaseline = {};
gvfg_preview_get_delivery_stats(channel.previewHandle, &channel.previewBaseline);
{
std::lock_guard<std::mutex> lock(channel.audioQueueMutex);
channel.audioQueue.clear();
channel.audioReceivedBytes = channel.audioAcceptedBytes = channel.audioQueuedBytes = 0;
channel.audioDroppedBytes = channel.audioCancelledBytes = 0;
channel.audioFailedBytes = channel.audioIdGaps = channel.audioIdResets = 0;
channel.audioLastId = channel.audioLastDropId = 0;
channel.audioLastDropTimeMs = 0;
channel.audioMaxWriteStallMs = 0;
channel.audioMaxReadGapMs = 0;
}
#if GVFG_INTERNAL_DIAGNOSTICS
channel.haveDebugBaseline = false;
@@ -609,6 +627,9 @@ void MainWindow::stopCapture(int channelIndex)
channel.audioQueueReady.notify_all();
joinCaptureThread(channelIndex);
joinAudioThread(channelIndex);
if (gvfg_preview_wait_idle(channel.previewHandle, 2000) != GVFG_PREVIEW_OK)
appendLog(QStringLiteral("CH%1 Preview drain timed out; remaining in_flight is not counted as lost.").arg(channelIndex));
logDeliveryStatus(channelIndex, true);
gvfg_stop_channel(handle_, channelIndex);
channel.running.store(false, std::memory_order_release);
channel.frameAvailable.store(false, std::memory_order_release);
@@ -770,18 +791,17 @@ void MainWindow::updateSignalStatus(bool queryHardware)
.arg(zeroCopy ? QStringLiteral("Zero-copy") : QStringLiteral("Copy"));
if (channel.audioEnabled)
{
statusLines << QStringLiteral("CH%1 Audio | %2 Hz %3 ch %4-bit | frames=%5 bytes=%6 queue_drops=%7")
statusLines << QStringLiteral("CH%1 Audio | %2 Hz %3 ch %4-bit | queue_drops=%5")
.arg(channelIndex)
.arg(channel.audioFormat.sample_rate)
.arg(channel.audioFormat.channels)
.arg(channel.audioFormat.bits_per_sample)
.arg(static_cast<qulonglong>(channel.audioFrames.load(std::memory_order_relaxed)))
.arg(static_cast<qulonglong>(channel.audioBytes.load(std::memory_order_relaxed)))
.arg(static_cast<qulonglong>(channel.audioQueueDrops.load(std::memory_order_relaxed)));
}
statusLines << QStringLiteral("CH%1 Preview | %2 FPS | %3")
.arg(channelIndex)
.arg(previewFps, previewFrame);
logDeliveryStatus(channelIndex);
const uint64_t readSamples = channel.getFrameSamples.load(std::memory_order_relaxed);
statusLines << (readSamples >= 300
? QStringLiteral("CH%1 Read | avg=%2 max300=%3 max=%4 ms samples=%5")
@@ -1005,6 +1025,94 @@ void MainWindow::appendLog(const QString &message)
}
}
void MainWindow::logDeliveryStatus(int channelIndex, bool finalSnapshot)
{
auto &c = channels_[channelIndex];
if (!finalSnapshot && !c.running.load())
return;
const qint64 now = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
// Keep normal operation quiet; aggregate repeated failures at most every 5 s.
if (!finalSnapshot && now - c.lastDeliveryLogMs < 5000)
return;
const auto count = [](uint64_t value) { return QString::number(static_cast<qulonglong>(value)); };
gvfg_preview_delivery_stats_t p{};
const bool previewOk = c.previewHandle &&
gvfg_preview_get_delivery_stats(c.previewHandle, &p) == GVFG_PREVIEW_OK;
const auto &b = c.previewBaseline;
const uint64_t replaced = previewOk ? p.replaced - b.replaced : 0;
const uint64_t busy = previewOk ? p.busy - b.busy : 0;
const uint64_t failed = (previewOk ? p.failed - b.failed : 0) + c.videoFailed.load();
const uint64_t videoDrops = replaced + busy + failed;
const uint64_t videoIssues = videoDrops + c.videoIdGaps.load() + c.videoIdResets.load();
uint64_t audioIssues, audioDrops, audioGaps, audioResets, audioFailed, lastDropId;
double droppedMs, writeStallMs, readGapMs;
bool audioAccounted;
qint64 lastDropTime;
{
std::lock_guard<std::mutex> lock(c.audioQueueMutex);
const double bytesPerSecond = static_cast<double>(c.audioFormat.sample_rate) *
c.audioFormat.channels * (c.audioFormat.bits_per_sample / 8);
droppedMs = bytesPerSecond > 0 ? c.audioDroppedBytes * 1000.0 / bytesPerSecond : 0;
audioDrops = c.audioQueueDrops.load();
audioGaps = c.audioIdGaps;
audioResets = c.audioIdResets;
audioFailed = c.audioFailedBytes;
audioIssues = audioDrops + audioGaps + audioResets + c.audioFailedBytes;
writeStallMs = c.audioMaxWriteStallMs;
readGapMs = c.audioMaxReadGapMs;
lastDropId = c.audioLastDropId;
lastDropTime = c.audioLastDropTimeMs;
audioAccounted = c.audioQueuedBytes == 0 && c.audioReceivedBytes ==
c.audioAcceptedBytes + c.audioDroppedBytes + c.audioCancelledBytes + c.audioFailedBytes;
}
if (finalSnapshot)
{
appendLog(QStringLiteral("CH%1 Summary | video_received=%2 preview_drops=%3 | audio_drops=%4 (%5 ms)")
.arg(channelIndex).arg(count(c.videoReceived.load())).arg(count(videoDrops))
.arg(count(audioDrops)).arg(droppedMs, 0, 'f', 1));
const bool videoAccounted = previewOk && c.videoReceived.load() ==
c.videoSubmitted.load() + c.videoFailed.load() &&
c.videoSubmitted.load() == p.submitted - b.submitted;
if (!videoAccounted || !audioAccounted)
appendLog(QStringLiteral("CH%1 ERROR delivery accounting mismatch | video=%2 audio=%3")
.arg(channelIndex).arg(videoAccounted ? QStringLiteral("OK") : QStringLiteral("MISMATCH"))
.arg(audioAccounted ? QStringLiteral("OK") : QStringLiteral("MISMATCH")));
}
// Also flush any changes since the last aggregate when stopping.
if (videoIssues != c.lastLoggedVideoIssues)
{
QString message = QStringLiteral("CH%1 Video issue +%2 | preview_drops=%3 (replaced=%4 busy=%5 failed=%6)")
.arg(channelIndex).arg(count(videoIssues - c.lastLoggedVideoIssues)).arg(count(videoDrops))
.arg(count(replaced)).arg(count(busy)).arg(count(failed));
if (busy)
message += QStringLiteral(" | busy_reason: present=%1 slots=%2 last_frame_id=%3")
.arg(count(p.present_busy - b.present_busy)).arg(count(p.slots_busy - b.slots_busy))
.arg(count(p.last_busy_id));
if (c.videoIdGaps.load() || c.videoIdResets.load())
message += QStringLiteral(" | id_gaps=%1 reset_or_duplicate=%2")
.arg(count(c.videoIdGaps.load())).arg(count(c.videoIdResets.load()));
appendLog(message);
}
if (audioIssues != c.lastLoggedAudioIssues)
{
QString message = QStringLiteral("CH%1 Audio issue | drops=%2 (%3 ms) max_write_stall=%4 ms max_read_gap=%5 ms last_drop=%6@%7")
.arg(channelIndex).arg(count(audioDrops)).arg(droppedMs, 0, 'f', 1)
.arg(writeStallMs, 0, 'f', 1).arg(readGapMs, 0, 'f', 1).arg(count(lastDropId))
.arg(lastDropTime ? QDateTime::fromMSecsSinceEpoch(lastDropTime).toString(QStringLiteral("HH:mm:ss.zzz")) : QStringLiteral("--"));
if (audioGaps || audioResets || audioFailed)
message += QStringLiteral(" | id_gaps=%1 reset_or_duplicate=%2 failed_bytes=%3")
.arg(count(audioGaps)).arg(count(audioResets)).arg(count(audioFailed));
appendLog(message);
}
if (finalSnapshot || videoIssues != c.lastLoggedVideoIssues || audioIssues != c.lastLoggedAudioIssues)
c.lastDeliveryLogMs = now;
c.lastLoggedVideoIssues = videoIssues;
c.lastLoggedAudioIssues = audioIssues;
}
void MainWindow::captureReadLoop(int channelIndex)
{
constexpr uint64_t kTimingWarmupFrames = 30;
@@ -1032,6 +1140,14 @@ void MainWindow::captureReadLoop(int channelIndex)
.count();
if (st == GVFG_OK)
{
const uint64_t previousId = channel.videoLastId.exchange(frame.frame_id);
if (channel.videoReceived.fetch_add(1) != 0)
{
if (frame.frame_id > previousId && frame.frame_id - previousId > 1)
channel.videoIdGaps += frame.frame_id - previousId - 1;
else if (frame.frame_id <= previousId)
++channel.videoIdResets;
}
const bool timingWarmupComplete = ++successfulFrameCount > kTimingWarmupFrames;
if (timingWarmupComplete)
{
@@ -1103,6 +1219,7 @@ void MainWindow::captureReadLoop(int channelIndex)
std::chrono::duration<double, std::milli>(previewEnd - previewStart).count();
if (previewStatus != GVFG_PREVIEW_OK)
{
++channel.videoFailed;
const uint64_t failures = ++channel.previewFailureCount;
if (failures == 1)
{
@@ -1115,6 +1232,7 @@ void MainWindow::captureReadLoop(int channelIndex)
}
else
{
++channel.videoSubmitted;
if (channel.previewFailureCount != 0)
{
const uint64_t failures = channel.previewFailureCount;
@@ -1152,6 +1270,8 @@ void MainWindow::captureReadLoop(int channelIndex)
}
}
}
if (!channel.previewHandle)
++channel.videoFailed;
const gvfg_status_t releaseStatus = gvfg_release_channel_frame(handle_, channelIndex, &frame);
if (releaseStatus != GVFG_OK)
{
@@ -1213,6 +1333,7 @@ void MainWindow::joinCaptureThread(int channel)
void MainWindow::audioReadLoop(int channelIndex)
{
ChannelRuntime &channel = channels_[channelIndex];
auto lastArrival = std::chrono::steady_clock::time_point{};
while (!channel.stopRequested.load(std::memory_order_acquire))
{
gvfg_audio_frame_t frame{};
@@ -1230,10 +1351,33 @@ void MainWindow::audioReadLoop(int channelIndex)
break;
}
const uint64_t audioId = frame.frame_id;
const auto arrival = std::chrono::steady_clock::now();
{
std::lock_guard<std::mutex> lock(channel.audioQueueMutex);
if (lastArrival != std::chrono::steady_clock::time_point{})
channel.audioMaxReadGapMs = (std::max)(channel.audioMaxReadGapMs,
std::chrono::duration<double, std::milli>(arrival - lastArrival).count());
if (channel.audioReceivedBytes != 0)
{
if (audioId > channel.audioLastId && audioId - channel.audioLastId > 1)
channel.audioIdGaps += audioId - channel.audioLastId - 1;
else if (audioId <= channel.audioLastId)
++channel.audioIdResets;
}
channel.audioLastId = audioId;
channel.audioReceivedBytes += frame.data_size;
}
lastArrival = arrival;
std::vector<uint8_t> pcm(frame.data_size);
std::memcpy(pcm.data(), frame.data, frame.data_size);
const gvfg_status_t releaseStatus =
gvfg_release_channel_audio_frame(handle_, channelIndex, &frame);
if (releaseStatus != GVFG_OK)
{
std::lock_guard<std::mutex> lock(channel.audioQueueMutex);
channel.audioFailedBytes += pcm.size();
}
if (releaseStatus != GVFG_OK && !channel.stopRequested.load(std::memory_order_acquire))
{
QMetaObject::invokeMethod(this, [this, channelIndex, releaseStatus]()
@@ -1245,12 +1389,23 @@ void MainWindow::audioReadLoop(int channelIndex)
{
{
std::lock_guard<std::mutex> lock(channel.audioQueueMutex);
if (channel.stopRequested.load(std::memory_order_acquire))
{
channel.audioCancelledBytes += pcm.size();
break;
}
if (channel.audioQueue.size() >= kMaxQueuedAudioFrames)
{
const auto &oldest = channel.audioQueue.front();
channel.audioDroppedBytes += oldest.pcm.size();
channel.audioQueuedBytes -= oldest.pcm.size();
channel.audioLastDropId = oldest.id;
channel.audioLastDropTimeMs = QDateTime::currentMSecsSinceEpoch();
channel.audioQueue.pop_front();
channel.audioQueueDrops.fetch_add(1, std::memory_order_relaxed);
}
channel.audioQueue.push_back(std::move(pcm));
channel.audioQueuedBytes += pcm.size();
channel.audioQueue.push_back({std::move(pcm), audioId});
}
channel.audioQueueReady.notify_one();
}
@@ -1317,22 +1472,39 @@ void MainWindow::audioPlaybackLoop(int channelIndex)
});
if (channel.stopRequested.load(std::memory_order_acquire))
break;
pcm = std::move(channel.audioQueue.front());
pcm = std::move(channel.audioQueue.front().pcm);
channel.audioQueue.pop_front();
channel.audioQueuedBytes -= pcm.size();
}
qint64 written = 0;
auto lastProgress = std::chrono::steady_clock::now();
while (written < static_cast<qint64>(pcm.size()) &&
!channel.stopRequested.load(std::memory_order_acquire))
{
const qint64 result = audioOutput->write(
reinterpret_cast<const char *>(pcm.data()) + written,
static_cast<qint64>(pcm.size()) - written);
if (result < 0)
const auto writeEnd = std::chrono::steady_clock::now();
const bool stalled = result == 0 && writeEnd - lastProgress >= std::chrono::seconds(2);
{
QMetaObject::invokeMethod(this, [this, channelIndex]()
std::lock_guard<std::mutex> lock(channel.audioQueueMutex);
channel.audioMaxWriteStallMs = (std::max)(channel.audioMaxWriteStallMs,
std::chrono::duration<double, std::milli>(writeEnd - lastProgress).count());
if (result > 0)
channel.audioAcceptedBytes += static_cast<uint64_t>(result);
else if (result < 0 || stalled)
channel.audioFailedBytes += pcm.size() - static_cast<uint64_t>(written);
}
if (result > 0)
lastProgress = writeEnd;
if (result < 0 || stalled)
{
appendLog(QStringLiteral("CH%1 Audio output write failed").arg(channelIndex));
QMetaObject::invokeMethod(this, [this, channelIndex, stalled]()
{
appendLog(stalled
? QStringLiteral("CH%1 Audio output made no write progress for 2 seconds; stopping. Check the playback device, then Start again.").arg(channelIndex)
: QStringLiteral("CH%1 Audio output write failed").arg(channelIndex));
stopCapture(channelIndex); }, Qt::QueuedConnection);
audioSink.stop();
return;
@@ -1349,6 +1521,11 @@ void MainWindow::audioPlaybackLoop(int channelIndex)
channel.audioFrames.fetch_add(1, std::memory_order_relaxed);
channel.audioBytes.fetch_add(pcm.size(), std::memory_order_relaxed);
}
else
{
std::lock_guard<std::mutex> lock(channel.audioQueueMutex);
channel.audioCancelledBytes += pcm.size() - static_cast<uint64_t>(written);
}
}
audioSink.stop();
}
@@ -1361,5 +1538,7 @@ void MainWindow::joinAudioThread(int channel)
if (channels_[channel].audioPlaybackThread.joinable())
channels_[channel].audioPlaybackThread.join();
std::lock_guard<std::mutex> lock(channels_[channel].audioQueueMutex);
channels_[channel].audioCancelledBytes += channels_[channel].audioQueuedBytes;
channels_[channel].audioQueuedBytes = 0;
channels_[channel].audioQueue.clear();
}
+24 -1
View File
@@ -51,12 +51,34 @@ private:
std::thread audioPlaybackThread;
std::mutex audioQueueMutex;
std::condition_variable audioQueueReady;
std::deque<std::vector<uint8_t>> audioQueue;
struct AudioPacket { std::vector<uint8_t> pcm; uint64_t id; };
std::deque<AudioPacket> audioQueue;
bool audioEnabled = false;
gvfg_audio_format_t audioFormat{};
std::atomic<uint64_t> audioFrames{0};
std::atomic<uint64_t> audioBytes{0};
std::atomic<uint64_t> audioQueueDrops{0};
// Audio accounting is protected by audioQueueMutex. Accepted means
// written to QAudioSink, not physically played by the device.
uint64_t audioReceivedBytes = 0;
uint64_t audioAcceptedBytes = 0;
uint64_t audioQueuedBytes = 0;
uint64_t audioDroppedBytes = 0;
uint64_t audioCancelledBytes = 0;
uint64_t audioFailedBytes = 0;
uint64_t audioIdGaps = 0;
uint64_t audioIdResets = 0;
uint64_t audioLastId = 0;
uint64_t audioLastDropId = 0;
qint64 audioLastDropTimeMs = 0;
double audioMaxWriteStallMs = 0;
double audioMaxReadGapMs = 0;
std::atomic<uint64_t> videoReceived{0}, videoSubmitted{0}, videoFailed{0};
std::atomic<uint64_t> videoIdGaps{0}, videoIdResets{0};
std::atomic<uint64_t> videoLastId{0};
gvfg_preview_delivery_stats_t previewBaseline{};
uint64_t lastLoggedVideoIssues = 0, lastLoggedAudioIssues = 0;
qint64 lastDeliveryLogMs = 0;
std::atomic<double> getFrameAverageMs{0.0};
std::atomic<double> getFrameMaximumMs{0.0};
std::atomic<double> getFrameWindowMaximumMs{0.0};
@@ -105,6 +127,7 @@ private:
void audioPlaybackLoop(int channel);
void joinCaptureThread(int channel);
void joinAudioThread(int channel);
void logDeliveryStatus(int channel, bool finalSnapshot = false);
static constexpr qint64 kMaxLogFileBytes = 20ll * 1024ll * 1024ll;
+76 -143
View File
@@ -80,30 +80,6 @@ cbuffer ProcAmp : register(b0)
float pad1;
};
static float3 apply_rgb_procamp(float3 rgb)
{
// contrast + brightness
rgb = (rgb - 0.5) * ct + 0.5 + br;
// saturation
float l = dot(rgb, float3(0.299, 0.587, 0.114));
rgb = lerp(float3(l, l, l), rgb, sat);
return saturate(rgb);
}
static float2 rotate_uv(float2 uv01)
{
// uv01 is 0..1, convert to signed around 0
float2 uv = uv01 - 0.5;
float u = uv.x;
float v = uv.y;
float u2 = u * hueCos - v * hueSin;
float v2 = u * hueSin + v * hueCos;
return float2(u2, v2) + 0.5;
}
float3 yuv_to_rgb709(float y, float u, float v)
{
y = y * 255.0;
@@ -118,46 +94,14 @@ float3 yuv_to_rgb709(float y, float u, float v)
return float3(r,g,b)/255.0;
}
float loadY(int x, int y)
{
x = clamp(x, 0, (int)width - 1);
y = clamp(y, 0, (int)height - 1);
uint4 p = texP.Load(int3(x >> 1, y, 0));
uint yy = ((x & 1) != 0) ? p.b : p.r;
return (float)yy / 255.0;
}
float2 loadUV01(int x, int y)
{
x = clamp(x, 0, (int)width - 1);
y = clamp(y, 0, (int)height - 1);
uint4 p = texP.Load(int3(x >> 1, y, 0));
float u = (float)p.g / 255.0;
float v = (float)p.a / 255.0;
return float2(u, v);
}
float4 main(float4 pos:SV_Position, float2 uv:TEXCOORD0) : SV_Target
{
int2 ip = int2(pos.xy);
int px = ip.x;
int py = ip.y;
// Sharpness on luma
float yC = loadY(px, py);
float yL = loadY(px - 1, py);
float yR = loadY(px + 1, py);
float yU = loadY(px, py - 1);
float yD = loadY(px, py + 1);
float blur = (yC*4.0 + yL + yR + yU + yD) / 8.0;
float y = saturate(yC + sharpAmt * (yC - blur));
float2 uv01 = loadUV01(px, py);
uv01 = rotate_uv(uv01);
float3 rgb = yuv_to_rgb709(y, uv01.x, uv01.y);
rgb = apply_rgb_procamp(rgb);
return float4(rgb, 1.0);
uint4 p = texP.Load(int3(ip.x >> 1, ip.y, 0));
float y = (float)(((ip.x & 1) != 0) ? p.b : p.r) / 255.0;
float u = (float)p.g / 255.0;
float v = (float)p.a / 255.0;
return float4(saturate(yuv_to_rgb709(y, u, v)), 1.0);
}
)";
@@ -190,24 +134,6 @@ cbuffer ProcAmp : register(b0)
float pad1;
};
static float3 apply_rgb_procamp(float3 rgb)
{
rgb = (rgb - 0.5) * ct + 0.5 + br;
float l = dot(rgb, float3(0.299, 0.587, 0.114));
rgb = lerp(float3(l, l, l), rgb, sat);
return saturate(rgb);
}
static float2 rotate_uv(float2 uv01)
{
float2 uv = uv01 - 0.5;
float u = uv.x;
float v = uv.y;
float u2 = u * hueCos - v * hueSin;
float v2 = u * hueSin + v * hueCos;
return float2(u2, v2) + 0.5;
}
float3 yuv_to_rgb709(float y, float u, float v)
{
y = y * 255.0;
@@ -222,58 +148,23 @@ float3 yuv_to_rgb709(float y, float u, float v)
return float3(r,g,b)/255.0;
}
float loadY(int x, int y)
{
x = clamp(x, 0, (int)width - 1);
y = clamp(y, 0, (int)height - 1);
uint4 p = texP.Load(int3(x >> 1, y, 0));
uint yy = (((x & 1) != 0) ? p.b : p.r) >> 6;
return (float)(yy & 1023) / 1023.0;
}
float2 loadUV01(int x, int y)
{
x = clamp(x, 0, (int)width - 1);
y = clamp(y, 0, (int)height - 1);
uint4 p = texP.Load(int3(x >> 1, y, 0));
uint chroma1 = (p.g >> 6) & 1023;
uint chroma2 = (p.a >> 6) & 1023;
uint u10 = kSwapUV ? chroma2 : chroma1;
uint v10 = kSwapUV ? chroma1 : chroma2;
// An odd-width tail has no complete second chroma word; match the old
// upload behavior by reusing the available chroma component.
if (((width & 1) != 0) && x == (int)width - 1)
{
if (kSwapUV)
u10 = v10;
else
v10 = u10;
}
float u = (float)u10 / 1023.0;
float v = (float)v10 / 1023.0;
return float2(u, v);
}
float4 main(float4 pos:SV_Position, float2 uv:TEXCOORD0) : SV_Target
{
int2 ip = int2(pos.xy);
int px = ip.x;
int py = ip.y;
float yC = loadY(px, py);
float yL = loadY(px - 1, py);
float yR = loadY(px + 1, py);
float yU = loadY(px, py - 1);
float yD = loadY(px, py + 1);
float blur = (yC*4.0 + yL + yR + yU + yD) / 8.0;
float y = saturate(yC + sharpAmt * (yC - blur));
float2 uv01 = loadUV01(px, py);
uv01 = rotate_uv(uv01);
float3 rgb = yuv_to_rgb709(y, uv01.x, uv01.y);
rgb = apply_rgb_procamp(rgb);
return float4(rgb, 1.0);
uint4 p = texP.Load(int3(ip.x >> 1, ip.y, 0));
uint yy = ((((ip.x & 1) != 0) ? p.b : p.r) >> 6) & 1023;
uint c1 = (p.g >> 6) & 1023;
uint c2 = (p.a >> 6) & 1023;
uint u10 = kSwapUV ? c2 : c1;
uint v10 = kSwapUV ? c1 : c2;
// Preserve the existing odd-width tail chroma rule.
if (((width & 1) != 0) && ip.x == (int)width - 1)
{
if (kSwapUV) u10 = v10;
else v10 = u10;
}
return float4(saturate(yuv_to_rgb709((float)yy / 1023.0,
(float)u10 / 1023.0, (float)v10 / 1023.0)), 1.0);
}
)";
@@ -407,8 +298,8 @@ bool D3DPreviewPipeline::create_shaders_and_states()
{
if (vs_ && il_ &&
ps_yuy2_ && ps_y210_ &&
ps_fp16_to_rgba8_ &&
ps_fp16_to_nv12_y_ && ps_fp16_to_nv12_uv_ &&
(preview_only_ || (ps_fp16_to_rgba8_ &&
ps_fp16_to_nv12_y_ && ps_fp16_to_nv12_uv_)) &&
ps_fp16_to_preview_ && ps_rgba8_to_preview_ &&
vb_ && samp_ && cs_params_)
return true;
@@ -441,6 +332,8 @@ bool D3DPreviewPipeline::create_shaders_and_states()
if (FAILED(d3d_->CreatePixelShader(psbY210->GetBufferPointer(), psbY210->GetBufferSize(), nullptr, &ps_y210_)))
return false;
if (!preview_only_)
{
if (FAILED(D3DCompile(g_ps_fp16_to_rgba8, strlen(g_ps_fp16_to_rgba8), nullptr, nullptr, nullptr,
"main", "ps_5_0", 0, 0, &psb4, &err)))
return false;
@@ -459,6 +352,8 @@ bool D3DPreviewPipeline::create_shaders_and_states()
nullptr, &ps_fp16_to_nv12_uv_)))
return false;
}
if (FAILED(D3DCompile(g_ps_fp16_to_preview, strlen(g_ps_fp16_to_preview), nullptr, nullptr, nullptr,
"main", "ps_5_0", 0, 0, &psb5, &err)))
return false;
@@ -510,16 +405,23 @@ bool D3DPreviewPipeline::create_shaders_and_states()
return true;
}
bool D3DPreviewPipeline::ensure_rt_and_pipeline(int w, int h)
bool D3DPreviewPipeline::ensure_rt_and_pipeline(int w, int h, bool previewOnly)
{
if (!d3d_ || !ctx_ || w <= 0 || h <= 0)
return false;
const bool hasAllTargets = rt_fp16_ && rtv_fp16_ && srv_fp16_ &&
rt_scene_fp16_ && rtv_scene_fp16_ && srv_scene_fp16_ &&
rt_rgba_ && rtv_rgba_ && srv_rgba_ &&
rt_rgb10_ && rtv_rgb10_ &&
rt_nv12_y_ && rtv_nv12_y_ && rt_nv12_uv_ && rtv_nv12_uv_;
if (hasAllTargets && rt_w_ == w && rt_h_ == h)
return true;
const bool hasPreviewTarget = rt_fp16_ && rtv_fp16_ && srv_fp16_;
if ((previewOnly ? hasPreviewTarget : hasAllTargets) &&
preview_only_ == previewOnly && rt_w_ == w && rt_h_ == h)
return create_shaders_and_states();
preview_only_ = previewOnly;
ctx_->OMSetRenderTargets(0, nullptr, nullptr);
rt_fp16_.Reset();
rtv_fp16_.Reset();
@@ -561,6 +463,17 @@ bool D3DPreviewPipeline::ensure_rt_and_pipeline(int w, int h)
if (FAILED(d3d_->CreateShaderResourceView(rt_fp16_.Get(), nullptr, &srv_fp16_)))
return false;
// A preview needs only the full-precision conversion target. Export-only
// BGRA/RGB10/NV12 targets remain available to the public buffer converter.
if (previewOnly)
{
if (!create_shaders_and_states())
return false;
rt_w_ = w;
rt_h_ = h;
return true;
}
// 2) Scene FP16 target used by the preview path
td.Format = DXGI_FORMAT_R16G16B16A16_FLOAT;
td.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
@@ -990,13 +903,13 @@ bool D3DPreviewPipeline::render_uploaded_yuv_to_fp16(gvfg_render_pixfmt_t fmt, i
bool D3DPreviewPipeline::render_texture_to_fp16(ID3D11Texture2D *texture,
gvfg_render_pixfmt_t fmt,
int frame_w,
int frame_h)
int frame_h, ID3D11ShaderResourceView *cachedView)
{
if (!ctx_ || !vs_ || !il_ || !vb_ || !rtv_fp16_ || !rt_fp16_ || frame_w <= 0 || frame_h <= 0)
return false;
ID3D11PixelShader *ps = nullptr;
ComPtr<ID3D11ShaderResourceView> srv0;
ComPtr<ID3D11ShaderResourceView> srv0 = cachedView;
if (fmt == GVFG_RENDER_FMT_YUY2)
{
if (!texture)
@@ -1005,7 +918,7 @@ bool D3DPreviewPipeline::render_texture_to_fp16(ID3D11Texture2D *texture,
sd.Format = DXGI_FORMAT_R8G8B8A8_UINT;
sd.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
sd.Texture2D.MipLevels = 1;
if (FAILED(d3d_->CreateShaderResourceView(texture, &sd, &srv0)) || !srv0)
if (!srv0 && FAILED(d3d_->CreateShaderResourceView(texture, &sd, &srv0)))
return false;
ps = ps_yuy2_.Get();
if (!ps)
@@ -1019,7 +932,7 @@ bool D3DPreviewPipeline::render_texture_to_fp16(ID3D11Texture2D *texture,
sd.Format = DXGI_FORMAT_R16G16B16A16_UINT;
sd.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
sd.Texture2D.MipLevels = 1;
if (FAILED(d3d_->CreateShaderResourceView(texture, &sd, &srv0)) || !srv0)
if (!srv0 && FAILED(d3d_->CreateShaderResourceView(texture, &sd, &srv0)))
return false;
ps = ps_y210_.Get();
if (!ps)
@@ -1059,15 +972,19 @@ bool D3DPreviewPipeline::render_texture_to_fp16(ID3D11Texture2D *texture,
if (cs_params_)
{
D3D11_MAPPED_SUBRESOURCE mapped{};
if (SUCCEEDED(ctx_->Map(cs_params_.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped)))
if (params_w_ != frame_w || params_h_ != frame_h)
{
D3D11_MAPPED_SUBRESOURCE mapped{};
if (FAILED(ctx_->Map(cs_params_.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped)))
return false;
std::memcpy(mapped.pData, &cb, sizeof(cb));
ctx_->Unmap(cs_params_.Get(), 0);
params_w_ = frame_w;
params_h_ = frame_h;
}
ID3D11Buffer *cb0[1] = {cs_params_.Get()};
ctx_->PSSetConstantBuffers(0, 1, cb0);
}
}
UINT stride = sizeof(float) * 4, offset = 0;
ID3D11Buffer *pVB = vb_.Get();
@@ -1088,8 +1005,7 @@ bool D3DPreviewPipeline::render_texture_to_fp16(ID3D11Texture2D *texture,
ID3D11RenderTargetView *rtv = rtv_fp16_.Get();
ctx_->OMSetRenderTargets(1, &rtv, nullptr);
const float clear[4] = {0, 0, 0, 1};
ctx_->ClearRenderTargetView(rtv_fp16_.Get(), clear);
// The conversion draw covers every pixel of this target.
ID3D11ShaderResourceView *srvs[1] = {srv0.Get()};
ctx_->PSSetShaderResources(0, 1, srvs);
@@ -1114,6 +1030,8 @@ bool D3DPreviewPipeline::copy_fp16_to_scene()
void D3DPreviewPipeline::release_preview_swapchain()
{
if (ctx_)
ctx_->OMSetRenderTargets(0, nullptr, nullptr);
preview_rtv_.Reset();
preview_backbuf_.Reset();
preview_swapchain_.Reset();
@@ -1225,6 +1143,7 @@ bool D3DPreviewPipeline::ensure_preview_swapchain(int w, int h)
}
else if (preview_w_ != clientW || preview_h_ != clientH)
{
ctx_->OMSetRenderTargets(0, nullptr, nullptr);
preview_rtv_.Reset();
preview_backbuf_.Reset();
@@ -1360,7 +1279,14 @@ gvfg_preview_present_result_t D3DPreviewPipeline::present_preview(int src_w, int
ctx_->VSSetShader(vs_.Get(), nullptr, 0);
ID3D11ShaderResourceView *srv = nullptr;
if (preview_swapchain_10bit_)
if (preview_only_)
{
if (!srv_fp16_ || !ps_fp16_to_preview_)
return GVFG_PREVIEW_PRESENT_FAILED;
ctx_->PSSetShader(ps_fp16_to_preview_.Get(), nullptr, 0);
srv = srv_fp16_.Get();
}
else if (preview_swapchain_10bit_)
{
if (!srv_scene_fp16_ || !ps_fp16_to_preview_)
return GVFG_PREVIEW_PRESENT_FAILED;
@@ -1401,6 +1327,13 @@ gvfg_preview_present_result_t D3DPreviewPipeline::present_preview(int src_w, int
ID3D11ShaderResourceView *nullSrv[1] = {nullptr};
ctx_->PSSetShaderResources(0, 1, nullSrv);
return retry_preview_present();
}
gvfg_preview_present_result_t D3DPreviewPipeline::retry_preview_present()
{
if (!preview_swapchain_)
return GVFG_PREVIEW_PRESENT_FAILED;
HRESULT hr = preview_swapchain_->Present(0, DXGI_PRESENT_DO_NOT_WAIT);
if (hr == DXGI_ERROR_WAS_STILL_DRAWING)
{
+7 -2
View File
@@ -49,10 +49,12 @@ public:
void release_preview_swapchain();
bool create_shaders_and_states();
bool ensure_rt_and_pipeline(int w, int h);
bool ensure_rt_and_pipeline(int w, int h, bool previewOnly = false);
bool ensure_preview_swapchain(int w, int h);
bool preview_swapchain_10bit() const { return preview_swapchain_10bit_; }
gvfg_preview_present_result_t present_preview(int src_w, int src_h);
// Retry a busy Present while the caller retains exclusive context access.
gvfg_preview_present_result_t retry_preview_present();
bool clear_preview_black();
DXGI_FORMAT preview_backbuffer_format() const;
DXGI_FORMAT scene_texture_format() const;
@@ -66,7 +68,7 @@ public:
bool render_texture_to_fp16(ID3D11Texture2D *texture,
gvfg_render_pixfmt_t fmt,
int frame_w,
int frame_h);
int frame_h, ID3D11ShaderResourceView *cachedView = nullptr);
bool copy_fp16_to_scene();
bool readback_to_buffer(void *destination,
uint64_t destination_size,
@@ -133,6 +135,9 @@ public:
int rt_w_ = 0;
int rt_h_ = 0;
bool preview_only_ = false;
int params_w_ = 0;
int params_h_ = 0;
Microsoft::WRL::ComPtr<IDXGISwapChain1> preview_swapchain_;
Microsoft::WRL::ComPtr<ID3D11Texture2D> preview_backbuf_;