Diagnose preview stalls and FIFO frame loss

- add detailed FIFO loss and frame-hold timing diagnostics
- report slow preview calls and per-stage GPU timing
- reduce redundant preview pipeline and DXGI setup work
- move preview performance metrics into the sample status display
- avoid duplicate frame-loss warnings
This commit is contained in:
Mark.lin
2026-08-13 10:49:09 +08:00
parent aad8419c2a
commit bab59efcb5
7 changed files with 149 additions and 39 deletions
+1
View File
@@ -23,6 +23,7 @@ target_include_directories(gvfg_preview
target_compile_definitions(gvfg_preview PRIVATE target_compile_definitions(gvfg_preview PRIVATE
GVFG_PREVIEW_BUILD GVFG_PREVIEW_BUILD
GVFG_INTERNAL_DIAGNOSTICS=$<IF:$<CONFIG:Debug>,1,0>
) )
target_link_libraries(gvfg_preview target_link_libraries(gvfg_preview
+66 -5
View File
@@ -9,8 +9,10 @@
#include <cstddef> #include <cstddef>
#include <cstring> #include <cstring>
#include <deque> #include <deque>
#include <cstdio>
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <windows.h>
#include <wrl/client.h> #include <wrl/client.h>
using Microsoft::WRL::ComPtr; using Microsoft::WRL::ComPtr;
@@ -27,6 +29,9 @@ public:
resetPresentStats(); resetPresentStats();
hwnd_ = hwnd; hwnd_ = hwnd;
configured_ = hwnd_ != nullptr; configured_ = hwnd_ != nullptr;
preparedWidth_ = 0;
preparedHeight_ = 0;
preparedBitDepth_ = 0;
if (configured_ && ensureDevice()) if (configured_ && ensureDevice())
{ {
if (!pipeline_) if (!pipeline_)
@@ -53,6 +58,8 @@ public:
bool render(const gvfg_preview_frame_t &frame) bool render(const gvfg_preview_frame_t &frame)
{ {
using Clock = std::chrono::steady_clock;
const auto totalStart = Clock::now();
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
if (!configured_ || !hwnd_ || !frame.data || frame.width <= 0 || frame.height <= 0) if (!configured_ || !hwnd_ || !frame.data || frame.width <= 0 || frame.height <= 0)
{ {
@@ -68,7 +75,21 @@ public:
sourceBitDepth = 10; sourceBitDepth = 10;
} }
if (!ensureDevice() || !ensurePipeline(frame.width, frame.height, sourceBitDepth)) if (!ensureDevice())
{
clearActiveInfo();
return false;
}
const bool pipelineMatches = pipeline_ &&
preparedWidth_ == frame.width &&
preparedHeight_ == frame.height &&
preparedBitDepth_ == sourceBitDepth;
const bool pipelineReady = pipelineMatches
? pipeline_->ensure_preview_swapchain(frame.width, frame.height)
: ensurePipeline(frame.width, frame.height, sourceBitDepth);
const auto ensureEnd = Clock::now();
if (!pipelineReady)
{ {
clearActiveInfo(); clearActiveInfo();
return false; return false;
@@ -102,10 +123,14 @@ public:
default: default:
return false; return false;
} }
const auto uploadEnd = Clock::now();
if (!uploaded || const bool rendered = uploaded &&
!pipeline_->render_uploaded_yuv_to_fp16(renderFmt, frame.width, frame.height) || pipeline_->render_uploaded_yuv_to_fp16(renderFmt, frame.width, frame.height);
!pipeline_->copy_fp16_to_scene()) const auto renderEnd = Clock::now();
const bool copied = rendered && pipeline_->copy_fp16_to_scene();
const auto copyEnd = Clock::now();
if (!uploaded || !rendered || !copied)
{ {
clearActiveInfo(); clearActiveInfo();
return false; return false;
@@ -114,6 +139,7 @@ public:
bool ok = true; bool ok = true;
if (!pipeline_->preview_swapchain_10bit()) if (!pipeline_->preview_swapchain_10bit())
ok = pipeline_->blit_fp16_to_rgba8(frame.width, frame.height); ok = pipeline_->blit_fp16_to_rgba8(frame.width, frame.height);
const auto blitEnd = Clock::now();
if (!ok) if (!ok)
{ {
clearActiveInfo(); clearActiveInfo();
@@ -122,6 +148,28 @@ public:
const gvfg::internal::gvfg_preview_present_result_t presentResult = const gvfg::internal::gvfg_preview_present_result_t presentResult =
pipeline_->present_preview(frame.width, frame.height); pipeline_->present_preview(frame.width, frame.height);
const auto presentEnd = Clock::now();
#if GVFG_INTERNAL_DIAGNOSTICS
const auto milliseconds = [](Clock::duration duration)
{
return std::chrono::duration<double, std::milli>(duration).count();
};
const double totalMs = milliseconds(presentEnd - totalStart);
if (totalMs >= 10.0)
{
char line[512] = {};
std::snprintf(line, sizeof(line),
"[GVFG][PREVIEW] SLOW frame=%llu total=%.3f lock_ensure=%.3f upload=%.3f render=%.3f copy=%.3f blit=%.3f present=%.3f ms\n",
static_cast<unsigned long long>(frame.frame_id), totalMs,
milliseconds(ensureEnd - totalStart),
milliseconds(uploadEnd - ensureEnd),
milliseconds(renderEnd - uploadEnd),
milliseconds(copyEnd - renderEnd),
milliseconds(blitEnd - copyEnd),
milliseconds(presentEnd - blitEnd));
OutputDebugStringA(line);
}
#endif
if (presentResult == gvfg::internal::GVFG_PREVIEW_PRESENT_FAILED) if (presentResult == gvfg::internal::GVFG_PREVIEW_PRESENT_FAILED)
{ {
clearActiveInfo(); clearActiveInfo();
@@ -153,6 +201,9 @@ public:
pipeline_->release_preview_swapchain(); pipeline_->release_preview_swapchain();
pipeline_.reset(); pipeline_.reset();
d3d_.reset(); d3d_.reset();
preparedWidth_ = 0;
preparedHeight_ = 0;
preparedBitDepth_ = 0;
configured_ = false; configured_ = false;
hwnd_ = nullptr; hwnd_ = nullptr;
clearActiveInfo(); clearActiveInfo();
@@ -375,8 +426,15 @@ private:
desc.swapchain_10bit = gvfg::internal::GVFG_RENDER_PREVIEW_BITDEPTH_AUTO; desc.swapchain_10bit = gvfg::internal::GVFG_RENDER_PREVIEW_BITDEPTH_AUTO;
pipeline_->configurePreview(desc); pipeline_->configurePreview(desc);
pipeline_->set_source_bit_depth(sourceBitDepth > 0 ? sourceBitDepth : 8); pipeline_->set_source_bit_depth(sourceBitDepth > 0 ? sourceBitDepth : 8);
return pipeline_->ensure_rt_and_pipeline(width, height) && const bool ready = pipeline_->ensure_rt_and_pipeline(width, height) &&
pipeline_->ensure_preview_swapchain(width, height); pipeline_->ensure_preview_swapchain(width, height);
if (ready)
{
preparedWidth_ = width;
preparedHeight_ = height;
preparedBitDepth_ = sourceBitDepth > 0 ? sourceBitDepth : 8;
}
return ready;
} }
mutable std::mutex mutex_; mutable std::mutex mutex_;
@@ -387,6 +445,9 @@ private:
std::atomic<int> bitDepth_{0}; std::atomic<int> bitDepth_{0};
std::atomic<bool> swapchain10Bit_{false}; std::atomic<bool> swapchain10Bit_{false};
std::atomic<bool> active_{false}; std::atomic<bool> active_{false};
int preparedWidth_ = 0;
int preparedHeight_ = 0;
int preparedBitDepth_ = 0;
char adapterName_[160] = {}; char adapterName_[160] = {};
int adapterIndex_ = -1; int adapterIndex_ = -1;
std::deque<PresentClock::time_point> presentTimes_; std::deque<PresentClock::time_point> presentTimes_;
+18 -18
View File
@@ -378,6 +378,7 @@ void MainWindow::startCapture()
previewFailureCount_ = 0; previewFailureCount_ = 0;
previewCallAverageMs_.store(0.0, std::memory_order_relaxed); previewCallAverageMs_.store(0.0, std::memory_order_relaxed);
previewCallMaximumMs_.store(0.0, std::memory_order_relaxed);
previewCallSamples_.store(0, std::memory_order_relaxed); previewCallSamples_.store(0, std::memory_order_relaxed);
#if GVFG_INTERNAL_DIAGNOSTICS #if GVFG_INTERNAL_DIAGNOSTICS
haveDebugBaseline_ = false; haveDebugBaseline_ = false;
@@ -501,6 +502,7 @@ void MainWindow::updateSignalStatus()
? QStringLiteral("Measuring") ? QStringLiteral("Measuring")
: QStringLiteral("%1 FPS").arg(previewFps); : QStringLiteral("%1 FPS").arg(previewFps);
const double previewCallAverageMs = previewCallAverageMs_.load(std::memory_order_relaxed); const double previewCallAverageMs = previewCallAverageMs_.load(std::memory_order_relaxed);
const double previewCallMaximumMs = previewCallMaximumMs_.load(std::memory_order_relaxed);
const uint64_t previewCallSamples = previewCallSamples_.load(std::memory_order_relaxed); const uint64_t previewCallSamples = previewCallSamples_.load(std::memory_order_relaxed);
QStringList statusLines; QStringList statusLines;
statusLines << (signal.connected statusLines << (signal.connected
@@ -511,9 +513,10 @@ void MainWindow::updateSignalStatus()
.arg(signal.channel)); .arg(signal.channel));
statusLines << (previewInfoOk statusLines << (previewInfoOk
? previewCallSamples > 0 ? previewCallSamples > 0
? QStringLiteral("Preview | %1 | %2 | GPU call avg=%3 ms/frame samples=%4") ? QStringLiteral("Preview | %1 | %2 | GPU call avg=%3 max=%4 ms/frame samples=%5")
.arg(previewState, previewFrame) .arg(previewState, previewFrame)
.arg(previewCallAverageMs, 0, 'f', 3) .arg(previewCallAverageMs, 0, 'f', 3)
.arg(previewCallMaximumMs, 0, 'f', 3)
.arg(static_cast<qulonglong>(previewCallSamples)) .arg(static_cast<qulonglong>(previewCallSamples))
: QStringLiteral("Preview | %1 | %2 | GPU call measuring") : QStringLiteral("Preview | %1 | %2 | GPU call measuring")
.arg(previewState, previewFrame) .arg(previewState, previewFrame)
@@ -555,23 +558,6 @@ void MainWindow::updateSignalStatus()
valueOrDash(backendStats.backend_dma_errors))); valueOrDash(backendStats.backend_dma_errors)));
diagnosticProblemDetected = true; diagnosticProblemDetected = true;
} }
if (backendStats.backend_frames_dropped > lastDebugDroppedFrames_)
{
const uint64_t delta = backendStats.backend_frames_dropped - lastDebugDroppedFrames_;
pendingDroppedFrames_ += delta;
}
}
const qint64 nowMs = QDateTime::currentMSecsSinceEpoch();
if (pendingDroppedFrames_ > 0 &&
(lastDroppedWarningMs_ == 0 || nowMs - lastDroppedWarningMs_ >= 10000))
{
appendLog(QStringLiteral("WARNING dropped frames +%1, total=%2")
.arg(valueOrDash(pendingDroppedFrames_),
valueOrDash(backendStats.backend_frames_dropped)));
pendingDroppedFrames_ = 0;
lastDroppedWarningMs_ = nowMs;
diagnosticProblemDetected = true;
} }
lastDebugDmaErrors_ = backendStats.backend_dma_errors; lastDebugDmaErrors_ = backendStats.backend_dma_errors;
@@ -818,6 +804,20 @@ void MainWindow::captureReadLoop()
const auto previewEnd = std::chrono::steady_clock::now(); const auto previewEnd = std::chrono::steady_clock::now();
const double previewElapsedMs = const double previewElapsedMs =
std::chrono::duration<double, std::milli>(previewEnd - previewStart).count(); std::chrono::duration<double, std::milli>(previewEnd - previewStart).count();
double observedMaximum = previewCallMaximumMs_.load(std::memory_order_relaxed);
while (previewElapsedMs > observedMaximum &&
!previewCallMaximumMs_.compare_exchange_weak(
observedMaximum, previewElapsedMs, std::memory_order_relaxed))
{
}
if (previewElapsedMs >= 10.0)
{
QMetaObject::invokeMethod(this, [this, frameId = frame.frame_id, previewElapsedMs]()
{ appendLog(QStringLiteral("SLOW PREVIEW frame=%1 elapsed=%2 ms")
.arg(static_cast<qulonglong>(frameId))
.arg(previewElapsedMs, 0, 'f', 3)); },
Qt::QueuedConnection);
}
if (previewStatus != GVFG_PREVIEW_OK) if (previewStatus != GVFG_PREVIEW_OK)
{ {
const uint64_t failures = ++previewFailureCount_; const uint64_t failures = ++previewFailureCount_;
+1
View File
@@ -73,6 +73,7 @@ private:
std::thread captureThread_; std::thread captureThread_;
uint64_t previewFailureCount_ = 0; uint64_t previewFailureCount_ = 0;
std::atomic<double> previewCallAverageMs_{0.0}; std::atomic<double> previewCallAverageMs_{0.0};
std::atomic<double> previewCallMaximumMs_{0.0};
std::atomic<uint64_t> previewCallSamples_{0}; std::atomic<uint64_t> previewCallSamples_{0};
QTimer *signalStatusTimer_ = nullptr; QTimer *signalStatusTimer_ = nullptr;
QString lastSignalStatusText_; QString lastSignalStatusText_;
@@ -310,6 +310,8 @@ namespace gvfg::internal
slot.data.assign(bytes, 0); slot.data.assign(bytes, 0);
next_write_slot_ = 0; next_write_slot_ = 0;
active_delivery_slot_ = static_cast<size_t>(-1); active_delivery_slot_ = static_cast<size_t>(-1);
active_delivery_started_ = {};
last_delivery_started_ = {};
pending_events_ = 0; pending_events_ = 0;
latest_sequence_ = 0; latest_sequence_ = 0;
delivered_sequence_ = 0; delivered_sequence_ = 0;
@@ -505,6 +507,8 @@ namespace gvfg::internal
slot.ready = false; slot.ready = false;
slot.in_use = true; slot.in_use = true;
active_delivery_slot_ = readySlot; active_delivery_slot_ = readySlot;
active_delivery_started_ = std::chrono::steady_clock::now();
last_delivery_started_ = active_delivery_started_;
delivered_sequence_ = slot.sequence; delivered_sequence_ = slot.sequence;
++stats_.frames_delivered; ++stats_.frames_delivered;
@@ -535,6 +539,14 @@ namespace gvfg::internal
return PCIES2MM_EINVAL; return PCIES2MM_EINVAL;
frame_ring_[active_delivery_slot_].in_use = false; frame_ring_[active_delivery_slot_].in_use = false;
const double heldMs = active_delivery_started_.time_since_epoch().count() != 0
? std::chrono::duration<double, std::milli>(
std::chrono::steady_clock::now() - active_delivery_started_).count()
: 0.0;
if (heldMs >= 10.0)
PCIES2MM_LOG("slow frame release: frame=%llu held_ms=%.3f",
static_cast<unsigned long long>(frame.frame_id), heldMs);
active_delivery_started_ = {};
active_delivery_slot_ = static_cast<size_t>(-1); active_delivery_slot_ = static_cast<size_t>(-1);
data_cv_.notify_all(); data_cv_.notify_all();
return PCIES2MM_OK; return PCIES2MM_OK;
@@ -841,7 +853,6 @@ namespace gvfg::internal
switch (waitResult - WAIT_OBJECT_0) switch (waitResult - WAIT_OBJECT_0)
{ {
case 0: case 0:
PCIES2MM_LOG("event: DMA");
handle_dma_event(channel); handle_dma_event(channel);
break; break;
case 1: case 1:
@@ -938,6 +949,30 @@ namespace gvfg::internal
{ {
++stats_.frames_dropped; ++stats_.frames_dropped;
frameLost = true; frameLost = true;
#if GVFG_INTERNAL_DIAGNOSTICS
const auto now = std::chrono::steady_clock::now();
const double heldMs = active_delivery_started_.time_since_epoch().count() != 0
? std::chrono::duration<double, std::milli>(now - active_delivery_started_).count()
: 0.0;
const double sinceReadMs = last_delivery_started_.time_since_epoch().count() != 0
? std::chrono::duration<double, std::milli>(now - last_delivery_started_).count()
: 0.0;
PCIES2MM_LOG("FIFO LOSS: total=%llu overwrite_slot=%zu overwrite_seq=%llu delivered=%llu latest=%llu active_slot=%zu held_ms=%.3f since_read_ms=%.3f pending=%u",
static_cast<unsigned long long>(stats_.frames_dropped),
slotIndex,
static_cast<unsigned long long>(slot.sequence),
static_cast<unsigned long long>(delivered_sequence_),
static_cast<unsigned long long>(latest_sequence_),
active_delivery_slot_, heldMs, sinceReadMs, pending_events_);
for (size_t i = 0; i < frame_ring_.size(); ++i)
{
const FrameSlot &diagnosticSlot = frame_ring_[i];
PCIES2MM_LOG("FIFO slot[%zu]: ready=%d in_use=%d sequence=%llu bytes=%zu",
i, diagnosticSlot.ready ? 1 : 0, diagnosticSlot.in_use ? 1 : 0,
static_cast<unsigned long long>(diagnosticSlot.sequence),
diagnosticSlot.bytes);
}
#endif
} }
slot.ready = false; slot.ready = false;
slot.in_use = true; slot.in_use = true;
@@ -951,7 +986,13 @@ namespace gvfg::internal
emit_event(PCIES2MM_EVENT_FRAME_LOSS); emit_event(PCIES2MM_EVENT_FRAME_LOSS);
const uint32_t frameIndex = doneIndex % kDmaBufferCount; const uint32_t frameIndex = doneIndex % kDmaBufferCount;
const auto getFrameStarted = std::chrono::steady_clock::now();
const int ret = get_frame(channel, frameIndex, slotData, bytes); const int ret = get_frame(channel, frameIndex, slotData, bytes);
const double getFrameMs = std::chrono::duration<double, std::milli>(
std::chrono::steady_clock::now() - getFrameStarted).count();
if (getFrameMs >= 10.0)
PCIES2MM_LOG("slow GET_FRAME: done_index=%u frame_index=%u elapsed_ms=%.3f ret=%d",
doneIndex, frameIndex, getFrameMs, ret);
if (!running_) if (!running_)
return; return;
if (ret < 0 || static_cast<DWORD>(ret) != bytes) if (ret < 0 || static_cast<DWORD>(ret) != bytes)
@@ -7,6 +7,7 @@
#include <atomic> #include <atomic>
#include <condition_variable> #include <condition_variable>
#include <chrono>
#include <cstddef> #include <cstddef>
#include <cstdint> #include <cstdint>
#include <mutex> #include <mutex>
@@ -125,6 +126,8 @@ namespace gvfg::internal
uint64_t latest_sequence_ = 0; uint64_t latest_sequence_ = 0;
uint64_t delivered_sequence_ = 0; uint64_t delivered_sequence_ = 0;
uint64_t wait_timeout_count_ = 0; uint64_t wait_timeout_count_ = 0;
std::chrono::steady_clock::time_point active_delivery_started_{};
std::chrono::steady_clock::time_point last_delivery_started_{};
bool stream_error_ = false; bool stream_error_ = false;
pcies2mm_stream_stats_t stats_{}; pcies2mm_stream_stats_t stats_{};
mutable std::string last_error_; mutable std::string last_error_;
+17 -14
View File
@@ -1131,20 +1131,6 @@ bool D3DPreviewPipeline::ensure_preview_swapchain(int w, int h)
clientH = h; clientH = h;
} }
ComPtr<IDXGIDevice> dxgiDev;
if (!d3d_ || FAILED(d3d_->QueryInterface(IID_PPV_ARGS(&dxgiDev))) || !dxgiDev)
return false;
ComPtr<IDXGIAdapter> adapter;
if (FAILED(dxgiDev->GetAdapter(&adapter)) || !adapter)
return false;
ComPtr<IDXGIFactory2> factory;
if (FAILED(adapter->GetParent(__uuidof(IDXGIFactory2),
reinterpret_cast<void **>(factory.GetAddressOf()))) ||
!factory)
return false;
const int effectiveMode = (preview_swapchain_mode_ == GVFG_RENDER_PREVIEW_BITDEPTH_AUTO) const int effectiveMode = (preview_swapchain_mode_ == GVFG_RENDER_PREVIEW_BITDEPTH_AUTO)
? ((preview_source_bit_depth_ >= 10) ? GVFG_RENDER_PREVIEW_BITDEPTH_10BIT : GVFG_RENDER_PREVIEW_BITDEPTH_8BIT) ? ((preview_source_bit_depth_ >= 10) ? GVFG_RENDER_PREVIEW_BITDEPTH_10BIT : GVFG_RENDER_PREVIEW_BITDEPTH_8BIT)
: preview_swapchain_mode_; : preview_swapchain_mode_;
@@ -1164,6 +1150,23 @@ bool D3DPreviewPipeline::ensure_preview_swapchain(int w, int h)
if (!preview_swapchain_) if (!preview_swapchain_)
{ {
// Factory discovery is needed only while creating a swapchain. It
// used to run for every preview frame even when the existing
// swapchain size and format were unchanged.
ComPtr<IDXGIDevice> dxgiDev;
if (FAILED(d3d_->QueryInterface(IID_PPV_ARGS(&dxgiDev))) || !dxgiDev)
return false;
ComPtr<IDXGIAdapter> adapter;
if (FAILED(dxgiDev->GetAdapter(&adapter)) || !adapter)
return false;
ComPtr<IDXGIFactory2> factory;
if (FAILED(adapter->GetParent(__uuidof(IDXGIFactory2),
reinterpret_cast<void **>(factory.GetAddressOf()))) ||
!factory)
return false;
DXGI_SWAP_CHAIN_DESC1 sd{}; DXGI_SWAP_CHAIN_DESC1 sd{};
sd.Width = (UINT)clientW; sd.Width = (UINT)clientW;
sd.Height = (UINT)clientH; sd.Height = (UINT)clientH;