Streamline GigabyteLib capture control and diagnostics

Compared with d652f15:

- set the SDK release version to 1.0.0 for the new GigabyteLib backend and its required matching driver

- preserve GigabyteLib result codes and event names through the public SDK instead of translating vendor semantics

- expose cached Lib signal, SDI string fields, ErrorCount, and separate video/audio event counters for direct diagnostics

- serialize GigabyteLib capture calls and recover an active stream internally after a video input plugin event

- keep the SDK frame lifetime fence while following the current zero-copy contract without a vendor release call

- separate Sample logging and presentation counters from capture control, and report Lib-owned fields with explicit source names

- remove the manual Open Device control so Start lazily opens the selected device and revalidates VideoSignalLock once per request

- keep format selection side-effect free until Start opens the channel, then apply the selected output depth through GigabyteLib

- update the public API, diagnostics, architecture, error-handling, and build documentation for the simplified ownership model
This commit is contained in:
Mark.lin
2026-09-15 16:52:19 +08:00
parent d652f15369
commit 350e8e519c
27 changed files with 693 additions and 549 deletions
+2
View File
@@ -83,6 +83,8 @@ set(GVFG_QT_PREVIEW_SOURCES
main.cpp
capture_controller.cpp
capture_controller.h
sample_log.cpp
sample_log.h
mainwindow.cpp
mainwindow.h
mainwindow.ui
+2 -2
View File
@@ -6,7 +6,7 @@
- `[SDK]`/`[SDK API]`:SDK read 邊界或 API 回傳的現象。
- `[APP]`:Preview、audio output 或 Sample 自身核對的現象。
- 累計數字最多每 5 秒彙整一次;Stop 會補記尚未輸出的變化。
- Stop 不列印正常統計摘要。只有資料去向核對不一致時才印 `[APP] ERROR accounting mismatch`。正常停止清掉的待處理資料不算運行錯誤。
- Stop 不列印正常統計摘要;只有實際 API、preview 或 audio output 錯誤才記錄。
## 拿到 Log 後怎麼處理
@@ -14,7 +14,7 @@ Log 只標示觀測層、現象與數值。Video/audio `frame_id` 是 SDK 每次
預覽使用 Present(0, 0),讓 DXGI 等待呈現相依條件,不做外部重試。SyncInterval 仍為 0,並非每張都保證顯示。預覽改成 FIFO,最多保留 3 張待處理影像(包含正在上傳的容量保留),另有 1 個處理中槽位,共 4 個 GPU 槽。60 FPS 下 3 張約 50 ms;這不是刻意等滿 50 ms 才顯示。從上傳完成入列開始計時,等待超過 50 ms 的影像才丟棄(expired);容量滿時跳過新影像(busy),不替換仍在期限內的舊影像。50 ms 是開始處理前的等待期限,不含 GPU 執行/DXGI Present 等待,不保證端到端延遲或實體螢幕逐張呈現。Stop/關閉/鎖等待只處理 Windows 同步送達的視窗訊息,避免 DXGI 等待 UI 而 UI 又等待 worker;不處理一般排隊輸入或 Qt callbacks。
Audio 保留原本最多 10 個 PCM 區塊的播放佇列(`kMaxQueuedAudioFrames`);滿時丟掉最舊區塊,再加入新區塊。丟棄區塊、停滯與收音間隔仍保留為內部診斷計數,但不顯示在一般 Log;audio frame 不保證與 video frame 等長。
Audio 保留原本最多 10 個 PCM 區塊的播放佇列(`kMaxQueuedAudioFrames`);滿時丟掉最舊區塊,再加入新區塊。Sample 不統計輸出、丟棄或取消數量;audio frame 不保證與 video frame 等長。
播放 write 失敗,或持續回傳 0、兩秒沒有進展,會記錄原因並停止通道;檢查音效裝置後重新 Start。此檢查無法中斷本身永不返回的 write 呼叫。
+92 -232
View File
@@ -2,10 +2,6 @@
#include <QAudioDevice>
#include <QAudioFormat>
#include <QAudioSink>
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QIODevice>
#include <QMediaDevices>
#include <QMetaObject>
#include <QStringList>
@@ -26,15 +22,6 @@ namespace
{
constexpr size_t kMaxQueuedAudioFrames = 10;
QString logFilePrefix()
{
#if GVFG_INTERNAL_DIAGNOSTICS
return QStringLiteral("gvfg_qt_preview_debug");
#else
return QStringLiteral("gvfg_qt_preview");
#endif
}
#if GVFG_INTERNAL_DIAGNOSTICS
QString boolText(int value) { return value ? QStringLiteral("yes") : QStringLiteral("no"); }
@@ -71,10 +58,9 @@ namespace
{
switch (type)
{
case GVFG_EVENT_SIGNAL_CONNECTED: return QStringLiteral("SIGNAL_CONNECTED");
case GVFG_EVENT_SIGNAL_DISCONNECTED: return QStringLiteral("SIGNAL_DISCONNECTED");
case GVFG_EVENT_STREAM_READY: return QStringLiteral("STREAM_READY");
case GVFG_EVENT_FORMAT_CHANGE_BEGIN: return QStringLiteral("FORMAT_CHANGE_BEGIN");
case GVFG_EVENT_VIDEO_FORMAT_CHANGED: return QStringLiteral("VIDEO_FORMAT_CHANGED");
case GVFG_EVENT_VIDEO_INPUT_PLUGIN: return QStringLiteral("VIDEO_INPUT_PLUGIN");
case GVFG_EVENT_VIDEO_INPUT_UNPLUG: return QStringLiteral("VIDEO_INPUT_UNPLUG");
default: return QStringLiteral("UNKNOWN");
}
}
@@ -87,7 +73,6 @@ CaptureController::CaptureController(QObject *parent) : QObject(parent)
processPendingEvents();
updateSignalStatus(false);
});
openLogFile();
}
CaptureController::~CaptureController()
@@ -154,19 +139,6 @@ QString CaptureController::sdkVersion() const
return QString::fromLatin1(gvfg_get_version());
}
void CaptureController::logStartupInfo()
{
appendLog(QStringLiteral("GVFG SDK version | %1").arg(sdkVersion()));
appendLog(logFile_.isOpen()
? QStringLiteral("Log file | %1").arg(logFilePath_)
: QStringLiteral("Log file unavailable | %1").arg(logFilePath_));
}
void CaptureController::logUiMessage(const QString &message)
{
appendLog(message);
}
void CaptureController::refreshDevices()
{
if (handle_ != nullptr)
@@ -227,13 +199,15 @@ bool CaptureController::openDevice()
bool CaptureController::openChannel(int channel)
{
ChannelRuntime &runtime = channels_[channel];
if (runtime.opened)
return applyOutputFormat(channel);
if (handle_ == nullptr && !openDevice())
return false;
const bool newlyOpened = !runtime.opened;
const bool zeroCopyEnabled = runtime.zeroCopy;
gvfg_status_t status = gvfg_set_channel_zero_copy_enabled(handle_, channel, zeroCopyEnabled ? 1 : 0);
gvfg_status_t status = GVFG_OK;
if (newlyOpened)
{
status = gvfg_set_channel_zero_copy_enabled(handle_, channel, zeroCopyEnabled ? 1 : 0);
if (status != GVFG_OK)
{
reportError(QStringLiteral("gvfg_set_channel_zero_copy_enabled"), status, channel);
@@ -246,14 +220,27 @@ bool CaptureController::openChannel(int channel)
return false;
}
runtime.opened = true;
}
status = gvfg_set_channel_audio_enabled(
handle_, channel, runtime.requestedAudio ? 1 : 0);
if (status != GVFG_OK)
{
reportError(QStringLiteral("gvfg_set_channel_audio_enabled"), status, channel);
return false;
}
if (!applyOutputFormat(channel))
return false;
if (newlyOpened)
{
refreshSdiInfo(channel);
appendLog(QStringLiteral("Opened device index %1 CH%2 | mode=%3")
.arg(selectedDeviceIndex_)
.arg(channel)
.arg(zeroCopyEnabled ? QStringLiteral("zero-copy") : QStringLiteral("copy")));
updateSignalStatus();
}
return true;
}
@@ -270,7 +257,7 @@ bool CaptureController::applyOutputFormat(int channel)
reportError(QStringLiteral("gvfg_set_channel_video_format"), status, channel);
return false;
}
appendLog(QStringLiteral("CH%1 Output format | %2 (GigabyteLib extension)")
appendLog(QStringLiteral("CH%1 Output format | %2")
.arg(channel)
.arg(format == GVFG_PIXFMT_Y210 ? QStringLiteral("Y210") : QStringLiteral("YUY2")));
return true;
@@ -300,12 +287,14 @@ void CaptureController::closeDevice()
emit statusChanged(QStringLiteral("Idle"));
lastSignalStatusText_.clear();
emit sdiInfoChanged(QStringLiteral("SDI Info: --"));
selectedDeviceIndex_ = -1;
for (ChannelRuntime &channel : channels_)
{
channel.opened = false;
channel.cachedSignalStatus = {};
channel.haveCachedSignalStatus = false;
channel.cachedSdiInfoText.clear();
channel.lastLoggedInputStatus.clear();
}
emit stateChanged();
@@ -320,10 +309,10 @@ void CaptureController::startCapture(int channelIndex)
if (!openChannel(channelIndex))
return;
// Consume queued signal events first. gvfg_start_channel() performs the
// single authoritative hardware revalidation; preview setup reuses the
// most recent UI cache instead of issuing another register query here.
// Consume queued events, then query the current Lib signal state once for
// this explicit Start request. The periodic UI update only uses the cache.
processPendingEvents();
updateSignalStatus();
if (!channel.haveCachedSignalStatus || !channel.cachedSignalStatus.connected)
{
appendLog(QStringLiteral("CH%1 [LIB] No input signal; start skipped").arg(channelIndex));
@@ -331,19 +320,14 @@ void CaptureController::startCapture(int channelIndex)
}
const bool audioEnabled = channel.requestedAudio;
gvfg_status_t st = gvfg_set_channel_audio_enabled(handle_, channelIndex, audioEnabled ? 1 : 0);
if (st != GVFG_OK)
{
reportError(QStringLiteral("gvfg_set_channel_audio_enabled"), st, channelIndex);
return;
}
channel.audioFormat = {};
if (audioEnabled)
{
st = gvfg_get_channel_audio_format(handle_, channelIndex, &channel.audioFormat);
if (st != GVFG_OK)
const gvfg_status_t audioStatus =
gvfg_get_channel_audio_format(handle_, channelIndex, &channel.audioFormat);
if (audioStatus != GVFG_OK)
{
reportError(QStringLiteral("gvfg_get_channel_audio_format"), st, channelIndex);
reportError(QStringLiteral("gvfg_get_channel_audio_format"), audioStatus, channelIndex);
return;
}
if (channel.audioFormat.channels == 0 || channel.audioFormat.sample_rate == 0 ||
@@ -388,7 +372,7 @@ void CaptureController::startCapture(int channelIndex)
return;
}
channel.startupStartTime = std::chrono::steady_clock::now();
st = gvfg_start_channel(handle_, channelIndex);
const gvfg_status_t st = gvfg_start_channel(handle_, channelIndex);
const auto startupStartCallEnd = std::chrono::steady_clock::now();
channel.startupStartCallMs =
std::chrono::duration<double, std::milli>(
@@ -409,8 +393,7 @@ void CaptureController::startCapture(int channelIndex)
channel.getFrameWindowMaximumMs.store(0.0, std::memory_order_relaxed);
channel.getFrameSamples.store(0, std::memory_order_relaxed);
channel.audioEnabled = audioEnabled;
channel.videoReceived = 0; channel.videoSubmitted = 0;
channel.videoSkipped = 0; channel.videoFailed = 0;
channel.videoReceived = 0; channel.videoFailed = 0;
channel.lastLoggedPreviewFailures = 0;
channel.lastLoggedAudioReleaseFailures = channel.lastLoggedAudioOutputFailures = 0;
channel.lastDeliveryLogMs = 0;
@@ -421,8 +404,7 @@ void CaptureController::startCapture(int channelIndex)
{
std::lock_guard<std::mutex> lock(channel.audioQueueMutex);
channel.audioQueue.clear();
channel.audioReceivedFrames = channel.audioOutputFrames = 0;
channel.audioDroppedFrames = channel.audioCancelledFrames = 0;
channel.audioReceivedFrames = 0;
channel.audioReleaseFailedFrames = channel.audioOutputFailedFrames = 0;
}
channel.signalConnected.store(channel.cachedSignalStatus.connected != 0,
@@ -529,31 +511,63 @@ void CaptureController::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 [LIB] Event | %2").arg(channel).arg(eventTypeText(eventType)));
if (eventType == GVFG_EVENT_SIGNAL_CONNECTED ||
eventType == GVFG_EVENT_SIGNAL_DISCONNECTED ||
eventType == GVFG_EVENT_FORMAT_CHANGE_BEGIN ||
eventType == GVFG_EVENT_STREAM_READY)
if (eventType == GVFG_EVENT_VIDEO_FORMAT_CHANGED ||
eventType == GVFG_EVENT_VIDEO_INPUT_PLUGIN ||
eventType == GVFG_EVENT_VIDEO_INPUT_UNPLUG)
updateSignalStatus();
if (eventType == GVFG_EVENT_SIGNAL_DISCONNECTED)
if (eventType == GVFG_EVENT_VIDEO_INPUT_UNPLUG)
{
channels_[channel].signalConnected.store(false, std::memory_order_release);
else if (eventType == GVFG_EVENT_SIGNAL_CONNECTED ||
eventType == GVFG_EVENT_STREAM_READY)
}
else if (eventType == GVFG_EVENT_VIDEO_INPUT_PLUGIN)
{
channels_[channel].signalConnected.store(true, std::memory_order_release);
channels_[channel].signalReady.notify_all();
}
if (eventType == GVFG_EVENT_SIGNAL_DISCONNECTED && channels_[channel].previewHandle)
if (eventType == GVFG_EVENT_VIDEO_INPUT_PLUGIN ||
eventType == GVFG_EVENT_VIDEO_INPUT_UNPLUG ||
eventType == GVFG_EVENT_VIDEO_FORMAT_CHANGED)
refreshSdiInfo(channel);
if (eventType == GVFG_EVENT_VIDEO_INPUT_UNPLUG && channels_[channel].previewHandle)
gvfg_preview_clear(channels_[channel].previewHandle);
event = {};
event.struct_size = sizeof(event);
}
}
}
void CaptureController::refreshSdiInfo(int channel)
{
gvfg_sdi_info_t info{};
if (gvfg_get_channel_sdi_info(handle_, channel, &info) != GVFG_OK)
return;
const QString text = QStringLiteral("CH%1 SDI Info | %2 | %3 | %4 | %5 | %6 | %7 | %8 | %9 | %10 | ErrorCount=%11")
.arg(channel)
.arg(QString::fromUtf8(info.signal_lock_name))
.arg(QString::fromUtf8(info.mode_name))
.arg(QString::fromUtf8(info.resolution_name))
.arg(QString::fromUtf8(info.fps_name))
.arg(QString::fromUtf8(info.scan_name))
.arg(QString::fromUtf8(info.st352_format_name))
.arg(QString::fromUtf8(info.st352_fps_name))
.arg(QString::fromUtf8(info.st352_chroma_name))
.arg(QString::fromUtf8(info.st352_bit_depth_name))
.arg(info.error_count);
ChannelRuntime &runtime = channels_[channel];
if (runtime.cachedSdiInfoText == text)
return;
runtime.cachedSdiInfoText = text;
if (channel == GVFG_CHANNEL_0)
emit sdiInfoChanged(text);
}
void CaptureController::updateSignalStatus(bool queryHardware)
@@ -593,11 +607,14 @@ void CaptureController::updateSignalStatus(bool queryHardware)
const gvfg_signal_status_t &signal = channel.cachedSignalStatus;
const QString inputStatus = signal.connected
? QStringLiteral("CH%1 Connected | %2").arg(channelIndex).arg(signalFrameText(signal))
: QStringLiteral("CH%1 No signal").arg(channelIndex);
? QStringLiteral("CH%1 [LIB] GVFG_VIDEO_INFO.VideoSignalLock=1 | Video Locked | %2")
.arg(channelIndex)
.arg(signalFrameText(signal))
: QStringLiteral("CH%1 [LIB] GVFG_VIDEO_INFO.VideoSignalLock=0 | Video Undetected")
.arg(channelIndex);
if (inputStatus != channel.lastLoggedInputStatus)
{
appendLog(QStringLiteral("[LIB] Input status | %1").arg(inputStatus));
appendLog(inputStatus);
channel.lastLoggedInputStatus = inputStatus;
}
if (channel.previewVisible.load(std::memory_order_acquire) && signal.width > 0 && signal.height > 0)
@@ -610,9 +627,6 @@ void CaptureController::updateSignalStatus(bool queryHardware)
gvfg_preview_stats_t previewStats{};
const bool previewStatsOk = channel.previewHandle &&
gvfg_preview_get_stats(channel.previewHandle, &previewStats) == GVFG_PREVIEW_OK;
gvfg_preview_delivery_stats_t previewDelivery{};
const bool previewDeliveryOk = channel.previewHandle &&
gvfg_preview_get_delivery_stats(channel.previewHandle, &previewDelivery) == GVFG_PREVIEW_OK;
const QString previewFps = previewStatsOk && previewStats.present_fps > 0.0
? QString::number(previewStats.present_fps, 'f', 2)
: QStringLiteral("--");
@@ -641,21 +655,15 @@ void CaptureController::updateSignalStatus(bool queryHardware)
.arg(channel.audioFormat.bits_per_sample)
.arg(static_cast<qulonglong>(receivedFrames));
#if GVFG_INTERNAL_DIAGNOSTICS
uint64_t appOutputFrames = 0;
{
std::lock_guard<std::mutex> lock(channel.audioQueueMutex);
appOutputFrames = channel.audioOutputFrames;
}
gvfg_debug_backend_stats_t audioStats{};
if (gvfg_debug_get_channel_backend_stats(handle_, channelIndex, &audioStats) == GVFG_OK)
{
statusLines << QStringLiteral("CH%1 Audio Debug | LIB events DMA=%2 Extra=%3 | LIB->SDK %4 frames | SDK->APP %5 frames | APP->Output %6 frames")
statusLines << QStringLiteral("CH%1 Audio Debug | LIB events DMA=%2 Extra=%3 | LIB->SDK %4 frames | SDK->APP %5 frames")
.arg(channelIndex)
.arg(static_cast<qulonglong>(audioStats.audio_dma_event_wakes - channel.backendBaseline.audio_dma_event_wakes))
.arg(static_cast<qulonglong>(audioStats.extra_audio_event_wakes - channel.backendBaseline.extra_audio_event_wakes))
.arg(static_cast<qulonglong>(audioStats.audio_frames_from_lib - channel.backendBaseline.audio_frames_from_lib))
.arg(static_cast<qulonglong>(receivedFrames))
.arg(static_cast<qulonglong>(appOutputFrames));
.arg(static_cast<qulonglong>(receivedFrames));
}
#endif
}
@@ -688,14 +696,12 @@ void CaptureController::updateSignalStatus(bool queryHardware)
.arg(channelStats.get_frame_timing_max_us, 0, 'f', 3)
.arg(static_cast<qulonglong>(channelStats.get_frame_timing_samples))
: QStringLiteral("CH%1 [LIB] GetVideoFrame | measuring").arg(channelIndex));
statusLines << QStringLiteral("CH%1 Video Debug | LIB events=%2 | LIB->SDK %3 frames | SDK->APP %4 frames | APP->Preview %5 frames | Preview->DXGI %6 frames")
statusLines << QStringLiteral("CH%1 Video Debug | LIB events DMA=%2 Extra=%3 | LIB->SDK %4 frames | SDK->APP %5 frames")
.arg(channelIndex)
.arg(static_cast<qulonglong>(channelStats.video_event_wakes - channel.backendBaseline.video_event_wakes))
.arg(static_cast<qulonglong>(channelStats.video_dma_event_wakes - channel.backendBaseline.video_dma_event_wakes))
.arg(static_cast<qulonglong>(channelStats.extra_video_event_wakes - channel.backendBaseline.extra_video_event_wakes))
.arg(static_cast<qulonglong>(channelStats.video_frames_from_lib - channel.backendBaseline.video_frames_from_lib))
.arg(static_cast<qulonglong>(channel.videoReceived.load()))
.arg(static_cast<qulonglong>(channel.videoSubmitted.load()))
.arg(static_cast<qulonglong>(previewDeliveryOk
? previewDelivery.presented - channel.previewBaseline.presented : 0));
.arg(static_cast<qulonglong>(channel.videoReceived.load()));
}
#endif
}
@@ -717,10 +723,11 @@ void CaptureController::reportError(const QString &apiName, gvfg_status_t status
.arg(apiName, QString::fromUtf8(gvfg_strerror(status)));
if (channel == GVFG_CHANNEL_0 || channel == GVFG_CHANNEL_1)
message.prepend(QStringLiteral("CH%1 ").arg(channel));
if (handle_ != nullptr && (channel == GVFG_CHANNEL_0 || channel == GVFG_CHANNEL_1))
if (status < 0 && handle_ != nullptr &&
(channel == GVFG_CHANNEL_0 || channel == GVFG_CHANNEL_1))
{
char detail[512] = {};
if (gvfg_get_channel_last_error_detail(handle_, channel, detail, sizeof(detail)) == GVFG_OK &&
if (gvfg_get_channel_last_sdk_error_detail(handle_, channel, detail, sizeof(detail)) == GVFG_OK &&
detail[0] != '\0')
message += QStringLiteral(" | %1").arg(QString::fromUtf8(detail));
}
@@ -729,116 +736,13 @@ void CaptureController::reportError(const QString &apiName, gvfg_status_t status
void CaptureController::appendLog(const QString &message)
{
const QString timestamp = QDateTime::currentDateTime().toString(QStringLiteral("HH:mm:ss.zzz"));
const QStringList lines = message.split(QLatin1Char('\n'));
for (int i = 0; i < lines.size(); ++i)
{
const QString line = QStringLiteral("[%1] %2%3")
.arg(timestamp, i == 0 ? QString() : QStringLiteral(" "), lines.at(i));
writeLogFileLine(line);
emit logMessage(line);
}
}
void CaptureController::openLogFile()
{
logSessionStamp_ = QDateTime::currentDateTime().toString(QStringLiteral("yyyyMMdd_HHmmss"));
logPartIndex_ = 1;
logDirPath_ = QCoreApplication::applicationDirPath() + QStringLiteral("/logs");
if (!QDir().mkpath(logDirPath_))
{
logFilePath_ = logDirPath_;
return;
}
openLogFilePart();
}
bool CaptureController::openLogFilePart()
{
std::lock_guard<std::mutex> lock(logFileMutex_);
if (logFile_.isOpen())
logFile_.close();
logFilePath_ = QStringLiteral("%1/%2_%3_part%4.log")
.arg(logDirPath_, logFilePrefix(), logSessionStamp_)
.arg(logPartIndex_, 2, 10, QLatin1Char('0'));
logFile_.setFileName(logFilePath_);
if (!logFile_.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
return false;
const QString header = QStringLiteral("\n==== %1 session %2 part %3 ====\n")
.arg(logFilePrefix(),
QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz")))
.arg(logPartIndex_);
logFile_.write(header.toUtf8());
logFile_.flush();
return true;
}
void CaptureController::rotateLogFileIfNeeded()
{
if (!logFile_.isOpen() || logFile_.size() < kMaxLogFileBytes)
return;
const QString footer = QStringLiteral("==== log rotated at %1 ====\n")
.arg(QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz")));
logFile_.write(footer.toUtf8());
logFile_.flush();
++logPartIndex_;
openLogFilePart();
}
void CaptureController::writeLogFileLine(const QString &line)
{
std::lock_guard<std::mutex> lock(logFileMutex_);
if (!logFile_.isOpen())
return;
if (logFile_.size() >= kMaxLogFileBytes)
{
const QString footer = QStringLiteral("==== log rotated at %1 ====\n")
.arg(QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz")));
logFile_.write(footer.toUtf8());
logFile_.flush();
++logPartIndex_;
if (logFile_.isOpen())
logFile_.close();
logFilePath_ = QStringLiteral("%1/%2_%3_part%4.log")
.arg(logDirPath_, logFilePrefix(), logSessionStamp_)
.arg(logPartIndex_, 2, 10, QLatin1Char('0'));
logFile_.setFileName(logFilePath_);
if (logFile_.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
{
const QString header = QStringLiteral("\n==== %1 session %2 part %3 ====\n")
.arg(logFilePrefix(),
QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz")))
.arg(logPartIndex_);
logFile_.write(header.toUtf8());
}
}
if (!logFile_.isOpen())
return;
logFile_.write(line.toUtf8());
logFile_.write("\n");
logFile_.flush();
emit logMessage(message);
}
#if GVFG_INTERNAL_DIAGNOSTICS
void CaptureController::writeDiagnosticSnapshot(const QString &statusText)
{
const QString timestamp = QDateTime::currentDateTime().toString(QStringLiteral("HH:mm:ss.zzz"));
const QStringList lines = statusText.split(QLatin1Char('\n'));
for (int i = 0; i < lines.size(); ++i)
{
const QString line = QStringLiteral("[%1] %2%3")
.arg(timestamp,
i == 0 ? QStringLiteral("Diagnostic | ") : QStringLiteral(" "),
lines.at(i));
writeLogFileLine(line);
}
emit diagnosticMessage(statusText);
}
#endif
@@ -860,25 +764,10 @@ void CaptureController::logDeliveryStatus(int channelIndex, bool finalSnapshot)
const auto &b = c.previewBaseline;
const uint64_t failed = (previewOk ? p.failed - b.failed : 0) + c.videoFailed.load();
uint64_t audioReleaseFailed, audioOutputFailed;
bool audioAccounted;
{
std::lock_guard<std::mutex> lock(c.audioQueueMutex);
audioReleaseFailed = c.audioReleaseFailedFrames;
audioOutputFailed = c.audioOutputFailedFrames;
audioAccounted = c.audioQueue.empty() && c.audioReceivedFrames ==
c.audioOutputFrames + c.audioDroppedFrames + c.audioCancelledFrames +
c.audioReleaseFailedFrames + c.audioOutputFailedFrames;
}
if (finalSnapshot)
{
const bool videoAccounted = previewOk && c.videoReceived.load() ==
c.videoSubmitted.load() + c.videoSkipped.load() + c.videoFailed.load() &&
c.videoSubmitted.load() == p.submitted - b.submitted;
if (!videoAccounted || !audioAccounted)
appendLog(QStringLiteral("CH%1 [APP] ERROR accounting mismatch | video=%2 audio=%3")
.arg(QString::number(channelIndex),
videoAccounted ? QStringLiteral("OK") : QStringLiteral("MISMATCH"),
audioAccounted ? QStringLiteral("OK") : QStringLiteral("MISMATCH")));
}
// Also flush any changes since the last aggregate when stopping.
if (failed != c.lastLoggedPreviewFailures)
@@ -1029,7 +918,6 @@ void CaptureController::captureReadLoop(int channelIndex)
}
else
{
++channel.videoSubmitted;
if (!startupLatencyLogged)
{
startupLatencyLogged = true;
@@ -1073,8 +961,6 @@ void CaptureController::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)
{
@@ -1194,15 +1080,9 @@ void CaptureController::audioReadLoop(int channelIndex)
{
std::lock_guard<std::mutex> lock(channel.audioQueueMutex);
if (channel.stopRequested.load(std::memory_order_acquire))
{
++channel.audioCancelledFrames;
break;
}
if (channel.audioQueue.size() >= kMaxQueuedAudioFrames)
{
++channel.audioDroppedFrames;
channel.audioQueue.pop_front();
}
channel.audioQueue.push_back({std::move(pcm)});
}
channel.audioQueueReady.notify_one();
@@ -1247,10 +1127,7 @@ void CaptureController::audioPlaybackLoop(int channelIndex)
recovering = true;
std::unique_lock<std::mutex> lock(channel.audioQueueMutex);
while (!channel.audioQueue.empty())
{
++channel.audioDroppedFrames;
channel.audioQueue.pop_front();
}
channel.audioQueueReady.wait_for(lock, std::chrono::milliseconds(500), [&channel]() {
return channel.stopRequested.load(std::memory_order_acquire);
});
@@ -1268,10 +1145,7 @@ void CaptureController::audioPlaybackLoop(int channelIndex)
recovering = true;
std::unique_lock<std::mutex> lock(channel.audioQueueMutex);
while (!channel.audioQueue.empty())
{
++channel.audioDroppedFrames;
channel.audioQueue.pop_front();
}
channel.audioQueueReady.wait_for(lock, std::chrono::milliseconds(500), [&channel]() {
return channel.stopRequested.load(std::memory_order_acquire);
});
@@ -1331,16 +1205,6 @@ void CaptureController::audioPlaybackLoop(int channelIndex)
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
if (written != static_cast<qint64>(pcm.size()) && !restartPlayback)
{
std::lock_guard<std::mutex> lock(channel.audioQueueMutex);
++channel.audioCancelledFrames;
}
else if (written == static_cast<qint64>(pcm.size()))
{
std::lock_guard<std::mutex> lock(channel.audioQueueMutex);
++channel.audioOutputFrames;
}
}
audioSink.stop();
if (restartPlayback)
@@ -1348,10 +1212,7 @@ void CaptureController::audioPlaybackLoop(int channelIndex)
recovering = true;
std::unique_lock<std::mutex> lock(channel.audioQueueMutex);
while (!channel.audioQueue.empty())
{
++channel.audioDroppedFrames;
channel.audioQueue.pop_front();
}
channel.audioQueueReady.wait_for(lock, std::chrono::milliseconds(500), [&channel]() {
return channel.stopRequested.load(std::memory_order_acquire);
});
@@ -1367,6 +1228,5 @@ void CaptureController::joinAudioThread(int channel)
if (channels_[channel].audioPlaybackThread.joinable())
channels_[channel].audioPlaybackThread.join();
std::lock_guard<std::mutex> lock(channels_[channel].audioQueueMutex);
channels_[channel].audioCancelledFrames += channels_[channel].audioQueue.size();
channels_[channel].audioQueue.clear();
}
+9 -17
View File
@@ -4,7 +4,6 @@
#include <gvfg_debug.h>
#include <gvfg_preview.h>
#include <QFile>
#include <QObject>
#include <QStringList>
@@ -40,14 +39,10 @@ public:
bool frameAvailable(int channel) const;
bool cachedSignalStatus(int channel, gvfg_signal_status_t *status) const;
QString sdkVersion() const;
void logStartupInfo();
void logUiMessage(const QString &message);
public slots:
void refreshDevices();
bool openDevice();
void closeDevice();
bool applyOutputFormat(int channel);
void startCapture(int channel);
void stopCapture(int channel);
void stopAllCaptures();
@@ -59,12 +54,17 @@ signals:
void devicesChanged(const QStringList &names);
void stateChanged();
void statusChanged(const QString &text);
void sdiInfoChanged(const QString &text);
void logMessage(const QString &message);
void diagnosticMessage(const QString &message);
void previewSourceSizeChanged(int channel, int width, int height);
void previewShowRequested(int channel);
void previewCloseRequested(int channel);
private:
bool openDevice();
bool applyOutputFormat(int channel);
struct ChannelRuntime
{
struct AudioPacket { std::vector<uint8_t> pcm; };
@@ -84,10 +84,9 @@ private:
std::deque<AudioPacket> audioQueue;
bool audioEnabled = false;
gvfg_audio_format_t audioFormat{};
uint64_t audioReceivedFrames = 0, audioOutputFrames = 0;
uint64_t audioDroppedFrames = 0, audioCancelledFrames = 0;
uint64_t audioReceivedFrames = 0;
uint64_t audioReleaseFailedFrames = 0, audioOutputFailedFrames = 0;
std::atomic<uint64_t> videoReceived{0}, videoSubmitted{0}, videoSkipped{0}, videoFailed{0};
std::atomic<uint64_t> videoReceived{0}, videoFailed{0};
gvfg_preview_delivery_stats_t previewBaseline{};
gvfg_debug_backend_stats_t backendBaseline{};
std::chrono::steady_clock::time_point startupStartTime{};
@@ -100,16 +99,14 @@ private:
uint64_t previewFailureCount = 0;
gvfg_signal_status_t cachedSignalStatus{};
bool haveCachedSignalStatus = false;
QString cachedSdiInfoText;
QString lastLoggedInputStatus;
};
void reportError(const QString &apiName, gvfg_status_t status, int channel = -1);
void appendLog(const QString &message);
bool openChannel(int channel);
void openLogFile();
bool openLogFilePart();
void rotateLogFileIfNeeded();
void writeLogFileLine(const QString &line);
void refreshSdiInfo(int channel);
#if GVFG_INTERNAL_DIAGNOSTICS
void writeDiagnosticSnapshot(const QString &statusText);
#endif
@@ -120,7 +117,6 @@ private:
void joinAudioThread(int channel);
void logDeliveryStatus(int channel, bool finalSnapshot = false);
static constexpr qint64 kMaxLogFileBytes = 20ll * 1024ll * 1024ll;
std::array<gvfg_device_info_t, GVFG_MAX_DEVICES> devices_{};
int deviceCount_ = 0;
gvfg_handle handle_ = nullptr;
@@ -129,8 +125,4 @@ private:
std::array<bool, 2> channelStatusVisible_{{true, true}};
QTimer *runtimeStatusTimer_ = nullptr;
QString lastSignalStatusText_;
QFile logFile_;
std::mutex logFileMutex_;
QString logDirPath_, logFilePath_, logSessionStamp_;
int logPartIndex_ = 1;
};
+36 -25
View File
@@ -1,6 +1,7 @@
#include "mainwindow.h"
#include "capture_controller.h"
#include "previewwindow.h"
#include "sample_log.h"
#include "ui_mainwindow.h"
#include <QCloseEvent>
@@ -24,14 +25,15 @@ public:
protected:
void highlightBlock(const QString &text) override
{
if (text.contains(QStringLiteral("SIGNAL_DISCONNECTED")) ||
if (text.contains(QStringLiteral("VIDEO_INPUT_UNPLUG")) ||
text.contains(QStringLiteral("No signal"), Qt::CaseInsensitive) ||
text.contains(QStringLiteral("Video Undetected"), Qt::CaseInsensitive) ||
text.contains(QStringLiteral("failed"), Qt::CaseInsensitive) ||
text.contains(QStringLiteral("error"), Qt::CaseInsensitive))
setFormat(0, text.size(), error_);
else if (text.contains(QStringLiteral("warning"), Qt::CaseInsensitive))
setFormat(0, text.size(), warning_);
else if (text.contains(QStringLiteral("SIGNAL_CONNECTED")) ||
else if (text.contains(QStringLiteral("VIDEO_INPUT_PLUGIN")) ||
text.contains(QStringLiteral("recovered"), Qt::CaseInsensitive))
setFormat(0, text.size(), recovery_);
}
@@ -41,7 +43,8 @@ private:
}
MainWindow::MainWindow(QWidget *parent)
: QWidget(parent), ui_(new Ui::MainWindow), controller_(new CaptureController(this))
: QWidget(parent), ui_(new Ui::MainWindow), controller_(new CaptureController(this)),
log_(new SampleLog(this))
{
ui_->setupUi(this);
#if GVFG_INTERNAL_DIAGNOSTICS
@@ -71,7 +74,11 @@ MainWindow::MainWindow(QWidget *parent)
});
connect(controller_, &CaptureController::stateChanged, this, &MainWindow::updateUiState);
connect(controller_, &CaptureController::statusChanged, ui_->statusLabel, &QLabel::setText);
connect(controller_, &CaptureController::logMessage, this, &MainWindow::appendLogLine);
connect(controller_, &CaptureController::sdiInfoChanged, ui_->sdiInfoLabel, &QLabel::setText);
connect(controller_, &CaptureController::logMessage, log_, &SampleLog::append, Qt::QueuedConnection);
connect(controller_, &CaptureController::diagnosticMessage, log_, &SampleLog::appendDiagnostic,
Qt::QueuedConnection);
connect(log_, &SampleLog::lineReady, this, &MainWindow::appendLogLine);
connect(controller_, &CaptureController::previewSourceSizeChanged, this,
[this](int channel, int width, int height) {
if (width > 0 && height > 0) previewWindows_[channel]->setSourceSize(width, height);
@@ -85,14 +92,12 @@ MainWindow::MainWindow(QWidget *parent)
[this](int channel) { previewWindows_[channel]->closePreview(); });
connect(ui_->refreshButton, &QPushButton::clicked, controller_, &CaptureController::refreshDevices);
connect(ui_->openButton, &QPushButton::clicked, this, [this] {
if (controller_->deviceOpen()) controller_->closeDevice();
else {
syncControllerOptions(GVFG_CHANNEL_0);
syncControllerOptions(GVFG_CHANNEL_1);
controller_->setSelectedDeviceIndex(ui_->deviceCombo->currentData().toInt());
controller_->openDevice();
}
connect(ui_->deviceCombo, &QComboBox::currentIndexChanged, this, [this](int) {
const int selectedDevice = ui_->deviceCombo->currentData().toInt();
if (controller_->deviceOpen())
controller_->closeDevice();
controller_->setSelectedDeviceIndex(selectedDevice);
updateUiState();
});
connect(ui_->ch0StartButton, &QPushButton::clicked, this, [this] { syncControllerOptions(0); controller_->startCapture(0); });
connect(ui_->ch1StartButton, &QPushButton::clicked, this, [this] { syncControllerOptions(1); controller_->startCapture(1); });
@@ -106,24 +111,33 @@ MainWindow::MainWindow(QWidget *parent)
auto formatChanged = [this](int channel) {
updateOutputFormatOptions(channel);
syncControllerOptions(channel);
if (controller_->channelOpened(channel) && !controller_->channelRunning(channel))
{ controller_->applyOutputFormat(channel); controller_->updateSignalStatus(); }
};
connect(ui_->ch0OutputFormatCombo, &QComboBox::currentIndexChanged, this, [formatChanged](int) { formatChanged(0); });
connect(ui_->ch1OutputFormatCombo, &QComboBox::currentIndexChanged, this, [formatChanged](int) { formatChanged(1); });
connect(ui_->ch0ZeroCopyCheckBox, &QCheckBox::toggled, this, [this](bool) {
syncControllerOptions(GVFG_CHANNEL_0);
if (controller_->deviceOpen()) controller_->updateSignalStatus(false);
if (controller_->deviceOpen()) {
const int selectedDevice = ui_->deviceCombo->currentData().toInt();
controller_->closeDevice();
controller_->setSelectedDeviceIndex(selectedDevice);
}
});
connect(ui_->ch1ZeroCopyCheckBox, &QCheckBox::toggled, this, [this](bool) {
syncControllerOptions(GVFG_CHANNEL_1);
if (controller_->deviceOpen()) controller_->updateSignalStatus(false);
if (controller_->deviceOpen()) {
const int selectedDevice = ui_->deviceCombo->currentData().toInt();
controller_->closeDevice();
controller_->setSelectedDeviceIndex(selectedDevice);
}
});
updateOutputFormatOptions();
updateUiState();
controller_->logStartupInfo();
log_->append(QStringLiteral("GVFG SDK version | %1").arg(controller_->sdkVersion()));
log_->append(log_->fileAvailable()
? QStringLiteral("Log file | %1").arg(log_->filePath())
: QStringLiteral("Log file unavailable | %1").arg(log_->filePath()));
controller_->refreshDevices();
}
@@ -166,7 +180,7 @@ void MainWindow::showPreviewWindow(int channel, bool fullscreen)
else previewWindows_[channel]->showPreview();
controller_->setPreviewTarget(channel, previewWindows_[channel]->nativePreviewHandle());
if (!controller_->applyPreview(channel))
controller_->logUiMessage(
log_->append(
fullscreen
? QStringLiteral("CH%1 [APP] Fullscreen preview failed | window update").arg(channel)
: QStringLiteral("CH%1 [APP] Show preview failed | window update").arg(channel));
@@ -188,20 +202,17 @@ void MainWindow::updateOutputFormatOptions(int changedChannel)
if (model && model->item(y210)) model->item(y210)->setEnabled(enabled[channel]);
combos[channel]->setToolTip(
enabled[channel]
? QStringLiteral("Requested CH%1 capture output format (GigabyteLib extension)").arg(channel)
? QStringLiteral("Requested CH%1 capture output format").arg(channel)
: QStringLiteral("Y210 is already selected by the other channel"));
}
}
void MainWindow::updateUiState()
{
const bool open = controller_->deviceOpen();
const bool running[] = {controller_->channelRunning(0), controller_->channelRunning(1)};
const bool anyRunning = running[0] || running[1];
const bool selected = ui_->deviceCombo->currentData().toInt() >= 0;
ui_->openButton->setText(open ? QStringLiteral("Close Device") : QStringLiteral("Open Device"));
ui_->openButton->setEnabled(!anyRunning);
ui_->refreshButton->setEnabled(!open); ui_->deviceCombo->setEnabled(!open);
ui_->refreshButton->setEnabled(!anyRunning); ui_->deviceCombo->setEnabled(!anyRunning);
ui_->ch0StartButton->setEnabled(selected && !running[0]); ui_->ch1StartButton->setEnabled(selected && !running[1]);
ui_->ch0StopButton->setEnabled(running[0]); ui_->ch1StopButton->setEnabled(running[1]);
ui_->ch0PreviewButton->setEnabled(running[0] && controller_->frameAvailable(0));
@@ -209,8 +220,8 @@ void MainWindow::updateUiState()
ui_->ch0FullscreenButton->setEnabled(ui_->ch0PreviewButton->isEnabled());
ui_->ch1FullscreenButton->setEnabled(ui_->ch1PreviewButton->isEnabled());
ui_->ch0OutputFormatCombo->setEnabled(!running[0]); ui_->ch1OutputFormatCombo->setEnabled(!running[1]);
ui_->ch0ZeroCopyCheckBox->setEnabled(!controller_->channelOpened(0));
ui_->ch1ZeroCopyCheckBox->setEnabled(!controller_->channelOpened(1));
ui_->ch0ZeroCopyCheckBox->setEnabled(!anyRunning);
ui_->ch1ZeroCopyCheckBox->setEnabled(!anyRunning);
ui_->ch0AudioCheckBox->setEnabled(!running[0]);
ui_->channel1GroupBox->setVisible(kChannel1UiVisible);
}
+2
View File
@@ -8,6 +8,7 @@
class CaptureController;
class QCloseEvent;
class PreviewWindow;
class SampleLog;
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
@@ -33,6 +34,7 @@ private:
Ui::MainWindow *ui_ = nullptr;
CaptureController *controller_ = nullptr;
SampleLog *log_ = nullptr;
std::array<PreviewWindow *, 2> previewWindows_{};
};
+12 -9
View File
@@ -45,16 +45,19 @@
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="openButton">
<property name="text">
<string>Open Device</string>
</property>
</widget>
</item>
</layout>
</item>
<item row="1" column="0">
<widget class="QLabel" name="sdiInfoLabel">
<property name="text">
<string>SDI Info: --</string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item row="2" column="0">
<layout class="QHBoxLayout" name="channelPanelsLayout" stretch="1,1">
<item>
<widget class="QGroupBox" name="channel0GroupBox">
@@ -219,14 +222,14 @@
</item>
</layout>
</item>
<item row="2" column="0">
<item row="3" column="0">
<widget class="QLabel" name="statusLabel">
<property name="text">
<string>Idle</string>
</property>
</widget>
</item>
<item row="3" column="0">
<item row="4" column="0">
<widget class="QPlainTextEdit" name="logEdit">
<property name="readOnly">
<bool>true</bool>
+78
View File
@@ -0,0 +1,78 @@
#include "sample_log.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QStringList>
namespace
{
QString filePrefix()
{
#if GVFG_INTERNAL_DIAGNOSTICS
return QStringLiteral("gvfg_qt_preview_debug");
#else
return QStringLiteral("gvfg_qt_preview");
#endif
}
}
SampleLog::SampleLog(QObject *parent) : QObject(parent)
{
sessionStamp_ = QDateTime::currentDateTime().toString(QStringLiteral("yyyyMMdd_HHmmss"));
directoryPath_ = QCoreApplication::applicationDirPath() + QStringLiteral("/logs");
if (QDir().mkpath(directoryPath_)) openPart();
else filePath_ = directoryPath_;
}
void SampleLog::append(const QString &message)
{
const QString timestamp = QDateTime::currentDateTime().toString(QStringLiteral("HH:mm:ss.zzz"));
const QStringList lines = message.split(QLatin1Char('\n'));
for (int i = 0; i < lines.size(); ++i)
{
const QString line = QStringLiteral("[%1] %2%3")
.arg(timestamp, i == 0 ? QString() : QStringLiteral(" "), lines.at(i));
writeLine(line);
emit lineReady(line);
}
}
void SampleLog::appendDiagnostic(const QString &message)
{
const QString timestamp = QDateTime::currentDateTime().toString(QStringLiteral("HH:mm:ss.zzz"));
const QStringList lines = message.split(QLatin1Char('\n'));
for (int i = 0; i < lines.size(); ++i)
writeLine(QStringLiteral("[%1] %2%3").arg(
timestamp, i == 0 ? QStringLiteral("Diagnostic | ") : QStringLiteral(" "), lines.at(i)));
}
bool SampleLog::openPart()
{
if (file_.isOpen()) file_.close();
filePath_ = QStringLiteral("%1/%2_%3_part%4.log")
.arg(directoryPath_, filePrefix(), sessionStamp_).arg(partIndex_, 2, 10, QLatin1Char('0'));
file_.setFileName(filePath_);
if (!file_.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) return false;
file_.write(QStringLiteral("\n==== %1 session %2 part %3 ====\n")
.arg(filePrefix(), QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz")))
.arg(partIndex_).toUtf8());
file_.flush();
return true;
}
void SampleLog::writeLine(const QString &line)
{
if (!file_.isOpen()) return;
if (file_.size() >= kMaxFileBytes)
{
file_.write(QStringLiteral("==== log rotated at %1 ====\n")
.arg(QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz"))).toUtf8());
file_.flush();
++partIndex_;
if (!openPart()) return;
}
file_.write(line.toUtf8());
file_.write("\n");
file_.flush();
}
+30
View File
@@ -0,0 +1,30 @@
#pragma once
#include <QFile>
#include <QObject>
#include <QString>
class SampleLog final : public QObject
{
Q_OBJECT
public:
explicit SampleLog(QObject *parent = nullptr);
QString filePath() const { return filePath_; }
bool fileAvailable() const { return file_.isOpen(); }
public slots:
void append(const QString &message);
void appendDiagnostic(const QString &message);
signals:
void lineReady(const QString &line);
private:
bool openPart();
void writeLine(const QString &line);
static constexpr qint64 kMaxFileBytes = 20ll * 1024ll * 1024ll;
QFile file_;
QString directoryPath_, filePath_, sessionStamp_;
int partIndex_ = 1;
};
+1 -1
View File
@@ -1,6 +1,6 @@
cmake_minimum_required(VERSION 3.16)
project(gvfg_sdk VERSION 0.3.0 LANGUAGES CXX)
project(gvfg_sdk VERSION 1.0.0 LANGUAGES CXX)
include(GNUInstallDirs)
@@ -25,6 +25,6 @@ Build the preview DLL with the changed shared pipeline source. If distributing t
On the target Ryzen 7 7700 system, compare identical resolution/FPS/window size and input formats before/after. Check 8-bit and 10-bit colors (including gradients), resize/fullscreen, repeated Start/Stop, Present skip counts and GPU engine utilization. Also verify public BGRA8/RGB10A2/NV12 buffer conversion if shipping its rebuilt DLL. Capture HRESULT details if 10-bit still fails; do not infer insufficient GPU capacity solely from utilization.
Expected preview pacing skips and audio queue evictions remain internal counters and are not logged. Preview/render failures, frame-ID anomalies, audio write failures, and delivery-accounting mismatches are logged as errors, aggregated at most once per five seconds. Mutex/drain/join waits service synchronous Windows sent messages without dispatching queued application input. Blocking Present still has no application timeout; device hangs and window transitions require hardware validation.
Expected preview pacing skips and audio queue evictions are not reported by the Sample. Preview/render failures, frame-ID anomalies, and audio write failures are logged as errors, aggregated at most once per five seconds. Mutex/drain/join waits service synchronous Windows sent messages without dispatching queued application input. Blocking Present still has no application timeout; device hangs and window transitions require hardware validation.
Preview queue policy: three pending/upload-reserved slots plus one presenting slot. Consume in enqueue order, keep frames within a 50 ms queue-age limit, and skip incoming frames only when capacity is full. Expired queued frames are counted in the existing replaced field (APP label: expired). This is not a 50 ms bound on blocking Present or physical scanout.
+1 -1
View File
@@ -29,7 +29,7 @@ EXPORTS
gvfg_get_version
gvfg_pixel_format_name
gvfg_strerror
gvfg_get_channel_last_error_detail
gvfg_get_channel_last_sdk_error_detail
gvfg_debug_get_channel_backend_stats
gvfg_debug_read_register
gvfg_debug_write_register
+17 -15
View File
@@ -78,16 +78,20 @@ extern "C"
GVFG_MAX_DEVICES = 16,
};
typedef enum
typedef int32_t gvfg_status_t;
enum
{
GVFG_OK = 0,
GVFG_EINVAL = -1, /* Invalid argument, such as NULL handle/output pointer. */
GVFG_ENODEV = -2, /* No GVFG capture device, or the device cannot be opened. */
GVFG_ESTATE = -3, /* API was called in the wrong state. */
GVFG_EIO = -4, /* Driver/backend I/O failure. */
GVFG_EIO = -4, /* SDK-owned I/O, GPU, or internal extension failure. */
GVFG_ENOTSUP = -5, /* Requested feature or format is not supported. */
GVFG_ETIMEOUT = -6 /* Timed out waiting for driver/backend work. */
} gvfg_status_t;
};
/* Positive return values are unmodified GigabyteLib GVFG_HRESULT values. */
typedef enum
{
@@ -169,6 +173,7 @@ extern "C"
int level_b;
uint32_t st352_payload;
uint32_t error_count;
char signal_lock_name[32];
char mode_name[16];
char resolution_name[64];
char fps_name[24];
@@ -243,12 +248,9 @@ extern "C"
typedef enum
{
GVFG_EVENT_UNKNOWN = 0,
GVFG_EVENT_SIGNAL_CONNECTED = 1,
GVFG_EVENT_SIGNAL_DISCONNECTED = 2,
/* First complete frame after stream start, plug-in, or format recovery is ready. */
GVFG_EVENT_STREAM_READY = 3,
/* Input format is changing; pause use of resources created for the old format. */
GVFG_EVENT_FORMAT_CHANGE_BEGIN = 4
GVFG_EVENT_VIDEO_FORMAT_CHANGED = 1,
GVFG_EVENT_VIDEO_INPUT_PLUGIN = 2,
GVFG_EVENT_VIDEO_INPUT_UNPLUG = 3
} gvfg_event_type_t;
typedef struct
@@ -324,7 +326,7 @@ extern "C"
* - GVFG_OK on success.
* - GVFG_EINVAL if handle is NULL or channel_index is invalid.
* - GVFG_ENODEV if the device cannot be opened.
* - GVFG_EIO for driver/backend failures.
* - A positive, unmodified GVFG_HRESULT for GigabyteLib failures.
*/
GVFG_API gvfg_status_t gvfg_open_channel(
GVFG_PARAM_IN gvfg_handle handle,
@@ -413,7 +415,7 @@ extern "C"
* - GVFG_ESTATE if capture is not running or a previous frame has not been
* released.
* - GVFG_ETIMEOUT if no frame is ready before timeout_ms expires.
* - GVFG_EIO for driver/backend failures.
* - A positive, unmodified GVFG_HRESULT for GigabyteLib failures.
*
* In copy mode the returned data pointer is owned by the SDK. In zero-copy
* mode it points to driver-owned memory. In both modes it remains valid
@@ -604,7 +606,7 @@ extern "C"
GVFG_PARAM_IN int channel_index,
GVFG_PARAM_OUT gvfg_runtime_info_t *out_info);
/* Return the loaded GVFG runtime DLL version, for example "0.3.0". */
/* Return the loaded GVFG runtime DLL version, for example "1.0.0". */
GVFG_API const char *gvfg_get_version(void);
/* Convert a gvfg_pixel_format_t value to a static English format name. */
@@ -624,11 +626,11 @@ extern "C"
GVFG_PARAM_IN gvfg_status_t status);
/*
* Copy the most recent detailed fault or rejected API call for one
* channel. Normal frame-read and event-poll timeouts are not stored.
* Copy the most recent SDK-owned detailed fault or rejected API call for
* one channel. Positive GigabyteLib results and normal timeouts are not stored.
* A successful gvfg_start_channel() begins a new diagnostic lifetime.
*/
GVFG_API gvfg_status_t gvfg_get_channel_last_error_detail(
GVFG_API gvfg_status_t gvfg_get_channel_last_sdk_error_detail(
GVFG_PARAM_IN gvfg_handle handle,
GVFG_PARAM_IN int channel_index,
GVFG_PARAM_OUT char *out_message,
+2 -1
View File
@@ -20,7 +20,8 @@ typedef struct
int running;
int frame_held;
uint32_t event_queue_depth;
uint64_t video_event_wakes;
uint64_t video_dma_event_wakes;
uint64_t extra_video_event_wakes;
uint64_t video_frames_from_lib;
uint64_t audio_dma_event_wakes;
uint64_t extra_audio_event_wakes;
@@ -3,8 +3,6 @@
#include <algorithm>
#include <array>
#include <iomanip>
#include <sstream>
namespace
{
@@ -33,6 +31,7 @@ uint32_t bit_depth(int format)
return format == GVFG_PIXFMT_Y210 ? 10u :
format == GVFG_PIXFMT_YUY2 ? 8u : 0u;
}
}
namespace gvfg::internal
@@ -89,7 +88,7 @@ gvfg_status_t GigabyteCaptureSession::ensure_vendor_channel_open() const
? GVFG_VIDEO_FRAME_ZERO_COPY | GVFG_AUDIO_FRAME_BUF_COPY
: GVFG_VIDEO_FRAME_BUF_COPY | GVFG_AUDIO_FRAME_BUF_COPY;
gvfg_status_t status = from_vendor(
GvfgOpenDev(device_handle_, &context_, memoryMode), "GvfgOpenDev");
GvfgOpenDev(device_handle_, &context_, memoryMode));
if (status != GVFG_OK)
{
CloseHandle(device_handle_);
@@ -98,8 +97,7 @@ gvfg_status_t GigabyteCaptureSession::ensure_vendor_channel_open() const
return status;
}
status = from_vendor(GvfgCreateEvents(&events_, audio_enabled_ ? FALSE : TRUE),
"GvfgCreateEvents");
status = from_vendor(GvfgCreateEvents(&events_, audio_enabled_ ? FALSE : TRUE));
if (status != GVFG_OK)
{
GvfgCloseDev(&context_);
@@ -115,16 +113,21 @@ gvfg_status_t GigabyteCaptureSession::ensure_vendor_channel_open() const
close_vendor_channel();
return reject(GVFG_EIO, "CreateEvent for GigabyteLib cancellation failed");
}
recovery_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr);
if (!recovery_event_)
{
close_vendor_channel();
return reject(GVFG_EIO, "CreateEvent for GigabyteLib recovery failed");
}
status = from_vendor(GvfgOpenVideoChn(context_, channel_, &events_),
"GvfgOpenVideoChn");
status = from_vendor(GvfgOpenVideoChn(context_, channel_, &events_));
if (status != GVFG_OK)
{
close_vendor_channel();
return status;
}
channel_open_ = true;
return refresh_video_info();
return GVFG_OK;
}
void GigabyteCaptureSession::close_vendor_channel() const
@@ -132,6 +135,11 @@ void GigabyteCaptureSession::close_vendor_channel() const
if (channel_open_ && context_)
GvfgCloseVideoChn(context_, channel_);
channel_open_ = false;
{
std::lock_guard<std::mutex> lock(state_mutex_);
video_info_valid_ = false;
audio_info_valid_ = false;
}
if (context_)
GvfgCloseDev(&context_);
if (events_created_)
@@ -141,6 +149,9 @@ void GigabyteCaptureSession::close_vendor_channel() const
if (stop_event_)
CloseHandle(stop_event_);
stop_event_ = nullptr;
if (recovery_event_)
CloseHandle(recovery_event_);
recovery_event_ = nullptr;
if (device_handle_ != INVALID_HANDLE_VALUE)
CloseHandle(device_handle_);
device_handle_ = INVALID_HANDLE_VALUE;
@@ -177,8 +188,13 @@ gvfg_status_t GigabyteCaptureSession::set_audio_enabled(bool enabled)
{
if (running_)
return reject(GVFG_ESTATE, "GigabyteLib audio mode cannot change while running");
if (channel_open_ && audio_enabled_ != enabled)
if (audio_enabled_ != enabled)
{
if (channel_open_)
close_vendor_channel();
std::lock_guard<std::mutex> lock(state_mutex_);
audio_info_valid_ = false;
}
audio_enabled_ = enabled;
return GVFG_OK;
}
@@ -197,7 +213,7 @@ gvfg_status_t GigabyteCaptureSession::set_video_format(gvfg_pixel_format_t forma
? GVFG_VIDEO_COLOR_DEPTH_10_BITS
: GVFG_VIDEO_COLOR_DEPTH_8_BITS;
const gvfg_status_t status = from_vendor(
GvfgSetVideoColorDepth(context_, channel_, colorDepth), "GvfgSetVideoColorDepth");
GvfgSetVideoColorDepth(context_, channel_, colorDepth));
return status == GVFG_OK ? refresh_video_info() : status;
}
@@ -206,8 +222,11 @@ gvfg_status_t GigabyteCaptureSession::refresh_video_info() const
if (!context_)
return reject(GVFG_ESTATE, "GigabyteLib video info requested before open");
GVFG_VIDEO_INFO info{};
const gvfg_status_t status = from_vendor(
GvfgGetVideoInfo(context_, channel_, &info), "GvfgGetVideoInfo");
gvfg_status_t status = GVFG_OK;
{
std::lock_guard<std::mutex> captureLock(capture_mutex_);
status = from_vendor(GvfgGetVideoInfo(context_, channel_, &info));
}
if (status != GVFG_OK)
return status;
gvfg_signal_status_t signal{};
@@ -222,6 +241,7 @@ gvfg_status_t GigabyteCaptureSession::refresh_video_info() const
std::lock_guard<std::mutex> lock(state_mutex_);
cached_signal_ = signal;
video_info_ = info;
video_info_valid_ = true;
}
return GVFG_OK;
}
@@ -231,6 +251,9 @@ gvfg_status_t GigabyteCaptureSession::get_signal_status(gvfg_signal_status_t &ou
const gvfg_status_t openStatus = ensure_vendor_channel_open();
if (openStatus != GVFG_OK)
return openStatus;
const gvfg_status_t status = refresh_video_info();
if (status != GVFG_OK)
return status;
std::lock_guard<std::mutex> lock(state_mutex_);
out = cached_signal_;
return GVFG_OK;
@@ -243,7 +266,7 @@ gvfg_status_t GigabyteCaptureSession::get_device_capabilities(
if (openStatus != GVFG_OK)
return openStatus;
GVFG_DEV_INFO info{};
const gvfg_status_t status = from_vendor(GvfgGetDevInfo(context_, &info), "GvfgGetDevInfo");
const gvfg_status_t status = from_vendor(GvfgGetDevInfo(context_, &info));
if (status != GVFG_OK)
return status;
out = {};
@@ -259,13 +282,11 @@ gvfg_status_t GigabyteCaptureSession::get_sdi_info(gvfg_sdi_info_t &out) const
return openStatus;
GVFG_SDI_VIDEO_INFO info{};
gvfg_status_t status = from_vendor(
GvfgGetSdiVideoInputInfo(context_, channel_, &info), "GvfgGetSdiVideoInputInfo");
GvfgGetSdiVideoInputInfo(context_, channel_, &info));
if (status != GVFG_OK)
return status;
GVFG_SDI_VIDEO_INFO_STR text{};
status = from_vendor(
GvfgStringifySdiVideoInputInfo(context_, &info, &text),
"GvfgStringifySdiVideoInputInfo");
status = from_vendor(GvfgStringifySdiVideoInputInfo(context_, &info, &text));
if (status != GVFG_OK)
return status;
out = {};
@@ -277,6 +298,7 @@ gvfg_status_t GigabyteCaptureSession::get_sdi_info(gvfg_sdi_info_t &out) const
out.level_b = info.LevelB ? 1 : 0;
out.st352_payload = info.St352Payload;
out.error_count = info.ErrorCount;
strncpy_s(out.signal_lock_name, text.VideoSignalLock, _TRUNCATE);
strncpy_s(out.mode_name, text.Mode, _TRUNCATE);
strncpy_s(out.resolution_name, text.Resol, _TRUNCATE);
strncpy_s(out.fps_name, text.Fps, _TRUNCATE);
@@ -293,9 +315,17 @@ gvfg_status_t GigabyteCaptureSession::get_audio_format(GigabyteAudioInfo &out) c
const gvfg_status_t openStatus = ensure_vendor_channel_open();
if (openStatus != GVFG_OK)
return openStatus;
bool refresh = false;
{
std::lock_guard<std::mutex> lock(state_mutex_);
refresh = !audio_info_valid_;
}
if (refresh)
{
const gvfg_status_t status = refresh_audio_info();
if (status != GVFG_OK)
return status;
}
std::lock_guard<std::mutex> lock(state_mutex_);
out = {};
out.sample_rate = audio_info_.SamplesPerSec;
@@ -309,11 +339,12 @@ gvfg_status_t GigabyteCaptureSession::refresh_audio_info() const
{
GVFG_AUDIO_INFO info{};
const gvfg_status_t status = from_vendor(
GvfgGetAudioInfo(context_, channel_, &info), "GvfgGetAudioInfo");
GvfgGetAudioInfo(context_, channel_, &info));
if (status != GVFG_OK)
return status;
std::lock_guard<std::mutex> lock(state_mutex_);
audio_info_ = info;
audio_info_valid_ = true;
return GVFG_OK;
}
@@ -333,9 +364,17 @@ gvfg_status_t GigabyteCaptureSession::configure_stream()
const gvfg_status_t openStatus = ensure_vendor_channel_open();
if (openStatus != GVFG_OK)
return openStatus;
const gvfg_status_t infoStatus = refresh_video_info();
if (infoStatus != GVFG_OK)
return infoStatus;
bool refresh = false;
{
std::lock_guard<std::mutex> lock(state_mutex_);
refresh = !video_info_valid_;
}
if (refresh)
{
const gvfg_status_t status = refresh_video_info();
if (status != GVFG_OK)
return status;
}
configured_ = true;
return GVFG_OK;
}
@@ -347,8 +386,11 @@ gvfg_status_t GigabyteCaptureSession::start_stream()
if (!configured_)
return reject(GVFG_ESTATE, "GigabyteLib stream has not been configured");
ResetEvent(stop_event_);
const gvfg_status_t status = from_vendor(
GvfgStartCapture(context_, channel_), "GvfgStartCapture");
ResetEvent(recovery_event_);
recovery_pending_ = false;
recovery_status_ = GVFG_OK;
std::lock_guard<std::mutex> captureLock(capture_mutex_);
const gvfg_status_t status = from_vendor(GvfgStartCapture(context_, channel_));
if (status != GVFG_OK)
return status;
{
@@ -363,22 +405,24 @@ gvfg_status_t GigabyteCaptureSession::start_stream()
gvfg_status_t GigabyteCaptureSession::stop_stream()
{
const bool wasRunning = running_.exchange(false);
recovery_pending_ = false;
recovery_status_ = GVFG_OK;
if (stop_event_)
SetEvent(stop_event_);
stop_event_monitoring();
if (recovery_event_)
SetEvent(recovery_event_);
gvfg_status_t result = GVFG_OK;
{
std::lock_guard<std::mutex> lock(state_mutex_);
if (frame_held_ && zero_copy_enabled_ && context_)
result = from_vendor(GvfgReleaseVideoFrameZeroCopy(context_, channel_),
"GvfgReleaseVideoFrameZeroCopy during stop");
frame_held_ = false;
}
recovery_cv_.notify_all();
stop_event_monitoring();
gvfg_status_t result = GVFG_OK;
if (wasRunning && channel_open_ && context_)
{
const gvfg_status_t stopStatus = from_vendor(
GvfgStopCapture(context_, channel_), "GvfgStopCapture");
std::lock_guard<std::mutex> captureLock(capture_mutex_);
const gvfg_status_t stopStatus = from_vendor(GvfgStopCapture(context_, channel_));
if (result == GVFG_OK)
result = stopStatus;
}
@@ -396,9 +440,10 @@ gvfg_status_t GigabyteCaptureSession::wait_frame(uint32_t timeoutMs, gvfg_frame_
return reject(GVFG_ESTATE, "GigabyteLib frame read rejected: previous frame is held");
}
std::array<HANDLE, 3> handles{stop_event_, events_.hVideoFrameInEvent, events_.hVideoExtraFrame};
const DWORD count = handles[2] ? 3u : 2u;
if (!handles[1])
std::array<HANDLE, 4> handles{stop_event_, recovery_event_,
events_.hVideoFrameInEvent, events_.hVideoExtraFrame};
const DWORD count = handles[3] ? 4u : 3u;
if (!handles[2])
return reject(GVFG_EIO, "GigabyteLib did not provide a video-frame event");
const DWORD waitMs = timeoutMs == UINT32_MAX ? INFINITE : timeoutMs;
const DWORD wait = WaitForMultipleObjects(count, handles.data(), FALSE, waitMs);
@@ -406,11 +451,16 @@ gvfg_status_t GigabyteCaptureSession::wait_frame(uint32_t timeoutMs, gvfg_frame_
return GVFG_ETIMEOUT;
if (wait == WAIT_OBJECT_0)
return GVFG_ESTATE;
if (wait != WAIT_OBJECT_0 + 1 && wait != WAIT_OBJECT_0 + 2)
if (wait == WAIT_OBJECT_0 + 1)
return wait_for_recovery(timeoutMs);
if (wait != WAIT_OBJECT_0 + 2 && wait != WAIT_OBJECT_0 + 3)
return reject(GVFG_EIO, "GigabyteLib video event wait failed");
{
std::lock_guard<std::mutex> lock(state_mutex_);
++video_event_wakes_;
if (wait == WAIT_OBJECT_0 + 2)
++video_dma_event_wakes_;
else
++extra_video_event_wakes_;
}
gvfg_signal_status_t signal{};
@@ -432,8 +482,10 @@ gvfg_status_t GigabyteCaptureSession::wait_frame(uint32_t timeoutMs, gvfg_frame_
{
void *buffer = nullptr;
const auto begin = std::chrono::steady_clock::now();
status = from_vendor(GvfgGetVideoFrameZeroCopy(context_, channel_, &buffer),
"GvfgGetVideoFrameZeroCopy");
{
std::lock_guard<std::mutex> captureLock(capture_mutex_);
status = from_vendor(GvfgGetVideoFrameZeroCopy(context_, channel_, &buffer));
}
const auto end = std::chrono::steady_clock::now();
record_get_frame_timing(std::chrono::duration<double, std::micro>(end - begin).count());
data = buffer;
@@ -443,9 +495,11 @@ gvfg_status_t GigabyteCaptureSession::wait_frame(uint32_t timeoutMs, gvfg_frame_
if (copy_buffer_.size() != bytes)
copy_buffer_.assign(bytes, 0);
const auto begin = std::chrono::steady_clock::now();
{
std::lock_guard<std::mutex> captureLock(capture_mutex_);
status = from_vendor(GvfgGetVideoFrame(context_, channel_, copy_buffer_.data(),
static_cast<ULONG>(copy_buffer_.size())),
"GvfgGetVideoFrame");
static_cast<ULONG>(copy_buffer_.size())));
}
const auto end = std::chrono::steady_clock::now();
record_get_frame_timing(std::chrono::duration<double, std::micro>(end - begin).count());
data = copy_buffer_.data();
@@ -471,18 +525,15 @@ gvfg_status_t GigabyteCaptureSession::wait_frame(uint32_t timeoutMs, gvfg_frame_
}
gvfg_status_t GigabyteCaptureSession::release_frame()
{
{
std::lock_guard<std::mutex> lock(state_mutex_);
if (!frame_held_)
return reject(GVFG_ESTATE, "GigabyteLib frame release rejected: no frame is held");
if (zero_copy_enabled_)
{
const gvfg_status_t status = from_vendor(
GvfgReleaseVideoFrameZeroCopy(context_, channel_), "GvfgReleaseVideoFrameZeroCopy");
if (status != GVFG_OK)
return status;
}
// Current GigabyteLib zero-copy contract requires no per-frame release call.
frame_held_ = false;
}
recovery_cv_.notify_all();
return GVFG_OK;
}
@@ -502,25 +553,31 @@ gvfg_status_t GigabyteCaptureSession::wait_audio(
if (!events_.hAudioFrameInEvent)
return reject(GVFG_EIO, "GigabyteLib did not provide an audio-frame event");
std::array<HANDLE, 3> handles{stop_event_, events_.hAudioFrameInEvent, events_.hAudioExtraFrame};
const DWORD count = handles[2] ? 3u : 2u;
std::array<HANDLE, 4> handles{stop_event_, recovery_event_,
events_.hAudioFrameInEvent, events_.hAudioExtraFrame};
const DWORD count = handles[3] ? 4u : 3u;
const DWORD waitMs = timeoutMs == UINT32_MAX ? INFINITE : timeoutMs;
const DWORD wait = WaitForMultipleObjects(count, handles.data(), FALSE, waitMs);
if (wait == WAIT_TIMEOUT)
return GVFG_ETIMEOUT;
if (wait == WAIT_OBJECT_0)
return GVFG_ESTATE;
if (wait != WAIT_OBJECT_0 + 1 && wait != WAIT_OBJECT_0 + 2)
if (wait == WAIT_OBJECT_0 + 1)
return wait_for_recovery(timeoutMs);
if (wait != WAIT_OBJECT_0 + 2 && wait != WAIT_OBJECT_0 + 3)
return reject(GVFG_EIO, "GigabyteLib audio event wait failed");
{
std::lock_guard<std::mutex> lock(state_mutex_);
if (wait == WAIT_OBJECT_0 + 1)
if (wait == WAIT_OBJECT_0 + 2)
++audio_event_wakes_;
else
++extra_audio_event_wakes_;
}
const gvfg_status_t status = from_vendor(
GvfgGetAudioFrame(context_, channel_, destination, frameBytes), "GvfgGetAudioFrame");
gvfg_status_t status = GVFG_OK;
{
std::lock_guard<std::mutex> captureLock(capture_mutex_);
status = from_vendor(GvfgGetAudioFrame(context_, channel_, destination, frameBytes));
}
if (status != GVFG_OK)
return status;
outBytes = frameBytes;
@@ -576,15 +633,20 @@ void GigabyteCaptureSession::event_thread_proc()
return;
if (kind == 1)
{
emit_event(GVFG_EVENT_FORMAT_CHANGE_BEGIN);
refresh_video_info();
emit_event(GVFG_EVENT_STREAM_READY);
emit_event(GVFG_EVENT_VIDEO_FORMAT_CHANGED);
}
else if (kind == 2)
{
refresh_video_info();
emit_event(GVFG_EVENT_SIGNAL_CONNECTED);
emit_event(GVFG_EVENT_STREAM_READY);
if (running_)
{
recovery_status_ = GVFG_OK;
recovery_pending_ = true;
SetEvent(recovery_event_);
recover_stream_after_plugin();
}
emit_event(GVFG_EVENT_VIDEO_INPUT_PLUGIN);
}
else if (kind == 3)
{
@@ -592,8 +654,9 @@ void GigabyteCaptureSession::event_thread_proc()
std::lock_guard<std::mutex> lock(state_mutex_);
cached_signal_ = {};
cached_signal_.channel = channel_;
video_info_valid_ = false;
}
emit_event(GVFG_EVENT_SIGNAL_DISCONNECTED);
emit_event(GVFG_EVENT_VIDEO_INPUT_UNPLUG);
}
}
}
@@ -608,7 +671,8 @@ void GigabyteCaptureSession::emit_event(gvfg_event_type_t type) const
void GigabyteCaptureSession::fill_debug_stats(gvfg_debug_backend_stats_t &out) const
{
std::lock_guard<std::mutex> lock(state_mutex_);
out.video_event_wakes = video_event_wakes_;
out.video_dma_event_wakes = video_dma_event_wakes_;
out.extra_video_event_wakes = extra_video_event_wakes_;
out.video_frames_from_lib = video_frames_from_lib_;
out.audio_dma_event_wakes = audio_event_wakes_;
out.extra_audio_event_wakes = extra_audio_event_wakes_;
@@ -642,25 +706,56 @@ gvfg_status_t GigabyteCaptureSession::debug_write_register(uint32_t offset, uint
return GVFG_OK;
}
gvfg_status_t GigabyteCaptureSession::from_vendor(GVFG_HRESULT result, const char *operation) const
gvfg_status_t GigabyteCaptureSession::from_vendor(GVFG_HRESULT result)
{
if (result == GVFG_HRESULT_OK)
return static_cast<gvfg_status_t>(result);
}
gvfg_status_t GigabyteCaptureSession::recover_stream_after_plugin()
{
{
std::unique_lock<std::mutex> stateLock(state_mutex_);
recovery_cv_.wait(stateLock, [this]() { return !frame_held_ || !running_; });
}
std::lock_guard<std::mutex> captureLock(capture_mutex_);
if (!recovery_pending_)
{
ResetEvent(recovery_event_);
return GVFG_OK;
gvfg_status_t status = GVFG_EIO;
if (result == GVFG_HRESULT_DEV_BUSY || result == GVFG_HRESULT_CONTEXT_ERROR)
status = GVFG_ESTATE;
else if (result == GVFG_HRESULT_VIDEO_CHN_INVALID)
status = GVFG_EINVAL;
else if (result == GVFG_HRESULT_DEV_ERROR)
status = GVFG_ENODEV;
std::ostringstream stream;
stream << (operation ? operation : "GigabyteLib")
<< " failed with GVFG_HRESULT 0x" << std::hex << std::uppercase
<< static_cast<unsigned int>(result);
error_state_.set(stream.str());
}
if (!running_)
{
recovery_pending_ = false;
ResetEvent(recovery_event_);
recovery_cv_.notify_all();
return GVFG_OK;
}
gvfg_status_t status = from_vendor(GvfgStopCapture(context_, channel_));
if (status == GVFG_OK)
status = from_vendor(GvfgStartCapture(context_, channel_));
recovery_status_ = status;
recovery_pending_ = false;
ResetEvent(recovery_event_);
recovery_cv_.notify_all();
return status;
}
gvfg_status_t GigabyteCaptureSession::wait_for_recovery(uint32_t timeoutMs)
{
std::unique_lock<std::mutex> lock(state_mutex_);
const auto complete = [this]() { return !recovery_pending_ || !running_; };
if (timeoutMs == UINT32_MAX)
recovery_cv_.wait(lock, complete);
else if (!recovery_cv_.wait_for(lock, std::chrono::milliseconds(timeoutMs), complete))
return GVFG_ETIMEOUT;
if (!running_)
return GVFG_ESTATE;
const gvfg_status_t status = recovery_status_.load();
return status == GVFG_OK ? GVFG_ETIMEOUT : status;
}
gvfg_status_t GigabyteCaptureSession::reject(gvfg_status_t status, const char *message) const
{
error_state_.set(message ? message : "GigabyteLib operation rejected");
@@ -9,6 +9,7 @@
#include <windows.h>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <mutex>
@@ -69,9 +70,11 @@ namespace gvfg::internal
void stop_event_monitoring();
void event_thread_proc();
void emit_event(gvfg_event_type_t type) const;
gvfg_status_t recover_stream_after_plugin();
gvfg_status_t wait_for_recovery(uint32_t timeoutMs);
gvfg_status_t refresh_video_info() const;
gvfg_status_t refresh_audio_info() const;
gvfg_status_t from_vendor(GVFG_HRESULT result, const char *operation) const;
static gvfg_status_t from_vendor(GVFG_HRESULT result);
gvfg_status_t reject(gvfg_status_t status, const char *message) const;
void record_get_frame_timing(double elapsedUs);
@@ -81,8 +84,11 @@ namespace gvfg::internal
mutable PGVFG_CONTEXT context_ = nullptr;
mutable GVFG_VIDEO_CHN_EVENT events_{};
mutable HANDLE stop_event_ = nullptr;
mutable HANDLE recovery_event_ = nullptr;
mutable bool events_created_ = false;
mutable bool channel_open_ = false;
mutable bool video_info_valid_ = false;
mutable bool audio_info_valid_ = false;
mutable gvfg_signal_status_t cached_signal_{};
mutable GVFG_VIDEO_INFO video_info_{};
mutable GVFG_AUDIO_INFO audio_info_{};
@@ -91,17 +97,22 @@ namespace gvfg::internal
bool zero_copy_enabled_ = false;
bool audio_enabled_ = false;
std::atomic<bool> running_{false};
std::atomic<bool> recovery_pending_{false};
std::atomic<gvfg_status_t> recovery_status_{GVFG_OK};
std::atomic<bool> monitoring_{false};
std::thread event_thread_;
mutable std::mutex callback_mutex_;
GigabyteEventCallback event_callback_ = nullptr;
void *event_callback_user_ = nullptr;
mutable std::mutex state_mutex_;
std::condition_variable recovery_cv_;
mutable std::mutex capture_mutex_;
std::vector<uint8_t> copy_buffer_;
bool frame_held_ = false;
uint64_t video_frames_from_lib_ = 0;
uint64_t audio_frames_from_lib_ = 0;
uint64_t video_event_wakes_ = 0;
uint64_t video_dma_event_wakes_ = 0;
uint64_t extra_video_event_wakes_ = 0;
uint64_t audio_event_wakes_ = 0;
uint64_t extra_audio_event_wakes_ = 0;
uint64_t get_frame_timing_samples_ = 0;
+18 -21
View File
@@ -435,21 +435,8 @@ struct gvfg_channel_session_t
if (!frameHeld)
return reject(GVFG_ESTATE, "gvfg_release_channel_frame rejected: no frame is currently held");
int expectedStride = 0;
if (native_row_stride_bytes(heldSessionFrame.width,
heldSessionFrame.pixel_format,
expectedStride) != GVFG_OK)
return reject(GVFG_ESTATE, "gvfg_release_channel_frame rejected: held frame has an invalid row stride");
if (frameToken.data != heldSessionFrame.data ||
frameToken.data_size != static_cast<uint64_t>(heldSessionFrame.data_size) ||
frameToken.width != static_cast<int>(heldSessionFrame.width) ||
frameToken.height != static_cast<int>(heldSessionFrame.height) ||
frameToken.row_stride_bytes != expectedStride ||
frameToken.pixel_format != heldSessionFrame.pixel_format ||
frameToken.bit_depth != static_cast<int>(heldSessionFrame.bit_depth) ||
frameToken.frame_id != heldSessionFrame.frame_id ||
frameToken.timestamp_ns != heldSessionFrame.timestamp_ns)
frameToken.frame_id != heldSessionFrame.frame_id)
return reject(GVFG_EINVAL, "gvfg_release_channel_frame rejected: frame token does not match the held frame");
const gvfg_status_t st = session->release_frame();
@@ -656,11 +643,7 @@ struct gvfg_channel_session_t
std::lock_guard<std::mutex> lock(audioMutex);
if (!audioFrameHeld)
return reject(GVFG_ESTATE, "gvfg_release_channel_audio_frame rejected: no audio frame is currently held");
if (token.data != heldAudioFrame.data || token.data_size != heldAudioFrame.data_size ||
token.sample_rate != heldAudioFrame.sample_rate || token.channels != heldAudioFrame.channels ||
token.bits_per_sample != heldAudioFrame.bits_per_sample ||
token.reserved != heldAudioFrame.reserved || token.frame_id != heldAudioFrame.frame_id ||
token.timestamp_ns != heldAudioFrame.timestamp_ns)
if (token.data != heldAudioFrame.data || token.frame_id != heldAudioFrame.frame_id)
return reject(GVFG_EINVAL, "gvfg_release_channel_audio_frame rejected: frame token does not match the held audio frame");
heldAudioFrame = {};
audioFrameHeld = false;
@@ -1249,12 +1232,26 @@ extern "C"
return "Not supported";
case GVFG_ETIMEOUT:
return "Timeout";
case GVFG_HRESULT_ERROR:
return "GVFG_HRESULT_ERROR";
case GVFG_HRESULT_DEV_ERROR:
return "GVFG_HRESULT_DEV_ERROR";
case GVFG_HRESULT_DEV_BUSY:
return "GVFG_HRESULT_DEV_BUSY";
case GVFG_HRESULT_VIDEO_CHN_ERROR:
return "GVFG_HRESULT_VIDEO_CHN_ERROR";
case GVFG_HRESULT_CONTEXT_ERROR:
return "GVFG_HRESULT_CONTEXT_ERROR";
case GVFG_HRESULT_VIDEO_CHN_INVALID:
return "GVFG_HRESULT_VIDEO_CHN_INVALID";
case GVFG_HRESULT_API_ERROR:
return "GVFG_HRESULT_API_ERROR";
default:
return "Unknown";
return status > 0 ? "GVFG_HRESULT_UNKNOWN" : "Unknown";
}
}
gvfg_status_t gvfg_get_channel_last_error_detail(gvfg_handle handle,
gvfg_status_t gvfg_get_channel_last_sdk_error_detail(gvfg_handle handle,
int channel_index,
char *out_message,
uint32_t out_message_size)
+4 -14
View File
@@ -91,20 +91,10 @@ gvfg_set_channel_zero_copy_enabled(handle, GVFG_CHANNEL_0, 1);
gvfg_open_channel(handle, device_index, GVFG_CHANNEL_0);
```
每個 channel 可在 open 前選擇要註冊/接收的事件:
```c
uint32_t events = GVFG_EVENT_MASK_SIGNAL_CONNECTED |
GVFG_EVENT_MASK_SIGNAL_DISCONNECTED |
GVFG_EVENT_MASK_FORMAT_CHANGE_BEGIN;
gvfg_set_channel_event_mask(handle, GVFG_CHANNEL_0, events);
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,不應在已知無訊號時持續
SDK 直接使用 GigabyteLib 建立的 video frame、format changed、input plug-in 與
input unplug events;audio 開啟時才使用 audio frame events。Application 收到
`GVFG_EVENT_VIDEO_INPUT_UNPLUG` 後應暫停 video/audio read,等待
`GVFG_EVENT_VIDEO_INPUT_PLUGIN` 或 stop 再喚醒 worker,不應在已知無訊號時持續
輪詢 timeout。
每個成功取得的 video/audio frame 都包含 `timestamp_ns`。兩者使用相同的
+1 -1
View File
@@ -59,7 +59,7 @@
<mxCell id="ring" parent="1" style="rounded=1;whiteSpace=wrap;html=1;arcSize=8;fillColor=#ffffff;strokeColor=#d6b656;fontSize=14;" value="one outstanding frame per channel&lt;br&gt;copy_buffer_ or driver pointer&lt;br&gt;read / held / release" vertex="1">
<mxGeometry height="58" width="270" x="880" y="610" as="geometry" />
</mxCell>
<mxCell id="eventFlow" parent="1" style="rounded=1;whiteSpace=wrap;html=1;arcSize=8;fillColor=#ffffff;strokeColor=#d6b656;fontSize=13;" value="Public event flow&lt;br&gt;driver format IRQ -&gt; FORMAT_CHANGE_BEGIN&lt;br&gt;first new frame published -&gt; STREAM_READY" vertex="1">
<mxCell id="eventFlow" parent="1" style="rounded=1;whiteSpace=wrap;html=1;arcSize=8;fillColor=#ffffff;strokeColor=#d6b656;fontSize=13;" value="Public event flow&lt;br&gt;hVideoFormatChangedEvent -&gt; VIDEO_FORMAT_CHANGED&lt;br&gt;hVideoInputPluginEvent / hVideoInputUnplugEvent -&gt; matching public event" vertex="1">
<mxGeometry height="82" width="330" x="850" y="690" as="geometry" />
</mxCell>
<mxCell id="externalBoundary" parent="1" style="rounded=1;whiteSpace=wrap;html=1;arcSize=8;fillColor=#f5f5f5;strokeColor=#666666;dashed=1;fontColor=#333333;fontSize=14;" value="vfg100.sys / FPGA / DMA frame and events" vertex="1">
+20 -16
View File
@@ -104,7 +104,7 @@ int main(void)
保存,必須先複製。
- 每個 channel 同時最多持有一個 frame。尚未 release 又對同一 channel 呼叫
`gvfg_read_channel_frame()`,會回傳 `GVFG_ESTATE`。
- release 時必須傳回原本的完整 `gvfg_frame_t`,不可修改欄位。
- release 時傳回 read 取得的 `gvfg_frame_t`;SDK 以 `data + frame_id` 確認目前 held frame。
- `gvfg_stop()` 會中止等待並使尚未 release 的 frame 失效。
- 同一個 handle 的 lifecycle 操作應由應用程式自行序列化;不要同時 open、
start、stop 或 destroy。
@@ -116,7 +116,7 @@ Audio 採用相同的 pull 與 ownership 模型:
`gvfg_release_channel_audio_frame()` 前有效。
- 同一 channel 同時只能持有一個 audio frame;未 release 再 read 會回傳
`GVFG_ESTATE`。
- release 必須傳回未修改的完整 `gvfg_audio_frame_t` token。
- release 時傳回 read 取得的 `gvfg_audio_frame_t`;SDK 以 `data + frame_id` 確認目前 held frame。
- 若播放或錄音需要在 release 後繼續使用 PCM,Application 必須先複製。
- SDK 只保有單一交付 buffer,不建立 audio ring;播放排程與 buffering 屬於
Application/Qt/WASAPI。
@@ -136,16 +136,21 @@ Audio 採用相同的 pull 與 ownership 模型:
| `GVFG_EINVAL` | 參數、channel 或 frame token 無效 |
| `GVFG_ENODEV` | 找不到裝置或裝置無法開啟 |
| `GVFG_ESTATE` | 呼叫時機或 handle 狀態不正確 |
| `GVFG_EIO` | driver/backend I/O 失敗 |
| `GVFG_EIO` | SDK 自身 I/O、GPU 或 internal extension 失敗 |
| `GVFG_ENOTSUP` | 格式或功能不支援 |
| `GVFG_ETIMEOUT` | 等待逾時 |
GigabyteLib 呼叫失敗時,SDK 不重新分類;原始正數 `GVFG_HRESULT` 直接回傳給
Application。負數只代表 SDK 自己檢查出的錯誤。所有結果都應使用
`status != GVFG_OK` 判斷,不可套用 Windows `FAILED()`/`SUCCEEDED()`。
可用 `gvfg_strerror()` 取得靜態英文說明字串;呼叫端不可釋放該字串。
可用 `gvfg_get_version()` 查詢目前實際載入的 `gvfg.dll` 版本。回傳值為
靜態字串,例如 `"0.3.0"`,呼叫端不可釋放。
靜態字串,例如 `"1.0.0"`,呼叫端不可釋放。
需要記錄最近一次失敗的詳細原因時,可在 API 失敗後立即呼叫
`gvfg_get_channel_last_error_detail()`;driver/register 等內部診斷仍保留在 debug API。
`gvfg_get_channel_last_sdk_error_detail()`;只保存負數 SDK error 的細節,正數 GigabyteLib
result 原樣回傳且不寫入此狀態。driver/register 等內部診斷仍保留在 debug API。
## 5. 資料格式
@@ -206,10 +211,10 @@ audio API 不是 zero-copy,但上層仍使用和 video 相同的 read/release
- `gvfg_stop(handle)`:停止擷取;重複呼叫仍回傳成功。
- `gvfg_destroy(handle)`:必要時先停止,再銷毀 handle。銷毀後不得再使用。
Zero-copy mode 的 driver lifecycle 由 SDK 管理:open 時 enable,每次成功
`gvfg_read_channel_frame()` 後由 `gvfg_release_channel_frame()` 歸還 driver frame,destroy/close
前 disable。Device open 後不可直接切換;應 destroy session、重新 create、設定模式
後再 open。
Zero-copy mode 的 driver lifecycle 由 SDK 管理:open 時 enable,destroy/close 前 disable。
每次成功 `gvfg_read_channel_frame()` 後仍須呼叫 `gvfg_release_channel_frame()`,用來結束
公開 pointer/token lifetime;依目前 Lib 契約不送逐 frame driver release。Device open 後
不可直接切換;應 destroy session、重新 create、設定模式後再 open。
### Frame
@@ -246,10 +251,9 @@ Zero-copy mode 的 driver lifecycle 由 SDK 管理:open 時 enable,每次成
| Event | 應用程式動作 |
| -------------------------------- | --------------------------- |
| `GVFG_EVENT_SIGNAL_CONNECTED` | 訊號已接上;等待 stream ready/frame |
| `GVFG_EVENT_SIGNAL_DISCONNECTED` | 停止使用目前影像內容 |
| `GVFG_EVENT_FORMAT_CHANGE_BEGIN` | 暫停使用依賴舊尺寸/格式的資源 |
| `GVFG_EVENT_STREAM_READY` | 第一個完整 frame 已就緒,可依新格式重建資源 |
| `GVFG_EVENT_VIDEO_FORMAT_CHANGED` | Lib 的 video format changed event |
| `GVFG_EVENT_VIDEO_INPUT_PLUGIN` | Lib 的 video input plug-in event |
| `GVFG_EVENT_VIDEO_INPUT_UNPLUG` | Lib 的 video input unplug event |
呼叫前應將 `gvfg_event_t` 清零並設定 `struct_size = sizeof(gvfg_event_t)`。
事件是狀態通知,不取代 `gvfg_get_channel_signal_status()`;需要完整 metadata 時應重新查詢。
@@ -297,12 +301,12 @@ DXGI 成功接受的 Present;swapchain busy 而略過者記在 `skipped_presen
## 9. 錯誤處理建議
- `GVFG_ETIMEOUT`:連線期間通常可重試,並檢查 signal status/event。收到
`GVFG_EVENT_SIGNAL_DISCONNECTED` 後,不應高速輪詢 read API;應等待
`GVFG_EVENT_SIGNAL_CONNECTED`(或 application stop)再恢復 video/audio read。
`GVFG_EVENT_VIDEO_INPUT_UNPLUG` 後,不應高速輪詢 read API;應等待
`GVFG_EVENT_VIDEO_INPUT_PLUGIN`(或 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_EVENT_VIDEO_FORMAT_CHANGED`:依 Lib 更新後的 video info 重建格式相關資源。
- `GVFG_ESTATE`:檢查 lifecycle、是否重複 read、或是否已 stop。
- `GVFG_EIO`/`GVFG_ENODEV`:停止 session,記錄 `gvfg_strerror()`,再由應用程式
決定是否重新列舉與開啟。
+24 -17
View File
@@ -21,7 +21,8 @@ register 與 DMA 實作不屬於本文件。
### 1.2 `gvfg_status_t`
所有回傳 `gvfg_status_t` 的函式都使用以下狀態碼:
`gvfg_status_t` 是 32-bit 整數。`0` 表示成功,負數是 SDK 自己產生的錯誤;
GigabyteLib API 失敗時,正數回傳值是未修改的原始 `GVFG_HRESULT`。
| 成員 | 值 | 說明 |
| --------------- | ---:| ---------------------------------------------- |
@@ -29,10 +30,14 @@ register 與 DMA 實作不屬於本文件。
| `GVFG_EINVAL` | -1 | NULL pointer、無效 channel、buffer 大小或 token 等參數錯誤 |
| `GVFG_ENODEV` | -2 | 找不到裝置或裝置無法開啟 |
| `GVFG_ESTATE` | -3 | 呼叫順序或目前 session 狀態不允許此操作 |
| `GVFG_EIO` | -4 | Driver、backend 或 GPU I/O 失敗 |
| `GVFG_EIO` | -4 | SDK 自身 I/O、GPU 或 internal extension 失敗 |
| `GVFG_ENOTSUP` | -5 | 不支援指定功能或格式 |
| `GVFG_ETIMEOUT` | -6 | 在期限內等不到 frame、event 或 backend 工作 |
正數不可用 Windows `FAILED()`/`SUCCEEDED()` 判斷;統一以 `status != GVFG_OK`
判斷失敗。`gvfg_strerror()` 會直接回傳對應的 GigabyteLib enum 名稱,例如
`GVFG_HRESULT_DEV_BUSY`;未知正數顯示 `GVFG_HRESULT_UNKNOWN`。
### 1.3 `gvfg_pixel_format_t`
| 成員 | 值 | 說明 |
@@ -83,7 +88,7 @@ UI 應優先顯示 `gvfg_sdi_info_t` 的對應 `*_name`;程式邏輯則比較
### 1.5b `gvfg_sdi_info_t`
由 `gvfg_get_channel_sdi_info()` 填入。數值欄位直接來自
`GVFG_SDI_VIDEO_INFO`;`mode_name`、`resolution_name`、`fps_name`、`scan_name`
`GVFG_SDI_VIDEO_INFO`;`signal_lock_name`、`mode_name`、`resolution_name`、`fps_name`、`scan_name`
以及 `st352_format_name`、`st352_fps_name`、`st352_chroma_name`、
`st352_bit_depth_name` 直接來自 `GvfgStringifySdiVideoInputInfo()`。
@@ -115,7 +120,7 @@ timing 屬於內部診斷資訊,不放入客戶 runtime 結構。
### 1.8 `gvfg_frame_t`
由 `gvfg_read_channel_frame()` 填入,也是稍後傳給 `gvfg_release_channel_frame()` 的完整 token。
由 `gvfg_read_channel_frame()` 填入,也是稍後傳給 `gvfg_release_channel_frame()` 的 frame descriptor。
| 欄位 | 型別 | 說明 |
| ------------------ | -------------- | -------------------------------------------- |
@@ -129,7 +134,7 @@ timing 屬於內部診斷資訊,不放入客戶 runtime 結構。
| `frame_id` | `uint64_t` | SDK 成功交付序號;每次 channel Start 從 1 重新開始 |
| `timestamp_ns` | `uint64_t` | SDK 交付時間;與 audio 共用 monotonic clock,單位 ns |
Caller 不得修改任何欄位再 release。SDK 會將完整 token 與目前 held frame 比對。
Caller 應把 read 取得的 descriptor 傳回 release;SDK 以 `data + frame_id` 確認目前 held frame。
### 1.8a `gvfg_audio_format_t`
@@ -148,7 +153,7 @@ Driver 一次傳回多少 bytes、buffer capacity 與 block alignment 均由 SDK
### 1.8b `gvfg_audio_frame_t`
由 `gvfg_read_channel_audio_frame()` 填入,也是稍後傳給
`gvfg_release_channel_audio_frame()` 的完整 token。
`gvfg_release_channel_audio_frame()` 的 audio frame descriptor。
| 欄位 | 型別 | 說明 |
| --- | --- | --- |
@@ -160,8 +165,8 @@ Driver 一次傳回多少 bytes、buffer capacity 與 block alignment 均由 SDK
| `frame_id` | `uint64_t` | SDK 成功交付序號;每次 channel Start 從 1 重新開始 |
| `timestamp_ns` | `uint64_t` | SDK 交付時間;與 video 共用 monotonic clock,單位 ns |
與 video 相同,每個 channel 同時只能持有一個 audio frame,且 caller 不得修改
descriptor 後再 release。
與 video 相同,每個 channel 同時只能持有一個 audio frame;release 以
`data + frame_id` 確認目前 held frame。
Video/audio 的 `timestamp_ns` 可在同一 process/session 內直接比較。它代表 SDK
delivery timing,不是 driver 或硬體 capture timestamp。
@@ -190,10 +195,9 @@ delivery timing,不是 driver 或硬體 capture timestamp。
| 成員 | 值 | 說明 |
| -------------------------------- | ---:| ----------------------------- |
| `GVFG_EVENT_UNKNOWN` | 0 | 未知事件;正常流程不應依賴此值 |
| `GVFG_EVENT_SIGNAL_CONNECTED` | 1 | 指定 channel 偵測到輸入訊號 |
| `GVFG_EVENT_SIGNAL_DISCONNECTED` | 2 | 輸入訊號中斷 |
| `GVFG_EVENT_STREAM_READY` | 3 | 啟動、重新接線或格式恢復後,第一個完整 frame 已就緒 |
| `GVFG_EVENT_FORMAT_CHANGE_BEGIN` | 4 | 輸入格式正在改變,應暫停使用舊格式資源 |
| `GVFG_EVENT_VIDEO_FORMAT_CHANGED` | 1 | Lib 的 video format changed event |
| `GVFG_EVENT_VIDEO_INPUT_PLUGIN` | 2 | Lib 的 video input plug-in event |
| `GVFG_EVENT_VIDEO_INPUT_UNPLUG` | 3 | Lib 的 video input unplug event |
`gvfg_event_t` 是 `gvfg_poll_channel_event()` 的輸出。呼叫前將結構清零並把
`struct_size` 設為 `sizeof(gvfg_event_t)`。`type` 是上述事件型別。
@@ -331,7 +335,7 @@ gvfg_status_t gvfg_start_channel(gvfg_handle handle, int channel_index);
- `GVFG_OK`:開始擷取、已經 running,或無訊號但成功進入訊號監看模式。
- `GVFG_EINVAL`:handle 為 NULL。
- `GVFG_ESTATE`:尚未 open 裝置。
- 也可能回傳 backend 的 `GVFG_EIO`、`GVFG_ENOTSUP` 等錯誤。
- GigabyteLib 失敗時回傳原始正數 `GVFG_HRESULT`。
### 1.21 `gvfg_read_channel_frame`
@@ -349,7 +353,7 @@ gvfg_status_t gvfg_read_channel_frame(gvfg_handle handle,
- `GVFG_EINVAL`:handle 或 output pointer 為 NULL。
- `GVFG_ESTATE`:未 running、已有 held frame、已有另一個 read,或等待時被 stop。
- `GVFG_ETIMEOUT`:期限內沒有 frame。
- `GVFG_EIO`/`GVFG_ENOTSUP`:frame/backend 無效或格式不支援。
- 正數:GigabyteLib 原始 `GVFG_HRESULT`;`GVFG_ENOTSUP` 表示 SDK 不支援該格式。
Copy mode 回傳 SDK 的單一 frame buffer;zero-copy mode 回傳 driver-owned buffer。兩者的
pointer 都只保證有效到對應的 `gvfg_release_channel_frame()`。
@@ -507,7 +511,7 @@ gvfg_status_t gvfg_get_channel_runtime_info(
const char *gvfg_get_version(void);
```
- 回傳目前實際載入的 GVFG runtime DLL 版本,例如 `"0.3.0"`。
- 回傳目前實際載入的 GVFG runtime DLL 版本,例如 `"1.0.0"`。
- 回傳值是靜態 null-terminated 字串,caller 不可 free。
- 可用於 log、問題回報,以及確認 header、LIB、DLL 是否來自同一版本。
@@ -530,15 +534,18 @@ const char *gvfg_strerror(gvfg_status_t status);
- 回傳:靜態、null-terminated 英文說明字串;未知值回傳 unknown 類型說明。
Caller 不可 free。
### 1.35 `gvfg_get_channel_last_error_detail`
### 1.35 `gvfg_get_channel_last_sdk_error_detail`
```c
gvfg_status_t gvfg_get_channel_last_error_detail(gvfg_handle handle,
gvfg_status_t gvfg_get_channel_last_sdk_error_detail(gvfg_handle handle,
int channel_index,
char *out_message,
uint32_t out_message_size);
```
只供負數 `GVFG_E*` 使用。正數 GigabyteLib result 原樣回傳,不會產生或覆寫
SDK error detail。
- 複製指定 channel 最近一次 fault 或被拒絕操作的 UTF-8 詳細說明;即使該 channel open 失敗仍可查詢。
- `gvfg_read_channel_frame()`/`gvfg_poll_channel_event()` 的 timeout、non-blocking 無資料,
以及正常 stop 喚醒 waiter 都不會覆寫此內容。
+21 -26
View File
@@ -1,12 +1,13 @@
# GVFG SDK 錯誤處理架構
本文說明目前 SDK 如何產生、傳遞與保存錯誤。重點不是只看回傳碼,而是同時保留「錯誤分類」與「實際失敗位置」。
本文說明目前 SDK 如何產生、傳遞與保存錯誤。SDK 自身錯誤使用負數;
GigabyteLib 的正數 `GVFG_HRESULT` 不轉換、不重新分類。
## 1. 三層錯誤資訊
```text
公開 gvfg_status_t
用來讓 application 判斷錯誤類別
0 成功;負數為 SDK 錯誤;正數為原始 GigabyteLib GVFG_HRESULT
ChannelErrorState 詳細字串
用來指出哪個操作被拒絕,或哪個 Win32/driver 呼叫真正失敗
@@ -32,11 +33,12 @@ Win32 GetLastError()
| `GVFG_EINVAL` | 參數錯誤 | null pointer、錯誤 channel、frame token 不符 |
| `GVFG_ENODEV` | 找不到裝置 | device index 不存在 |
| `GVFG_ESTATE` | 呼叫時機或狀態錯誤 | 尚未 open、尚未 start、上一張 frame 未 release |
| `GVFG_EIO` | backend/driver/OS I/O 失敗 | event、register、IOCTL 失敗 |
| `GVFG_EIO` | SDK 自身 I/O 失敗 | GPU、register extension 或 SDK 內部資料錯誤 |
| `GVFG_ENOTSUP` | 不支援 | pixel format 或功能不支援 |
| `GVFG_ETIMEOUT` | 等待超時 | deadline 前沒有 frame/event |
`gvfg_strerror(status)` 只回傳固定分類文字,例如 `"I/O error"`。它不包含實際 Win32 error 或失敗函式。
`gvfg_strerror(status)` 對 SDK 負數回傳固定分類文字;對 Lib 正數回傳對應的
enum 名稱。只有 SDK 負數錯誤會另外保存 channel detail。
## 3. 每條 channel 的 `ChannelErrorState`
@@ -155,21 +157,17 @@ return fail(GIGABYTE_EIO, "wait DMA event", err);
2. 透過 error diagnostic log 輸出。
3. 回傳 backend status。
## 6. Backend status 如何轉成公開 status
## 6. GigabyteLib result 如何回到公開 API
backend 使用 `gigabyte_status_t`,facade 透過 `map_status()` 轉成 `gvfg_status_t`:
SDK 不推測或重分類主管 library 的錯誤:
```text
GIGABYTE_OK -> GVFG_OK
GIGABYTE_EINVAL -> GVFG_EINVAL
GIGABYTE_ENODEV -> GVFG_ENODEV
GIGABYTE_ESTATE -> GVFG_ESTATE
GIGABYTE_ENOTSUP -> GVFG_ENOTSUP
GIGABYTE_ETIMEOUT -> GVFG_ETIMEOUT
GIGABYTE_EIO -> GVFG_EIO
GVFG_HRESULT_OK -> GVFG_OK
其他 GVFG_HRESULT -> 原始正數不修改,直接回傳
```
轉換只改錯誤分類,不應覆蓋 backend 已寫入的詳細訊息。
負數 `GVFG_E*` 只用於 SDK 自身的參數、lifecycle、timeout、GPU 或 extension
錯誤,detail 保存 SDK 判定的具體原因。Lib API 的正數結果不會產生或覆寫 detail。
## 7. Application 正確取得錯誤的方式
@@ -177,10 +175,10 @@ GIGABYTE_EIO -> GVFG_EIO
const gvfg_status_t status =
gvfg_read_channel_frame(handle, channel, &frame, 1000);
if (status != GVFG_OK && status != GVFG_ETIMEOUT)
if (status < 0 && status != GVFG_ETIMEOUT)
{
char detail[512] = {};
gvfg_get_channel_last_error_detail(
gvfg_get_channel_last_sdk_error_detail(
handle,
channel,
detail,
@@ -202,8 +200,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 |
| 已確認 unplug 後 release 回 `ERROR_BAD_COMMAND (22)` | 清除相符 held state | driver 已撤銷該 ownership;保留 token 會阻塞 unplug/replug lifecycle |
| zero-copy 正確 token release | 清除 held state | 只結束 SDK pointer lifetime,不送 Lib/driver release |
| stop 時仍持有 zero-copy token | 清除 held state | driver/Lib 不要求逐 frame release,stop 負責結束 capture lifecycle |
## 9. Transient retry 規則
@@ -236,19 +234,16 @@ transient error
```text
facade running = false
-> 嘗試 release facade held frame
-> 清除 facade held frame
-> backend stop_stream()
-> 停 DMA/喚醒 wait
-> 等 read 結束
-> release backend pending zero-copy frame
-> 清除 backend pending zero-copy token
-> 停 event monitoring/thread
```
一般 zero-copy release 失敗時,backend 不應假裝已經釋放;錯誤必須回傳並保留
足以重試的狀態。若已確認 signal disconnected,且 release 回
`ERROR_BAD_COMMAND (22)`,則表示 driver 已在拔線流程撤銷 ownership;backend 會
清除相符的本地 held state 並完成 release,避免 event-monitor thread 永久等待。
這個例外不可套用到 connected 狀態或其他錯誤碼。
依目前 driver/Lib 契約,zero-copy 公開 release 不送底層 release command。Token 驗證
仍由 SDK 執行;錯誤 token 不清除 held state,正確 token 或 stop 才結束 SDK lifetime。
正常 `stop()` 為了結束 blocking read/event poll 而喚醒 waiter 時,只回傳 `GVFG_ESTATE`,不寫入
永久錯誤;application 應以自己的 stop flag 判斷這是不是預期的結束流程。
@@ -258,7 +253,7 @@ facade running = false
遇到錯誤時依序記錄:
1. 公開 API 名稱與 `gvfg_status_t`。
2. `gvfg_get_channel_last_error_detail()`。
2. 負數 SDK error 再呼叫 `gvfg_get_channel_last_sdk_error_detail()`;正數 Lib result 不需要。
3. channel index、copy/zero-copy mode、解析度與格式。
4. 是否有成功 read 但尚未 release 的 frame。
5. 是否正在 stop、拔插或 format change。
+24 -29
View File
@@ -26,7 +26,7 @@ flowchart LR
CH -->|gvfg_frame_t| APP
APP -->|release_channel_frame| CH
CH --> BE
BE -->|GvfgReleaseVideoFrameZeroCopy| IO
BE -->|clear SDK held token| CH
```
`GvfgSdk.lib` 是主管提供的靜態 library。GVFG adapter 保留公開 API 的
@@ -52,7 +52,7 @@ frame ownership 與 timeout 契約,不再直接操作 driver IOCTL 或 FPGA re
| `running` | `atomic<bool>` | facade 是否允許 read |
| `readInProgress` | `frameMutex` | 是否已有一個 caller 正在 blocking read |
| `frameHeld` | `frameMutex` | 是否已有成功 frame 尚未 release |
| `heldBackendFrame` | `frameMutex` | release 時要交還 backend 的完整 token |
| `heldSessionFrame` | `frameMutex` | 目前交付給 caller 的 frame 身分與 metadata |
| `eventQueue` | `eventMutex` | facade 待 application poll 的 event queue |
| signal 欄位 | `stateMutex` | width/height/format/connected cache |
| delivered/FPS 欄位 | atomic | UI/debug runtime 統計 |
@@ -70,7 +70,6 @@ frame ownership 與 timeout 契約,不再直接操作 driver IOCTL 或 FPGA re
| `capture_active_` | atomic | VIDEO_START 是否已送出 |
| `reader_ready_` | atomic | application 是否已進入 read path |
| `signal_probe_active_` | atomic | 有 signal,可在第一次 read 啟動 DMA |
| `stream_ready_pending_` | atomic | 首張成功 frame 後是否要送 STREAM_READY |
| `read_in_progress_` | `mutex_` | backend 是否已有 wait_frame 執行中 |
| `frame_held_` | `mutex_` | backend 是否已交付一張尚未 release 的 frame |
| `held_frame_` | `mutex_` | backend lifetime token |
@@ -172,7 +171,6 @@ copy_buffer_.clear();
-> ResetEvent(dma_event_)
-> VIDEO_START(channel)
-> capture_active_ = true
-> stream_ready_pending_ = true
-> read_in_progress_ = true
-> WaitForSingleObject(dma_event_, remaining deadline)
```
@@ -191,7 +189,7 @@ DMA event
-> driver 將資料複製到 SDK copy_buffer_
-> held_frame_.data = copy_buffer_.data()
-> backend frame_held_ = true
-> facade heldBackendFrame = frame
-> facade heldSessionFrame = frame
-> facade frameHeld = true
-> gvfg_frame_t.data 交給 application
```
@@ -222,10 +220,9 @@ Application 使用完成後:
```text
gvfg_release_channel_frame
-> facade 驗證完整 token
-> backend 驗證完整 token
-> GvfgReleaseVideoFrameZeroCopy(context, channel)
-> release 成功後才清除 held state
-> facade 以 data + frame_id 確認 held frame
-> backend 清除 SDK held state
-> 不呼叫 GigabyteLib/driver release
```
Zero-copy 的 `data` 不是 SDK memory。release 前不能保存 pointer 給非同步工作繼續使用。
@@ -239,7 +236,7 @@ stateDiagram-v2
Reading --> Idle: timeout/error
Reading --> Held: successful delivery
Held --> Held: another read rejected
Held --> Held: wrong token/release failure
Held --> Held: wrong token
Held --> Idle: release success
Held --> Idle: stop releases frame successfully
```
@@ -247,38 +244,36 @@ stateDiagram-v2
Facade 與 backend 各自保存一層狀態:
```text
facade: readInProgress / frameHeld / heldBackendFrame
backend: read_in_progress_ / frame_held_ / held_frame_
facade: readInProgress / frameHeld / heldSessionFrame
backend: frame_held_
```
兩層的目的不同:
- facade 保護公開 API contract 與 `gvfg_frame_t` token。
- backend 保護 driver buffer/DMA ownership 與底層 concurrent read。
- backend 阻止公開 release 前再次取得 frame;driver/Lib 不要求逐 frame release。
## 10. Release token 為什麼要完整比對
## 10. Release token 的最小身分確認
Release 不是只看 `data` pointer。程式會比對:
Release 只比對識別目前 held frame 所需的兩個欄位:
- data pointer
- data size
- frame ID
- width/height
- stride
- pixel format
- bit depth
這可避免 caller 把 CH0 token 用於 CH1、使用舊 frame、修改 descriptor,或重複 release。
channel 已由 release API 的參數指定;`data + frame_id` 可避免舊 frame 或錯誤 frame
結束目前 frame 的 lifetime,不額外驗證內容 metadata。
重要規則: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。
重要規則:token 驗證失敗時不可清除 held state。依目前 driver/Lib 契約,zero-copy
不需要送 release;Application 仍必須對每次成功 read 呼叫一次公開 release,明確結束
pointer lifetime,SDK 驗證 token 後才允許下一次 read。
## 11. Signal 與 format-change 狀態
Running 期間收到 `VIDEO_INPUT_PLUGIN` 時,SDK 標記 recovery 並喚醒 video/audio read。
SDK event worker 等待已交付的 video frame release,並與進行中的 Lib frame call 同步後,執行一次
`GvfgStopCapture()` → `GvfgStartCapture()`。Read 在恢復期間等待而不 busy-loop;public event
仍送給 Application 更新狀態,但 Application 不需要重啟 capture。
Backend 維護:
```text
@@ -331,7 +326,7 @@ signal_probe_active_ = false
-> VIDEO_STOP
-> SetEvent(dma_event_) 喚醒 blocking wait
-> 等 read_in_progress_ 結束
-> release pending zero-copy frame
-> clear pending SDK zero-copy token
-> stop/join event monitoring thread
```
@@ -351,7 +346,7 @@ signal_probe_active_ = false
- copy 與 zero-copy 各自的雙通道壓力測試。
- stop while read is blocked。
- stop while application holds a frame。
- zero-copy release IOCTL 失敗後的 retry。
- zero-copy 公開 release 後下一次 read,以及 stop-with-held-frame。
- plug out/in 後重新啟動 DMA。
- format change 時 buffer 重建與舊 pointer 失效邊界。
+83 -15
View File
@@ -3,8 +3,9 @@
## GigabyteLib backend 邊界
`gvfg.dll` 保留公開 API facade、裝置列舉、雙 channel session、frame ownership 與
事件轉換。底層 capture lifecycle、video/audio frame access 及 zero-copy release
全部透過主管提供的 `GvfgSdk.lib` API;舊 `giga_ioctl.dll` 與直接 register/IOCTL
事件轉換。底層 capture lifecycle 與 video/audio frame access 全部透過主管提供的
`GvfgSdk.lib` API;zero-copy 的公開 release 只結束 SDK token lifetime,不再呼叫 Lib
release。舊 `giga_ioctl.dll` 與直接 register/IOCTL
backend 已移除。`GvfgSdk.lib` 靜態連結進 `gvfg.dll`,不是客戶 runtime 相依。
本文件只供 GVFG SDK、driver、FPGA 與內部診斷工具維護者使用。客戶行為與公開
@@ -48,6 +49,37 @@ customer/sample (optional)
- `third_party/GigabyteLib`:主管提供的靜態 library 與其 private headers,只供 SDK build。
- `src/gpu/*`:D3D11 同步轉換及 readback 到 caller buffer。
### 2.1 公開 API 對 GigabyteLib 的包裝
公開 API 不直接暴露 GigabyteLib handle、結構或 HRESULT。Facade 依功能分成以下三類:
| 公開 API/資料 | 底層來源 | SDK 提供給上層前的處理 |
|---|---|---|
| `gvfg_enumerate_devices()` | Windows SetupAPI | 轉成 UTF-8、提供 fallback name,並附加 `#1`、`#2` 顯示序號;不呼叫 GigabyteLib |
| `gvfg_create()`、`gvfg_destroy()` | SDK | 管理 opaque handle、雙 channel session、錯誤狀態與自動 stop/close |
| `gvfg_open_channel()` | SDK + GigabyteLib | 先建立 logical channel;真正的 `GvfgOpenDev()`、events 與 `GvfgOpenVideoChn()` 延遲到第一次需要 vendor channel 時執行 |
| zero-copy enable/getter | `GvfgOpenDev()` memory mode + SDK cache | 使用者只選模式;SDK 在 vendor open 時轉成 Lib memory-mode flags,getter 不詢問 Lib |
| audio enable | `GvfgCreateEvents()` | 使用者只選是否啟用 audio;SDK 轉成 Lib 的 no-audio event 建立參數 |
| `gvfg_set_channel_video_format()` | `GvfgSetVideoColorDepth()` | YUY2/Y210 轉成 8/10-bit color depth,成功後更新 video info |
| `gvfg_get_channel_signal_status()` | `GVFG_VIDEO_INFO` cache | `VideoSignalLock` 轉 connected、FourCC 轉 SDK pixel format,並由格式推導 bit depth;正常 UI refresh 只讀 cache |
| `gvfg_get_device_capabilities()` | `GvfgGetDevInfo()` | 只公開 video channel count 與 audio capability |
| `gvfg_get_channel_sdi_info()` | `GvfgGetSdiVideoInputInfo()`、`GvfgStringifySdiVideoInputInfo()` | 同時提供 Lib 原始欄位的 SDK enum/value 與全部八個未改寫的 Lib 格式化字串,不公開 private struct |
| `gvfg_get_channel_audio_format()` | `GvfgGetAudioInfo()` | 只公開 sample rate、channels、bits per sample;`cbBufSize` 留在 SDK 作為讀取 buffer 大小,忽略 Lib FrameCount |
| `gvfg_start_channel()`、stop APIs | `GvfgStartCapture()`、`GvfgStopCapture()` | 驗證狀態、處理 wait cancellation、held frame、event queue、熱插拔恢復與 SDK counters |
| `gvfg_read_channel_frame()` | Lib video events + GetFrame API | 驗證 read/held 狀態,加入 row stride、SDK delivery frame ID、monotonic timestamp 與 delivery FPS 統計 |
| `gvfg_release_channel_frame()` | SDK | 以 `data + frame_id` 確認 held frame 並結束 pointer lifetime;zero-copy 不呼叫 Lib release |
| `gvfg_read_channel_audio_frame()` | Lib audio events + `GvfgGetAudioFrame()` | SDK 配置 copy buffer,加入格式、SDK delivery frame ID 與 monotonic timestamp |
| `gvfg_release_channel_audio_frame()` | SDK | 以 `data + frame_id` 確認 held audio frame 並解除 SDK copy buffer ownership,不呼叫 Lib release |
| `gvfg_poll_channel_event()` | Lib event handles | Callback 轉成容量 64 的 thread-safe SDK queue,補上 non-blocking、timeout 與 stop wake semantics |
| `gvfg_get_channel_runtime_info()` | SDK | FPS 與 delivered frame count 都在成功交付 frame 的 SDK 邊界計算,不是 driver/Lib counter |
| GPU conversion APIs | SDK D3D11 | 驗證 layout/size,再轉成 BGRA8、RGB10A2 或 NV12;GigabyteLib 不參與 |
| version/name/error APIs | SDK | SDK version、公開名稱與錯誤文字;Lib `GVFG_HRESULT` 正數原樣回傳,不產生 SDK detail |
| register R/W debug APIs | direct driver extension | 不屬於 GigabyteLib 正式 API,只能留在 internal debug surface |
資料來源必須對上層說清楚:video/audio `frame_id`、`timestamp_ns`、runtime FPS 與
delivered frame count 都由 SDK 產生;width、height、buffer size、signal、audio format
與 SDI info 來自 GigabyteLib。SDK 不應把 delivery counter 描述成 driver/FPGA counter。
## 3. 公開 facade 狀態
概念狀態:
@@ -58,8 +90,9 @@ Created/Closed -> Opened -> Running -> Opened -> Destroyed
+----------+ stop
```
- `open()` 會先 close 舊 backend、建立 session、設定 channel 並建立 event monitoring;
signal descriptor 在 start/configure 階段重新查詢。
- `open()` 會先 close 舊 backend、建立 logical session 並設定 channel;此時尚未必呼叫
`GvfgOpenDev()`。Vendor channel、event handles 與初始 signal descriptor 在第一次
set-format/query/start 需要時才建立。
- `start()` 先 `configureStream()`,清空 facade event queue,再啟動 backend。
- 無訊號時使用最小 placeholder descriptor 進入 event-monitoring mode;訊號恢復後
backend 依真實 descriptor 啟用 DMA。
@@ -68,7 +101,7 @@ Created/Closed -> Opened -> Running -> Opened -> Destroyed
- `destroy()` 允許 NULL,並透過 destructor/close 保證 stop。
每個 `gvfg_channel_session_t` 各有自己的 `readInProgress`、`frameHeld` 與
`heldBackendFrame`;同一 handle 的 CH0、CH1 可由兩條 worker thread 分別 read。
`heldSessionFrame`;同一 handle 的 CH0、CH1 可由兩條 worker thread 分別 read。
Open/start/stop/destroy 等 handle lifecycle 仍應由 caller 序列化;若日後要宣告完整
thread-safe,必須先補足這些操作彼此的同步與 handle lifetime 保護。
@@ -103,7 +136,7 @@ gvfg_create
-> facade 回傳 driver-owned pointer
-> customer/preview/conversion
-> gvfg_release_channel_frame(channel)
-> IOCTL_GIGA_RELEASE_VIDEO_FRAME(channel)
-> SDK 清除 held token;不送 Lib/driver release
-> close/destroy 時 IOCTL_GIGA_DISABLE_FRAME_ZEROCOPY(channel)
```
@@ -142,10 +175,9 @@ Backend event 映射:
| Backend | Public |
|---|---|
| `GIGABYTE_EVENT_PLUG_IN` | `GVFG_EVENT_SIGNAL_CONNECTED` |
| `GIGABYTE_EVENT_PLUG_OUT` | `GVFG_EVENT_SIGNAL_DISCONNECTED` |
| `GIGABYTE_EVENT_STREAM_READY` | `GVFG_EVENT_STREAM_READY` |
| `GIGABYTE_EVENT_FORMAT_CHANGE_BEGIN` | `GVFG_EVENT_FORMAT_CHANGE_BEGIN` |
| `hVideoFormatChangedEvent` | `GVFG_EVENT_VIDEO_FORMAT_CHANGED` |
| `hVideoInputPluginEvent` | `GVFG_EVENT_VIDEO_INPUT_PLUGIN` |
| `hVideoInputUnplugEvent` | `GVFG_EVENT_VIDEO_INPUT_UNPLUG` |
依 GigabyteLib 行為,video、format-change、plug-in 與 unplug events 在 open channel
時固定註冊;使用者只選擇是否啟用 audio,SDK 不再提供重複的 event mask 層。
@@ -153,9 +185,14 @@ Backend event 映射:
Facade queue 上限為 64;滿時丟棄最舊事件。`pollEvent()` 只允許 running 狀態,支援
non-blocking、有限 timeout 與 infinite wait;stop 透過 `eventCv` 喚醒 waiter。
事件順序的維護目標:format change begin 後停止使用舊 descriptor,完成重新配置且
第一個完整 frame 可用時才送 stream ready。更動 driver event mapping 或 recovery
流程時,要同時驗證無訊號啟動、拔插、解析度切換及 stop-during-wait。
目前 backend 在 format-changed/plug-in event 後更新 cached video info;unplug 則先清空
cached signal,再送 public event。Running 期間的 plug-in event 會喚醒 read;SDK event worker
等待 held video frame release,並以同一把 Lib capture lock 避開進行中的 video/audio frame call,
再執行一次 `GvfgStopCapture()` → `GvfgStartCapture()`。Application 只處理事件顯示,不控制重啟;
此恢復只由 plug-in event 驅動,不 polling。
更動 driver event mapping 或 recovery 流程時,要同時驗證無訊號啟動、拔插、解析度
切換及 stop-during-wait,並確認 consumer 收到事件時對應 cache 已經完成更新。
## 7. Internal debug API
@@ -170,8 +207,8 @@ non-blocking、有限 timeout 與 infinite wait;stop 透過 `eventCv` 喚醒 w
GigabyteLib 未提供的 DMA error、IRQ 或 driver sequence counter。
客戶診斷使用 `gvfg_get_channel_signal_status()`、`gvfg_get_channel_runtime_info()`、event、
`gvfg_strerror()` 與 `gvfg_get_channel_last_error_detail()`。每個 channel 的 `ChannelErrorState`
由 `gvfg_handle_t` 持有,facade 與 backend 共用同一份;因此 channel open 失敗後也能取得詳細錯誤。
`gvfg_strerror()` 與 `gvfg_get_channel_last_sdk_error_detail()`。每個 channel 的 `ChannelErrorState`
由 `gvfg_handle_t` 持有,只記錄 SDK 自己產生的負數錯誤;正數 Lib result 不會改寫它。
## 8. GPU conversion
@@ -213,3 +250,34 @@ frame、原生格式限 YUY2/Y210、event queue 非持久化且可能淘汰最
8. 驗證 x64 ABI static assertions、DLL exports、import library 與 customer sample。
9. 用乾淨 install tree 編譯 customer sample,避免意外依賴 source tree。
10. 確認客戶文件沒有 register、IOCTL、IRQ、ring slot 或未承諾的規格。
## 11. 完成項目與後續維護
### 本次已完成
1. **Public event ABI 已同步。** 公開 enum、Qt Sample、SDI Info 更新條件與文件使用
`GVFG_EVENT_VIDEO_FORMAT_CHANGED`、`GVFG_EVENT_VIDEO_INPUT_PLUGIN`、
`GVFG_EVENT_VIDEO_INPUT_UNPLUG`,不得再引入另一套合成事件名稱。
2. **Zero-copy release 契約已套用。** 正常 release 與 stop-with-held-frame 都只清除
SDK held state,不呼叫 `GvfgReleaseVideoFrameZeroCopy()`;caller 仍須呼叫公開
release,作為 pointer lifetime 的結束邊界。
### Lib query 維護規則
1. **VideoInfo query 已快取。** `GvfgSetVideoColorDepth()` 成功後更新一次;start/configure
只在 cache 尚未有效時查詢。format/plugin event 先更新 cache 再通知 consumer。
2. **AudioInfo query 已快取。** 第一次需要 audio format 時更新;Sample getter 與 start
共用同一份 cache,Stop/Start 不重查。
3. **SDI Info query 已改為事件驅動。** 第一次 channel open 可讀一次;之後只在 video format changed、
input plug-in 或 input unplug event 驅動更新。200 ms UI timer、一般 status render、
Stop/Start 都不得重查;新值與 cache 相同時不重設 UI。
### 後續邊界維護
1. 決定 SetupAPI enumerate 加 `#N` 是否為長期公開顯示契約;若只是 Sample 顯示需求,
應避免讓排序序號被誤認為硬體穩定 ID。
2. register R/W 持續標記為 GigabyteLib gap 與 internal-only;主管提供正式 Lib API 後
移除 `gigabyte_driver_extensions.*`,不得讓 direct IOCTL 擴張回第二套 backend。
3. 每次改公開 struct、event enum 或 frame lifetime,都必須同步
`gvfg_capture.h`、兩份 customer docs、internal notes、流程圖與 sample,再重新驗證
x64 ABI、DLL exports 及乾淨 install tree build。
+2 -1
View File
@@ -35,7 +35,8 @@
- 每條 channel 各自擁有 backend、event、capture thread、copy buffer 與 frame lifetime state。
- 公開 API 已改為 channel-aware:open/start/read/release/poll/stop 都帶 `channel_index`。
- copy mode 直接把 driver frame 寫入該 channel 的 `copy_buffer_`。
- zero-copy mode 保存 driver-owned pointer,成功 read 必須配對一次 release。
- zero-copy mode 保存 driver-owned pointer,成功 read 必須配對一次公開 release 以結束
SDK pointer lifetime;目前不送逐 frame Lib/driver release。
- `ChannelErrorState` 由 `gvfg_handle_t` 逐 channel 持有,facade/backend 共用同一份詳細錯誤。
- `firstOpenChannel()` 與「第二條 channel 從第一條借 backend」的 ownership 已移除。
- 重複的 `device_`、`opened_`、device path/name session 狀態已移除;`device_connection_` 是 device handle 的唯一來源。
+1 -1
View File
@@ -211,7 +211,7 @@ struct gvfg_channel_session_t
bool readInProgress;
bool frameHeld;
gigabyte_frame_t heldBackendFrame;
GigabyteFrame heldSessionFrame;
// FPS、signal、event queue 等其他狀態
};
+3 -3
View File
@@ -38,11 +38,11 @@
## 4. 更新 SDK 版本
版本只有一個來源:`GVFG_SDK/CMakeLists.txt` 的 `project()`。例如準備 `0.3.0`
版本只有一個來源:`GVFG_SDK/CMakeLists.txt` 的 `project()`。例如準備 `1.0.0`
時改成:
```cmake
project(gvfg_sdk VERSION 0.3.0 LANGUAGES CXX)
project(gvfg_sdk VERSION 1.0.0 LANGUAGES CXX)
```
`sdk/gvfg` 會直接繼承根 project version,並將它編入 `gvfg.dll`。不再存在 `GVFG_SDK_VERSION` cache option,也不應使用 `-DGVFG_SDK_VERSION=...` 覆寫。修改版本後要重新 configure,再重新建置 DLL。
@@ -119,7 +119,7 @@ Debug 診斷會增加 log 與檢查成本,不應拿來判斷正式版本效能
- 使用 `gvfg_get_version()` 查詢實際載入的 runtime DLL 版本。
- signal status、runtime FPS 與 channel event。
- GPU conversion:BGRA8、RGB10A2、NV12。
- 公開詳細錯誤 API:`gvfg_get_channel_last_error_detail()`。
- SDK 詳細錯誤 API:`gvfg_get_channel_last_sdk_error_detail()`;只適用於負數 SDK error。
- 內部 debug API:backend stats、register read/write。
目前 FPGA 的 8-bit format register 仍可能回報舊 `YVYU` 值;SDK 只把它當作 legacy register identifier,對外格式與實際 DMA layout一律是 YUY2(`Y0 U0 Y1 V0`)。