Add HDMI audio input queries and split OSD into a helper in GVFG SDK 3.2

- Expose HDMI audio input information through the capture API and refresh the bundled Gigabyte library.
- Move OSD rendering into gvfg_osd.dll, connect channel OSD through the capture frame processor, and remove the experimental in-place zero-copy OSD path.
- Update playback integration, the customer API documentation, and the internal build guide.

Validation: git diff --cached --check passed. The MSVC Release SDK build passed. Capture hardware and runtime behavior were not tested.
This commit is contained in:
2026-11-25 09:35:49 +08:00
parent 7a7027391e
commit a47ab190bc
26 changed files with 1080 additions and 867 deletions
@@ -183,6 +183,7 @@ namespace gvfg::internal
if (channel_open_ && context_)
GvfgCloseVideoChn(context_, channel_);
channel_open_ = false;
driver_stream_running_ = false;
{
std::lock_guard<std::mutex> lock(state_mutex_);
video_info_valid_ = false;
@@ -263,15 +264,24 @@ namespace gvfg::internal
if (openStatus != GVFG_OK)
return openStatus;
gvfg_pixel_format_t requestedFormat = GVFG_PIXFMT_UNKNOWN;
const gvfg_status_t readStatus = refresh_video_info();
if (readStatus != GVFG_OK)
return readStatus;
gvfg_pixel_format_t previousFormat = GVFG_PIXFMT_UNKNOWN;
bool signalConnected = false;
{
std::lock_guard<std::mutex> lock(state_mutex_);
requestedFormat = requested_video_format_;
previousFormat = requested_video_format_;
signalConnected = cached_signal_.connected != 0;
if (signalConnected && cached_signal_.pixel_format == format)
{
requested_video_format_ = format;
format_change_pending_ = false;
return GVFG_OK;
}
}
if (requestedFormat == format)
return GVFG_OK;
if (!events_.hVideoFormatChangedEvent)
return reject(GVFG_EIO, "Capture backend did not provide a video-format event");
#ifndef NDEBUG
@@ -286,14 +296,31 @@ namespace gvfg::internal
: GVFG_VIDEO_COLOR_DEPTH_8_BITS;
const gvfg_status_t status = from_vendor(
GvfgSetVideoColorDepth(context_, channel_, colorDepth), "GvfgSetVideoColorDepth");
if (status == GVFG_OK)
if (status != GVFG_OK)
return status;
{
std::lock_guard<std::mutex> lock(state_mutex_);
requested_video_format_ = format;
format_change_pending_ = true;
video_info_valid_ = false;
}
return status;
// Without a locked input, verify the accepted request at start.
if (!signalConnected)
return GVFG_OK;
gvfg_signal_status_t signal{};
const gvfg_status_t verifyStatus = get_signal_status(signal, true);
if (verifyStatus == GVFG_OK && signal.connected)
return GVFG_OK;
{
std::lock_guard<std::mutex> lock(state_mutex_);
requested_video_format_ = previousFormat;
format_change_pending_ = false;
}
if (verifyStatus != GVFG_OK)
return verifyStatus;
return reject(GVFG_ETIMEOUT, "Input signal lost while verifying capture video format");
}
gvfg_status_t GigabyteCaptureSession::refresh_video_info()
@@ -325,7 +352,8 @@ namespace gvfg::internal
return GVFG_OK;
}
gvfg_status_t GigabyteCaptureSession::get_signal_status(gvfg_signal_status_t &out)
gvfg_status_t GigabyteCaptureSession::get_signal_status(gvfg_signal_status_t &out,
bool verifyRequestedFormat)
{
const gvfg_status_t openStatus = ensure_vendor_channel_open();
if (openStatus != GVFG_OK)
@@ -352,33 +380,30 @@ namespace gvfg::internal
return reject(GVFG_EIO, "Capture video-format event wait failed");
if (wait == WAIT_OBJECT_0)
Sleep(kVideoFormatSettleMs);
// Setting the already-active color depth does not necessarily emit a
// format-change event. Query once after the wait and accept the
// request when the hardware is already reporting the requested format.
const gvfg_status_t status = refresh_video_info();
if (status != GVFG_OK)
return status;
bool formatMatches = false;
{
std::lock_guard<std::mutex> lock(state_mutex_);
format_change_pending_ = false;
formatMatches = cached_signal_.pixel_format == requestedFormat;
out = cached_signal_;
}
if (!formatMatches)
return reject(GVFG_ETIMEOUT,
"Capture video format did not match the requested format");
return GVFG_OK;
}
// The already-active color depth may not emit an event. Read the
// hardware status even when the event wait times out.
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_;
{
std::lock_guard<std::mutex> lock(state_mutex_);
if (formatChangePending && requested_video_format_ == requestedFormat)
format_change_pending_ = false;
out = cached_signal_;
}
if ((formatChangePending || verifyRequestedFormat) && out.connected &&
requestedFormat != GVFG_PIXFMT_UNKNOWN && out.pixel_format != requestedFormat)
{
char message[128]{};
std::snprintf(message, sizeof(message),
"Capture channel %d expected %s, hardware reports %s",
static_cast<int>(channel_), gvfg_pixel_format_name(requestedFormat),
gvfg_pixel_format_name(static_cast<gvfg_pixel_format_t>(out.pixel_format)));
return reject(GVFG_ETIMEOUT, message);
}
return GVFG_OK;
}
@@ -406,7 +431,7 @@ namespace gvfg::internal
GVFG_HDMI_VIDEO_INPUT_INFO info{};
{
std::lock_guard<std::mutex> captureLock(capture_mutex_);
std::lock_guard<std::mutex> inputInfoLock(input_info_mutex_);
const gvfg_status_t status = from_vendor(
GvfgGetHdmiVideoInputInfo(context_, channel_, &info), "GvfgGetHdmiVideoInputInfo");
if (status != GVFG_OK)
@@ -438,6 +463,49 @@ namespace gvfg::internal
return GVFG_OK;
}
gvfg_status_t GigabyteCaptureSession::get_hdmi_audio_info(gvfg_hdmi_audio_info_t &out)
{
const gvfg_status_t openStatus = ensure_vendor_channel_open();
if (openStatus != GVFG_OK)
return openStatus;
GVFG_HDMI_AUDIO_INPUT_INFO info{};
{
std::lock_guard<std::mutex> inputInfoLock(input_info_mutex_);
const gvfg_status_t status = from_vendor(
GvfgGetHdmiAudioInputInfo(context_, channel_, &info), "GvfgGetHdmiAudioInputInfo");
if (status != GVFG_OK)
return status;
}
out.connected = info.AudioSignalLock != 0;
out.sample_frequency = info.SamplesPerSec;
out.bits_per_sample = info.BitsPerSample;
out.channels = info.Channels;
out.format = info.Format;
if (!out.connected)
return GVFG_OK;
// Indexed by GVFG_HDMI_AUDIO_SAMPLE_FREQ and GVFG_HDMI_AUDIO_FORMAT.
constexpr const char *frequencies[] = {
"32 kHz", "44.1 kHz", "48 kHz", "88.2 kHz", "96 kHz", "176.4 kHz",
"192 kHz", "HBR", "From stream"
};
constexpr const char *formats[] = {
"Unknown", "Linear PCM", "AC-3", "MPEG-1", "MP3", "MPEG-2", "AAC", "DTS",
"ATRAC", "One Bit Audio", "Dolby Digital", "DTS-HD", "MAT", "DST", "WMA Pro"
};
const char *frequency = out.sample_frequency < sizeof(frequencies) / sizeof(frequencies[0])
? frequencies[out.sample_frequency] : "Unknown";
const char *format = out.format < sizeof(formats) / sizeof(formats[0])
? formats[out.format] : "Unknown";
if (out.format == GVFG_HDMI_AUD_FMT_COMPRESSED_AUDIO)
format = "Compressed Audio";
strncpy_s(out.sample_frequency_name, frequency, _TRUNCATE);
strncpy_s(out.format_name, format, _TRUNCATE);
return GVFG_OK;
}
gvfg_status_t GigabyteCaptureSession::get_chip_info(gvfg_chip_info_t &out)
{
const gvfg_status_t openStatus = ensure_vendor_channel_open();
@@ -469,9 +537,20 @@ namespace gvfg::internal
const gvfg_status_t openStatus = ensure_vendor_channel_open();
if (openStatus != GVFG_OK)
return openStatus;
std::lock_guard<std::mutex> inputInfoLock(input_info_mutex_);
GVFG_SDI_VIDEO_INFO info{};
gvfg_status_t status = from_vendor(
GvfgGetSdiVideoInputInfo(context_, channel_, &info), "GvfgGetSdiVideoInputInfo");
const GVFG_HRESULT result = GvfgGetSdiVideoInputInfo(context_, channel_, &info);
char debugMessage[256];
std::snprintf(debugMessage, sizeof(debugMessage),
"[GVFG] GvfgGetSdiVideoInputInfo CH%" PRIu32
" returned 0x%08" PRIX32 " | VideoSignalLock=%" PRIu32
" | ErrorCount=%" PRIu32 "\n",
static_cast<uint32_t>(channel_), static_cast<uint32_t>(result),
static_cast<uint32_t>(info.VideoSignalLock),
static_cast<uint32_t>(info.ErrorCount));
OutputDebugStringA(debugMessage);
gvfg_status_t status = from_vendor(result, "GvfgGetSdiVideoInputInfo");
if (status != GVFG_OK)
return status;
GVFG_SDI_VIDEO_INFO_STR text{};
@@ -505,12 +584,7 @@ namespace gvfg::internal
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)
if (!running_)
{
const gvfg_status_t status = refresh_audio_info();
if (status != GVFG_OK)
@@ -518,6 +592,10 @@ namespace gvfg::internal
}
std::lock_guard<std::mutex> lock(state_mutex_);
out = {};
if (recovery_pending_)
return GVFG_ETIMEOUT;
if (!audio_info_valid_)
return audio_info_status_;
out.sample_rate = audio_info_.SamplesPerSec;
out.channels = audio_info_.Channels;
out.bits_per_sample = audio_info_.BitsPerSample;
@@ -528,14 +606,19 @@ namespace gvfg::internal
gvfg_status_t GigabyteCaptureSession::refresh_audio_info()
{
GVFG_AUDIO_INFO info{};
std::lock_guard<std::mutex> captureLock(capture_mutex_);
const gvfg_status_t status = from_vendor(
GvfgGetAudioInfo(context_, channel_, &info), "GvfgGetAudioInfo");
if (status != GVFG_OK)
return status;
std::lock_guard<std::mutex> lock(state_mutex_);
audio_info_ = info;
audio_info_valid_ = true;
return GVFG_OK;
audio_info_ = {};
audio_info_status_ = status;
audio_info_valid_ = status == GVFG_OK && info.cbBufSize && info.SamplesPerSec &&
info.Channels && info.BitsPerSample;
if (audio_info_valid_)
audio_info_ = info;
else if (status == GVFG_OK)
audio_info_status_ = reject(GVFG_ETIMEOUT, "Capture audio format is unavailable");
return audio_info_status_;
}
gvfg_status_t GigabyteCaptureSession::set_event_callback(
@@ -554,14 +637,20 @@ namespace gvfg::internal
const gvfg_status_t openStatus = ensure_vendor_channel_open();
if (openStatus != GVFG_OK)
return openStatus;
// Clear stale frame notifications without consuming format or input events.
const gvfg_status_t status = reset_frame_events();
configured_ = status == GVFG_OK;
return status;
}
gvfg_status_t GigabyteCaptureSession::reset_frame_events()
{
// Preserve format and input events for the monitor.
for (HANDLE frameEvent : {events_.hVideoFrameInEvent, events_.hVideoExtraFrame,
events_.hAudioFrameInEvent, events_.hAudioExtraFrame})
{
if (frameEvent && !ResetEvent(frameEvent))
return reject(GVFG_EIO, "Capture frame event reset failed");
}
configured_ = true;
return GVFG_OK;
}
@@ -580,6 +669,7 @@ namespace gvfg::internal
"GvfgStartCapture");
if (status != GVFG_OK)
return status;
driver_stream_running_ = true;
{
std::lock_guard<std::mutex> lock(state_mutex_);
frame_held_ = false;
@@ -613,12 +703,14 @@ namespace gvfg::internal
if (wasRunning && channel_open_ && context_)
{
std::lock_guard<std::mutex> captureLock(capture_mutex_);
const gvfg_status_t stopStatus = from_vendor(GvfgStopCapture(context_, channel_),
"GvfgStopCapture");
const gvfg_status_t stopStatus = driver_stream_running_
? from_vendor(GvfgStopCapture(context_, channel_), "GvfgStopCapture")
: GVFG_OK;
if (result == GVFG_OK)
result = stopStatus;
if (stopStatus == GVFG_OK)
{
driver_stream_running_ = false;
#ifndef NDEBUG
if (events_.hVideoFormatChangedEvent &&
WaitForSingleObject(events_.hVideoFormatChangedEvent, 0) == WAIT_OBJECT_0)
@@ -641,10 +733,14 @@ namespace gvfg::internal
*acquisitionBeginNs = 0;
if (!running_ || !context_)
return reject(GVFG_ESTATE, "Capture frame read rejected: stream is not running");
uint64_t generation = 0;
{
std::lock_guard<std::mutex> lock(state_mutex_);
generation = signal_generation_;
if (frame_held_)
return reject(GVFG_ESTATE, "Capture frame read rejected: previous frame is held");
if (!recovery_pending_ && !video_info_valid_ && video_info_status_ != GVFG_ETIMEOUT)
return video_info_status_;
}
std::array<HANDLE, 4> handles{stop_event_, recovery_event_,
@@ -674,19 +770,23 @@ namespace gvfg::internal
++extra_video_event_wakes_;
}
std::lock_guard<std::mutex> captureLock(capture_mutex_);
gvfg_signal_status_t signal{};
size_t bytes = 0;
{
std::lock_guard<std::mutex> lock(state_mutex_);
if (!running_)
return GVFG_ESTATE;
if (recovery_pending_ || generation != signal_generation_)
return GVFG_ETIMEOUT;
if (!video_info_valid_)
return video_info_status_;
signal = cached_signal_;
bytes = video_info_.cbBufSize;
}
if (!signal.connected || signal.width == 0 || signal.height == 0)
return GVFG_ETIMEOUT;
size_t bytes = 0;
{
std::lock_guard<std::mutex> lock(state_mutex_);
bytes = video_info_.cbBufSize;
}
const void *data = nullptr;
void *zeroCopyData = nullptr;
gvfg_status_t status = GVFG_OK;
@@ -694,11 +794,8 @@ namespace gvfg::internal
{
void *buffer = nullptr;
const auto begin = std::chrono::steady_clock::now();
{
std::lock_guard<std::mutex> captureLock(capture_mutex_);
status = from_vendor(GvfgGetVideoFrameZeroCopy(context_, channel_, &buffer),
"GvfgGetVideoFrameZeroCopy");
}
status = from_vendor(GvfgGetVideoFrameZeroCopy(context_, channel_, &buffer),
"GvfgGetVideoFrameZeroCopy");
const auto end = std::chrono::steady_clock::now();
record_get_frame_timing(std::chrono::duration<double, std::micro>(end - begin).count());
data = buffer;
@@ -709,12 +806,9 @@ namespace gvfg::internal
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");
}
status = from_vendor(GvfgGetVideoFrame(context_, channel_, copy_buffer_.data(),
static_cast<ULONG>(copy_buffer_.size())),
"GvfgGetVideoFrame");
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();
@@ -750,20 +844,6 @@ namespace gvfg::internal
return copy_buffer_.data();
}
uint8_t *GigabyteCaptureSession::experimental_zero_copy_frame_data(const gvfg_frame_t &frame)
{
#ifdef GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE
std::lock_guard<std::mutex> lock(state_mutex_);
if (!zero_copy_enabled_ || !frame_held_ || !held_zero_copy_data_ ||
frame.data != held_zero_copy_data_ || frame.data_size != held_zero_copy_bytes_)
return nullptr;
return static_cast<uint8_t *>(held_zero_copy_data_);
#else
(void)frame;
return nullptr;
#endif
}
gvfg_status_t GigabyteCaptureSession::release_frame()
{
{
@@ -779,25 +859,31 @@ namespace gvfg::internal
return GVFG_OK;
}
void GigabyteCaptureSession::get_cached_signal_status(gvfg_signal_status_t &out) const
gvfg_status_t GigabyteCaptureSession::get_cached_signal_status(gvfg_signal_status_t &out) const
{
std::lock_guard<std::mutex> lock(state_mutex_);
out = {};
if (recovery_pending_)
return GVFG_ETIMEOUT;
if (!video_info_valid_)
return video_info_status_;
out = cached_signal_;
return GVFG_OK;
}
gvfg_status_t GigabyteCaptureSession::wait_audio(
uint32_t timeoutMs, void *destination, uint32_t destinationCapacity, uint32_t &outBytes)
uint32_t timeoutMs, std::vector<uint8_t> &buffer, GigabyteAudioInfo &format)
{
outBytes = 0;
if (!running_ || !audio_enabled_ || !destination)
format = {};
if (!running_ || !audio_enabled_)
return reject(GVFG_ESTATE, "Capture audio read rejected");
uint32_t frameBytes = 0;
uint64_t generation = 0;
{
std::lock_guard<std::mutex> lock(state_mutex_);
frameBytes = audio_info_.cbBufSize;
generation = signal_generation_;
if (!recovery_pending_ && !audio_info_valid_ && audio_info_status_ != GVFG_ETIMEOUT)
return audio_info_status_;
}
if (frameBytes == 0 || frameBytes > destinationCapacity)
return reject(GVFG_EINVAL, "Capture audio destination is too small");
if (!events_.hAudioFrameInEvent)
return reject(GVFG_EIO, "Capture backend did not provide an audio-frame event");
@@ -814,22 +900,30 @@ namespace gvfg::internal
return wait_for_recovery(timeoutMs);
if (wait != WAIT_OBJECT_0 + 2 && wait != WAIT_OBJECT_0 + 3)
return reject(GVFG_EIO, "Capture audio event wait failed");
std::lock_guard<std::mutex> captureLock(capture_mutex_);
{
std::lock_guard<std::mutex> lock(state_mutex_);
if (!running_)
return GVFG_ESTATE;
if (recovery_pending_ || generation != signal_generation_)
return GVFG_ETIMEOUT;
if (!audio_info_valid_)
return audio_info_status_;
format.sample_rate = audio_info_.SamplesPerSec;
format.channels = audio_info_.Channels;
format.bits_per_sample = audio_info_.BitsPerSample;
format.frame_bytes = audio_info_.cbBufSize;
if (wait == WAIT_OBJECT_0 + 2)
++audio_event_wakes_;
else
++extra_audio_event_wakes_;
}
gvfg_status_t status = GVFG_OK;
{
std::lock_guard<std::mutex> captureLock(capture_mutex_);
status = from_vendor(GvfgGetAudioFrame(context_, channel_, destination, frameBytes),
"GvfgGetAudioFrame");
}
buffer.resize(format.frame_bytes);
const gvfg_status_t status = from_vendor(
GvfgGetAudioFrame(context_, channel_, buffer.data(), format.frame_bytes),
"GvfgGetAudioFrame");
if (status != GVFG_OK)
return status;
outBytes = frameBytes;
{
std::lock_guard<std::mutex> lock(state_mutex_);
++audio_frames_from_lib_;
@@ -880,39 +974,10 @@ namespace gvfg::internal
const int kind = kinds[wait - WAIT_OBJECT_0];
if (kind == 0 || !monitoring_)
return;
if (kind == 1)
{
#ifndef NDEBUG
OutputDebugStringA("[GVFG] Received VIDEO_FORMAT_CHANGED\n");
#endif
refresh_video_info();
emit_event(GVFG_EVENT_VIDEO_FORMAT_CHANGED);
}
else if (kind == 2)
{
refresh_video_info();
if (running_)
{
recovery_status_ = GVFG_OK;
recovery_pending_ = true;
SetEvent(recovery_event_);
recover_stream_after_plugin();
// Recovery restarts the vendor stream. Refresh the geometry
// again before publishing the plug-in event to clients.
refresh_video_info();
}
emit_event(GVFG_EVENT_VIDEO_INPUT_PLUGIN);
}
else if (kind == 3)
{
{
std::lock_guard<std::mutex> lock(state_mutex_);
cached_signal_ = {};
cached_signal_.channel = channel_;
video_info_valid_ = false;
}
emit_event(GVFG_EVENT_VIDEO_INPUT_UNPLUG);
}
constexpr std::array<gvfg_event_type_t, 3> signalEvents{
GVFG_EVENT_VIDEO_FORMAT_CHANGED, GVFG_EVENT_VIDEO_INPUT_PLUGIN,
GVFG_EVENT_VIDEO_INPUT_UNPLUG};
handle_signal_event(signalEvents[static_cast<size_t>(kind - 1)]);
}
}
@@ -1042,7 +1107,100 @@ namespace gvfg::internal
return status;
}
gvfg_status_t GigabyteCaptureSession::recover_stream_after_plugin()
void GigabyteCaptureSession::handle_signal_event(gvfg_event_type_t event)
{
const bool unplugged = event == GVFG_EVENT_VIDEO_INPUT_UNPLUG;
GVFG_VIDEO_INFO previousVideo{};
GVFG_AUDIO_INFO previousAudio{};
bool previousVideoValid = false;
bool previousAudioValid = false;
{
std::lock_guard<std::mutex> captureLock(capture_mutex_);
std::lock_guard<std::mutex> stateLock(state_mutex_);
if (!running_)
return;
++signal_generation_;
previousVideo = video_info_;
previousAudio = audio_info_;
previousVideoValid = video_info_valid_;
previousAudioValid = audio_info_valid_;
cached_signal_ = {};
cached_signal_.channel = channel_;
video_info_ = {};
audio_info_ = {};
video_info_valid_ = unplugged;
audio_info_valid_ = false;
video_info_status_ = GVFG_ETIMEOUT;
audio_info_status_ = GVFG_ETIMEOUT;
recovery_status_ = GVFG_OK;
recovery_pending_ = !unplugged;
if (recovery_pending_)
SetEvent(recovery_event_);
}
if (!unplugged)
{
gvfg_signal_status_t signal{};
gvfg_status_t status = get_signal_status(signal, true);
if (status == GVFG_OK && !signal.connected)
status = reject(GVFG_ETIMEOUT, "Input signal is not locked during capture recovery");
gvfg_status_t audioStatus = GVFG_OK;
if (status == GVFG_OK && audio_enabled_)
audioStatus = refresh_audio_info();
bool restart = event == GVFG_EVENT_VIDEO_INPUT_PLUGIN || !previousVideoValid;
{
std::lock_guard<std::mutex> lock(state_mutex_);
restart = restart || previousVideo.Fourcc != video_info_.Fourcc ||
previousVideo.Width != video_info_.Width ||
previousVideo.Height != video_info_.Height ||
previousVideo.cbBufSize != video_info_.cbBufSize ||
previousVideo.VideoSignalLock != video_info_.VideoSignalLock ||
(audio_enabled_ && audio_info_valid_ &&
(!previousAudioValid ||
previousAudio.SamplesPerSec != audio_info_.SamplesPerSec ||
previousAudio.Channels != audio_info_.Channels ||
previousAudio.BitsPerSample != audio_info_.BitsPerSample ||
previousAudio.cbBufSize != audio_info_.cbBufSize));
}
if (status == GVFG_OK && restart)
{
status = restart_stream_after_signal_change();
if (status == GVFG_OK)
status = get_signal_status(signal, true);
if (status == GVFG_OK && !signal.connected)
status = reject(GVFG_ETIMEOUT, "Input signal lost after capture restarted");
if (status == GVFG_OK && audio_enabled_)
audioStatus = refresh_audio_info();
}
{
std::lock_guard<std::mutex> lock(state_mutex_);
if (status != GVFG_OK)
{
video_info_valid_ = false;
audio_info_valid_ = false;
video_info_status_ = status;
audio_info_status_ = status;
}
else if (audioStatus != GVFG_OK)
{
audio_info_valid_ = false;
audio_info_status_ = audioStatus;
}
recovery_status_ = status;
recovery_pending_ = false;
ResetEvent(recovery_event_);
}
recovery_cv_.notify_all();
}
if (running_)
emit_event(event);
}
gvfg_status_t GigabyteCaptureSession::restart_stream_after_signal_change()
{
{
std::unique_lock<std::mutex> stateLock(state_mutex_);
@@ -1051,26 +1209,22 @@ namespace gvfg::internal
}
std::lock_guard<std::mutex> captureLock(capture_mutex_);
if (!recovery_pending_)
{
ResetEvent(recovery_event_);
return GVFG_OK;
}
if (!running_)
return GVFG_ESTATE;
if (driver_stream_running_)
{
recovery_pending_ = false;
ResetEvent(recovery_event_);
recovery_cv_.notify_all();
return GVFG_OK;
const gvfg_status_t stopStatus =
from_vendor(GvfgStopCapture(context_, channel_), "GvfgStopCapture");
if (stopStatus != GVFG_OK)
return stopStatus;
driver_stream_running_ = false;
}
gvfg_status_t status = from_vendor(GvfgStopCapture(context_, channel_), "GvfgStopCapture");
if (status == GVFG_OK)
status = from_vendor(GvfgStartCapture(context_, channel_), "GvfgStartCapture");
recovery_status_ = status;
recovery_pending_ = false;
ResetEvent(recovery_event_);
recovery_cv_.notify_all();
const gvfg_status_t resetStatus = reset_frame_events();
if (resetStatus != GVFG_OK)
return resetStatus;
const gvfg_status_t status =
from_vendor(GvfgStartCapture(context_, channel_), "GvfgStartCapture");
driver_stream_running_ = status == GVFG_OK;
return status;
}
@@ -46,10 +46,12 @@ namespace gvfg::internal
bool zero_copy_enabled() const { return zero_copy_enabled_; }
gvfg_status_t set_audio_enabled(bool enabled);
gvfg_status_t set_video_format(gvfg_pixel_format_t format);
gvfg_status_t get_signal_status(gvfg_signal_status_t &out);
void get_cached_signal_status(gvfg_signal_status_t &out) const;
gvfg_status_t get_signal_status(gvfg_signal_status_t &out,
bool verifyRequestedFormat);
gvfg_status_t get_cached_signal_status(gvfg_signal_status_t &out) const;
gvfg_status_t get_device_capabilities(gvfg_debug_device_capabilities_t &out);
gvfg_status_t get_sdi_info(gvfg_sdi_info_t &out);
gvfg_status_t get_hdmi_audio_info(gvfg_hdmi_audio_info_t &out);
gvfg_status_t get_hdmi_info(gvfg_hdmi_info_t &out);
gvfg_status_t get_chip_info(gvfg_chip_info_t &out);
gvfg_status_t set_user_led(bool on);
@@ -63,10 +65,8 @@ namespace gvfg::internal
// Internal writable access only to the currently held SDK-owned copy.
// Driver zero-copy buffers are never returned. Valid until release.
uint8_t *writable_copy_frame_data(const gvfg_frame_t &frame);
// Opt-in test candidate only, not a driver write/hold guarantee.
uint8_t *experimental_zero_copy_frame_data(const gvfg_frame_t &frame);
gvfg_status_t wait_audio(uint32_t timeoutMs, void *destination,
uint32_t destinationCapacity, uint32_t &outBytes);
gvfg_status_t wait_audio(uint32_t timeoutMs, std::vector<uint8_t> &buffer,
GigabyteAudioInfo &format);
gvfg_status_t release_frame();
void fill_debug_stats(gvfg_debug_backend_stats_t &out);
gvfg_status_t debug_read_register(uint32_t offset, uint32_t &outValue);
@@ -80,7 +80,9 @@ 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();
void handle_signal_event(gvfg_event_type_t event);
gvfg_status_t restart_stream_after_signal_change();
gvfg_status_t reset_frame_events();
gvfg_status_t wait_for_recovery(uint32_t timeoutMs);
gvfg_status_t refresh_video_info();
gvfg_status_t refresh_audio_info();
@@ -98,6 +100,9 @@ namespace gvfg::internal
bool events_created_ = false;
bool channel_open_ = false;
bool video_info_valid_ = false;
gvfg_status_t video_info_status_ = GVFG_ETIMEOUT;
gvfg_status_t audio_info_status_ = GVFG_ETIMEOUT;
uint64_t signal_generation_ = 0;
bool format_change_pending_ = false;
gvfg_pixel_format_t requested_video_format_ = GVFG_PIXFMT_UNKNOWN;
bool audio_info_valid_ = false;
@@ -108,6 +113,7 @@ namespace gvfg::internal
bool configured_ = false;
bool zero_copy_enabled_ = false;
bool audio_enabled_ = false;
bool driver_stream_running_ = false; // Protected by capture_mutex_ while open.
std::atomic<bool> running_{false};
std::atomic<bool> recovery_pending_{false};
std::atomic<gvfg_status_t> recovery_status_{GVFG_OK};
@@ -119,6 +125,7 @@ namespace gvfg::internal
mutable std::mutex state_mutex_;
std::condition_variable recovery_cv_;
std::mutex capture_mutex_;
std::mutex input_info_mutex_;
std::vector<uint8_t> copy_buffer_;
bool frame_held_ = false;
void *held_zero_copy_data_ = nullptr;
-745
View File
@@ -1,745 +0,0 @@
#include "gvfg_gpu_osd.h"
#include "gvfg_osd.h"
#include <d3d11_4.h>
#include <d3dcompiler.h>
#include <wrl/client.h>
#include <algorithm>
#include <array>
#include <chrono>
#include <cstdint>
#include <cstring>
#include <iterator>
#include <limits>
#include <mutex>
#include <utility>
using Microsoft::WRL::ComPtr;
namespace gvfg::internal
{
namespace
{
#ifdef GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE
// Permission snapshot only: this does NOT establish exclusive DMA ownership.
bool writableExperimentalRange(const gvfg_frame_t &source, uint64_t offset, uint64_t span,
gvfg_debug_osd_page_check_t *result)
{
gvfg_debug_osd_page_check_t check{};
const auto reject = [&](gvfg_debug_osd_page_reason_t reason) {
check.reason = static_cast<uint32_t>(reason);
if (result)
*result = check;
return false;
};
const uintptr_t base = reinterpret_cast<uintptr_t>(source.data);
const uintptr_t limit = (std::numeric_limits<uintptr_t>::max)();
if (!span || offset > source.data_size || span > source.data_size - offset ||
offset > limit - base || span > limit - (base + offset))
return reject(GVFG_DEBUG_OSD_PAGE_INVALID_RANGE);
uintptr_t cursor = base + static_cast<uintptr_t>(offset);
const uintptr_t end = cursor + static_cast<uintptr_t>(span);
while (cursor < end)
{
MEMORY_BASIC_INFORMATION info{};
const SIZE_T queried = VirtualQuery(reinterpret_cast<const void *>(cursor), &info, sizeof(info));
// Capture the error immediately, and only on a failed native call.
check.win32_error = queried == 0 ? GetLastError() : 0;
check.query_bytes = static_cast<uint32_t>(queried);
check.protect = info.Protect;
check.state = info.State;
check.type = info.Type;
if (queried != sizeof(info))
return reject(GVFG_DEBUG_OSD_PAGE_QUERY_FAILED);
if (info.State != MEM_COMMIT)
return reject(GVFG_DEBUG_OSD_PAGE_NOT_COMMITTED);
if (info.Protect & (PAGE_GUARD | PAGE_NOACCESS))
return reject(GVFG_DEBUG_OSD_PAGE_GUARD_OR_NOACCESS);
if ((info.Protect & 0xffu) != PAGE_READWRITE)
return reject(GVFG_DEBUG_OSD_PAGE_NOT_READWRITE);
const uintptr_t regionBase = reinterpret_cast<uintptr_t>(info.BaseAddress);
if (info.RegionSize > limit - regionBase)
return reject(GVFG_DEBUG_OSD_PAGE_INVALID_REGION);
const uintptr_t next = regionBase + info.RegionSize;
if (next <= cursor)
return reject(GVFG_DEBUG_OSD_PAGE_INVALID_REGION);
cursor = next;
}
if (result)
*result = {};
return true;
}
#endif
constexpr char kOsdBlendShader[] = R"(
Texture2D<uint4> sourceTexture : register(t0);
Texture2D<uint4> osdTexture : register(t1);
Texture2D<uint2> maskTexture : register(t2);
Texture2D<uint4> osdTexture1 : register(t3);
Texture2D<uint2> maskTexture1 : register(t4);
RWTexture2D<uint4> outputTexture : register(u0);
cbuffer BlendParameters : register(b0)
{
uint outputValueMask;
uint visibleSlots;
uint2 padding;
};
uint blendComponent(uint sourceValue, uint osdValue, uint alpha)
{
return ((sourceValue * (255u - alpha) + osdValue * alpha + 127u) / 255u) &
outputValueMask;
}
uint4 blendLayer(uint4 sourceValue, uint4 osdValue, uint2 maskValue)
{
uint pairAlpha = max(maskValue.x, maskValue.y);
uint4 result;
result.x = blendComponent(sourceValue.x, osdValue.x, maskValue.x);
result.y = blendComponent(sourceValue.y, osdValue.y, pairAlpha);
result.z = blendComponent(sourceValue.z, osdValue.z, maskValue.y);
result.w = blendComponent(sourceValue.w, osdValue.w, pairAlpha);
return result;
}
[numthreads(16, 16, 1)]
void main(uint3 id : SV_DispatchThreadID)
{
uint width = 0;
uint height = 0;
outputTexture.GetDimensions(width, height);
if (id.x >= width || id.y >= height)
return;
const uint3 location = uint3(id.xy, 0);
uint4 result = sourceTexture.Load(location);
if ((visibleSlots & 1u) != 0u)
result = blendLayer(result, osdTexture.Load(location), maskTexture.Load(location));
if ((visibleSlots & 2u) != 0u)
result = blendLayer(result, osdTexture1.Load(location), maskTexture1.Load(location));
outputTexture[id.xy] = result;
}
)";
bool copyRowsToMapped(const uint8_t *source, int sourceStride,
uint32_t rowBytes, uint32_t height,
const D3D11_MAPPED_SUBRESOURCE &mapped)
{
if (!source || sourceStride < 0 || static_cast<uint32_t>(sourceStride) < rowBytes ||
mapped.RowPitch < rowBytes)
return false;
if (static_cast<uint32_t>(sourceStride) == rowBytes && mapped.RowPitch == rowBytes)
{
std::memcpy(mapped.pData, source, static_cast<size_t>(rowBytes) * height);
return true;
}
for (uint32_t y = 0; y < height; ++y)
{
std::memcpy(static_cast<uint8_t *>(mapped.pData) + static_cast<size_t>(y) * mapped.RowPitch,
source + static_cast<size_t>(y) * static_cast<size_t>(sourceStride),
rowBytes);
}
return true;
}
struct OsdRegion
{
uint32_t left = 0;
uint32_t top = 0;
uint32_t width = 0;
uint32_t height = 0;
bool empty() const { return width == 0 || height == 0; }
};
OsdRegion findCoveredRegion(const std::vector<uint8_t> &mask,
uint32_t frameWidth, uint32_t frameHeight)
{
uint32_t left = frameWidth;
uint32_t top = frameHeight;
uint32_t right = 0;
uint32_t bottom = 0;
for (uint32_t row = 0; row < frameHeight; ++row)
{
const uint8_t *maskRow = mask.data() + static_cast<size_t>(row) * frameWidth;
for (uint32_t column = 0; column < frameWidth; column += 2u)
{
// Keep both luma samples and their shared U/V inside the region.
if (maskRow[column] == 0 && maskRow[column + 1u] == 0)
continue;
left = (std::min)(left, column);
right = (std::max)(right, column + 2u);
top = (std::min)(top, row);
bottom = row + 1u;
}
}
return right > left ? OsdRegion{left, top, right - left, bottom - top}
: OsdRegion{};
}
void copyFrameRows(const gvfg_frame_t &source, uint8_t *destination,
uint32_t rowBytes)
{
const auto *sourceData = static_cast<const uint8_t *>(source.data);
if (static_cast<uint32_t>(source.row_stride_bytes) == rowBytes)
{
std::memcpy(destination, sourceData,
static_cast<size_t>(rowBytes) * static_cast<size_t>(source.height));
return;
}
for (int row = 0; row < source.height; ++row)
{
std::memcpy(destination + static_cast<size_t>(row) * rowBytes,
sourceData + static_cast<size_t>(row) * source.row_stride_bytes,
rowBytes);
}
}
}
struct GpuOsdProcessor::Impl
{
struct Slot
{
bool configured = false;
bool visible = false;
bool dirty = true;
std::string text;
std::string fontFamily;
int32_t x = 0, y = 0;
uint32_t fontSize = 0, colorRgb = 0xffffffu;
uint32_t width = 0, height = 0;
int format = GVFG_PIXFMT_UNKNOWN;
OsdRegion region;
std::vector<uint8_t> yuv, mask;
ComPtr<ID3D11Texture2D> texture, maskTexture;
ComPtr<ID3D11ShaderResourceView> srv, maskSrv;
};
gvfg_status_t configure(uint32_t index, const gvfg_channel_osd_config_t &value)
{
if (index >= slots.size())
return GVFG_EINVAL;
uint32_t width = 0, height = 0;
const auto status = gvfg_measure_osd_text(&value, &width, &height);
if (status != GVFG_OK)
return status;
// Allocate copies before changing state so failures retain the old slot.
std::string text(value.text), family(value.font_family);
std::lock_guard<std::mutex> lock(mutex);
auto &slot = slots[index];
const bool changed = !slot.configured || slot.text != text || slot.fontFamily != family ||
slot.x != value.x || slot.y != value.y || slot.fontSize != value.font_size_px ||
slot.colorRgb != (value.color_rgb & 0x00ffffffu);
slot.text.swap(text);
slot.fontFamily.swap(family);
slot.x = value.x;
slot.y = value.y;
slot.fontSize = value.font_size_px;
slot.colorRgb = value.color_rgb & 0x00ffffffu;
slot.configured = slot.visible = true;
slot.dirty = slot.dirty || changed;
surfaceDirty = surfaceDirty || changed;
return GVFG_OK;
}
gvfg_status_t clear(uint32_t index)
{
if (index >= slots.size())
return GVFG_EINVAL;
std::lock_guard<std::mutex> lock(mutex);
slots[index] = Slot{};
surfaceDirty = true;
return GVFG_OK;
}
gvfg_status_t setVisible(uint32_t index, int visible)
{
if (index >= slots.size() || (visible != 0 && visible != 1))
return GVFG_EINVAL;
std::lock_guard<std::mutex> lock(mutex);
if (!slots[index].configured && visible)
return GVFG_ESTATE;
slots[index].visible = visible != 0;
// Keep rasterized surfaces and GPU textures intact.
return GVFG_OK;
}
bool ensureDevice()
{
if (device && context && shader && blendParameters)
return true;
UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
#ifdef _DEBUG
flags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
const D3D_FEATURE_LEVEL levels[] = {
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
};
D3D_FEATURE_LEVEL actual{};
HRESULT hr = D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr,
flags, levels, static_cast<UINT>(std::size(levels)),
D3D11_SDK_VERSION, &device, &actual, &context);
#ifdef _DEBUG
if (FAILED(hr))
{
flags &= ~D3D11_CREATE_DEVICE_DEBUG;
hr = D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr,
flags, levels, static_cast<UINT>(std::size(levels)),
D3D11_SDK_VERSION, &device, &actual, &context);
}
#endif
if (FAILED(hr) || !device || !context)
return false;
ComPtr<ID3DBlob> bytecode;
ComPtr<ID3DBlob> errors;
hr = D3DCompile(kOsdBlendShader, sizeof(kOsdBlendShader) - 1,
"gvfg_osd_blend", nullptr, nullptr, "main", "cs_5_0",
D3DCOMPILE_ENABLE_STRICTNESS, 0, &bytecode, &errors);
if (FAILED(hr) || !bytecode)
return false;
if (FAILED(device->CreateComputeShader(bytecode->GetBufferPointer(),
bytecode->GetBufferSize(),
nullptr, &shader)))
return false;
D3D11_BUFFER_DESC parameterDesc{};
parameterDesc.ByteWidth = 16;
parameterDesc.Usage = D3D11_USAGE_DEFAULT;
parameterDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
return SUCCEEDED(device->CreateBuffer(&parameterDesc, nullptr, &blendParameters));
}
bool ensureTexture(ComPtr<ID3D11Texture2D> &texture,
uint32_t textureWidth, uint32_t textureHeight,
DXGI_FORMAT format, D3D11_USAGE usage,
UINT bindFlags, UINT cpuAccess)
{
if (texture)
{
D3D11_TEXTURE2D_DESC current{};
texture->GetDesc(&current);
if (current.Width == textureWidth && current.Height == textureHeight &&
current.Format == format && current.Usage == usage &&
current.BindFlags == bindFlags && current.CPUAccessFlags == cpuAccess)
return true;
texture.Reset();
}
D3D11_TEXTURE2D_DESC desc{};
desc.Width = textureWidth;
desc.Height = textureHeight;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = format;
desc.SampleDesc.Count = 1;
desc.Usage = usage;
desc.BindFlags = bindFlags;
desc.CPUAccessFlags = cpuAccess;
return SUCCEEDED(device->CreateTexture2D(&desc, nullptr, &texture));
}
bool ensureResources(uint32_t regionWidth, uint32_t regionHeight, int pixelFormat)
{
const DXGI_FORMAT packedFormat = pixelFormat == GVFG_PIXFMT_YUY2
? DXGI_FORMAT_R8G8B8A8_UINT : DXGI_FORMAT_R16G16B16A16_UINT;
const bool changed = resourceWidth != regionWidth || resourceHeight != regionHeight ||
resourceFormat != pixelFormat;
if (changed)
{
sourceSrv.Reset();
outputUav.Reset();
for (auto &slot : slots) { slot.srv.Reset(); slot.maskSrv.Reset(); }
resourceWidth = resourceHeight = 0;
resourceFormat = GVFG_PIXFMT_UNKNOWN;
}
const uint32_t pairWidth = regionWidth / 2u;
if (!ensureTexture(sourceTexture, pairWidth, regionHeight, packedFormat,
D3D11_USAGE_DYNAMIC, D3D11_BIND_SHADER_RESOURCE, D3D11_CPU_ACCESS_WRITE) ||
!ensureTexture(outputTexture, pairWidth, regionHeight, packedFormat,
D3D11_USAGE_DEFAULT, D3D11_BIND_UNORDERED_ACCESS, 0) ||
!ensureTexture(readbackTexture, pairWidth, regionHeight, packedFormat,
D3D11_USAGE_STAGING, 0, D3D11_CPU_ACCESS_READ))
return false;
for (auto &slot : slots)
{
if (!ensureTexture(slot.texture, pairWidth, regionHeight, packedFormat,
D3D11_USAGE_DYNAMIC, D3D11_BIND_SHADER_RESOURCE, D3D11_CPU_ACCESS_WRITE) ||
!ensureTexture(slot.maskTexture, pairWidth, regionHeight, DXGI_FORMAT_R8G8_UINT,
D3D11_USAGE_DYNAMIC, D3D11_BIND_SHADER_RESOURCE, D3D11_CPU_ACCESS_WRITE))
return false;
if ((!slot.srv && FAILED(device->CreateShaderResourceView(slot.texture.Get(), nullptr, &slot.srv))) ||
(!slot.maskSrv && FAILED(device->CreateShaderResourceView(slot.maskTexture.Get(), nullptr, &slot.maskSrv))))
return false;
}
if ((!sourceSrv && FAILED(device->CreateShaderResourceView(sourceTexture.Get(), nullptr, &sourceSrv))) ||
(!outputUav && FAILED(device->CreateUnorderedAccessView(outputTexture.Get(), nullptr, &outputUav))))
return false;
resourceWidth = regionWidth;
resourceHeight = regionHeight;
resourceFormat = pixelFormat;
return true;
}
bool rebuildSlot(Slot &slot, uint32_t width, uint32_t height, int format)
{
if (!slot.dirty && slot.width == width && slot.height == height && slot.format == format)
return true;
const uint32_t stride = width * (format == GVFG_PIXFMT_YUY2 ? 2u : 4u);
slot.yuv.assign(static_cast<size_t>(stride) * height, 0);
slot.mask.assign(static_cast<size_t>(width) * height, 0);
slot.region = {};
if (slot.configured)
{
gvfg_osd_handle raw = nullptr;
if (gvfg_osd_create(&raw) != GVFG_OSD_OK)
return false;
std::unique_ptr<void, decltype(&gvfg_osd_destroy)> helper(raw, &gvfg_osd_destroy);
uint32_t textWidth = 0, textHeight = 0;
const auto measured = gvfg_osd_measure(raw, slot.text.c_str(),
static_cast<uint32_t>(slot.text.size()), slot.fontSize, slot.fontFamily.c_str(),
&textWidth, &textHeight);
if (measured != GVFG_OSD_OK)
return false;
// Oversized text skips only this slot, preserving capture and the other slot.
if (textWidth <= width && textHeight <= height)
{
gvfg_osd_config_t config{};
config.struct_size = sizeof(config);
config.width = width;
config.height = height;
config.pixel_format = format == GVFG_PIXFMT_YUY2 ? GVFG_OSD_PIXFMT_YUY2 : GVFG_OSD_PIXFMT_Y210;
config.text = slot.text.c_str();
config.text_length = static_cast<uint32_t>(slot.text.size());
config.font_family = slot.fontFamily.c_str();
config.font_size_px = slot.fontSize;
config.color_rgb = slot.colorRgb;
config.x = slot.x;
config.y = slot.y;
gvfg_osd_output_t output{};
output.struct_size = sizeof(output);
output.yuv_data = slot.yuv.data();
output.yuv_size = slot.yuv.size();
output.yuv_stride = stride;
output.mask_data = slot.mask.data();
output.mask_size = slot.mask.size();
output.mask_stride = width;
if (gvfg_osd_render(raw, &config, &output) != GVFG_OSD_OK)
return false;
slot.region = findCoveredRegion(slot.mask, width, height);
}
}
slot.width = width;
slot.height = height;
slot.format = format;
slot.dirty = false;
return true;
}
bool rebuildSurface(uint32_t width, uint32_t height, int format)
{
surfaceDirty = true; // Retry partial failures, including upload failures.
region = {};
for (auto &slot : slots)
{
if (!rebuildSlot(slot, width, height, format))
return false;
if (slot.region.empty())
continue;
if (region.empty())
region = slot.region;
else
{
const uint32_t right = (std::max)(region.left + region.width, slot.region.left + slot.region.width);
const uint32_t bottom = (std::max)(region.top + region.height, slot.region.top + slot.region.height);
region.left = (std::min)(region.left, slot.region.left);
region.top = (std::min)(region.top, slot.region.top);
region.width = right - region.left;
region.height = bottom - region.top;
}
}
// Include hidden slots in the shared ROI so show/hide never rerasterizes
// glyphs or recreates textures. Visibility is a shader constant.
if (!region.empty())
{
if (!ensureDevice() || !ensureResources(region.width, region.height, format))
return false;
const uint32_t bpp = format == GVFG_PIXFMT_YUY2 ? 2u : 4u;
const size_t yuvOffset = (static_cast<size_t>(region.top) * width + region.left) * bpp;
const size_t maskOffset = static_cast<size_t>(region.top) * width + region.left;
for (auto &slot : slots)
{
D3D11_MAPPED_SUBRESOURCE mapped{};
if (FAILED(context->Map(slot.texture.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped)))
return false;
const bool yuvOk = copyRowsToMapped(slot.yuv.data() + yuvOffset,
static_cast<int>(width * bpp), region.width * bpp, region.height, mapped);
context->Unmap(slot.texture.Get(), 0);
if (!yuvOk || FAILED(context->Map(slot.maskTexture.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped)))
return false;
const bool maskOk = copyRowsToMapped(slot.mask.data() + maskOffset,
static_cast<int>(width), region.width, region.height, mapped);
context->Unmap(slot.maskTexture.Get(), 0);
if (!maskOk)
return false;
}
}
surfaceWidth = width;
surfaceHeight = height;
surfaceFormat = format;
surfaceDirty = false;
return true;
}
gvfg_status_t process(const gvfg_frame_t &source,
std::vector<uint8_t> &destination,
int &destinationStride,
bool &applied,
gvfg_debug_osd_frame_timing_t *timing,
uint8_t *writableSource,
bool experimentalZeroCopy,
bool *inPlaceApplied,
uint32_t *experimentFlags,
gvfg_debug_osd_page_check_t *pageCheck)
{
if (pageCheck)
*pageCheck = {};
if (inPlaceApplied)
*inPlaceApplied = false;
#ifndef GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE
if (experimentalZeroCopy)
return GVFG_EINVAL;
(void)experimentFlags;
#endif
using Clock = std::chrono::steady_clock;
auto stageStart = timing ? Clock::now() : Clock::time_point{};
const auto finishStage = [timing, &stageStart](gvfg_debug_osd_stage_t stage) {
if (timing)
{
const auto end = Clock::now();
timing->stage_ms[stage] = std::chrono::duration<double, std::milli>(end - stageStart).count();
stageStart = end;
}
};
std::lock_guard<std::mutex> lock(mutex);
finishStage(GVFG_DEBUG_OSD_LOCK_WAIT);
applied = false;
uint32_t visibleSlots = 0;
for (uint32_t i = 0; i < slots.size(); ++i)
if (slots[i].configured && slots[i].visible)
visibleSlots |= 1u << i;
if (!visibleSlots)
return GVFG_OK;
if (!source.data || source.width <= 0 || source.height <= 0 ||
(source.width & 1) != 0 || source.row_stride_bytes <= 0 ||
(source.pixel_format != GVFG_PIXFMT_YUY2 &&
source.pixel_format != GVFG_PIXFMT_Y210))
return GVFG_EINVAL;
const uint64_t rowBytes64 = static_cast<uint64_t>(source.width) *
(source.pixel_format == GVFG_PIXFMT_YUY2 ? 2u : 4u);
if (rowBytes64 > static_cast<uint64_t>((std::numeric_limits<int>::max)()) ||
static_cast<uint64_t>(source.row_stride_bytes) < rowBytes64)
return GVFG_EINVAL;
const uint64_t requiredSource =
static_cast<uint64_t>(source.row_stride_bytes) *
static_cast<uint64_t>(source.height - 1) +
rowBytes64;
if (source.data_size < requiredSource)
return GVFG_EINVAL;
if (writableSource && static_cast<const void *>(writableSource) != source.data)
return GVFG_EINVAL;
const bool rebuild = surfaceDirty || surfaceWidth != static_cast<uint32_t>(source.width) ||
surfaceHeight != static_cast<uint32_t>(source.height) ||
surfaceFormat != source.pixel_format;
if (timing)
timing->surface_rebuilt = rebuild ? 1 : 0;
if (rebuild &&
!rebuildSurface(static_cast<uint32_t>(source.width),
static_cast<uint32_t>(source.height), source.pixel_format))
return GVFG_EIO;
finishStage(GVFG_DEBUG_OSD_SURFACE);
// Invisible text needs no processed buffer or GPU work.
bool hasVisibleInk = false;
for (const auto &slot : slots)
hasVisibleInk = hasVisibleInk || (slot.visible && !slot.region.empty());
if (region.empty() || !hasVisibleInk)
return GVFG_OK;
const uint32_t rowBytes = static_cast<uint32_t>(rowBytes64);
const uint32_t bytesPerPixel = source.pixel_format == GVFG_PIXFMT_YUY2 ? 2u : 4u;
const uint32_t regionRowBytes = region.width * bytesPerPixel;
const uint64_t sourceOffset64 = static_cast<uint64_t>(region.top) * source.row_stride_bytes +
static_cast<uint64_t>(region.left) * bytesPerPixel;
if (sourceOffset64 > (std::numeric_limits<size_t>::max)())
return GVFG_EINVAL;
const size_t sourceOffset = static_cast<size_t>(sourceOffset64);
#ifdef GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE
const uint64_t writeSpan = static_cast<uint64_t>(region.height - 1u) *
source.row_stride_bytes + regionRowBytes;
if (experimentalZeroCopy &&
(!writableSource || !writableExperimentalRange(source, sourceOffset, writeSpan, pageCheck)))
{
if (!writableSource && pageCheck)
pageCheck->reason = GVFG_DEBUG_OSD_PAGE_NO_POINTER;
writableSource = nullptr;
if (experimentFlags)
*experimentFlags |= GVFG_DEBUG_OSD_EXPERIMENT_REJECTED;
}
#endif
if (!writableSource)
destination.resize(static_cast<size_t>(rowBytes) * static_cast<size_t>(source.height));
uint8_t *outputData = writableSource ? writableSource : destination.data();
const uint32_t outputStride = writableSource ? static_cast<uint32_t>(source.row_stride_bytes) : rowBytes;
if (timing)
{
timing->roi_width = region.width;
timing->roi_height = region.height;
}
finishStage(GVFG_DEBUG_OSD_PREPARE);
D3D11_MAPPED_SUBRESOURCE mapped{};
if (FAILED(context->Map(sourceTexture.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped)))
return GVFG_EIO;
const bool copiedSource = copyRowsToMapped(
static_cast<const uint8_t *>(source.data) + sourceOffset,
source.row_stride_bytes, regionRowBytes, region.height, mapped);
context->Unmap(sourceTexture.Get(), 0);
if (!copiedSource)
return GVFG_EIO;
finishStage(GVFG_DEBUG_OSD_UPLOAD);
const uint32_t blendValues[4] = {
source.pixel_format == GVFG_PIXFMT_Y210 ? 0xffc0u : 0x00ffu, visibleSlots, 0u, 0u};
context->UpdateSubresource(blendParameters.Get(), 0, nullptr, blendValues, 0, 0);
ID3D11ShaderResourceView *srvs[] = {sourceSrv.Get(), slots[0].srv.Get(), slots[0].maskSrv.Get(),
slots[1].srv.Get(), slots[1].maskSrv.Get()};
ID3D11UnorderedAccessView *uavs[] = {outputUav.Get()};
context->CSSetShader(shader.Get(), nullptr, 0);
ID3D11Buffer *constantBuffers[] = {blendParameters.Get()};
context->CSSetConstantBuffers(0, 1, constantBuffers);
context->CSSetShaderResources(0, 5, srvs);
context->CSSetUnorderedAccessViews(0, 1, uavs, nullptr);
context->Dispatch((region.width / 2u + 15u) / 16u,
(region.height + 15u) / 16u, 1);
ID3D11ShaderResourceView *nullSrvs[] = {nullptr, nullptr, nullptr, nullptr, nullptr};
ID3D11UnorderedAccessView *nullUav = nullptr;
context->CSSetShaderResources(0, 5, nullSrvs);
context->CSSetUnorderedAccessViews(0, 1, &nullUav, nullptr);
ID3D11Buffer *nullBuffer = nullptr;
context->CSSetConstantBuffers(0, 1, &nullBuffer);
context->CSSetShader(nullptr, nullptr, 0);
context->CopyResource(readbackTexture.Get(), outputTexture.Get());
finishStage(GVFG_DEBUG_OSD_SUBMIT);
// Driver zero-copy input requires an independent frame by default.
// SDK-owned copy input already contains the untouched full frame, so
// only its ROI is overwritten after GPU readback; no full copy/resize.
if (!writableSource)
{
copyFrameRows(source, outputData, rowBytes);
finishStage(GVFG_DEBUG_OSD_FRAME_COPY);
}
if (FAILED(context->Map(readbackTexture.Get(), 0, D3D11_MAP_READ, 0, &mapped)))
return GVFG_EIO;
finishStage(GVFG_DEBUG_OSD_READBACK_WAIT);
if (mapped.RowPitch < regionRowBytes)
{
context->Unmap(readbackTexture.Get(), 0);
return GVFG_EIO;
}
const size_t destinationOffset = static_cast<size_t>(region.top) * outputStride +
static_cast<size_t>(region.left) * bytesPerPixel;
#ifdef GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE
// Recheck immediately before writing. Permissions can still change after
// this check; neither this nor the SDK hold prevents concurrent DMA.
if (experimentalZeroCopy && writableSource &&
!writableExperimentalRange(source, sourceOffset, writeSpan, pageCheck))
{
context->Unmap(readbackTexture.Get(), 0);
return GVFG_EIO;
}
#endif
for (uint32_t row = 0; row < region.height; ++row)
{
std::memcpy(outputData + destinationOffset + static_cast<size_t>(row) * outputStride,
static_cast<const uint8_t *>(mapped.pData) +
static_cast<size_t>(row) * mapped.RowPitch,
regionRowBytes);
}
context->Unmap(readbackTexture.Get(), 0);
finishStage(GVFG_DEBUG_OSD_ROI_COPY);
destinationStride = static_cast<int>(outputStride);
applied = true;
if (inPlaceApplied)
*inPlaceApplied = writableSource != nullptr;
if (experimentalZeroCopy && writableSource && experimentFlags)
*experimentFlags |= GVFG_DEBUG_OSD_EXPERIMENT_USED;
if (timing)
timing->osd_applied = 1;
return GVFG_OK;
}
mutable std::mutex mutex;
std::array<Slot, GVFG_OSD_SLOT_COUNT> slots;
bool surfaceDirty = true;
OsdRegion region;
uint32_t surfaceWidth = 0;
uint32_t surfaceHeight = 0;
int surfaceFormat = GVFG_PIXFMT_UNKNOWN;
uint32_t resourceWidth = 0;
uint32_t resourceHeight = 0;
int resourceFormat = GVFG_PIXFMT_UNKNOWN;
ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> context;
ComPtr<ID3D11ComputeShader> shader;
ComPtr<ID3D11Buffer> blendParameters;
ComPtr<ID3D11Texture2D> sourceTexture;
ComPtr<ID3D11Texture2D> outputTexture;
ComPtr<ID3D11Texture2D> readbackTexture;
ComPtr<ID3D11ShaderResourceView> sourceSrv;
ComPtr<ID3D11UnorderedAccessView> outputUav;
};
GpuOsdProcessor::GpuOsdProcessor() : impl_(std::make_unique<Impl>()) {}
GpuOsdProcessor::~GpuOsdProcessor() = default;
gvfg_status_t GpuOsdProcessor::configure(uint32_t index, const gvfg_channel_osd_config_t &config)
{
try
{
return impl_->configure(index, config);
}
catch (...)
{
return GVFG_EIO;
}
}
gvfg_status_t GpuOsdProcessor::clear(uint32_t index) { return impl_->clear(index); }
gvfg_status_t GpuOsdProcessor::setVisible(uint32_t index, int visible) { return impl_->setVisible(index, visible); }
gvfg_status_t GpuOsdProcessor::process(const gvfg_frame_t &source,
std::vector<uint8_t> &destination,
int &destinationStride,
bool &applied,
gvfg_debug_osd_frame_timing_t *timing,
uint8_t *writableSource,
bool experimentalZeroCopy,
bool *inPlaceApplied,
uint32_t *experimentFlags,
gvfg_debug_osd_page_check_t *pageCheck)
{
try
{
return impl_->process(source, destination, destinationStride, applied, timing, writableSource,
experimentalZeroCopy, inPlaceApplied, experimentFlags, pageCheck);
}
catch (...)
{
applied = false;
if (inPlaceApplied)
*inPlaceApplied = false;
destinationStride = 0;
return GVFG_EIO;
}
}
}
-41
View File
@@ -1,41 +0,0 @@
#pragma once
#include "gvfg_capture.h"
#include "gvfg_debug.h"
#include <memory>
#include <string>
#include <vector>
namespace gvfg::internal
{
class GpuOsdProcessor
{
public:
GpuOsdProcessor();
~GpuOsdProcessor();
gvfg_status_t configure(uint32_t index, const gvfg_channel_osd_config_t &config);
gvfg_status_t clear(uint32_t index);
gvfg_status_t setVisible(uint32_t index, int visible);
// writableSource must equal source.data. Only the backend can grant this
// writable SDK-owned storage, held until the caller releases the frame.
// The default-OFF experimental override admits driver storage only after
// page checks; this is not a driver/DMA ownership guarantee.
// nullptr preserves the separate-output path used for driver zero-copy.
gvfg_status_t process(const gvfg_frame_t &source,
std::vector<uint8_t> &destination,
int &destinationStride,
bool &applied,
gvfg_debug_osd_frame_timing_t *timing = nullptr,
uint8_t *writableSource = nullptr,
bool experimentalZeroCopy = false,
bool *inPlaceApplied = nullptr,
uint32_t *experimentFlags = nullptr,
gvfg_debug_osd_page_check_t *pageCheck = nullptr);
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
}
+85 -290
View File
@@ -6,8 +6,7 @@
#include "gvfg_debug.h"
#include "gigabyte_capture_session.h"
#include "gpu/gvfg_gpu_osd.h"
#include "gvfg_osd.h"
#include "gvfg_frame_processor.h"
#include "gvfgframework.h"
#include <algorithm>
@@ -199,7 +198,8 @@ struct gvfg_channel_session_t
return cfg;
if (audioEnabled)
{
const gvfg_status_t audioStatus = session->get_audio_format(cachedAudioFormat);
GigabyteAudioInfo format{};
const gvfg_status_t audioStatus = session->get_audio_format(format);
if (audioStatus != GVFG_OK)
return audioStatus;
}
@@ -315,13 +315,13 @@ struct gvfg_channel_session_t
eventCv.notify_one();
}
gvfg_status_t querySignal()
gvfg_status_t querySignal(bool verifyRequestedFormat = false)
{
if (!session)
return GVFG_ESTATE;
gvfg_signal_status_t sig{};
const gvfg_status_t status = session->get_signal_status(sig);
const gvfg_status_t status = session->get_signal_status(sig, verifyRequestedFormat);
std::lock_guard<std::mutex> lock(stateMutex);
width = status == GVFG_OK ? sig.width : 0;
@@ -341,7 +341,7 @@ struct gvfg_channel_session_t
return GVFG_ESTATE;
gvfg_signal_status_t sig{};
session->get_cached_signal_status(sig);
const gvfg_status_t status = session->get_cached_signal_status(sig);
std::lock_guard<std::mutex> lock(stateMutex);
width = sig.width > 0 ? static_cast<uint32_t>(sig.width) : 0;
@@ -350,7 +350,7 @@ struct gvfg_channel_session_t
pixelFormat = static_cast<gvfg_pixel_format_t>(sig.pixel_format);
videoInterface = sig.video_interface;
signalConnected = sig.connected != 0;
return GVFG_OK;
return status;
}
gvfg_status_t configureStream()
@@ -358,7 +358,7 @@ struct gvfg_channel_session_t
if (!session)
return reject(GVFG_ESTATE, "configure stream rejected: channel is not open");
const gvfg_status_t signalStatus = querySignal();
const gvfg_status_t signalStatus = querySignal(true);
if (signalStatus != GVFG_OK)
return signalStatus;
{
@@ -430,28 +430,23 @@ struct gvfg_channel_session_t
}
bool osdApplied = false;
int processedStride = 0;
// This capability comes from the backend, never from const_cast of a
// public frame pointer. Driver storage is excluded by default; only
// the explicit unsafe build option below can admit it for experiments.
uint8_t *writableSource = session->writable_copy_frame_data(frame);
bool experimentalZeroCopy = false;
bool inPlaceApplied = false;
uint32_t experimentFlags = 0;
gvfg_debug_osd_page_check_t pageCheck{};
#ifdef GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE
experimentFlags = GVFG_DEBUG_OSD_EXPERIMENT_ENABLED;
if (!writableSource)
gvfg_frame_t processedFrame{};
const gvfg_frame_processor *processor = nullptr;
void *processorContext = nullptr;
{
writableSource = session->experimental_zero_copy_frame_data(frame);
experimentalZeroCopy = writableSource != nullptr;
std::lock_guard<std::mutex> lock(processorMutex);
processor = frameProcessor.ops;
processorContext = frameProcessor.context;
}
#endif
// Only SDK-owned copy-mode buffers are available for in-place writes.
uint8_t *writableSource = processor ? session->writable_copy_frame_data(frame) : nullptr;
bool inPlaceApplied = false;
const uint64_t processBeginNs = timing ? now_ns() : 0;
const gvfg_status_t osdStatus =
osdProcessor.process(frame, processedVideoBuffer, processedStride, osdApplied, timing,
writableSource, experimentalZeroCopy, &inPlaceApplied, &experimentFlags, &pageCheck);
if (timing)
const gvfg_status_t osdStatus = processor
? processor->process(processorContext, frame, processedFrame, osdApplied, timing,
writableSource, &inPlaceApplied)
: GVFG_OK;
if (timing && processor)
timing->stage_ms[GVFG_DEBUG_OSD_PROCESS_TOTAL] = static_cast<double>(now_ns() - processBeginNs) / 1e6;
if (osdStatus != GVFG_OK)
{
@@ -477,9 +472,9 @@ struct gvfg_channel_session_t
return releaseStatus;
}
backendFrameHeld = false;
frame.data = processedVideoBuffer.data();
frame.data_size = static_cast<uint64_t>(processedVideoBuffer.size());
frame.row_stride_bytes = processedStride;
frame.data = processedFrame.data;
frame.data_size = processedFrame.data_size;
frame.row_stride_bytes = processedFrame.row_stride_bytes;
}
bool stoppedWhileWaiting = false;
@@ -494,8 +489,6 @@ struct gvfg_channel_session_t
{
frame.frame_id = ++videoFrameId;
heldSessionFrame = frame;
heldOsdExperimentFlags = experimentFlags;
heldOsdPageCheck = pageCheck;
heldFrameNeedsBackendRelease = backendFrameHeld;
readInProgress = false;
frameHeld = true;
@@ -526,31 +519,6 @@ struct gvfg_channel_session_t
return GVFG_OK;
}
gvfg_status_t osdExperimentFlags(uint64_t frameId, uint32_t &flags)
{
flags = 0;
#ifdef GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE
flags = GVFG_DEBUG_OSD_EXPERIMENT_ENABLED;
#endif
if (frameId == 0)
return GVFG_OK;
std::lock_guard<std::mutex> lock(frameMutex);
if (!frameHeld || heldSessionFrame.frame_id != frameId)
return GVFG_ESTATE;
flags = heldOsdExperimentFlags;
return GVFG_OK;
}
gvfg_status_t osdPageCheck(uint64_t frameId, gvfg_debug_osd_page_check_t &check)
{
check = {};
std::lock_guard<std::mutex> lock(frameMutex);
if (!frameId || !frameHeld || heldSessionFrame.frame_id != frameId)
return GVFG_ESTATE;
check = heldOsdPageCheck;
return GVFG_OK;
}
gvfg_status_t releaseFrame(const gvfg_frame_t &frameToken)
{
if (!session)
@@ -684,31 +652,28 @@ struct gvfg_channel_session_t
return session->set_video_format(format);
}
gvfg_status_t setOsd(uint32_t index, const gvfg_channel_osd_config_t &config)
gvfg_status_t controlFrameProcessor(const gvfg_frame_processor *processor, bool create,
gvfg_frame_processor_control control, const void *argument,
const char *error)
{
if (!session)
return reject(GVFG_ESTATE, "gvfg_set_channel_osd rejected: channel is not open");
const gvfg_status_t status = osdProcessor.configure(index, config);
return status == GVFG_OK
? GVFG_OK
: reject(status, status == GVFG_EINVAL
? "gvfg_set_channel_osd rejected: configuration is invalid"
: "gvfg_set_channel_osd failed to store configuration");
}
return reject(GVFG_ESTATE, "Frame processor channel is not open");
gvfg_status_t clearOsd(uint32_t index)
{
if (!session)
return reject(GVFG_ESTATE, "gvfg_clear_channel_osd rejected: channel is not open");
return osdProcessor.clear(index);
}
std::lock_guard<std::mutex> lock(processorMutex);
if (!frameProcessor.ops)
{
if (!create)
return GVFG_OK;
const auto status = processor->create(&frameProcessor.context);
if (status != GVFG_OK)
return reject(status, error);
frameProcessor.ops = processor;
}
if (frameProcessor.ops != processor)
return reject(GVFG_ESTATE, "A different frame processor is already attached");
gvfg_status_t setOsdVisible(uint32_t index, int visible)
{
if (!session)
return reject(GVFG_ESTATE, "OSD visibility rejected: channel is not open");
const gvfg_status_t status = osdProcessor.setVisible(index, visible);
return status == GVFG_OK ? status : reject(status, "OSD visibility rejected: invalid slot, visibility, or no saved configuration");
const auto status = control(frameProcessor.context, argument);
return status == GVFG_OK ? status : reject(status, error);
}
gvfg_status_t setAudioEnabled(bool enabled)
@@ -740,7 +705,6 @@ struct gvfg_channel_session_t
const gvfg_status_t status = session->get_audio_format(format);
if (status != GVFG_OK)
return status;
cachedAudioFormat = format;
out.sample_rate = format.sample_rate;
out.channels = format.channels;
out.bits_per_sample = format.bits_per_sample;
@@ -764,26 +728,19 @@ struct gvfg_channel_session_t
audioReadInProgress = true;
}
const GigabyteAudioInfo format = cachedAudioFormat;
gvfg_status_t status = format.frame_bytes != 0 ? GVFG_OK : GVFG_ESTATE;
uint32_t bytes = 0;
if (status == GVFG_OK)
{
audioBuffer.resize(format.frame_bytes);
status = session->wait_audio(timeoutMs, audioBuffer.data(),
static_cast<uint32_t>(audioBuffer.size()), bytes);
}
GigabyteAudioInfo format{};
const gvfg_status_t status = session->wait_audio(timeoutMs, audioBuffer, format);
{
std::lock_guard<std::mutex> lock(audioMutex);
audioReadInProgress = false;
if (status != GVFG_OK)
return status;
if (!running.load(std::memory_order_acquire) || bytes == 0 || bytes > audioBuffer.size())
if (!running.load(std::memory_order_acquire))
return reject(GVFG_ESTATE, "gvfg_read_channel_audio_frame completed after capture stopped or returned invalid data");
audioFrameHeld = true;
out.data = audioBuffer.data();
out.data_size = bytes;
out.data_size = format.frame_bytes;
out.sample_rate = format.sample_rate;
out.channels = format.channels;
out.bits_per_sample = format.bits_per_sample;
@@ -871,7 +828,6 @@ struct gvfg_channel_session_t
uint32_t selectedChannel = GVFG_CHANNEL_0;
bool zeroCopyRequested = false;
bool audioEnabled = false;
GigabyteAudioInfo cachedAudioFormat{};
uint32_t width = 0;
uint32_t height = 0;
@@ -892,14 +848,22 @@ struct gvfg_channel_session_t
std::atomic<bool> running{false};
std::mutex frameMutex;
bool readInProgress = false;
uint32_t heldOsdExperimentFlags = 0;
gvfg_debug_osd_page_check_t heldOsdPageCheck{};
bool frameHeld = false;
bool heldFrameNeedsBackendRelease = false;
uint64_t videoFrameId = 0;
gvfg_frame_t heldSessionFrame{};
gvfg::internal::GpuOsdProcessor osdProcessor;
std::vector<uint8_t> processedVideoBuffer;
std::mutex processorMutex;
struct FrameProcessorState
{
const gvfg_frame_processor *ops = nullptr;
void *context = nullptr;
~FrameProcessorState()
{
if (ops)
ops->destroy(context);
}
} frameProcessor;
std::mutex audioMutex;
std::vector<uint8_t> audioBuffer;
bool audioReadInProgress = false;
@@ -1212,179 +1176,18 @@ extern "C"
return handle->setChannelVideoFormat(channel_index, format);
}
gvfg_status_t gvfg_get_osd_fonts(gvfg_osd_font_list_t *out_list)
{
if (!out_list)
return GVFG_EINVAL;
*out_list = {};
const auto status = gvfg_osd_get_fonts(&out_list->count, &out_list->names);
return status == GVFG_OSD_OK ? GVFG_OK : GVFG_EIO;
}
gvfg_status_t gvfg_measure_osd_text(const gvfg_channel_osd_config_t *config,
uint32_t *out_width, uint32_t *out_height)
{
if (out_width) *out_width = 0;
if (out_height) *out_height = 0;
if (!config || !config->text || !out_width || !out_height)
return GVFG_EINVAL;
const size_t length = strnlen_s(config->text, GVFG_OSD_MAX_TEXT_CHARACTERS + 1u);
if (length == 0 || length > GVFG_OSD_MAX_TEXT_CHARACTERS)
return GVFG_EINVAL;
try
{
gvfg_osd_handle rawHandle = nullptr;
if (gvfg_osd_create(&rawHandle) != GVFG_OSD_OK)
return GVFG_EIO;
const std::unique_ptr<void, decltype(&gvfg_osd_destroy)> helper(rawHandle, &gvfg_osd_destroy);
const auto status = gvfg_osd_measure(helper.get(), config->text,
static_cast<uint32_t>(length), config->font_size_px, config->font_family,
out_width, out_height);
return status == GVFG_OSD_OK ? GVFG_OK :
status == GVFG_OSD_EINVAL ? GVFG_EINVAL : GVFG_EIO;
}
catch (...) { return GVFG_EIO; }
}
static gvfg_status_t renderOsdBgraTile(const gvfg_channel_osd_config_t *config,
gvfg_osd_bitmap_t *out_bitmap,
std::vector<uint8_t> &pixels)
{
if (!config || !config->text)
return GVFG_EINVAL;
const size_t length = strnlen_s(config->text, GVFG_OSD_MAX_TEXT_CHARACTERS + 1u);
if (length == 0 || length > GVFG_OSD_MAX_TEXT_CHARACTERS)
return GVFG_EINVAL;
try
{
gvfg_osd_handle rawHandle = nullptr;
if (gvfg_osd_create(&rawHandle) != GVFG_OSD_OK)
return GVFG_EIO;
const std::unique_ptr<void, decltype(&gvfg_osd_destroy)> helper(rawHandle, &gvfg_osd_destroy);
uint32_t width = 0, height = 0;
auto status = gvfg_osd_measure(helper.get(), config->text,
static_cast<uint32_t>(length), config->font_size_px, config->font_family,
&width, &height);
if (status != GVFG_OSD_OK)
return status == GVFG_OSD_EINVAL ? GVFG_EINVAL : GVFG_EIO;
const uint64_t stride = static_cast<uint64_t>(width) * 4u;
// WIC GetDataPointer reports its byte count as UINT.
if (width > INT_MAX || height > INT_MAX || stride > UINT_MAX ||
stride * height > UINT_MAX ||
stride * height > (std::numeric_limits<size_t>::max)())
return GVFG_EINVAL;
pixels.resize(static_cast<size_t>(stride * height));
gvfg_osd_config_t render{};
render.struct_size = sizeof(render);
render.width = width;
render.height = height;
render.text = config->text;
render.font_family = config->font_family;
render.text_length = static_cast<uint32_t>(length);
render.font_size_px = config->font_size_px;
render.color_rgb = config->color_rgb;
status = gvfg_osd_render_bgra(helper.get(), &render, pixels.data(), pixels.size(),
static_cast<uint32_t>(stride));
if (status != GVFG_OSD_OK)
return status == GVFG_OSD_EINVAL ? GVFG_EINVAL : GVFG_EIO;
out_bitmap->data = pixels.data();
out_bitmap->data_size = pixels.size();
out_bitmap->width = width;
out_bitmap->height = height;
out_bitmap->stride = static_cast<uint32_t>(stride);
return GVFG_OK;
}
catch (...) { return GVFG_EIO; }
}
gvfg_status_t gvfg_render_osd_frame_bgra(uint32_t video_width, uint32_t video_height,
const gvfg_channel_osd_config_t *slot0,
const gvfg_channel_osd_config_t *slot1,
gvfg_osd_bitmap_t *out_bitmap)
{
thread_local std::vector<uint8_t> frame;
frame.clear();
if (!out_bitmap)
return GVFG_EINVAL;
*out_bitmap = {};
const uint64_t stride = static_cast<uint64_t>(video_width) * 4u;
if (!video_width || !video_height || stride > UINT32_MAX ||
stride * video_height > UINT32_MAX ||
stride * video_height > (std::numeric_limits<size_t>::max)())
return GVFG_EINVAL;
try
{
frame.assign(static_cast<size_t>(stride * video_height), 0);
std::vector<uint8_t> tilePixels;
for (const auto *slot : {slot0, slot1})
{
if (!slot)
continue;
gvfg_osd_bitmap_t tile{};
const auto status = renderOsdBgraTile(slot, &tile, tilePixels);
if (status != GVFG_OK)
return status;
if (tile.width > video_width || tile.height > video_height)
continue;
const size_t x = std::clamp<int64_t>(slot->x, 0, video_width - tile.width);
const size_t y = std::clamp<int64_t>(slot->y, 0, video_height - tile.height);
for (uint32_t row = 0; row < tile.height; ++row)
{
const auto *src = tile.data + static_cast<size_t>(row) * tile.stride;
auto *dst = frame.data() + (y + row) * static_cast<size_t>(stride) + x * 4u;
for (uint32_t col = 0; col < tile.width; ++col, src += 4, dst += 4)
{
if (!src[3])
continue;
// Both layers are premultiplied, including at glyph edges.
const unsigned remaining = 255u - src[3];
for (unsigned c = 0; c < 4; ++c)
dst[c] = static_cast<uint8_t>(src[c] + (dst[c] * remaining + 127u) / 255u);
}
}
}
*out_bitmap = {frame.data(), frame.size(), video_width, video_height,
static_cast<uint32_t>(stride)};
return GVFG_OK;
}
catch (...) { return GVFG_EIO; }
}
gvfg_status_t gvfg_set_channel_osd(gvfg_handle handle, int channel_index,
uint32_t osd_index, const gvfg_channel_osd_config_t *config)
gvfg_status_t gvfg_control_frame_processor(
gvfg_handle handle, int channel_index, const gvfg_frame_processor *processor,
bool create, gvfg_frame_processor_control control, const void *argument,
const char *error)
{
if (!handle)
return GVFG_EINVAL;
if (!config || osd_index >= GVFG_OSD_SLOT_COUNT)
return handle->rejectChannel(channel_index, GVFG_EINVAL, "OSD config or index is invalid");
if (!control)
return handle->rejectChannel(channel_index, GVFG_EINVAL, error);
auto *channel = handle->findChannel(channel_index);
return channel ? channel->setOsd(osd_index, *config)
: handle->rejectChannel(channel_index, GVFG_ESTATE, "OSD channel is not open");
}
gvfg_status_t gvfg_set_channel_osd_visible(gvfg_handle handle, int channel_index,
uint32_t osd_index, int visible)
{
if (!handle)
return GVFG_EINVAL;
if (osd_index >= GVFG_OSD_SLOT_COUNT || (visible != 0 && visible != 1))
return handle->rejectChannel(channel_index, GVFG_EINVAL, "OSD index or visibility is invalid");
auto *channel = handle->findChannel(channel_index);
return channel ? channel->setOsdVisible(osd_index, visible)
: handle->rejectChannel(channel_index, GVFG_ESTATE, "OSD channel is not open");
}
gvfg_status_t gvfg_clear_channel_osd(gvfg_handle handle, int channel_index, uint32_t osd_index)
{
if (!handle)
return GVFG_EINVAL;
if (osd_index >= GVFG_OSD_SLOT_COUNT)
return handle->rejectChannel(channel_index, GVFG_EINVAL, "OSD index is invalid");
auto *channel = handle->findChannel(channel_index);
return channel ? channel->clearOsd(osd_index)
: handle->rejectChannel(channel_index, GVFG_ESTATE, "OSD channel is not open");
return channel ? channel->controlFrameProcessor(processor, create, control, argument, error)
: handle->rejectChannel(channel_index, GVFG_ESTATE, "Frame processor channel is not open");
}
gvfg_status_t gvfg_set_channel_audio_enabled(gvfg_handle handle,
@@ -1467,32 +1270,6 @@ extern "C"
"gvfg_debug_read_channel_frame_profiled rejected: channel is not open");
}
gvfg_status_t gvfg_debug_get_channel_osd_experiment_flags(gvfg_handle handle,
int channel_index,
uint64_t frame_id,
uint32_t *out_flags)
{
if (out_flags)
*out_flags = 0;
if (!handle || !out_flags)
return GVFG_EINVAL;
gvfg_channel_session_t *channel = handle->findChannel(channel_index);
return channel ? channel->osdExperimentFlags(frame_id, *out_flags) : GVFG_ESTATE;
}
gvfg_status_t gvfg_debug_get_channel_osd_page_check(gvfg_handle handle,
int channel_index,
uint64_t frame_id,
gvfg_debug_osd_page_check_t *out_check)
{
if (out_check)
*out_check = {};
if (!handle || !out_check)
return GVFG_EINVAL;
gvfg_channel_session_t *channel = handle->findChannel(channel_index);
return channel ? channel->osdPageCheck(frame_id, *out_check) : GVFG_ESTATE;
}
gvfg_status_t gvfg_release_channel_frame(gvfg_handle handle,
int channel_index,
const gvfg_frame_t *frame)
@@ -1654,6 +1431,24 @@ extern "C"
return channel->session->get_hdmi_info(*out_info);
}
gvfg_status_t gvfg_get_channel_hdmi_audio_info(
gvfg_handle handle, int channel_index, gvfg_hdmi_audio_info_t *out_info)
{
if (!handle || (channel_index != GVFG_CHANNEL_0 && channel_index != GVFG_CHANNEL_1))
return GVFG_EINVAL;
if (!out_info)
return handle->rejectChannel(
channel_index, GVFG_EINVAL,
"gvfg_get_channel_hdmi_audio_info rejected: out_info is null");
*out_info = {};
auto *channel = handle->findChannel(channel_index);
if (!channel || !channel->session)
return handle->rejectChannel(
channel_index, GVFG_ESTATE,
"gvfg_get_channel_hdmi_audio_info rejected: channel is not open");
return channel->session->get_hdmi_audio_info(*out_info);
}
gvfg_status_t gvfg_get_chip_info(gvfg_handle handle, gvfg_chip_info_t *out_info)
{
if (!handle)
@@ -0,0 +1,19 @@
#pragma once
#include "gvfg_debug.h"
struct gvfg_frame_processor
{
gvfg_status_t (*create)(void **);
void (*destroy)(void *);
gvfg_status_t (*process)(void *, const gvfg_frame_t &, gvfg_frame_t &,
bool &, gvfg_debug_osd_frame_timing_t *, uint8_t *,
bool *);
};
using gvfg_frame_processor_control = gvfg_status_t (*)(void *, const void *);
extern "C" GVFG_API gvfg_status_t gvfg_control_frame_processor(
gvfg_handle handle, int channel, const gvfg_frame_processor *processor,
bool create, gvfg_frame_processor_control control, const void *argument,
const char *error);