feat(gvfg): add event-driven signal and format control

Expose gvfg_set_video_format() so applications select YUY2 or Y210 through the SDK while the backend temporarily writes absolute register 0x80 (0=YUY2, 1=Y210).

Define RX mode/timing lock registers and treat the input as connected only when both lock values equal one. Keep plug/unplug/format monitoring active for the complete open-channel lifetime, cache signal metadata, and avoid unnecessary resolution/format register queries.

Keep the driver-compatible GET_VIDEO_DONE_INDEX then GET_FRAME sequence, reject repeated consecutive DMA done indexes, and calculate capture FPS over a one-second delivery window instead of adjacent-frame timing.

Update the standalone Qt sample with YUY2/Y210 selection, event-driven signal state, no-signal Start blocking, streamlined diagnostics, and monitoring that remains active while capture is stopped.

Validation: Release builds completed for the Visual Studio and Qt Creator build trees; the Qt Creator DLL relink requires the consuming viewer to be closed when it is running.
This commit is contained in:
Mark.lin
2026-08-14 16:36:38 +08:00
parent 17fb9bfabd
commit d7500ed9fd
8 changed files with 396 additions and 114 deletions
+106 -44
View File
@@ -173,8 +173,8 @@ MainWindow::MainWindow(QWidget *parent)
ui_->logEdit->setMaximumBlockCount(300); ui_->logEdit->setMaximumBlockCount(300);
new LogHighlighter(ui_->logEdit->document()); new LogHighlighter(ui_->logEdit->document());
ui_->statusLabel->setWordWrap(true); ui_->statusLabel->setWordWrap(true);
signalStatusTimer_ = new QTimer(this); runtimeStatusTimer_ = new QTimer(this);
signalStatusTimer_->setInterval(1000); runtimeStatusTimer_->setInterval(1000);
openLogFile(); openLogFile();
connect(ui_->refreshButton, &QPushButton::clicked, this, [this]() connect(ui_->refreshButton, &QPushButton::clicked, this, [this]()
@@ -191,10 +191,21 @@ MainWindow::MainWindow(QWidget *parent)
{ showFullscreenPreviewWindow(); }); { showFullscreenPreviewWindow(); });
connect(ui_->startButton, &QPushButton::clicked, this, [this]() connect(ui_->startButton, &QPushButton::clicked, this, [this]()
{ startCapture(); }); { startCapture(); });
connect(ui_->outputFormatCombo, &QComboBox::currentIndexChanged, this, [this](int)
{
if (handle_)
{
applyOutputFormat();
updateSignalStatus();
}
});
connect(ui_->stopButton, &QPushButton::clicked, this, [this]() connect(ui_->stopButton, &QPushButton::clicked, this, [this]()
{ stopCapture(); }); { stopCapture(); });
connect(signalStatusTimer_, &QTimer::timeout, this, [this]() connect(runtimeStatusTimer_, &QTimer::timeout, this, [this]()
{ updateSignalStatus(); }); {
processPendingEvents();
updateSignalStatus(false);
});
updateUiState(); updateUiState();
appendLog(QStringLiteral("GVFG SDK version | %1") appendLog(QStringLiteral("GVFG SDK version | %1")
@@ -316,17 +327,26 @@ bool MainWindow::openDevice()
return false; return false;
} }
if (!applyOutputFormat())
{
closeDevice();
return false;
}
lastSignalStatusText_.clear(); lastSignalStatusText_.clear();
appendLog(QStringLiteral("Opened device index %1 CH%2").arg(deviceIndex).arg(channelIndex)); appendLog(QStringLiteral("Opened device index %1 CH%2").arg(deviceIndex).arg(channelIndex));
appendLog(QStringLiteral("Signal monitoring active")); appendLog(QStringLiteral("Signal monitoring active"));
updateSignalStatus(); updateSignalStatus();
signalStatusTimer_->start(); runtimeStatusTimer_->start();
updateUiState(); updateUiState();
return true; return true;
} }
void MainWindow::closeDevice() void MainWindow::closeDevice()
{ {
if (runtimeStatusTimer_)
runtimeStatusTimer_->stop();
stopCapture(); stopCapture();
if (previewHandle_) if (previewHandle_)
{ {
@@ -334,9 +354,6 @@ void MainWindow::closeDevice()
previewHandle_ = nullptr; previewHandle_ = nullptr;
} }
if (signalStatusTimer_)
signalStatusTimer_->stop();
if (handle_) if (handle_)
{ {
gvfg_destroy(handle_); gvfg_destroy(handle_);
@@ -347,9 +364,30 @@ void MainWindow::closeDevice()
ui_->statusLabel->setText(QStringLiteral("Idle")); ui_->statusLabel->setText(QStringLiteral("Idle"));
lastSignalStatusText_.clear(); lastSignalStatusText_.clear();
lastLoggedInputStatus_.clear(); lastLoggedInputStatus_.clear();
cachedSignalStatus_ = {};
haveCachedSignalStatus_ = false;
updateUiState(); updateUiState();
} }
bool MainWindow::applyOutputFormat()
{
if (!handle_)
return false;
const gvfg_pixel_format_t format = ui_->outputFormatCombo->currentIndex() == 1
? GVFG_PIXFMT_Y210
: GVFG_PIXFMT_YUY2;
const gvfg_status_t status = gvfg_set_video_format(handle_, format);
if (status != GVFG_OK)
{
showError(QStringLiteral("set output format register"), status);
return false;
}
appendLog(QStringLiteral("Output format | %1")
.arg(format == GVFG_PIXFMT_Y210 ? QStringLiteral("Y210") : QStringLiteral("YUY2")));
return true;
}
void MainWindow::startCapture() void MainWindow::startCapture()
{ {
if (captureRunning_) if (captureRunning_)
@@ -358,6 +396,18 @@ void MainWindow::startCapture()
if (!handle_ && !openDevice()) if (!handle_ && !openDevice())
return; return;
// Revalidate on the user action as a final guard against an unplug event
// that is queued but has not yet reached the UI.
updateSignalStatus();
if (!haveCachedSignalStatus_ || !cachedSignalStatus_.connected)
{
appendLog(QStringLiteral("Start skipped: no input signal"));
return;
}
if (!applyOutputFormat())
return;
frameAvailable_.store(false, std::memory_order_release); frameAvailable_.store(false, std::memory_order_release);
updatePreviewSourceSize(); updatePreviewSourceSize();
previewWindow_->showPreview(); previewWindow_->showPreview();
@@ -468,14 +518,51 @@ void MainWindow::updatePreviewSourceSize()
updatePreviewSourceSize(signal); updatePreviewSourceSize(signal);
} }
void MainWindow::updateSignalStatus() void MainWindow::processPendingEvents()
{
if (!handle_)
return;
gvfg_event_t event{};
event.struct_size = sizeof(event);
while (gvfg_poll_event(handle_, &event, 0) == GVFG_OK)
{
const auto eventType = static_cast<gvfg_event_type_t>(event.type);
if (eventType == GVFG_EVENT_FRAME_LOSS)
appendLog(QStringLiteral("WARNING dropped frames +%1").arg(event.count));
else
appendLog(QStringLiteral("EVENT %1").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)
updateSignalStatus();
event = {};
event.struct_size = sizeof(event);
}
}
void MainWindow::updateSignalStatus(bool queryHardware)
{ {
if (!handle_) if (!handle_)
return; return;
gvfg_signal_status_t signal{}; gvfg_signal_status_t signal{};
if (gvfg_get_signal_status(handle_, &signal) != GVFG_OK) if (queryHardware)
return; {
if (gvfg_get_signal_status(handle_, &signal) != GVFG_OK)
return;
cachedSignalStatus_ = signal;
haveCachedSignalStatus_ = true;
}
else
{
if (!haveCachedSignalStatus_)
return;
signal = cachedSignalStatus_;
}
const QString inputStatus = signal.connected const QString inputStatus = signal.connected
? QStringLiteral("CH%1 Connected | %2") ? QStringLiteral("CH%1 Connected | %2")
@@ -605,6 +692,7 @@ void MainWindow::updateSignalStatus()
ui_->statusLabel->setText(statusText); ui_->statusLabel->setText(statusText);
lastSignalStatusText_ = statusText; lastSignalStatusText_ = statusText;
} }
updateUiState();
#if GVFG_INTERNAL_DIAGNOSTICS #if GVFG_INTERNAL_DIAGNOSTICS
if (diagnosticProblemDetected) if (diagnosticProblemDetected)
@@ -619,12 +707,14 @@ void MainWindow::updateUiState()
frameAvailable_.load(std::memory_order_acquire); frameAvailable_.load(std::memory_order_acquire);
ui_->openButton->setText(deviceOpen ? QStringLiteral("Close Device") : QStringLiteral("Open Device")); ui_->openButton->setText(deviceOpen ? QStringLiteral("Close Device") : QStringLiteral("Open Device"));
ui_->openButton->setEnabled(!captureRunning_); ui_->openButton->setEnabled(!captureRunning_);
ui_->startButton->setEnabled(deviceOpen && !captureRunning_); const bool signalConnected = haveCachedSignalStatus_ && cachedSignalStatus_.connected != 0;
ui_->startButton->setEnabled(deviceOpen && signalConnected && !captureRunning_);
ui_->stopButton->setEnabled(captureRunning_); ui_->stopButton->setEnabled(captureRunning_);
ui_->showPreviewButton->setEnabled(viewAvailable); ui_->showPreviewButton->setEnabled(viewAvailable);
ui_->fullscreenPreviewButton->setEnabled(viewAvailable); ui_->fullscreenPreviewButton->setEnabled(viewAvailable);
ui_->refreshButton->setEnabled(!deviceOpen && !captureRunning_); ui_->refreshButton->setEnabled(!deviceOpen && !captureRunning_);
ui_->deviceCombo->setEnabled(!deviceOpen && !captureRunning_); ui_->deviceCombo->setEnabled(!deviceOpen && !captureRunning_);
ui_->outputFormatCombo->setEnabled(deviceOpen);
} }
void MainWindow::showError(const QString &apiName, gvfg_status_t status) void MainWindow::showError(const QString &apiName, gvfg_status_t status)
@@ -762,25 +852,6 @@ void MainWindow::captureReadLoop()
while (!captureStop_.load(std::memory_order_acquire)) while (!captureStop_.load(std::memory_order_acquire))
{ {
gvfg_event_t event{};
event.struct_size = sizeof(event);
while (gvfg_poll_event(handle_, &event, 0) == GVFG_OK)
{
const auto eventType = static_cast<gvfg_event_type_t>(event.type);
const QString type = eventTypeText(eventType);
const uint64_t count = event.count;
QMetaObject::invokeMethod(this, [this, eventType, type, count]()
{
if (eventType == GVFG_EVENT_FRAME_LOSS)
appendLog(QStringLiteral("WARNING dropped frames +%1").arg(count));
else
appendLog(QStringLiteral("EVENT %1").arg(type));
},
Qt::QueuedConnection);
event = {};
event.struct_size = sizeof(event);
}
gvfg_frame_t frame{}; gvfg_frame_t frame{};
const gvfg_status_t st = gvfg_read_frame(handle_, &frame, 200); const gvfg_status_t st = gvfg_read_frame(handle_, &frame, 200);
if (st == GVFG_OK) if (st == GVFG_OK)
@@ -902,23 +973,14 @@ void MainWindow::captureReadLoop()
const bool periodicReport = captureStalledLogged && (consecutiveTimeouts % 50) == 0; const bool periodicReport = captureStalledLogged && (consecutiveTimeouts % 50) == 0;
if (firstReport || periodicReport) if (firstReport || periodicReport)
{ {
gvfg_signal_status_t signal{};
const gvfg_status_t signalStatus = gvfg_get_signal_status(handle_, &signal);
const QString detail = signalStatus != GVFG_OK
? QStringLiteral("signal query failed: %1")
.arg(QString::fromUtf8(gvfg_strerror(signalStatus)))
: signal.connected
? signalFrameText(signal)
: QStringLiteral("No signal");
captureStalledLogged = true; captureStalledLogged = true;
const uint32_t elapsedMs = consecutiveTimeouts * 200u; const uint32_t elapsedMs = consecutiveTimeouts * 200u;
QMetaObject::invokeMethod(this, [this, elapsedMs, detail]() QMetaObject::invokeMethod(this, [this, elapsedMs]()
{ {
appendLog(QStringLiteral("ERROR no capture frame for %1 ms | %2") appendLog(QStringLiteral("ERROR no capture frame for %1 ms")
.arg(elapsedMs) .arg(elapsedMs));
.arg(detail));
#if GVFG_INTERNAL_DIAGNOSTICS #if GVFG_INTERNAL_DIAGNOSTICS
updateSignalStatus(); updateSignalStatus(false);
writeDiagnosticSnapshot(lastSignalStatusText_); writeDiagnosticSnapshot(lastSignalStatusText_);
#endif #endif
}, },
+6 -2
View File
@@ -40,13 +40,15 @@ private:
void showPreviewWindow(); void showPreviewWindow();
void showFullscreenPreviewWindow(); void showFullscreenPreviewWindow();
bool openDevice(); bool openDevice();
bool applyOutputFormat();
void closeDevice(); void closeDevice();
void startCapture(); void startCapture();
void stopCapture(); void stopCapture();
bool applyPreview(); bool applyPreview();
void updatePreviewSourceSize(const gvfg_signal_status_t &signal); void updatePreviewSourceSize(const gvfg_signal_status_t &signal);
void updatePreviewSourceSize(); void updatePreviewSourceSize();
void updateSignalStatus(); void processPendingEvents();
void updateSignalStatus(bool queryHardware = true);
void updateUiState(); void updateUiState();
void showError(const QString &apiName, gvfg_status_t status); void showError(const QString &apiName, gvfg_status_t status);
void openLogFile(); void openLogFile();
@@ -76,7 +78,9 @@ private:
std::atomic<double> previewCallAverageMs_{0.0}; std::atomic<double> previewCallAverageMs_{0.0};
std::atomic<double> previewCallMaximumMs_{0.0}; std::atomic<double> previewCallMaximumMs_{0.0};
std::atomic<uint64_t> previewCallSamples_{0}; std::atomic<uint64_t> previewCallSamples_{0};
QTimer *signalStatusTimer_ = nullptr; QTimer *runtimeStatusTimer_ = nullptr;
gvfg_signal_status_t cachedSignalStatus_{};
bool haveCachedSignalStatus_ = false;
QString lastSignalStatusText_; QString lastSignalStatusText_;
QString lastLoggedInputStatus_; QString lastLoggedInputStatus_;
#if GVFG_INTERNAL_DIAGNOSTICS #if GVFG_INTERNAL_DIAGNOSTICS
+66 -1
View File
@@ -18,6 +18,18 @@
<layout class="QHBoxLayout" name="topLayout"> <layout class="QHBoxLayout" name="topLayout">
<item> <item>
<widget class="QLabel" name="deviceLabel"> <widget class="QLabel" name="deviceLabel">
<property name="minimumSize">
<size>
<width>86</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>86</width>
<height>16777215</height>
</size>
</property>
<property name="text"> <property name="text">
<string>Device:</string> <string>Device:</string>
</property> </property>
@@ -77,13 +89,66 @@
</layout> </layout>
</item> </item>
<item row="1" column="0"> <item row="1" column="0">
<layout class="QHBoxLayout" name="formatLayout">
<item>
<widget class="QLabel" name="outputFormatLabel">
<property name="minimumSize">
<size>
<width>86</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>86</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>Output format:</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="outputFormatCombo">
<property name="toolTip">
<string>Requested capture output format</string>
</property>
<item>
<property name="text">
<string>YUY2 (8-bit 4:2:2)</string>
</property>
</item>
<item>
<property name="text">
<string>Y210 (10-bit 4:2:2)</string>
</property>
</item>
</widget>
</item>
<item>
<spacer name="formatSpacer">
<property name="orientation">
<enum>Qt::Orientation::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item row="2" column="0">
<widget class="QLabel" name="statusLabel"> <widget class="QLabel" name="statusLabel">
<property name="text"> <property name="text">
<string>Idle</string> <string>Idle</string>
</property> </property>
</widget> </widget>
</item> </item>
<item row="2" column="0"> <item row="3" column="0">
<widget class="QPlainTextEdit" name="logEdit"> <widget class="QPlainTextEdit" name="logEdit">
<property name="readOnly"> <property name="readOnly">
<bool>true</bool> <bool>true</bool>
+15 -2
View File
@@ -258,6 +258,18 @@ extern "C"
_In_ int device_index, _In_ int device_index,
_In_ int channel_index); _In_ int channel_index);
/*
* Select the native capture format. This may be called before or during
* capture. A running stream reports GVFG_EVENT_FORMAT_CHANGE_BEGIN while
* the new format is applied.
*
* Currently the SDK implements this through a temporary hardware register;
* applications must use this API so the backend can move to an IOCTL later.
*/
GVFG_API gvfg_status_t gvfg_set_video_format(
_In_ gvfg_handle handle,
_In_ gvfg_pixel_format_t format);
/* /*
* Configure and start capture on an opened device. * Configure and start capture on an opened device.
* *
@@ -383,7 +395,7 @@ extern "C"
* Returns: * Returns:
* - GVFG_OK on success. * - GVFG_OK on success.
* - GVFG_EINVAL if handle/out_event is NULL or struct_size is invalid. * - GVFG_EINVAL if handle/out_event is NULL or struct_size is invalid.
* - GVFG_ESTATE if capture is not running or is stopped while waiting. * - GVFG_ESTATE if no capture device is open.
* - GVFG_ETIMEOUT if no event is available before timeout_ms expires. * - GVFG_ETIMEOUT if no event is available before timeout_ms expires.
*/ */
GVFG_API gvfg_status_t gvfg_poll_event( GVFG_API gvfg_status_t gvfg_poll_event(
@@ -401,7 +413,8 @@ extern "C"
* - GVFG_OK on success, including when capture is already stopped. * - GVFG_OK on success, including when capture is already stopped.
* - GVFG_EINVAL if handle is NULL. * - GVFG_EINVAL if handle is NULL.
* *
* This stops backend capture and invalidates any unreleased frame. * This stops DMA capture and invalidates any unreleased frame. Signal and
* format event monitoring remains active until gvfg_destroy().
*/ */
GVFG_API gvfg_status_t gvfg_stop( GVFG_API gvfg_status_t gvfg_stop(
_In_ gvfg_handle handle); _In_ gvfg_handle handle);
@@ -171,6 +171,7 @@ namespace gvfg::internal
signal_presence_known_.store(false, std::memory_order_release); signal_presence_known_.store(false, std::memory_order_release);
signal_present_.store(false, std::memory_order_release); signal_present_.store(false, std::memory_order_release);
signal_probe_active_.store(false, std::memory_order_release); signal_probe_active_.store(false, std::memory_order_release);
signal_metadata_valid_ = false;
clear_last_error(); clear_last_error();
PCIES2MM_LOG("open_device: %s", wide_to_utf8(base_path_).c_str()); PCIES2MM_LOG("open_device: %s", wide_to_utf8(base_path_).c_str());
return PCIES2MM_OK; return PCIES2MM_OK;
@@ -179,12 +180,14 @@ namespace gvfg::internal
pcies2mm_status_t PcieS2mmCaptureSession::close() pcies2mm_status_t PcieS2mmCaptureSession::close()
{ {
stop_stream(); stop_stream();
stop_event_monitoring();
close_handles(); close_handles();
opened_ = false; opened_ = false;
configured_ = false; configured_ = false;
signal_presence_known_.store(false, std::memory_order_release); signal_presence_known_.store(false, std::memory_order_release);
signal_present_.store(false, std::memory_order_release); signal_present_.store(false, std::memory_order_release);
signal_probe_active_.store(false, std::memory_order_release); signal_probe_active_.store(false, std::memory_order_release);
signal_metadata_valid_ = false;
base_path_.clear(); base_path_.clear();
friendly_name_.clear(); friendly_name_.clear();
reset_stats(stats_, PCIES2MM_STREAM_STOPPED); reset_stats(stats_, PCIES2MM_STREAM_STOPPED);
@@ -210,6 +213,28 @@ namespace gvfg::internal
if (channel >= kMaxChannels) if (channel >= kMaxChannels)
return PCIES2MM_EINVAL; return PCIES2MM_EINVAL;
channel_ = channel; channel_ = channel;
signal_metadata_valid_ = false;
if (!start_event_monitoring())
return fail(PCIES2MM_EIO, "start event monitoring");
return PCIES2MM_OK;
}
pcies2mm_status_t PcieS2mmCaptureSession::set_video_format(pcies2mm_pixel_format_t format)
{
if (!opened_)
return PCIES2MM_ESTATE;
uint32_t value = 0;
if (format == PCIES2MM_PIXFMT_Y210)
value = 1;
else if (format != PCIES2MM_PIXFMT_YUY2)
return PCIES2MM_EINVAL;
if (!write_reg(VIDEO_OUTPUT_FORMAT_REGISTER, value))
return fail(PCIES2MM_EIO, "set_video_format");
std::lock_guard<std::mutex> lock(mutex_);
signal_metadata_valid_ = false;
return PCIES2MM_OK; return PCIES2MM_OK;
} }
@@ -219,6 +244,31 @@ namespace gvfg::internal
return PCIES2MM_ESTATE; return PCIES2MM_ESTATE;
std::memset(&out, 0, sizeof(out)); std::memset(&out, 0, sizeof(out));
out.channel = channel_;
uint32_t modeLocked = 0;
uint32_t timingLocked = 0;
if (!read_reg(video_base() + VIDEO_RX_MODE_LOCKED_OFFSET, modeLocked) ||
!read_reg(video_base() + VIDEO_RX_T_LOCKED_OFFSET, timingLocked))
return fail(PCIES2MM_EIO, "read signal lock registers");
const bool signalPresent = modeLocked == 1u && timingLocked == 1u;
signal_presence_known_.store(true, std::memory_order_release);
signal_present_.store(signalPresent, std::memory_order_release);
if (!signalPresent)
{
std::lock_guard<std::mutex> lock(mutex_);
signal_metadata_valid_ = false;
return PCIES2MM_ENODEV;
}
std::lock_guard<std::mutex> lock(mutex_);
if (signal_metadata_valid_)
{
out = cached_signal_;
return PCIES2MM_OK;
}
uint32_t rawWidth = 0; uint32_t rawWidth = 0;
uint32_t rawHeight = 0; uint32_t rawHeight = 0;
uint32_t rawFormat = 0; uint32_t rawFormat = 0;
@@ -227,17 +277,14 @@ namespace gvfg::internal
const bool formatOk = read_reg(video_base() + VIDEO_FORMAT_OFFSET, rawFormat); const bool formatOk = read_reg(video_base() + VIDEO_FORMAT_OFFSET, rawFormat);
const bool haveRawSize = widthOk && heightOk && rawWidth != 0 && rawHeight != 0; const bool haveRawSize = widthOk && heightOk && rawWidth != 0 && rawHeight != 0;
const bool presenceKnown = signal_presence_known_.load(std::memory_order_acquire);
// H/V/format registers can retain their previous values after signal
// loss. They describe a candidate DMA layout, never signal presence.
const bool signalPresent = presenceKnown &&
signal_present_.load(std::memory_order_acquire);
pcies2mm_pixel_format_t fmt = formatOk ? decode_pixel_format(rawFormat) : PCIES2MM_PIXFMT_UNKNOWN; pcies2mm_pixel_format_t fmt = formatOk ? decode_pixel_format(rawFormat) : PCIES2MM_PIXFMT_UNKNOWN;
const uint32_t width = signalPresent && haveRawSize ? rawWidth : 0; const uint32_t width = signalPresent && haveRawSize ? rawWidth : 0;
const uint32_t height = signalPresent && haveRawSize ? rawHeight : 0; const uint32_t height = signalPresent && haveRawSize ? rawHeight : 0;
const uint32_t bitDepth = bit_depth_for_pixfmt(fmt); const uint32_t bitDepth = bit_depth_for_pixfmt(fmt);
const bool connected = signalPresent && haveRawSize && fmt != PCIES2MM_PIXFMT_UNKNOWN; // Signal presence is defined only by the two receiver lock bits. Size
// and format are metadata and must not participate in that decision.
const bool connected = signalPresent;
out.connected = connected ? 1 : 0; out.connected = connected ? 1 : 0;
out.channel = channel_; out.channel = channel_;
@@ -245,11 +292,9 @@ namespace gvfg::internal
out.height = height; out.height = height;
out.pixel_format = fmt; out.pixel_format = fmt;
out.bit_depth = bitDepth; out.bit_depth = bitDepth;
if (connected) cached_signal_ = out;
return PCIES2MM_OK; signal_metadata_valid_ = widthOk && heightOk && formatOk && haveRawSize;
if (signalPresent && haveRawSize && formatOk) return PCIES2MM_OK;
return PCIES2MM_ENOTSUP;
return PCIES2MM_ENODEV;
} }
pcies2mm_status_t PcieS2mmCaptureSession::set_event_callback(pcies2mm_event_callback_t callback, void *user, uint32_t eventMask) pcies2mm_status_t PcieS2mmCaptureSession::set_event_callback(pcies2mm_event_callback_t callback, void *user, uint32_t eventMask)
@@ -315,19 +360,16 @@ namespace gvfg::internal
pending_events_ = 0; pending_events_ = 0;
latest_sequence_ = 0; latest_sequence_ = 0;
delivered_sequence_ = 0; delivered_sequence_ = 0;
have_last_done_index_ = false;
last_done_index_ = 0;
wait_timeout_count_ = 0; wait_timeout_count_ = 0;
stream_error_ = false; stream_error_ = false;
reset_stats(stats_, PCIES2MM_STREAM_CONFIGURED); reset_stats(stats_, PCIES2MM_STREAM_CONFIGURED);
} }
const uint32_t channel = active_channel(); const uint32_t channel = active_channel();
if (!create_and_register_events(channel)) if (!monitoring_.load(std::memory_order_acquire))
{ return fail(PCIES2MM_ESTATE, "event monitoring is not active", ERROR_INVALID_STATE);
const DWORD err = GetLastError();
unregister_events(channel);
close_event_handles();
return fail(PCIES2MM_EIO, "REGISTER_EVENT", err);
}
// Events are edge-triggered, so a source connected before registration // Events are edge-triggered, so a source connected before registration
// may not produce a plug-in event. Probe DMA using the register layout, // may not produce a plug-in event. Probe DMA using the register layout,
// but do not report connected until a full frame is received. // but do not report connected until a full frame is received.
@@ -340,21 +382,6 @@ namespace gvfg::internal
reader_ready_ = false; reader_ready_ = false;
signal_probe_active_ = probeAvailable; signal_probe_active_ = probeAvailable;
stream_ready_pending_ = false; stream_ready_pending_ = false;
try
{
capture_thread_ = std::thread(&PcieS2mmCaptureSession::capture_thread_proc, this);
}
catch (...)
{
running_ = false;
capture_active_ = false;
signal_probe_active_ = false;
stream_ready_pending_ = false;
unregister_events(channel);
close_event_handles();
return fail(PCIES2MM_EIO, "capture_thread", ERROR_NOT_ENOUGH_MEMORY);
}
PCIES2MM_LOG("start: channel=%u base=0x%x bytes=%zu probe_available=%d reader_deferred=1", PCIES2MM_LOG("start: channel=%u base=0x%x bytes=%zu probe_available=%d reader_deferred=1",
channel, channel,
video_base(), video_base(),
@@ -365,10 +392,9 @@ namespace gvfg::internal
pcies2mm_status_t PcieS2mmCaptureSession::stop_stream() pcies2mm_status_t PcieS2mmCaptureSession::stop_stream()
{ {
if (!running_ && !capture_thread_.joinable()) if (!running_)
return PCIES2MM_OK; return PCIES2MM_OK;
const uint32_t channel = active_channel();
running_ = false; running_ = false;
capture_active_ = false; capture_active_ = false;
reader_ready_ = false; reader_ready_ = false;
@@ -379,7 +405,6 @@ namespace gvfg::internal
{ {
write_reg(video_base() + VIDEO_DMA_EN_OFFSET, 0); write_reg(video_base() + VIDEO_DMA_EN_OFFSET, 0);
write_reg(video_base() + VIDEO_EN_OFFSET, 0); write_reg(video_base() + VIDEO_EN_OFFSET, 0);
write_reg(INTERRUPT_BASE + IRQ_MASK_W1C_OFFSET, video_irq_mask_bit());
} }
if (dma_event_) if (dma_event_)
@@ -387,14 +412,6 @@ namespace gvfg::internal
frame_cv_.notify_all(); frame_cv_.notify_all();
data_cv_.notify_all(); data_cv_.notify_all();
if (capture_thread_.joinable())
capture_thread_.join();
if (device_ != INVALID_HANDLE_VALUE)
unregister_events(channel);
close_event_handles();
{ {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
pending_events_ = 0; pending_events_ = 0;
@@ -738,6 +755,50 @@ namespace gvfg::internal
return true; return true;
} }
bool PcieS2mmCaptureSession::start_event_monitoring()
{
if (monitoring_.load(std::memory_order_acquire))
return true;
const uint32_t channel = active_channel();
if (!create_and_register_events(channel))
{
unregister_events(channel);
close_event_handles();
return false;
}
monitoring_.store(true, std::memory_order_release);
try
{
capture_thread_ = std::thread(&PcieS2mmCaptureSession::capture_thread_proc, this);
}
catch (...)
{
monitoring_.store(false, std::memory_order_release);
unregister_events(channel);
close_event_handles();
return false;
}
return true;
}
void PcieS2mmCaptureSession::stop_event_monitoring()
{
if (!monitoring_.exchange(false, std::memory_order_acq_rel) &&
!capture_thread_.joinable())
return;
if (dma_event_)
SetEvent(dma_event_);
if (capture_thread_.joinable())
capture_thread_.join();
if (device_ != INVALID_HANDLE_VALUE)
unregister_events(active_channel());
close_event_handles();
}
int PcieS2mmCaptureSession::get_frame(uint32_t channelIndex, uint32_t frameIndex, uint8_t *buffer, DWORD bufferSize) const int PcieS2mmCaptureSession::get_frame(uint32_t channelIndex, uint32_t frameIndex, uint8_t *buffer, DWORD bufferSize) const
{ {
ULONG input[2] = {channelIndex, frameIndex}; ULONG input[2] = {channelIndex, frameIndex};
@@ -776,16 +837,18 @@ namespace gvfg::internal
constexpr DWORD waitHandleCount = 4; constexpr DWORD waitHandleCount = 4;
uint64_t diagnosticTimeouts = 0; uint64_t diagnosticTimeouts = 0;
while (running_) while (monitoring_.load(std::memory_order_acquire))
{ {
const DWORD waitResult = WaitForMultipleObjects(waitHandleCount, const DWORD waitResult = WaitForMultipleObjects(waitHandleCount,
waitHandles, waitHandles,
FALSE, FALSE,
1000); 1000);
if (!running_) if (!monitoring_.load(std::memory_order_acquire))
break; break;
if (waitResult == WAIT_TIMEOUT) if (waitResult == WAIT_TIMEOUT)
{ {
if (!running_.load(std::memory_order_acquire))
continue;
++diagnosticTimeouts; ++diagnosticTimeouts;
if (diagnosticTimeouts <= 5 || (diagnosticTimeouts % 10) == 0) if (diagnosticTimeouts <= 5 || (diagnosticTimeouts % 10) == 0)
{ {
@@ -893,6 +956,15 @@ namespace gvfg::internal
return; return;
} }
{
std::lock_guard<std::mutex> lock(mutex_);
// A repeated wake-up can expose the same completed DMA buffer.
// Do not publish it again as a new frame. A valid ring wrap is
// still accepted because other done indexes occur in between.
if (have_last_done_index_ && doneIndex == last_done_index_)
return;
}
const DWORD bytes = static_cast<DWORD>(frame_size_bytes()); const DWORD bytes = static_cast<DWORD>(frame_size_bytes());
size_t slotIndex = frame_ring_.size(); size_t slotIndex = frame_ring_.size();
uint8_t *slotData = nullptr; uint8_t *slotData = nullptr;
@@ -1023,6 +1095,8 @@ namespace gvfg::internal
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
if (pending_events_ > 0) if (pending_events_ > 0)
--pending_events_; --pending_events_;
have_last_done_index_ = true;
last_done_index_ = doneIndex;
publish_frame(slotIndex, static_cast<size_t>(ret)); publish_frame(slotIndex, static_cast<size_t>(ret));
} }
@@ -1032,6 +1106,10 @@ namespace gvfg::internal
void PcieS2mmCaptureSession::handle_format_change_event(uint32_t channel) void PcieS2mmCaptureSession::handle_format_change_event(uint32_t channel)
{ {
{
std::lock_guard<std::mutex> lock(mutex_);
signal_metadata_valid_ = false;
}
emit_event(PCIES2MM_EVENT_FORMAT_CHANGE_BEGIN); emit_event(PCIES2MM_EVENT_FORMAT_CHANGE_BEGIN);
write_reg(video_base() + VIDEO_DMA_EN_OFFSET, 0); write_reg(video_base() + VIDEO_DMA_EN_OFFSET, 0);
write_reg(video_base() + VIDEO_EN_OFFSET, 0); write_reg(video_base() + VIDEO_EN_OFFSET, 0);
@@ -1057,6 +1135,10 @@ namespace gvfg::internal
signal_probe_active_.store(false, std::memory_order_release); signal_probe_active_.store(false, std::memory_order_release);
signal_present_.store(true, std::memory_order_release); signal_present_.store(true, std::memory_order_release);
signal_presence_known_.store(true, std::memory_order_release); signal_presence_known_.store(true, std::memory_order_release);
{
std::lock_guard<std::mutex> lock(mutex_);
signal_metadata_valid_ = false;
}
emit_event(PCIES2MM_EVENT_PLUG_IN); emit_event(PCIES2MM_EVENT_PLUG_IN);
if (reader_ready_.load(std::memory_order_acquire)) if (reader_ready_.load(std::memory_order_acquire))
resume_capture_from_signal(channel); resume_capture_from_signal(channel);
@@ -1077,6 +1159,7 @@ namespace gvfg::internal
{ {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
signal_metadata_valid_ = false;
pending_events_ = 0; pending_events_ = 0;
for (FrameSlot &slot : frame_ring_) for (FrameSlot &slot : frame_ring_)
{ {
@@ -1202,6 +1285,13 @@ namespace gvfg::internal
stream_desc_.height = height; stream_desc_.height = height;
stream_desc_.pixel_format = pixelFormat; stream_desc_.pixel_format = pixelFormat;
stream_bit_depth_ = bitDepth; stream_bit_depth_ = bitDepth;
cached_signal_.connected = 1;
cached_signal_.channel = channel_;
cached_signal_.width = width;
cached_signal_.height = height;
cached_signal_.pixel_format = pixelFormat;
cached_signal_.bit_depth = bitDepth;
signal_metadata_valid_ = true;
if (resizeRing) if (resizeRing)
{ {
frame_ring_.assign(stream_desc_.buffer_count, FrameSlot{}); frame_ring_.assign(stream_desc_.buffer_count, FrameSlot{});
@@ -29,6 +29,7 @@ namespace gvfg::internal
pcies2mm_status_t close(); pcies2mm_status_t close();
pcies2mm_status_t set_channel(uint32_t channel); pcies2mm_status_t set_channel(uint32_t channel);
pcies2mm_status_t set_video_format(pcies2mm_pixel_format_t format);
pcies2mm_status_t get_signal_status(pcies2mm_signal_status_t &out) const; pcies2mm_status_t get_signal_status(pcies2mm_signal_status_t &out) const;
pcies2mm_status_t set_event_callback(pcies2mm_event_callback_t callback, void *user, uint32_t eventMask); pcies2mm_status_t set_event_callback(pcies2mm_event_callback_t callback, void *user, uint32_t eventMask);
@@ -54,6 +55,8 @@ namespace gvfg::internal
bool register_event(uint32_t channelIndex, uint32_t eventType, HANDLE eventHandle); bool register_event(uint32_t channelIndex, uint32_t eventType, HANDLE eventHandle);
void unregister_event(uint32_t channelIndex, uint32_t eventType); void unregister_event(uint32_t channelIndex, uint32_t eventType);
bool create_and_register_events(uint32_t channelIndex); bool create_and_register_events(uint32_t channelIndex);
bool start_event_monitoring();
void stop_event_monitoring();
void unregister_events(uint32_t channelIndex); void unregister_events(uint32_t channelIndex);
void close_event_handles(); void close_event_handles();
bool get_video_done_index(uint32_t channelIndex, uint32_t &doneIndex) const; bool get_video_done_index(uint32_t channelIndex, uint32_t &doneIndex) const;
@@ -104,12 +107,15 @@ namespace gvfg::internal
bool configured_ = false; bool configured_ = false;
std::atomic<bool> running_{false}; std::atomic<bool> running_{false};
std::atomic<bool> monitoring_{false};
std::atomic<bool> capture_active_{false}; std::atomic<bool> capture_active_{false};
std::atomic<bool> reader_ready_{false}; std::atomic<bool> reader_ready_{false};
std::atomic<bool> signal_probe_active_{false}; std::atomic<bool> signal_probe_active_{false};
std::atomic<bool> stream_ready_pending_{false}; std::atomic<bool> stream_ready_pending_{false};
mutable std::atomic<bool> signal_presence_known_{false}; mutable std::atomic<bool> signal_presence_known_{false};
mutable std::atomic<bool> signal_present_{false}; mutable std::atomic<bool> signal_present_{false};
mutable bool signal_metadata_valid_ = false;
mutable pcies2mm_signal_status_t cached_signal_{};
std::thread capture_thread_; std::thread capture_thread_;
mutable std::mutex mutex_; mutable std::mutex mutex_;
@@ -125,6 +131,8 @@ namespace gvfg::internal
size_t active_delivery_slot_ = static_cast<size_t>(-1); size_t active_delivery_slot_ = static_cast<size_t>(-1);
uint64_t latest_sequence_ = 0; uint64_t latest_sequence_ = 0;
uint64_t delivered_sequence_ = 0; uint64_t delivered_sequence_ = 0;
bool have_last_done_index_ = false;
uint32_t last_done_index_ = 0;
uint64_t wait_timeout_count_ = 0; uint64_t wait_timeout_count_ = 0;
std::chrono::steady_clock::time_point active_delivery_started_{}; std::chrono::steady_clock::time_point active_delivery_started_{};
std::chrono::steady_clock::time_point last_delivery_started_{}; std::chrono::steady_clock::time_point last_delivery_started_{};
@@ -123,6 +123,11 @@
#define VIDEO_IRQ_STATUS_OFFSET 0x038 /* WO/RO: Video IRQ status [7:0] (write=clear, read=external) */ #define VIDEO_IRQ_STATUS_OFFSET 0x038 /* WO/RO: Video IRQ status [7:0] (write=clear, read=external) */
#define VIDEO_DMA_IRQ_STATUS_OFFSET 0x03C /* WO/RO: Video DMA IRQ status [1:0] (read=external, write=clear); bit[0]=DMA done, bit[1]=reset done */ #define VIDEO_DMA_IRQ_STATUS_OFFSET 0x03C /* WO/RO: Video DMA IRQ status [1:0] (read=external, write=clear); bit[0]=DMA done, bit[1]=reset done */
#define VIDEO_DMA_SOFT_RESET_OFFSET 0x040 /* WO: DMA soft reset [31:0] (write value determines whether to send IRQ after reset) */ #define VIDEO_DMA_SOFT_RESET_OFFSET 0x040 /* WO: DMA soft reset [31:0] (write value determines whether to send IRQ after reset) */
#define VIDEO_RX_MODE_LOCKED_OFFSET 0x048 /* RO: Xilinx XAPP 1097 rx_mode_locked */
#define VIDEO_RX_T_LOCKED_OFFSET 0x04C /* RO: Xilinx XAPP 1097 rx_t_locked */
/* Temporary global control register; intentionally not relative to CHx_VIDEO_BASE. */
#define VIDEO_OUTPUT_FORMAT_REGISTER 0x080 /* WO: 1=Y210, 0=YUY2 */
/* ======================================================================== /* ========================================================================
* Audio Register Offsets (relative to CHx_AUDIO_BASE) * Audio Register Offsets (relative to CHx_AUDIO_BASE)
+54 -19
View File
@@ -548,40 +548,39 @@ struct gvfg_handle_t
gvfg_status_t pollEvent(gvfg_event_t &out, uint32_t timeoutMs) gvfg_status_t pollEvent(gvfg_event_t &out, uint32_t timeoutMs)
{ {
if (!backend || !running.load(std::memory_order_acquire)) if (!backend)
return GVFG_ESTATE; return GVFG_ESTATE;
std::unique_lock<std::mutex> lock(eventMutex); std::unique_lock<std::mutex> lock(eventMutex);
const auto eventAvailableOrStopped = [this]() const auto eventAvailable = [this]()
{ {
return !eventQueue.empty() || !running.load(std::memory_order_acquire); return !eventQueue.empty();
}; };
bool waitConditionMet = false; bool waitConditionMet = false;
if (timeoutMs == 0) if (timeoutMs == 0)
{ {
// Non-blocking: inspect the current state without sleeping. // Non-blocking: inspect the current state without sleeping.
waitConditionMet = eventAvailableOrStopped(); waitConditionMet = eventAvailable();
} }
else if (timeoutMs == GVFG_TIMEOUT_INFINITE) else if (timeoutMs == GVFG_TIMEOUT_INFINITE)
{ {
// Wake when an event arrives or capture is stopped. // Wake when an event arrives or capture is stopped.
eventCv.wait(lock, eventAvailableOrStopped); eventCv.wait(lock, eventAvailable);
waitConditionMet = true; waitConditionMet = true;
} }
else else
{ {
waitConditionMet = eventCv.wait_for(lock, waitConditionMet = eventCv.wait_for(lock,
std::chrono::milliseconds(timeoutMs), std::chrono::milliseconds(timeoutMs),
eventAvailableOrStopped); eventAvailable);
} }
if (!waitConditionMet) if (!waitConditionMet)
return GVFG_ETIMEOUT; return GVFG_ETIMEOUT;
// A wake-up without an event means capture was stopped while waiting.
if (eventQueue.empty()) if (eventQueue.empty())
return GVFG_ESTATE; return GVFG_ETIMEOUT;
out = eventQueue.front(); out = eventQueue.front();
eventQueue.pop_front(); eventQueue.pop_front();
@@ -645,6 +644,25 @@ struct gvfg_handle_t
return map_status(backend->debug_read_register(offset, outValue)); return map_status(backend->debug_read_register(offset, outValue));
} }
gvfg_status_t setVideoFormat(gvfg_pixel_format_t format)
{
if (!backend)
return GVFG_ESTATE;
pcies2mm_pixel_format_t backendFormat = PCIES2MM_PIXFMT_UNKNOWN;
if (format == GVFG_PIXFMT_YUY2)
backendFormat = PCIES2MM_PIXFMT_YUY2;
else if (format == GVFG_PIXFMT_Y210)
backendFormat = PCIES2MM_PIXFMT_Y210;
else
return GVFG_EINVAL;
const pcies2mm_status_t status = backend->set_video_format(backendFormat);
if (status != PCIES2MM_OK)
recordError(pcies2mm_error_text(status, backend.get()));
return map_status(status);
}
gvfg_status_t debugWriteRegister(uint32_t offset, uint32_t value) gvfg_status_t debugWriteRegister(uint32_t offset, uint32_t value)
{ {
if (!backend) if (!backend)
@@ -671,22 +689,31 @@ struct gvfg_handle_t
void updateRuntimeFps(uint64_t ptsNs) void updateRuntimeFps(uint64_t ptsNs)
{ {
const uint64_t prevPtsNs = lastPtsNs.exchange(ptsNs, std::memory_order_relaxed); constexpr uint64_t kFpsWindowNs = 1000000000ULL;
if (prevPtsNs != 0 && ptsNs > prevPtsNs) const uint64_t windowStart = fpsWindowStartNs.load(std::memory_order_relaxed);
if (windowStart == 0 || ptsNs <= windowStart)
{ {
const double fps = 1e9 / static_cast<double>(ptsNs - prevPtsNs); fpsWindowStartNs.store(ptsNs, std::memory_order_relaxed);
if (fps > 0.0 && fps < 1000.0) fpsWindowFrameCount.store(0, std::memory_order_relaxed);
{ return;
const double current = runtimeFps.load(std::memory_order_relaxed);
runtimeFps.store((current <= 0.0) ? fps : current * 0.9 + fps * 0.1,
std::memory_order_relaxed);
}
} }
const uint64_t frameCount = fpsWindowFrameCount.fetch_add(1, std::memory_order_relaxed) + 1;
const uint64_t elapsedNs = ptsNs - windowStart;
if (elapsedNs < kFpsWindowNs)
return;
runtimeFps.store(static_cast<double>(frameCount) * 1e9 /
static_cast<double>(elapsedNs),
std::memory_order_relaxed);
fpsWindowStartNs.store(ptsNs, std::memory_order_relaxed);
fpsWindowFrameCount.store(0, std::memory_order_relaxed);
} }
void resetRuntimeCounters() void resetRuntimeCounters()
{ {
lastPtsNs.store(0, std::memory_order_relaxed); fpsWindowStartNs.store(0, std::memory_order_relaxed);
fpsWindowFrameCount.store(0, std::memory_order_relaxed);
deliveredFrames.store(0, std::memory_order_relaxed); deliveredFrames.store(0, std::memory_order_relaxed);
deliveredWidth.store(0, std::memory_order_relaxed); deliveredWidth.store(0, std::memory_order_relaxed);
deliveredHeight.store(0, std::memory_order_relaxed); deliveredHeight.store(0, std::memory_order_relaxed);
@@ -714,7 +741,8 @@ struct gvfg_handle_t
pcies2mm_pixel_format_t pixelFormat = PCIES2MM_PIXFMT_UNKNOWN; pcies2mm_pixel_format_t pixelFormat = PCIES2MM_PIXFMT_UNKNOWN;
bool signalConnected = false; bool signalConnected = false;
mutable std::mutex stateMutex; mutable std::mutex stateMutex;
std::atomic<uint64_t> lastPtsNs{0}; std::atomic<uint64_t> fpsWindowStartNs{0};
std::atomic<uint64_t> fpsWindowFrameCount{0};
std::atomic<uint64_t> deliveredFrames{0}; std::atomic<uint64_t> deliveredFrames{0};
std::atomic<uint32_t> deliveredWidth{0}; std::atomic<uint32_t> deliveredWidth{0};
std::atomic<uint32_t> deliveredHeight{0}; std::atomic<uint32_t> deliveredHeight{0};
@@ -794,6 +822,13 @@ extern "C"
return handle->start(); return handle->start();
} }
gvfg_status_t gvfg_set_video_format(gvfg_handle handle, gvfg_pixel_format_t format)
{
if (!handle)
return GVFG_EINVAL;
return handle->setVideoFormat(format);
}
gvfg_status_t gvfg_read_frame(gvfg_handle handle, gvfg_frame_t *out_frame, uint32_t timeout_ms) gvfg_status_t gvfg_read_frame(gvfg_handle handle, gvfg_frame_t *out_frame, uint32_t timeout_ms)
{ {
if (!handle || !out_frame) if (!handle || !out_frame)