Improve GVFG audio playback and event shutdown

- Split PCM acquisition from Qt audio playback in the preview sample.
- Copy SDK-owned audio frames into a bounded application queue before release.
- Track and display dropped audio queue entries.
- Add a dedicated stop event for the SDK event-monitor thread.
- Replace periodic event-monitor wakeups with an interruptible infinite wait.
- Poll public channel events every 200 ms for responsive format and signal updates.
- Preserve finite 200 ms video and audio reads for ownership-safe worker shutdown.
This commit is contained in:
Mark.lin
2026-09-03 18:34:39 +08:00
parent 29444470db
commit 2b62a85912
4 changed files with 117 additions and 36 deletions
+86 -30
View File
@@ -22,11 +22,14 @@
#include <algorithm> #include <algorithm>
#include <chrono> #include <chrono>
#include <cstring>
#include <utility>
#include <vector> #include <vector>
namespace namespace
{ {
constexpr bool kChannel1UiVisible = false; constexpr bool kChannel1UiVisible = false;
constexpr size_t kMaxQueuedAudioFrames = 10;
QString logFilePrefix() QString logFilePrefix()
{ {
@@ -176,7 +179,7 @@ MainWindow::MainWindow(QWidget *parent)
new LogHighlighter(ui_->logEdit->document()); new LogHighlighter(ui_->logEdit->document());
ui_->statusLabel->setWordWrap(true); ui_->statusLabel->setWordWrap(true);
runtimeStatusTimer_ = new QTimer(this); runtimeStatusTimer_ = new QTimer(this);
runtimeStatusTimer_->setInterval(1000); runtimeStatusTimer_->setInterval(200);
openLogFile(); openLogFile();
connect(ui_->refreshButton, &QPushButton::clicked, this, [this]() connect(ui_->refreshButton, &QPushButton::clicked, this, [this]()
@@ -566,6 +569,11 @@ void MainWindow::startCapture(int channelIndex)
channel.audioEnabled = audioEnabled; channel.audioEnabled = audioEnabled;
channel.audioFrames.store(0, std::memory_order_relaxed); channel.audioFrames.store(0, std::memory_order_relaxed);
channel.audioBytes.store(0, std::memory_order_relaxed); channel.audioBytes.store(0, std::memory_order_relaxed);
channel.audioQueueDrops.store(0, std::memory_order_relaxed);
{
std::lock_guard<std::mutex> lock(channel.audioQueueMutex);
channel.audioQueue.clear();
}
#if GVFG_INTERNAL_DIAGNOSTICS #if GVFG_INTERNAL_DIAGNOSTICS
channel.haveDebugBaseline = false; channel.haveDebugBaseline = false;
channel.lastDebugDmaErrors = 0; channel.lastDebugDmaErrors = 0;
@@ -575,8 +583,12 @@ void MainWindow::startCapture(int channelIndex)
channel.captureThread = std::thread([this, channelIndex]() channel.captureThread = std::thread([this, channelIndex]()
{ captureReadLoop(channelIndex); }); { captureReadLoop(channelIndex); });
if (audioEnabled) if (audioEnabled)
{
channel.audioPlaybackThread = std::thread([this, channelIndex]()
{ audioPlaybackLoop(channelIndex); });
channel.audioThread = std::thread([this, channelIndex]() channel.audioThread = std::thread([this, channelIndex]()
{ audioReadLoop(channelIndex); }); { audioReadLoop(channelIndex); });
}
updateUiState(); updateUiState();
appendLog(audioEnabled appendLog(audioEnabled
? QStringLiteral("CH%1 Started video + audio | %2 Hz %3 ch %4-bit") ? QStringLiteral("CH%1 Started video + audio | %2 Hz %3 ch %4-bit")
@@ -594,6 +606,7 @@ void MainWindow::stopCapture(int channelIndex)
if (handle_ && channel.running.load(std::memory_order_acquire)) if (handle_ && channel.running.load(std::memory_order_acquire))
{ {
channel.stopRequested.store(true, std::memory_order_release); channel.stopRequested.store(true, std::memory_order_release);
channel.audioQueueReady.notify_all();
joinCaptureThread(channelIndex); joinCaptureThread(channelIndex);
joinAudioThread(channelIndex); joinAudioThread(channelIndex);
gvfg_stop_channel(handle_, channelIndex); gvfg_stop_channel(handle_, channelIndex);
@@ -757,13 +770,14 @@ void MainWindow::updateSignalStatus(bool queryHardware)
.arg(zeroCopy ? QStringLiteral("Zero-copy") : QStringLiteral("Copy")); .arg(zeroCopy ? QStringLiteral("Zero-copy") : QStringLiteral("Copy"));
if (channel.audioEnabled) if (channel.audioEnabled)
{ {
statusLines << QStringLiteral("CH%1 Audio | %2 Hz %3 ch %4-bit | frames=%5 bytes=%6") statusLines << QStringLiteral("CH%1 Audio | %2 Hz %3 ch %4-bit | frames=%5 bytes=%6 queue_drops=%7")
.arg(channelIndex) .arg(channelIndex)
.arg(channel.audioFormat.sample_rate) .arg(channel.audioFormat.sample_rate)
.arg(channel.audioFormat.channels) .arg(channel.audioFormat.channels)
.arg(channel.audioFormat.bits_per_sample) .arg(channel.audioFormat.bits_per_sample)
.arg(static_cast<qulonglong>(channel.audioFrames.load(std::memory_order_relaxed))) .arg(static_cast<qulonglong>(channel.audioFrames.load(std::memory_order_relaxed)))
.arg(static_cast<qulonglong>(channel.audioBytes.load(std::memory_order_relaxed))); .arg(static_cast<qulonglong>(channel.audioBytes.load(std::memory_order_relaxed)))
.arg(static_cast<qulonglong>(channel.audioQueueDrops.load(std::memory_order_relaxed)));
} }
statusLines << QStringLiteral("CH%1 Preview | %2 FPS | %3") statusLines << QStringLiteral("CH%1 Preview | %2 FPS | %3")
.arg(channelIndex) .arg(channelIndex)
@@ -1197,6 +1211,54 @@ void MainWindow::joinCaptureThread(int channel)
} }
void MainWindow::audioReadLoop(int channelIndex) void MainWindow::audioReadLoop(int channelIndex)
{
ChannelRuntime &channel = channels_[channelIndex];
while (!channel.stopRequested.load(std::memory_order_acquire))
{
gvfg_audio_frame_t frame{};
const gvfg_status_t status = gvfg_read_channel_audio_frame(
handle_, channelIndex, &frame, 200);
if (status == GVFG_ETIMEOUT)
continue;
if (status != GVFG_OK)
{
if (!channel.stopRequested.load(std::memory_order_acquire))
{
QMetaObject::invokeMethod(this, [this, channelIndex, status]()
{ showError(QStringLiteral("gvfg_read_channel_audio_frame"), status, channelIndex); }, Qt::QueuedConnection);
}
break;
}
std::vector<uint8_t> pcm(frame.data_size);
std::memcpy(pcm.data(), frame.data, frame.data_size);
const gvfg_status_t releaseStatus =
gvfg_release_channel_audio_frame(handle_, channelIndex, &frame);
if (releaseStatus != GVFG_OK && !channel.stopRequested.load(std::memory_order_acquire))
{
QMetaObject::invokeMethod(this, [this, channelIndex, releaseStatus]()
{ showError(QStringLiteral("gvfg_release_channel_audio_frame"), releaseStatus, channelIndex); }, Qt::QueuedConnection);
break;
}
if (releaseStatus == GVFG_OK)
{
{
std::lock_guard<std::mutex> lock(channel.audioQueueMutex);
if (channel.audioQueue.size() >= kMaxQueuedAudioFrames)
{
channel.audioQueue.pop_front();
channel.audioQueueDrops.fetch_add(1, std::memory_order_relaxed);
}
channel.audioQueue.push_back(std::move(pcm));
}
channel.audioQueueReady.notify_one();
}
}
channel.audioQueueReady.notify_all();
}
void MainWindow::audioPlaybackLoop(int channelIndex)
{ {
ChannelRuntime &channel = channels_[channelIndex]; ChannelRuntime &channel = channels_[channelIndex];
const gvfg_audio_format_t format = channel.audioFormat; const gvfg_audio_format_t format = channel.audioFormat;
@@ -1244,37 +1306,34 @@ void MainWindow::audioReadLoop(int channelIndex)
return; return;
} }
while (!channel.stopRequested.load(std::memory_order_acquire)) for (;;)
{ {
gvfg_audio_frame_t frame{}; std::vector<uint8_t> pcm;
const gvfg_status_t status = gvfg_read_channel_audio_frame(
handle_, channelIndex, &frame, 200);
if (status == GVFG_ETIMEOUT)
continue;
if (status != GVFG_OK)
{ {
if (!channel.stopRequested.load(std::memory_order_acquire)) std::unique_lock<std::mutex> lock(channel.audioQueueMutex);
{ channel.audioQueueReady.wait(lock, [&channel]() {
QMetaObject::invokeMethod(this, [this, channelIndex, status]() return channel.stopRequested.load(std::memory_order_acquire) ||
{ showError(QStringLiteral("gvfg_read_channel_audio_frame"), status, channelIndex); }, Qt::QueuedConnection); !channel.audioQueue.empty();
} });
break; if (channel.stopRequested.load(std::memory_order_acquire))
break;
pcm = std::move(channel.audioQueue.front());
channel.audioQueue.pop_front();
} }
qint64 written = 0; qint64 written = 0;
while (written < static_cast<qint64>(frame.data_size) && while (written < static_cast<qint64>(pcm.size()) &&
!channel.stopRequested.load(std::memory_order_acquire)) !channel.stopRequested.load(std::memory_order_acquire))
{ {
const qint64 result = audioOutput->write( const qint64 result = audioOutput->write(
static_cast<const char *>(frame.data) + written, reinterpret_cast<const char *>(pcm.data()) + written,
static_cast<qint64>(frame.data_size) - written); static_cast<qint64>(pcm.size()) - written);
if (result < 0) if (result < 0)
{ {
QMetaObject::invokeMethod(this, [this, channelIndex]() QMetaObject::invokeMethod(this, [this, channelIndex]()
{ {
appendLog(QStringLiteral("CH%1 Audio output write failed").arg(channelIndex)); appendLog(QStringLiteral("CH%1 Audio output write failed").arg(channelIndex));
stopCapture(channelIndex); }, Qt::QueuedConnection); stopCapture(channelIndex); }, Qt::QueuedConnection);
gvfg_release_channel_audio_frame(handle_, channelIndex, &frame);
audioSink.stop(); audioSink.stop();
return; return;
} }
@@ -1285,18 +1344,10 @@ void MainWindow::audioReadLoop(int channelIndex)
} }
written += result; written += result;
} }
if (written == static_cast<qint64>(frame.data_size)) if (written == static_cast<qint64>(pcm.size()))
{ {
channel.audioFrames.fetch_add(1, std::memory_order_relaxed); channel.audioFrames.fetch_add(1, std::memory_order_relaxed);
channel.audioBytes.fetch_add(frame.data_size, std::memory_order_relaxed); channel.audioBytes.fetch_add(pcm.size(), std::memory_order_relaxed);
}
const gvfg_status_t releaseStatus =
gvfg_release_channel_audio_frame(handle_, channelIndex, &frame);
if (releaseStatus != GVFG_OK && !channel.stopRequested.load(std::memory_order_acquire))
{
QMetaObject::invokeMethod(this, [this, channelIndex, releaseStatus]()
{ showError(QStringLiteral("gvfg_release_channel_audio_frame"), releaseStatus, channelIndex); }, Qt::QueuedConnection);
break;
} }
} }
audioSink.stop(); audioSink.stop();
@@ -1306,4 +1357,9 @@ void MainWindow::joinAudioThread(int channel)
{ {
if (channels_[channel].audioThread.joinable()) if (channels_[channel].audioThread.joinable())
channels_[channel].audioThread.join(); channels_[channel].audioThread.join();
channels_[channel].audioQueueReady.notify_all();
if (channels_[channel].audioPlaybackThread.joinable())
channels_[channel].audioPlaybackThread.join();
std::lock_guard<std::mutex> lock(channels_[channel].audioQueueMutex);
channels_[channel].audioQueue.clear();
} }
+9
View File
@@ -9,9 +9,12 @@
#include <array> #include <array>
#include <atomic> #include <atomic>
#include <condition_variable>
#include <cstdint> #include <cstdint>
#include <deque>
#include <mutex> #include <mutex>
#include <thread> #include <thread>
#include <vector>
class QCloseEvent; class QCloseEvent;
class PreviewWindow; class PreviewWindow;
@@ -45,10 +48,15 @@ private:
std::atomic<bool> frameAvailable{false}; std::atomic<bool> frameAvailable{false};
std::thread captureThread; std::thread captureThread;
std::thread audioThread; std::thread audioThread;
std::thread audioPlaybackThread;
std::mutex audioQueueMutex;
std::condition_variable audioQueueReady;
std::deque<std::vector<uint8_t>> audioQueue;
bool audioEnabled = false; bool audioEnabled = false;
gvfg_audio_format_t audioFormat{}; gvfg_audio_format_t audioFormat{};
std::atomic<uint64_t> audioFrames{0}; std::atomic<uint64_t> audioFrames{0};
std::atomic<uint64_t> audioBytes{0}; std::atomic<uint64_t> audioBytes{0};
std::atomic<uint64_t> audioQueueDrops{0};
std::atomic<double> getFrameAverageMs{0.0}; std::atomic<double> getFrameAverageMs{0.0};
std::atomic<double> getFrameMaximumMs{0.0}; std::atomic<double> getFrameMaximumMs{0.0};
std::atomic<double> getFrameWindowMaximumMs{0.0}; std::atomic<double> getFrameWindowMaximumMs{0.0};
@@ -94,6 +102,7 @@ private:
void appendLog(const QString &message); void appendLog(const QString &message);
void captureReadLoop(int channel); void captureReadLoop(int channel);
void audioReadLoop(int channel); void audioReadLoop(int channel);
void audioPlaybackLoop(int channel);
void joinCaptureThread(int channel); void joinCaptureThread(int channel);
void joinAudioThread(int channel); void joinAudioThread(int channel);
@@ -1005,9 +1005,11 @@ namespace gvfg::internal
format_change_event_ = CreateEventW(nullptr, FALSE, FALSE, nullptr); format_change_event_ = CreateEventW(nullptr, FALSE, FALSE, nullptr);
plug_in_event_ = CreateEventW(nullptr, FALSE, FALSE, nullptr); plug_in_event_ = CreateEventW(nullptr, FALSE, FALSE, nullptr);
plug_out_event_ = CreateEventW(nullptr, FALSE, FALSE, nullptr); plug_out_event_ = CreateEventW(nullptr, FALSE, FALSE, nullptr);
monitor_stop_event_ = CreateEventW(nullptr, FALSE, FALSE, nullptr);
if (!dma_event_ || !extra_video_event_ || if (!dma_event_ || !extra_video_event_ ||
(audio_enabled_ && (!audio_event_ || !extra_audio_event_)) || (audio_enabled_ && (!audio_event_ || !extra_audio_event_)) ||
!format_change_event_ || !plug_in_event_ || !plug_out_event_) !format_change_event_ || !plug_in_event_ || !plug_out_event_ ||
!monitor_stop_event_)
return false; return false;
if (!register_event(channelIndex, GIGA_IOCTL_EVENT_VIDEO_DMA, dma_event_)) if (!register_event(channelIndex, GIGA_IOCTL_EVENT_VIDEO_DMA, dma_event_))
@@ -1084,6 +1086,11 @@ namespace gvfg::internal
CloseHandle(plug_out_event_); CloseHandle(plug_out_event_);
plug_out_event_ = nullptr; plug_out_event_ = nullptr;
} }
if (monitor_stop_event_)
{
CloseHandle(monitor_stop_event_);
monitor_stop_event_ = nullptr;
}
} }
bool PcieS2mmCaptureSession::start_event_monitoring() bool PcieS2mmCaptureSession::start_event_monitoring()
@@ -1128,6 +1135,8 @@ namespace gvfg::internal
SetEvent(extra_video_event_); SetEvent(extra_video_event_);
if (extra_audio_event_) if (extra_audio_event_)
SetEvent(extra_audio_event_); SetEvent(extra_audio_event_);
if (monitor_stop_event_)
SetEvent(monitor_stop_event_);
if (capture_thread_.joinable()) if (capture_thread_.joinable())
capture_thread_.join(); capture_thread_.join();
@@ -1162,15 +1171,19 @@ namespace gvfg::internal
void PcieS2mmCaptureSession::capture_thread_proc() void PcieS2mmCaptureSession::capture_thread_proc()
{ {
const uint32_t channel = active_channel(); const uint32_t channel = active_channel();
HANDLE waitHandles[] = {format_change_event_, plug_in_event_, plug_out_event_}; HANDLE waitHandles[] = {
constexpr DWORD waitHandleCount = 3; monitor_stop_event_,
format_change_event_,
plug_in_event_,
plug_out_event_};
constexpr DWORD waitHandleCount = 4;
while (monitoring_.load(std::memory_order_acquire)) while (monitoring_.load(std::memory_order_acquire))
{ {
const DWORD waitResult = WaitForMultipleObjects(waitHandleCount, const DWORD waitResult = WaitForMultipleObjects(waitHandleCount,
waitHandles, waitHandles,
FALSE, FALSE,
1000); INFINITE);
if (!monitoring_.load(std::memory_order_acquire)) if (!monitoring_.load(std::memory_order_acquire))
break; break;
if (waitResult == WAIT_TIMEOUT) if (waitResult == WAIT_TIMEOUT)
@@ -1188,14 +1201,16 @@ namespace gvfg::internal
switch (waitResult - WAIT_OBJECT_0) switch (waitResult - WAIT_OBJECT_0)
{ {
case 0: case 0:
break;
case 1:
PCIES2MM_LOG("event: FORMAT_CHANGE"); PCIES2MM_LOG("event: FORMAT_CHANGE");
handle_format_change_event(channel); handle_format_change_event(channel);
break; break;
case 1: case 2:
PCIES2MM_LOG("event: PLUG_IN"); PCIES2MM_LOG("event: PLUG_IN");
handle_plugin_event(channel); handle_plugin_event(channel);
break; break;
case 2: case 3:
PCIES2MM_LOG("event: PLUG_OUT"); PCIES2MM_LOG("event: PLUG_OUT");
handle_unplug_event(channel); handle_unplug_event(channel);
break; break;
@@ -113,6 +113,7 @@ namespace gvfg::internal
HANDLE format_change_event_ = nullptr; HANDLE format_change_event_ = nullptr;
HANDLE plug_in_event_ = nullptr; HANDLE plug_in_event_ = nullptr;
HANDLE plug_out_event_ = nullptr; HANDLE plug_out_event_ = nullptr;
HANDLE monitor_stop_event_ = nullptr;
pcies2mm_stream_desc_t stream_desc_{}; pcies2mm_stream_desc_t stream_desc_{};
uint32_t stream_bit_depth_ = 8; uint32_t stream_bit_depth_ = 8;