Harden GVFG signal recovery and preview lifecycle
Compared with d03f064:
- Pause the sample video and audio readers after signal disconnect events and resume them only after reconnect or stream-ready notification.
- Serialize plug, unplug, and format transitions against active reads and held zero-copy frames while keeping stop and close able to interrupt lifecycle waits.
- Treat ERROR_BAD_COMMAND as unplug-revoked zero-copy ownership only after the backend has confirmed signal loss, while preserving all other release failures for retry and diagnosis.
- Stop submitting frames when the user closes an independent preview window, account those frames as intentionally skipped, and resume submission when preview is reopened.
- Emit UTF-16 Windows debug output so localized Win32 error messages remain readable in Qt and debugger output.
- Add startup and first-frame timing diagnostics, reduce routine stream-ready logging, and update public and internal documentation for the new disconnect and ownership behavior.
Validation: git diff --check and focused symbol/document consistency searches passed; no build or hardware validation was run.
This commit is contained in:
@@ -105,6 +105,9 @@ gvfg_open_channel(handle, device_index, GVFG_CHANNEL_0);
|
||||
|
||||
`VIDEO_DMA` 為 frame capture 必需,SDK 固定註冊。Plug-in、Unplug 與
|
||||
Format-change driver event 則依 mask 註冊;關閉它們也會停用對應的自動訊號恢復。
|
||||
Application 收到 `GVFG_EVENT_SIGNAL_DISCONNECTED` 後應暫停 video/audio read,
|
||||
等待 `GVFG_EVENT_SIGNAL_CONNECTED` 或 stop 再喚醒 worker,不應在已知無訊號時持續
|
||||
輪詢 timeout。
|
||||
|
||||
每個 channel 預設為 copy mode。指定 channel open 後不可切換該路模式;
|
||||
另一條尚未 open 的 channel 仍可獨立選擇。Zero-copy mode 仍使用相同的 `gvfg_read_channel_frame()` /
|
||||
@@ -162,6 +165,9 @@ runtime API 都明確要求 `channel_index`;不再保留隱含 selected-channe
|
||||
`gvfg_qt_preview.exe` 只使用 public API,主畫面只顯示 input 與 Preview
|
||||
狀態;CH0、CH1 各自有 Start、Stop 與獨立 Preview 視窗,可單獨測試,
|
||||
也可同時啟動。第二個 channel open/start 失敗時不會停止已運作的 channel。
|
||||
關閉獨立 Preview 視窗只會停止該視窗的 frame submission;capture/audio 仍可繼續,
|
||||
未顯示的 frame 不計為 preview delivery failure。重新開啟 Preview 或 Fullscreen 會
|
||||
恢復 frame submission。
|
||||
IRQ、DMA 等資訊只存在 internal diagnostic tool。
|
||||
|
||||
## Consumer Layout
|
||||
|
||||
@@ -291,7 +291,12 @@ DXGI 成功接受的 Present;swapchain busy 而略過者記在 `skipped_presen
|
||||
|
||||
## 9. 錯誤處理建議
|
||||
|
||||
- `GVFG_ETIMEOUT`:通常可重試,並檢查 signal status/event。
|
||||
- `GVFG_ETIMEOUT`:連線期間通常可重試,並檢查 signal status/event。收到
|
||||
`GVFG_EVENT_SIGNAL_DISCONNECTED` 後,不應高速輪詢 read API;應等待
|
||||
`GVFG_EVENT_SIGNAL_CONNECTED`(或 application stop)再恢復 video/audio read。
|
||||
- 每次成功取得的 frame 仍必須恰好 release 一次。若 release 與實體拔線競爭,
|
||||
SDK 會處理 driver 已撤銷 zero-copy ownership 的情況,application 不應特判
|
||||
`ERROR_BAD_COMMAND (22)`。
|
||||
- `GVFG_EVENT_FORMAT_CHANGE_BEGIN`:先停用舊格式資源;等 stream ready 後重建。
|
||||
- `GVFG_ESTATE`:檢查 lifecycle、是否重複 read、或是否已 stop。
|
||||
- `GVFG_EIO`/`GVFG_ENODEV`:停止 session,記錄 `gvfg_strerror()`,再由應用程式
|
||||
|
||||
@@ -349,6 +349,10 @@ gvfg_status_t gvfg_release_channel_frame(gvfg_handle handle,
|
||||
- `handle`:取得該 frame 的同一個 handle。
|
||||
- `frame`:`gvfg_read_channel_frame()` 原封不動回傳的完整 descriptor。
|
||||
- `GVFG_OK`:成功歸還 frame;copy buffer 可再次使用,或 zero-copy frame 已歸還 driver。
|
||||
- 若 frame 原本合法取得,但 release 與 plug-out 競爭,driver 可能已先撤銷
|
||||
zero-copy ownership。SDK 僅在已確認 disconnected 且 driver 回
|
||||
`ERROR_BAD_COMMAND (22)` 時清除相符的 held token,並將 release 視為完成;
|
||||
application 仍照常呼叫一次 release,不需處理 driver error 22。
|
||||
- `GVFG_EINVAL`:NULL 或 token 內容與 held frame 不符。
|
||||
- `GVFG_ESTATE`:沒有 backend、目前沒有 held frame,或 backend release 狀態不正確。
|
||||
|
||||
|
||||
@@ -202,7 +202,8 @@ if (status != GVFG_OK && status != GVFG_ETIMEOUT)
|
||||
| `GVFG_EIO` 且沒有成功 frame | 否 | caller 沒有取得 ownership token |
|
||||
| 第二次 read 被 `frameHeld` 拒絕 | 否 | 應先 release 原本成功取得的 frame |
|
||||
| release token 不符 | 不可清除 held state | 正確 token 仍需重試 release |
|
||||
| zero-copy release IOCTL 失敗 | 不可清除 held state | driver frame 可能仍被占用,必須保留 token 供 retry |
|
||||
| zero-copy release IOCTL 一般失敗 | 不可清除 held state | driver frame 可能仍被占用,必須保留 token 供 retry |
|
||||
| 已確認 unplug 後 release 回 `ERROR_BAD_COMMAND (22)` | 清除相符 held state | driver 已撤銷該 ownership;保留 token 會阻塞 unplug/replug lifecycle |
|
||||
|
||||
## 9. Transient retry 規則
|
||||
|
||||
@@ -243,7 +244,11 @@ facade running = false
|
||||
-> 停 event monitoring/thread
|
||||
```
|
||||
|
||||
若 zero-copy release 失敗,backend 不應假裝已經釋放;錯誤必須回傳並保留足以重試的狀態。這是 teardown 正確性的核心。
|
||||
一般 zero-copy release 失敗時,backend 不應假裝已經釋放;錯誤必須回傳並保留
|
||||
足以重試的狀態。若已確認 signal disconnected,且 release 回
|
||||
`ERROR_BAD_COMMAND (22)`,則表示 driver 已在拔線流程撤銷 ownership;backend 會
|
||||
清除相符的本地 held state 並完成 release,避免 event-monitor thread 永久等待。
|
||||
這個例外不可套用到 connected 狀態或其他錯誤碼。
|
||||
|
||||
正常 `stop()` 為了結束 blocking read/event poll 而喚醒 waiter 時,只回傳 `GVFG_ESTATE`,不寫入
|
||||
永久錯誤;application 應以自己的 stop flag 判斷這是不是預期的結束流程。
|
||||
|
||||
@@ -270,7 +270,12 @@ Release 不是只看 `data` pointer。程式會比對:
|
||||
|
||||
這可避免 caller 把 CH0 token 用於 CH1、使用舊 frame、修改 descriptor,或重複 release。
|
||||
|
||||
重要規則:驗證失敗或 zero-copy release IOCTL 失敗時,不可先清除 held state。
|
||||
重要規則:token 驗證失敗或一般 zero-copy release IOCTL 失敗時,不可先清除
|
||||
held state。唯一例外是 backend 已經收到 plug-out、確認 signal disconnected,且
|
||||
driver 對該 outstanding frame 回傳 `ERROR_BAD_COMMAND (22)`;此時 driver 已因拔線
|
||||
撤銷 ownership,SDK 會清除相符的本地 held token,避免 unplug handler 與後續
|
||||
replug 永久卡住。Application 仍必須對每次成功 read 呼叫一次 release,不應自行
|
||||
特判 error 22。
|
||||
|
||||
## 11. Signal 與 format-change 狀態
|
||||
|
||||
|
||||
@@ -179,6 +179,13 @@ MainWindow::MainWindow(QWidget *parent)
|
||||
previewWindows_[GVFG_CHANNEL_1] = new PreviewWindow();
|
||||
previewWindows_[GVFG_CHANNEL_0]->setWindowTitle(QStringLiteral("GVFG Preview - CH0"));
|
||||
previewWindows_[GVFG_CHANNEL_1]->setWindowTitle(QStringLiteral("GVFG Preview - CH1"));
|
||||
for (int channel = GVFG_CHANNEL_0; channel <= GVFG_CHANNEL_1; ++channel)
|
||||
{
|
||||
connect(previewWindows_[channel], &PreviewWindow::previewVisibilityChanged,
|
||||
this, [this, channel](bool visible) {
|
||||
channels_[channel].previewVisible.store(visible, std::memory_order_release);
|
||||
});
|
||||
}
|
||||
ui_->logEdit->setMaximumBlockCount(300);
|
||||
new LogHighlighter(ui_->logEdit->document());
|
||||
ui_->statusLabel->setWordWrap(true);
|
||||
@@ -556,7 +563,13 @@ void MainWindow::startCapture(int channelIndex)
|
||||
appendLog(QStringLiteral("CH%1 Preview still busy from previous run; retry Start after it completes.").arg(channelIndex));
|
||||
return;
|
||||
}
|
||||
channel.startupStartTime = std::chrono::steady_clock::now();
|
||||
st = gvfg_start_channel(handle_, channelIndex);
|
||||
const auto startupStartCallEnd = std::chrono::steady_clock::now();
|
||||
channel.startupStartCallMs =
|
||||
std::chrono::duration<double, std::milli>(
|
||||
startupStartCallEnd - channel.startupStartTime)
|
||||
.count();
|
||||
if (st != GVFG_OK)
|
||||
{
|
||||
showError(QStringLiteral("gvfg_start_channel"), st, channelIndex);
|
||||
@@ -579,7 +592,8 @@ 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.videoReceived = 0; channel.videoSubmitted = 0;
|
||||
channel.videoSkipped = 0; channel.videoFailed = 0;
|
||||
channel.videoIdGaps = 0; channel.videoIdResets = 0;
|
||||
channel.videoLastId = 0;
|
||||
channel.lastLoggedVideoIssues = channel.lastLoggedAudioIssues = 0;
|
||||
@@ -601,6 +615,8 @@ void MainWindow::startCapture(int channelIndex)
|
||||
channel.haveDebugBaseline = false;
|
||||
channel.lastDebugDmaErrors = 0;
|
||||
#endif
|
||||
channel.signalConnected.store(channel.cachedSignalStatus.connected != 0,
|
||||
std::memory_order_release);
|
||||
channel.stopRequested.store(false, std::memory_order_release);
|
||||
channel.running.store(true, std::memory_order_release);
|
||||
channel.captureThread = std::thread([this, channelIndex]()
|
||||
@@ -629,6 +645,7 @@ void MainWindow::stopCapture(int channelIndex)
|
||||
if (handle_ && channel.running.load(std::memory_order_acquire))
|
||||
{
|
||||
channel.stopRequested.store(true, std::memory_order_release);
|
||||
channel.signalReady.notify_all();
|
||||
channel.audioQueueReady.notify_all();
|
||||
joinCaptureThread(channelIndex);
|
||||
joinAudioThread(channelIndex);
|
||||
@@ -703,6 +720,7 @@ void MainWindow::processPendingEvents()
|
||||
while (gvfg_poll_channel_event(handle_, channel, &event, 0) == GVFG_OK)
|
||||
{
|
||||
const auto eventType = static_cast<gvfg_event_type_t>(event.type);
|
||||
if (eventType != GVFG_EVENT_STREAM_READY)
|
||||
appendLog(QStringLiteral("CH%1 EVENT %2").arg(channel).arg(eventTypeText(eventType)));
|
||||
|
||||
if (eventType == GVFG_EVENT_SIGNAL_CONNECTED ||
|
||||
@@ -711,6 +729,15 @@ void MainWindow::processPendingEvents()
|
||||
eventType == GVFG_EVENT_STREAM_READY)
|
||||
updateSignalStatus();
|
||||
|
||||
if (eventType == GVFG_EVENT_SIGNAL_DISCONNECTED)
|
||||
channels_[channel].signalConnected.store(false, std::memory_order_release);
|
||||
else if (eventType == GVFG_EVENT_SIGNAL_CONNECTED ||
|
||||
eventType == GVFG_EVENT_STREAM_READY)
|
||||
{
|
||||
channels_[channel].signalConnected.store(true, std::memory_order_release);
|
||||
channels_[channel].signalReady.notify_all();
|
||||
}
|
||||
|
||||
if (eventType == GVFG_EVENT_SIGNAL_DISCONNECTED && channels_[channel].previewHandle)
|
||||
gvfg_preview_clear(channels_[channel].previewHandle);
|
||||
|
||||
@@ -1062,7 +1089,7 @@ void MainWindow::logDeliveryStatus(int channelIndex, bool finalSnapshot)
|
||||
if (finalSnapshot)
|
||||
{
|
||||
const bool videoAccounted = previewOk && c.videoReceived.load() ==
|
||||
c.videoSubmitted.load() + c.videoFailed.load() &&
|
||||
c.videoSubmitted.load() + c.videoSkipped.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")
|
||||
@@ -1098,6 +1125,7 @@ void MainWindow::captureReadLoop(int channelIndex)
|
||||
std::chrono::steady_clock::time_point noFrameSince{};
|
||||
std::chrono::steady_clock::time_point nextNoFrameReport{};
|
||||
bool captureStalledLogged = false;
|
||||
bool startupLatencyLogged = false;
|
||||
uint64_t successfulFrameCount = 0;
|
||||
uint64_t previewTimingSampleCount = 0;
|
||||
double previewTimingTotalMs = 0.0;
|
||||
@@ -1107,6 +1135,16 @@ void MainWindow::captureReadLoop(int channelIndex)
|
||||
ChannelRuntime &channel = channels_[channelIndex];
|
||||
while (!channel.stopRequested.load(std::memory_order_acquire))
|
||||
{
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(channel.signalMutex);
|
||||
channel.signalReady.wait(lock, [&channel]() {
|
||||
return channel.stopRequested.load(std::memory_order_acquire) ||
|
||||
channel.signalConnected.load(std::memory_order_acquire);
|
||||
});
|
||||
}
|
||||
if (channel.stopRequested.load(std::memory_order_acquire))
|
||||
break;
|
||||
|
||||
gvfg_frame_t frame{};
|
||||
const auto getFrameStart = std::chrono::steady_clock::now();
|
||||
const gvfg_status_t st = gvfg_read_channel_frame(handle_, channelIndex, &frame, 200);
|
||||
@@ -1163,7 +1201,9 @@ void MainWindow::captureReadLoop(int channelIndex)
|
||||
{ appendLog(QStringLiteral("CH%1 RECOVERED capture resumed").arg(channelIndex)); }, Qt::QueuedConnection);
|
||||
}
|
||||
|
||||
if (channel.previewHandle)
|
||||
const bool attemptedPreview = channel.previewHandle &&
|
||||
channel.previewVisible.load(std::memory_order_acquire);
|
||||
if (attemptedPreview)
|
||||
{
|
||||
gvfg_preview_frame_t previewFrame{};
|
||||
previewFrame.data = frame.data;
|
||||
@@ -1209,6 +1249,35 @@ void MainWindow::captureReadLoop(int channelIndex)
|
||||
else
|
||||
{
|
||||
++channel.videoSubmitted;
|
||||
if (!startupLatencyLogged)
|
||||
{
|
||||
startupLatencyLogged = true;
|
||||
const double startupLatencyMs =
|
||||
std::chrono::duration<double, std::milli>(
|
||||
previewEnd - channel.startupStartTime)
|
||||
.count();
|
||||
const double startCallMs = channel.startupStartCallMs;
|
||||
const double firstReadMs = getFrameElapsedMs;
|
||||
const double firstRenderFrameMs = previewElapsedMs;
|
||||
const uint64_t startupFrameId = frame.frame_id;
|
||||
QMetaObject::invokeMethod(
|
||||
this,
|
||||
[this, channelIndex, startCallMs, firstReadMs,
|
||||
firstRenderFrameMs, startupLatencyMs, startupFrameId]()
|
||||
{
|
||||
appendLog(QStringLiteral("CH%1 Startup latency | Start -> start_channel return=%2 ms | "
|
||||
"first read_frame call -> return=%3 ms | "
|
||||
"first render_frame call -> return=%4 ms | "
|
||||
"Start -> first render_frame return=%5 ms | frame_id=%6")
|
||||
.arg(channelIndex)
|
||||
.arg(startCallMs, 0, 'f', 3)
|
||||
.arg(firstReadMs, 0, 'f', 3)
|
||||
.arg(firstRenderFrameMs, 0, 'f', 3)
|
||||
.arg(startupLatencyMs, 0, 'f', 3)
|
||||
.arg(static_cast<qulonglong>(startupFrameId)));
|
||||
},
|
||||
Qt::QueuedConnection);
|
||||
}
|
||||
if (channel.previewFailureCount != 0)
|
||||
{
|
||||
const uint64_t failures = channel.previewFailureCount;
|
||||
@@ -1248,6 +1317,8 @@ void MainWindow::captureReadLoop(int channelIndex)
|
||||
}
|
||||
if (!channel.previewHandle)
|
||||
++channel.videoFailed;
|
||||
else if (!attemptedPreview)
|
||||
++channel.videoSkipped;
|
||||
const gvfg_status_t releaseStatus = gvfg_release_channel_frame(handle_, channelIndex, &frame);
|
||||
if (releaseStatus != GVFG_OK)
|
||||
{
|
||||
@@ -1285,10 +1356,6 @@ void MainWindow::captureReadLoop(int channelIndex)
|
||||
},
|
||||
Qt::QueuedConnection);
|
||||
}
|
||||
// Some incomplete channel implementations return GVFG_ETIMEOUT
|
||||
// immediately instead of waiting for timeout_ms. Avoid a hot loop
|
||||
// that floods the GUI event queue and makes every window unresponsive.
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(5));
|
||||
continue;
|
||||
}
|
||||
if (channel.stopRequested.load(std::memory_order_acquire))
|
||||
@@ -1322,6 +1389,16 @@ void MainWindow::audioReadLoop(int channelIndex)
|
||||
auto lastArrival = std::chrono::steady_clock::time_point{};
|
||||
while (!channel.stopRequested.load(std::memory_order_acquire))
|
||||
{
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(channel.signalMutex);
|
||||
channel.signalReady.wait(lock, [&channel]() {
|
||||
return channel.stopRequested.load(std::memory_order_acquire) ||
|
||||
channel.signalConnected.load(std::memory_order_acquire);
|
||||
});
|
||||
}
|
||||
if (channel.stopRequested.load(std::memory_order_acquire))
|
||||
break;
|
||||
|
||||
gvfg_audio_frame_t frame{};
|
||||
const gvfg_status_t status = gvfg_read_channel_audio_frame(
|
||||
handle_, channelIndex, &frame, 200);
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
@@ -45,7 +46,11 @@ private:
|
||||
gvfg_preview_handle previewHandle = nullptr;
|
||||
std::atomic<bool> running{false};
|
||||
std::atomic<bool> stopRequested{false};
|
||||
std::atomic<bool> signalConnected{false};
|
||||
std::mutex signalMutex;
|
||||
std::condition_variable signalReady;
|
||||
std::atomic<bool> frameAvailable{false};
|
||||
std::atomic<bool> previewVisible{false};
|
||||
std::thread captureThread;
|
||||
std::thread audioThread;
|
||||
std::thread audioPlaybackThread;
|
||||
@@ -73,10 +78,12 @@ private:
|
||||
qint64 audioLastDropTimeMs = 0;
|
||||
double audioMaxWriteStallMs = 0;
|
||||
double audioMaxReadGapMs = 0;
|
||||
std::atomic<uint64_t> videoReceived{0}, videoSubmitted{0}, videoFailed{0};
|
||||
std::atomic<uint64_t> videoReceived{0}, videoSubmitted{0}, videoSkipped{0}, videoFailed{0};
|
||||
std::atomic<uint64_t> videoIdGaps{0}, videoIdResets{0};
|
||||
std::atomic<uint64_t> videoLastId{0};
|
||||
gvfg_preview_delivery_stats_t previewBaseline{};
|
||||
std::chrono::steady_clock::time_point startupStartTime{};
|
||||
double startupStartCallMs = 0.0;
|
||||
uint64_t lastLoggedVideoIssues = 0, lastLoggedAudioIssues = 0;
|
||||
qint64 lastDeliveryLogMs = 0;
|
||||
std::atomic<double> getFrameAverageMs{0.0};
|
||||
|
||||
@@ -68,23 +68,28 @@ void PreviewWindow::setSourceSize(int sourceWidth, int sourceHeight)
|
||||
void PreviewWindow::closePreview()
|
||||
{
|
||||
closeAllowed_ = true;
|
||||
emit previewVisibilityChanged(false);
|
||||
close();
|
||||
}
|
||||
|
||||
void PreviewWindow::showPreview(int sourceWidth, int sourceHeight)
|
||||
{
|
||||
closeAllowed_ = false;
|
||||
setSourceSize(sourceWidth, sourceHeight);
|
||||
if (isFullScreen())
|
||||
showNormal();
|
||||
show();
|
||||
emit previewVisibilityChanged(true);
|
||||
raise();
|
||||
activateWindow();
|
||||
}
|
||||
|
||||
void PreviewWindow::showFullscreenPreview(int sourceWidth, int sourceHeight)
|
||||
{
|
||||
closeAllowed_ = false;
|
||||
setSourceSize(sourceWidth, sourceHeight);
|
||||
enterFullscreen();
|
||||
emit previewVisibilityChanged(true);
|
||||
}
|
||||
|
||||
void PreviewWindow::enterFullscreen()
|
||||
@@ -113,6 +118,7 @@ void PreviewWindow::closeEvent(QCloseEvent *event)
|
||||
}
|
||||
|
||||
hide();
|
||||
emit previewVisibilityChanged(false);
|
||||
event->ignore();
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,9 @@ public slots:
|
||||
void showPreview(int sourceWidth = 0, int sourceHeight = 0);
|
||||
void showFullscreenPreview(int sourceWidth = 0, int sourceHeight = 0);
|
||||
|
||||
signals:
|
||||
void previewVisibilityChanged(bool visible);
|
||||
|
||||
protected:
|
||||
void closeEvent(QCloseEvent *event) override;
|
||||
void keyPressEvent(QKeyEvent *event) override;
|
||||
|
||||
@@ -59,6 +59,23 @@ namespace
|
||||
return out;
|
||||
}
|
||||
|
||||
static std::wstring utf8_to_wide(const char *s)
|
||||
{
|
||||
if (!s || !*s)
|
||||
return std::wstring();
|
||||
const int needed = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
|
||||
s, -1, nullptr, 0);
|
||||
if (needed <= 0)
|
||||
return std::wstring();
|
||||
std::wstring out(static_cast<size_t>(needed), L'\0');
|
||||
if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
|
||||
s, -1, &out[0], needed) <= 0)
|
||||
return std::wstring();
|
||||
if (!out.empty() && out.back() == L'\0')
|
||||
out.pop_back();
|
||||
return out;
|
||||
}
|
||||
|
||||
static std::string win32_error(DWORD err)
|
||||
{
|
||||
wchar_t *msg = nullptr;
|
||||
@@ -110,11 +127,16 @@ namespace
|
||||
"[GVFG][PCIES2MM]%s %s\n",
|
||||
tag ? tag : "",
|
||||
msg);
|
||||
const std::wstring wideLine = utf8_to_wide(line);
|
||||
if (!wideLine.empty())
|
||||
OutputDebugStringW(wideLine.c_str());
|
||||
else
|
||||
OutputDebugStringA(line);
|
||||
}
|
||||
|
||||
#define PCIES2MM_LOG(...) trace_log(false, "", __VA_ARGS__)
|
||||
#define PCIES2MM_ERROR_LOG(...) trace_log(true, "[error]", __VA_ARGS__)
|
||||
#define PCIES2MM_TIMING_LOG(...) trace_log(true, "[timing]", __VA_ARGS__)
|
||||
|
||||
static uint32_t event_mask_for_type(pcies2mm_event_type_t type)
|
||||
{
|
||||
@@ -514,6 +536,7 @@ namespace gvfg::internal
|
||||
stream_desc_.pixel_format != PCIES2MM_PIXFMT_UNKNOWN;
|
||||
running_ = true;
|
||||
capture_active_ = false;
|
||||
signal_transition_active_ = false;
|
||||
reader_ready_ = false;
|
||||
signal_probe_active_ = probeAvailable;
|
||||
stream_ready_pending_ = false;
|
||||
@@ -536,6 +559,7 @@ namespace gvfg::internal
|
||||
|
||||
running_ = false;
|
||||
capture_active_ = false;
|
||||
signal_transition_active_ = false;
|
||||
reader_ready_ = false;
|
||||
signal_probe_active_ = false;
|
||||
stream_ready_pending_ = false;
|
||||
@@ -574,22 +598,26 @@ namespace gvfg::internal
|
||||
if (capture_active_.load(std::memory_order_acquire))
|
||||
return PCIES2MM_OK;
|
||||
if (!signal_presence_known_.load(std::memory_order_acquire) ||
|
||||
!signal_present_.load(std::memory_order_acquire))
|
||||
!signal_present_.load(std::memory_order_acquire) ||
|
||||
signal_transition_active_.load(std::memory_order_acquire))
|
||||
return PCIES2MM_ETIMEOUT;
|
||||
if (!ResetEvent(dma_event_) || !ResetEvent(extra_video_event_) ||
|
||||
(audio_enabled_ &&
|
||||
(!ResetEvent(audio_event_) || !ResetEvent(extra_audio_event_))))
|
||||
return fail(PCIES2MM_EIO, "reset capture event");
|
||||
|
||||
if (!start_capture(active_channel()))
|
||||
return fail(PCIES2MM_EIO, "enable reader capture");
|
||||
capture_active_.store(true, std::memory_order_release);
|
||||
stream_ready_pending_.store(true, std::memory_order_release);
|
||||
first_video_timing_pending_ = true;
|
||||
return PCIES2MM_OK;
|
||||
}
|
||||
|
||||
pcies2mm_status_t PcieS2mmCaptureSession::wait_frame(uint32_t timeoutMs, pcies2mm_frame_t &out)
|
||||
{
|
||||
constexpr uint64_t kTimingWarmupFrames = 30;
|
||||
bool logFirstVideoTiming = false;
|
||||
reader_ready_.store(true, std::memory_order_release);
|
||||
std::memset(&out, 0, sizeof(out));
|
||||
{
|
||||
@@ -599,6 +627,7 @@ namespace gvfg::internal
|
||||
const pcies2mm_status_t startStatus = ensure_capture_started();
|
||||
if (startStatus != PCIES2MM_OK)
|
||||
return startStatus;
|
||||
logFirstVideoTiming = first_video_timing_pending_;
|
||||
read_in_progress_ = true;
|
||||
}
|
||||
|
||||
@@ -614,7 +643,9 @@ namespace gvfg::internal
|
||||
: std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
|
||||
const DWORD bytes = static_cast<DWORD>(frame_size_bytes());
|
||||
const uint8_t *data = nullptr;
|
||||
double videoEventWaitMs = 0.0;
|
||||
double getFrameUs = 0.0;
|
||||
DWORD successfulWaitResult = WAIT_FAILED;
|
||||
for (;;)
|
||||
{
|
||||
DWORD waitMs = INFINITE;
|
||||
@@ -631,7 +662,11 @@ namespace gvfg::internal
|
||||
}
|
||||
|
||||
HANDLE videoReadyEvents[] = {dma_event_, extra_video_event_};
|
||||
const auto waitStarted = std::chrono::steady_clock::now();
|
||||
const DWORD waitResult = WaitForMultipleObjects(2, videoReadyEvents, FALSE, waitMs);
|
||||
const auto waitReturned = std::chrono::steady_clock::now();
|
||||
videoEventWaitMs += std::chrono::duration<double, std::milli>(
|
||||
waitReturned - waitStarted).count();
|
||||
if (waitResult == WAIT_TIMEOUT)
|
||||
{
|
||||
{
|
||||
@@ -657,7 +692,6 @@ namespace gvfg::internal
|
||||
finishRead();
|
||||
return PCIES2MM_ETIMEOUT;
|
||||
}
|
||||
|
||||
const auto getFrameStarted = std::chrono::steady_clock::now();
|
||||
int ret = -1;
|
||||
DWORD frameError = ERROR_SUCCESS;
|
||||
@@ -680,7 +714,10 @@ namespace gvfg::internal
|
||||
getFrameUs += std::chrono::duration<double, std::micro>(
|
||||
std::chrono::steady_clock::now() - getFrameStarted).count();
|
||||
if (ret >= 0 && static_cast<DWORD>(ret) == bytes)
|
||||
{
|
||||
successfulWaitResult = waitResult;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!is_transient_frame_not_ready_error(frameError))
|
||||
{
|
||||
@@ -730,6 +767,20 @@ namespace gvfg::internal
|
||||
out.bit_depth = stream_bit_depth_;
|
||||
held_frame_ = out;
|
||||
frame_held_ = true;
|
||||
if (logFirstVideoTiming)
|
||||
first_video_timing_pending_ = false;
|
||||
}
|
||||
if (logFirstVideoTiming)
|
||||
{
|
||||
const char *eventName = successfulWaitResult == WAIT_OBJECT_0
|
||||
? "dma_event"
|
||||
: "extra_video_event";
|
||||
PCIES2MM_TIMING_LOG("CH%u | video wait=%.3f ms | wake=%s | acquire/get_frame=%.3f ms | mode=%s",
|
||||
active_channel(),
|
||||
videoEventWaitMs,
|
||||
eventName,
|
||||
getFrameUs / 1000.0,
|
||||
zero_copy_enabled_ ? "zero-copy" : "copy");
|
||||
}
|
||||
if (stream_ready_pending_.exchange(false, std::memory_order_acq_rel))
|
||||
emit_event(PCIES2MM_EVENT_STREAM_READY);
|
||||
@@ -856,9 +907,24 @@ namespace gvfg::internal
|
||||
if (zero_copy_enabled_ && !release_zero_copy_frame(active_channel()))
|
||||
{
|
||||
const DWORD err = GetLastError();
|
||||
// The driver invalidates its zero-copy release list as soon as the
|
||||
// input is unplugged. A frame that was valid when delivered can
|
||||
// therefore report ERROR_BAD_COMMAND when the application releases
|
||||
// it after the unplug interrupt. In that exact state, ownership has
|
||||
// already been revoked by the driver; clear the matching SDK token
|
||||
// so unplug handling and subsequent capture can make progress.
|
||||
const bool revokedByUnplug =
|
||||
err == ERROR_BAD_COMMAND &&
|
||||
signal_presence_known_.load(std::memory_order_acquire) &&
|
||||
!signal_present_.load(std::memory_order_acquire);
|
||||
if (!revokedByUnplug)
|
||||
{
|
||||
lock.unlock();
|
||||
return fail(PCIES2MM_EIO, "release zero-copy frame", err);
|
||||
}
|
||||
PCIES2MM_LOG("zero-copy frame ownership revoked by unplug: frame=%llu",
|
||||
static_cast<unsigned long long>(frame.frame_id));
|
||||
}
|
||||
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()
|
||||
@@ -964,9 +1030,18 @@ namespace gvfg::internal
|
||||
if (zero_copy_enabled_ && held_frame_.data && !release_zero_copy_frame(active_channel()))
|
||||
{
|
||||
const DWORD err = GetLastError();
|
||||
const bool revokedByUnplug =
|
||||
err == ERROR_BAD_COMMAND &&
|
||||
signal_presence_known_.load(std::memory_order_acquire) &&
|
||||
!signal_present_.load(std::memory_order_acquire);
|
||||
if (!revokedByUnplug)
|
||||
{
|
||||
lock.unlock();
|
||||
return fail(PCIES2MM_EIO, "release pending zero-copy frame", err);
|
||||
}
|
||||
PCIES2MM_LOG("pending zero-copy frame ownership already revoked by unplug: frame=%llu",
|
||||
static_cast<unsigned long long>(held_frame_.frame_id));
|
||||
}
|
||||
held_frame_ = {};
|
||||
frame_held_ = false;
|
||||
read_finished_cv_.notify_all();
|
||||
@@ -1137,6 +1212,7 @@ namespace gvfg::internal
|
||||
SetEvent(extra_audio_event_);
|
||||
if (monitor_stop_event_)
|
||||
SetEvent(monitor_stop_event_);
|
||||
read_finished_cv_.notify_all();
|
||||
if (capture_thread_.joinable())
|
||||
capture_thread_.join();
|
||||
|
||||
@@ -1224,12 +1300,12 @@ namespace gvfg::internal
|
||||
|
||||
void PcieS2mmCaptureSession::handle_format_change_event(uint32_t channel)
|
||||
{
|
||||
signal_transition_active_.store(true, std::memory_order_release);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
signal_metadata_valid_ = false;
|
||||
}
|
||||
emit_event(PCIES2MM_EVENT_FORMAT_CHANGE_BEGIN);
|
||||
stop_capture(channel);
|
||||
capture_active_ = false;
|
||||
stream_ready_pending_ = false;
|
||||
if (dma_event_)
|
||||
@@ -1239,11 +1315,16 @@ namespace gvfg::internal
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
read_finished_cv_.wait(lock, [this] {
|
||||
return !read_in_progress_ && !audio_read_in_progress_ && !frame_held_;
|
||||
return !monitoring_.load(std::memory_order_acquire) ||
|
||||
(!read_in_progress_ && !audio_read_in_progress_ && !frame_held_);
|
||||
});
|
||||
}
|
||||
if (!monitoring_.load(std::memory_order_acquire))
|
||||
return;
|
||||
stop_capture(channel);
|
||||
if (running_.load(std::memory_order_acquire))
|
||||
refresh_stream_from_registers(true);
|
||||
signal_transition_active_.store(false, std::memory_order_release);
|
||||
}
|
||||
|
||||
void PcieS2mmCaptureSession::handle_plugin_event(uint32_t channel)
|
||||
@@ -1252,10 +1333,8 @@ namespace gvfg::internal
|
||||
signal_present_.load(std::memory_order_acquire))
|
||||
return;
|
||||
|
||||
if (capture_active_.exchange(false, std::memory_order_acq_rel))
|
||||
{
|
||||
stop_capture(channel);
|
||||
}
|
||||
signal_transition_active_.store(true, std::memory_order_release);
|
||||
capture_active_.store(false, std::memory_order_release);
|
||||
if (dma_event_)
|
||||
SetEvent(dma_event_);
|
||||
if (audio_event_)
|
||||
@@ -1267,30 +1346,46 @@ namespace gvfg::internal
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
signal_metadata_valid_ = false;
|
||||
}
|
||||
emit_event(PCIES2MM_EVENT_PLUG_IN);
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
read_finished_cv_.wait(lock, [this] {
|
||||
return !read_in_progress_ && !audio_read_in_progress_ && !frame_held_;
|
||||
return !monitoring_.load(std::memory_order_acquire) ||
|
||||
(!read_in_progress_ && !audio_read_in_progress_ && !frame_held_);
|
||||
});
|
||||
}
|
||||
if (!monitoring_.load(std::memory_order_acquire))
|
||||
return;
|
||||
stop_capture(channel);
|
||||
if (running_.load(std::memory_order_acquire))
|
||||
refresh_stream_from_registers(true);
|
||||
signal_transition_active_.store(false, std::memory_order_release);
|
||||
emit_event(PCIES2MM_EVENT_PLUG_IN);
|
||||
}
|
||||
|
||||
void PcieS2mmCaptureSession::handle_unplug_event(uint32_t channel)
|
||||
{
|
||||
signal_transition_active_.store(true, std::memory_order_release);
|
||||
signal_probe_active_.store(false, std::memory_order_release);
|
||||
stream_ready_pending_.store(false, std::memory_order_release);
|
||||
signal_present_.store(false, std::memory_order_release);
|
||||
signal_presence_known_.store(true, std::memory_order_release);
|
||||
stop_capture(channel);
|
||||
capture_active_ = false;
|
||||
if (dma_event_)
|
||||
SetEvent(dma_event_);
|
||||
if (audio_event_)
|
||||
SetEvent(audio_event_);
|
||||
emit_event(PCIES2MM_EVENT_PLUG_OUT);
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
read_finished_cv_.wait(lock, [this] {
|
||||
return !monitoring_.load(std::memory_order_acquire) ||
|
||||
(!read_in_progress_ && !audio_read_in_progress_ && !frame_held_);
|
||||
});
|
||||
}
|
||||
if (!monitoring_.load(std::memory_order_acquire))
|
||||
return;
|
||||
stop_capture(channel);
|
||||
signal_transition_active_.store(false, std::memory_order_release);
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
@@ -128,6 +128,7 @@ namespace gvfg::internal
|
||||
std::atomic<bool> reader_ready_{false};
|
||||
std::atomic<bool> signal_probe_active_{false};
|
||||
std::atomic<bool> stream_ready_pending_{false};
|
||||
std::atomic<bool> signal_transition_active_{false};
|
||||
mutable std::atomic<bool> signal_presence_known_{false};
|
||||
mutable std::atomic<bool> signal_present_{false};
|
||||
mutable bool signal_metadata_valid_ = false;
|
||||
@@ -154,6 +155,7 @@ namespace gvfg::internal
|
||||
bool frame_held_ = false;
|
||||
bool read_in_progress_ = false;
|
||||
bool audio_read_in_progress_ = false;
|
||||
bool first_video_timing_pending_ = false;
|
||||
std::chrono::steady_clock::time_point active_delivery_started_{};
|
||||
bool stream_error_ = false;
|
||||
pcies2mm_stream_stats_t stats_{};
|
||||
|
||||
Reference in New Issue
Block a user