Unify playback and harden preview/audio recovery for SDK 2.1.1

- expose one gvfg_playback DLL backed by static audio and preview libraries, retain public backend data types, and remove obsolete standalone backend exports and unused wrappers

- centralize playback clocks, timestamp scheduling, optional synchronization, audio rate correction, bounded queues and fallback while preserving legacy statistics buffer sizes

- provide still-image presentation and a helper-owned NO SIGNAL card with explicit SDK connection state, native window ownership and UI-thread checks

- report monitoring failures through EAUDIO without stopping video, retain the failed output state across timeline resets, and reject audio-only startup when output is unavailable

- make clearing an unconfigured preview a successful no-op so resetting before the first frame cannot leave playback stopped

- trace actual format-change events before event resets in Debug builds and refresh video metadata after plugin stream recovery while retaining the existing temporary HDMI lock bypass

- update SDK 2.1.1 public documentation, the playback guide and rendered API reference to describe the unified lifecycle, error handling and delivery boundaries

Validation: Full SDK Release build and git diff --cached --check passed. Native tests passed for video/reset lifecycle with synchronization enabled and disabled, signal-card lifecycle, bounded queue pressure and legacy statistics guards. Process-local WASAPI failure injection verified continued video, persistent monitoring failure and audio-only rejection; real WASAPI silence playback advanced the output clock in both synchronization modes. Public exports and rendered PDF pages/portable links were checked. No hardware capture, unplug/replug or long-running acoustic A/V synchronization test was performed.
This commit is contained in:
Mark.lin
2026-10-22 14:02:43 +08:00
parent da2ad24459
commit bfa9397f6b
36 changed files with 2389 additions and 2089 deletions
@@ -1,57 +1,13 @@
project(gvfg_audio_playback LANGUAGES CXX)
add_library(gvfg_audio_playback SHARED
gvfg_audio_playback.def
# Internal WASAPI backend. Only gvfg_playback is installed as a playback DLL.
add_library(gvfg_audio_playback STATIC
include/gvfg_audio_playback.h
src/audio_backend_internal.h
src/gvfg_audio_playback.cpp
src/audio_output_internal.h
)
set_target_properties(gvfg_audio_playback PROPERTIES
AUTOMOC OFF
AUTOUIC OFF
AUTORCC OFF
)
target_include_directories(gvfg_audio_playback
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/include
)
target_compile_definitions(gvfg_audio_playback PRIVATE
GVFG_AUDIO_PLAYBACK_BUILD
)
target_link_libraries(gvfg_audio_playback PRIVATE
ole32
)
if (MSVC)
set_target_properties(gvfg_audio_playback PROPERTIES AUTOMOC OFF AUTOUIC OFF AUTORCC OFF)
target_include_directories(gvfg_audio_playback PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(gvfg_audio_playback PRIVATE ole32)
if(MSVC)
target_compile_options(gvfg_audio_playback PRIVATE /utf-8 /EHsc)
endif()
if (MSVC AND GVFG_MINGW_DLLTOOL)
add_custom_command(TARGET gvfg_audio_playback POST_BUILD
COMMAND "${GVFG_MINGW_DLLTOOL}"
-d "${CMAKE_CURRENT_SOURCE_DIR}/gvfg_audio_playback.def"
-D gvfg_audio_playback.dll
-l libgvfg_audio_playback.dll.a
WORKING_DIRECTORY "${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}"
COMMENT "Generating MinGW import library for gvfg_audio_playback.dll"
VERBATIM
)
endif()
install(TARGETS gvfg_audio_playback
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
)
install(FILES include/gvfg_audio_playback.h
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
if (MSVC AND GVFG_MINGW_DLLTOOL)
install(FILES "${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}/libgvfg_audio_playback.dll.a"
DESTINATION ${CMAKE_INSTALL_LIBDIR}
)
endif()
@@ -1,12 +0,0 @@
LIBRARY gvfg_audio_playback
EXPORTS
gvfg_audio_player_create
gvfg_audio_player_start
gvfg_audio_player_write
gvfg_audio_player_write_timed
gvfg_audio_player_update_video_timestamp
gvfg_audio_player_reset_timeline
gvfg_audio_player_set_volume
gvfg_audio_player_stop
gvfg_audio_player_destroy
gvfg_audio_player_strerror
@@ -1,97 +1,11 @@
#pragma once
/*
* Optional GVFG audio playback helper.
*
* The helper copies application-owned interleaved PCM into a bounded queue
* and plays it through the Windows default audio output using WASAPI. It has
* no dependency on gvfg.dll or Qt.
*/
/* Public PCM format types used by gvfg_playback.h. */
#include <stdint.h>
#ifdef _WIN32
#ifdef GVFG_AUDIO_PLAYBACK_BUILD
#define GVFG_AUDIO_PLAYBACK_API __declspec(dllexport)
#else
#define GVFG_AUDIO_PLAYBACK_API __declspec(dllimport)
#endif
#else
#define GVFG_AUDIO_PLAYBACK_API
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef enum
{
GVFG_AUDIO_PLAYBACK_OK = 0,
GVFG_AUDIO_PLAYBACK_EINVAL = -1,
GVFG_AUDIO_PLAYBACK_ESTATE = -2,
GVFG_AUDIO_PLAYBACK_ENODEV = -3,
GVFG_AUDIO_PLAYBACK_EFORMAT = -4,
GVFG_AUDIO_PLAYBACK_EQUEUE_FULL = -5,
GVFG_AUDIO_PLAYBACK_EIO = -6
} gvfg_audio_playback_status_t;
typedef struct gvfg_audio_player_t *gvfg_audio_player;
typedef struct
{
uint32_t sample_rate;
uint16_t channels;
uint16_t bits_per_sample; /* Signed interleaved PCM; must be 16. */
} gvfg_audio_playback_format_t;
GVFG_AUDIO_PLAYBACK_API gvfg_audio_playback_status_t gvfg_audio_player_create(
gvfg_audio_player *out_player);
/* Start PCM16 playback on the Windows default output device. */
GVFG_AUDIO_PLAYBACK_API gvfg_audio_playback_status_t gvfg_audio_player_start(
gvfg_audio_player player,
const gvfg_audio_playback_format_t *format);
/*
* Copy one or more complete interleaved PCM frames into the playback queue.
* The caller may release or reuse data immediately after this function
* returns. EQUEUE_FULL means the packet was not accepted.
*/
GVFG_AUDIO_PLAYBACK_API gvfg_audio_playback_status_t gvfg_audio_player_write(
gvfg_audio_player player,
const void *data,
uint32_t data_size);
/* Queue PCM with its SDK delivery timestamp for A/V synchronization. */
GVFG_AUDIO_PLAYBACK_API gvfg_audio_playback_status_t gvfg_audio_player_write_timed(
gvfg_audio_player player,
const void *data,
uint32_t data_size,
uint64_t audio_timestamp_ns);
/* Publish the newest video timestamp from the same SDK clock domain. */
GVFG_AUDIO_PLAYBACK_API gvfg_audio_playback_status_t gvfg_audio_player_update_video_timestamp(
gvfg_audio_player player,
uint64_t video_timestamp_ns);
/* Clear queued PCM and establish a new A/V synchronization timeline. */
GVFG_AUDIO_PLAYBACK_API gvfg_audio_playback_status_t gvfg_audio_player_reset_timeline(
gvfg_audio_player player);
/* Set software PCM16 playback gain. The accepted range is 0.0 to 2.0. */
GVFG_AUDIO_PLAYBACK_API gvfg_audio_playback_status_t gvfg_audio_player_set_volume(
gvfg_audio_player player,
float volume);
GVFG_AUDIO_PLAYBACK_API gvfg_audio_playback_status_t gvfg_audio_player_stop(
gvfg_audio_player player);
GVFG_AUDIO_PLAYBACK_API void gvfg_audio_player_destroy(
gvfg_audio_player player);
GVFG_AUDIO_PLAYBACK_API const char *gvfg_audio_player_strerror(
gvfg_audio_playback_status_t status);
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,55 @@
#pragma once
/* Private static backend; not part of the customer API. */
#include "gvfg_audio_playback.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum
{
GVFG_AUDIO_PLAYBACK_OK = 0,
GVFG_AUDIO_PLAYBACK_EINVAL = -1,
GVFG_AUDIO_PLAYBACK_ESTATE = -2,
GVFG_AUDIO_PLAYBACK_ENODEV = -3,
GVFG_AUDIO_PLAYBACK_EFORMAT = -4,
GVFG_AUDIO_PLAYBACK_EQUEUE_FULL = -5,
GVFG_AUDIO_PLAYBACK_EIO = -6
} gvfg_audio_playback_status_t;
typedef struct gvfg_audio_player_t *gvfg_audio_player;
/* Start PCM16 playback on the Windows default output device. */
gvfg_audio_playback_status_t gvfg_audio_player_start(
gvfg_audio_player player,
const gvfg_audio_playback_format_t *format);
/*
* Copy one or more complete interleaved PCM frames into the playback queue.
* The caller may release or reuse data immediately after this function
* returns. EQUEUE_FULL means the packet was not accepted.
*/
gvfg_audio_playback_status_t gvfg_audio_player_write(
gvfg_audio_player player,
const void *data,
uint32_t data_size);
/* Clear queued PCM, reset the audio stream and its position bookkeeping. */
gvfg_audio_playback_status_t gvfg_audio_player_reset_timeline(
gvfg_audio_player player);
/* Set software PCM16 playback gain. The accepted range is 0.0 to 2.0. */
gvfg_audio_playback_status_t gvfg_audio_player_set_volume(
gvfg_audio_player player,
float volume);
gvfg_audio_playback_status_t gvfg_audio_player_stop(
gvfg_audio_player player);
void gvfg_audio_player_destroy(
gvfg_audio_player player);
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,16 @@
#pragma once
#include "audio_backend_internal.h"
#include <cstdint>
// Private bridge inside the same DLL; never exported or exposed to applications.
struct AudioOutputPosition {
uint64_t played_frames = 0;
uint64_t queued_frames = 0;
bool running = false;
bool paused = true;
bool resetting = false;
};
gvfg_audio_player audio_output_create_managed();
AudioOutputPosition audio_output_position(gvfg_audio_player p);
void audio_output_pause(gvfg_audio_player p, bool paused);
void audio_output_rate(gvfg_audio_player p, double ratio);
@@ -1,4 +1,5 @@
#include "gvfg_audio_playback.h"
#include "audio_backend_internal.h"
#include "audio_output_internal.h"
#include <windows.h>
#include <audioclient.h>
@@ -27,9 +28,14 @@ struct gvfg_audio_player_t
struct Packet
{
std::vector<uint8_t> pcm;
uint64_t timestamp_ns = 0;
};
uint64_t written_frames = 0, inflight_frames = 0;
uint64_t played_frames = 0, device_padding = 0;
uint64_t applied_generation = 0;
std::atomic<bool> pause_requested{true};
bool output_paused = false;
std::atomic<double> rate_ratio{1.0};
std::mutex mutex;
std::condition_variable ready;
std::condition_variable queued;
@@ -43,8 +49,7 @@ struct gvfg_audio_player_t
bool running = false;
bool stop_requested = false;
bool flush_requested = false;
std::atomic<uint64_t> latest_video_timestamp_ns{0};
std::atomic<uint64_t> timeline_generation{0};
std::atomic<uint64_t> buffer_generation{0};
std::atomic<float> volume{1.0f};
};
@@ -87,13 +92,17 @@ namespace
void playback_worker(gvfg_audio_player_t *player)
{
const HRESULT comResult = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
const bool uninitializeCom = SUCCEEDED(comResult);
struct ComScope {
bool initialized;
~ComScope() { if (initialized) CoUninitialize(); }
} comScope{SUCCEEDED(comResult)};
gvfg_audio_playback_status_t startStatus = GVFG_AUDIO_PLAYBACK_EIO;
ComPtr<IMMDeviceEnumerator> enumerator;
ComPtr<IMMDevice> device;
ComPtr<IAudioClient> client;
ComPtr<IAudioRenderClient> render;
ComPtr<IAudioClockAdjustment> adjustment;
UINT32 bufferFrames = 0;
if (SUCCEEDED(comResult) || comResult == RPC_E_CHANGED_MODE)
@@ -122,7 +131,8 @@ namespace
constexpr REFERENCE_TIME kBufferDuration = 1000000; // 100 ms
const DWORD flags = AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM |
AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;
AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY |
AUDCLNT_STREAMFLAGS_RATEADJUST;
hr = client->Initialize(AUDCLNT_SHAREMODE_SHARED, flags,
kBufferDuration, 0, &wave, nullptr);
if (hr == AUDCLNT_E_UNSUPPORTED_FORMAT)
@@ -132,7 +142,10 @@ namespace
if (SUCCEEDED(hr) && bufferFrames > 0)
hr = client->GetService(IID_PPV_ARGS(&render));
if (SUCCEEDED(hr) && render)
hr = client->GetService(IID_PPV_ARGS(&adjustment));
if (SUCCEEDED(hr) && render && !player->pause_requested.load())
hr = client->Start();
player->output_paused = player->pause_requested.load();
if (SUCCEEDED(hr) && render)
startStatus = GVFG_AUDIO_PLAYBACK_OK;
else if (startStatus != GVFG_AUDIO_PLAYBACK_EFORMAT)
@@ -146,22 +159,39 @@ namespace
player->start_status = startStatus;
player->start_complete = true;
player->running = startStatus == GVFG_AUDIO_PLAYBACK_OK;
player->applied_generation = player->buffer_generation.load();
}
player->ready.notify_one();
constexpr int64_t kLeadLimitNs = 40'000'000;
constexpr int64_t kLagDropNs = 80'000'000;
constexpr auto kMaxHold = std::chrono::milliseconds(100);
const uint32_t frameBytes = block_align(player->format);
uint64_t observedGeneration = player->timeline_generation.load(std::memory_order_acquire);
bool syncBaseValid = false;
int64_t syncBaseOffsetNs = 0;
uint64_t observedGeneration = player->buffer_generation.load(std::memory_order_acquire);
double appliedRate = 1.0;
auto updateOutput = [&]() -> bool {
const bool pause = player->pause_requested.load();
if (pause != player->output_paused) {
if (FAILED(pause ? client->Stop() : client->Start())) return false;
std::lock_guard<std::mutex> lock(player->mutex);
player->output_paused = pause;
}
const double rate = player->rate_ratio.load();
if (rate != appliedRate && adjustment) {
if (FAILED(adjustment->SetSampleRate(static_cast<float>(player->format.sample_rate * rate)))) return false;
appliedRate = rate;
}
UINT32 padding = 0;
if (FAILED(client->GetCurrentPadding(&padding))) return false;
std::lock_guard<std::mutex> lock(player->mutex);
player->device_padding = padding;
player->played_frames = player->written_frames > padding ? player->written_frames - padding : 0;
return true;
};
while (startStatus == GVFG_AUDIO_PLAYBACK_OK)
{
if (!updateOutput()) { startStatus = GVFG_AUDIO_PLAYBACK_EIO; break; }
gvfg_audio_player_t::Packet packet;
{
std::unique_lock<std::mutex> lock(player->mutex);
player->queued.wait(lock, [player]
player->queued.wait_for(lock, std::chrono::milliseconds(kPollingSleepMs), [player]
{ return player->stop_requested || player->flush_requested ||
!player->packets.empty(); });
if (player->stop_requested)
@@ -173,59 +203,25 @@ namespace
HRESULT hr = client->Stop();
if (SUCCEEDED(hr))
hr = client->Reset();
if (SUCCEEDED(hr))
if (SUCCEEDED(hr) && !player->pause_requested.load())
hr = client->Start();
{
std::lock_guard<std::mutex> stateLock(player->mutex);
player->written_frames = player->inflight_frames = player->device_padding = player->played_frames = 0;
player->output_paused = player->pause_requested.load();
player->applied_generation = player->buffer_generation.load();
}
if (FAILED(hr))
break;
observedGeneration = player->timeline_generation.load(std::memory_order_acquire);
syncBaseValid = false;
observedGeneration = player->buffer_generation.load(std::memory_order_acquire);
continue;
}
if (player->packets.empty()) continue;
packet = std::move(player->packets.front());
player->packets.pop_front();
player->queued_bytes -= packet.pcm.size();
}
const uint64_t generation = player->timeline_generation.load(std::memory_order_acquire);
if (generation != observedGeneration)
{
observedGeneration = generation;
syncBaseValid = false;
}
uint64_t videoTimestampNs = player->latest_video_timestamp_ns.load(std::memory_order_acquire);
if (packet.timestamp_ns != 0 && videoTimestampNs != 0)
{
const int64_t rawOffsetNs = static_cast<int64_t>(packet.timestamp_ns) -
static_cast<int64_t>(videoTimestampNs);
if (!syncBaseValid)
{
syncBaseOffsetNs = rawOffsetNs;
syncBaseValid = true;
}
int64_t driftNs = rawOffsetNs - syncBaseOffsetNs;
if (driftNs < -kLagDropNs)
continue;
const auto holdDeadline = std::chrono::steady_clock::now() + kMaxHold;
while (driftNs > kLeadLimitNs &&
std::chrono::steady_clock::now() < holdDeadline)
{
{
std::lock_guard<std::mutex> lock(player->mutex);
if (player->stop_requested)
break;
}
if (player->timeline_generation.load(std::memory_order_acquire) != observedGeneration)
{
syncBaseValid = false;
break;
}
Sleep(kPollingSleepMs);
videoTimestampNs = player->latest_video_timestamp_ns.load(std::memory_order_acquire);
driftNs = static_cast<int64_t>(packet.timestamp_ns) -
static_cast<int64_t>(videoTimestampNs) - syncBaseOffsetNs;
}
if (!syncBaseValid || driftNs > kLeadLimitNs)
continue;
player->inflight_frames = packet.pcm.size() / frameBytes;
observedGeneration = player->buffer_generation.load(std::memory_order_acquire);
}
apply_pcm16_gain(packet.pcm, player->volume.load(std::memory_order_acquire));
@@ -234,6 +230,8 @@ namespace
const uint32_t totalFrames = static_cast<uint32_t>(packet.pcm.size() / frameBytes);
while (frameOffset < totalFrames)
{
if (!updateOutput()) { startStatus = GVFG_AUDIO_PLAYBACK_EIO; break; }
if (player->buffer_generation.load() != observedGeneration) break;
{
std::lock_guard<std::mutex> lock(player->mutex);
if (player->stop_requested)
@@ -271,18 +269,22 @@ namespace
startStatus = GVFG_AUDIO_PLAYBACK_EIO;
break;
}
{
std::lock_guard<std::mutex> lock(player->mutex);
player->written_frames += framesNow;
player->inflight_frames -= framesNow;
}
frameOffset += framesNow;
}
}
if (client)
client->Stop();
adjustment.Reset();
render.Reset();
client.Reset();
device.Reset();
enumerator.Reset();
if (uninitializeCom)
CoUninitialize();
std::lock_guard<std::mutex> lock(player->mutex);
player->running = false;
@@ -291,14 +293,6 @@ namespace
extern "C"
{
gvfg_audio_playback_status_t gvfg_audio_player_create(gvfg_audio_player *out_player)
{
if (!out_player)
return GVFG_AUDIO_PLAYBACK_EINVAL;
*out_player = new (std::nothrow) gvfg_audio_player_t();
return *out_player ? GVFG_AUDIO_PLAYBACK_OK : GVFG_AUDIO_PLAYBACK_EIO;
}
gvfg_audio_playback_status_t gvfg_audio_player_start(
gvfg_audio_player player, const gvfg_audio_playback_format_t *format)
{
@@ -312,6 +306,7 @@ extern "C"
player->format = *format;
player->packets.clear();
player->queued_bytes = 0;
player->written_frames = player->inflight_frames = player->device_padding = player->played_frames = 0;
player->max_queued_bytes = static_cast<size_t>(format->sample_rate) *
block_align(*format) * kMaxQueuedAudioMs /
kMillisecondsPerSecond;
@@ -319,12 +314,20 @@ extern "C"
player->start_complete = false;
player->stop_requested = false;
player->flush_requested = false;
player->latest_video_timestamp_ns.store(0, std::memory_order_release);
player->timeline_generation.fetch_add(1, std::memory_order_acq_rel);
player->buffer_generation.fetch_add(1, std::memory_order_acq_rel);
try
{
player->worker = std::thread(playback_worker, player);
player->worker = std::thread([player] {
try { playback_worker(player); }
catch (...) {
std::lock_guard<std::mutex> lock(player->mutex);
player->running = false;
player->start_status = GVFG_AUDIO_PLAYBACK_EIO;
player->start_complete = true;
player->ready.notify_one();
}
});
}
catch (...)
{
@@ -342,13 +345,6 @@ extern "C"
gvfg_audio_playback_status_t gvfg_audio_player_write(
gvfg_audio_player player, const void *data, uint32_t data_size)
{
return gvfg_audio_player_write_timed(player, data, data_size, 0);
}
gvfg_audio_playback_status_t gvfg_audio_player_write_timed(
gvfg_audio_player player, const void *data, uint32_t data_size,
uint64_t audio_timestamp_ns)
{
if (!player || !data || data_size == 0)
return GVFG_AUDIO_PLAYBACK_EINVAL;
@@ -368,7 +364,6 @@ extern "C"
const auto *bytes = static_cast<const uint8_t *>(data);
gvfg_audio_player_t::Packet packet;
packet.pcm.assign(bytes, bytes + data_size);
packet.timestamp_ns = audio_timestamp_ns;
player->packets.push_back(std::move(packet));
}
catch (...)
@@ -380,15 +375,6 @@ extern "C"
return GVFG_AUDIO_PLAYBACK_OK;
}
gvfg_audio_playback_status_t gvfg_audio_player_update_video_timestamp(
gvfg_audio_player player, uint64_t video_timestamp_ns)
{
if (!player)
return GVFG_AUDIO_PLAYBACK_EINVAL;
player->latest_video_timestamp_ns.store(video_timestamp_ns, std::memory_order_release);
return GVFG_AUDIO_PLAYBACK_OK;
}
gvfg_audio_playback_status_t gvfg_audio_player_reset_timeline(gvfg_audio_player player)
{
if (!player)
@@ -398,9 +384,8 @@ extern "C"
player->packets.clear();
player->queued_bytes = 0;
player->flush_requested = true;
player->buffer_generation.fetch_add(1, std::memory_order_acq_rel);
}
player->latest_video_timestamp_ns.store(0, std::memory_order_release);
player->timeline_generation.fetch_add(1, std::memory_order_acq_rel);
player->queued.notify_one();
return GVFG_AUDIO_PLAYBACK_OK;
}
@@ -439,26 +424,27 @@ extern "C"
delete player;
}
const char *gvfg_audio_player_strerror(gvfg_audio_playback_status_t status)
{
switch (status)
{
case GVFG_AUDIO_PLAYBACK_OK:
return "ok";
case GVFG_AUDIO_PLAYBACK_EINVAL:
return "invalid argument";
case GVFG_AUDIO_PLAYBACK_ESTATE:
return "invalid state";
case GVFG_AUDIO_PLAYBACK_ENODEV:
return "default audio output unavailable";
case GVFG_AUDIO_PLAYBACK_EFORMAT:
return "PCM format unsupported";
case GVFG_AUDIO_PLAYBACK_EQUEUE_FULL:
return "playback queue full";
case GVFG_AUDIO_PLAYBACK_EIO:
return "audio playback failure";
default:
return "unknown audio playback status";
}
}
}
// Private output controls: no knowledge of video or synchronization policy.
gvfg_audio_player audio_output_create_managed()
{
return new (std::nothrow) gvfg_audio_player_t();
}
AudioOutputPosition audio_output_position(gvfg_audio_player p)
{
if (!p) return {};
std::lock_guard<std::mutex> lock(p->mutex);
const auto align = block_align(p->format);
return {p->played_frames, (align ? p->queued_bytes / align : 0) + p->inflight_frames + p->device_padding,
p->running, p->output_paused,
p->flush_requested || p->applied_generation != p->buffer_generation.load()};
}
void audio_output_pause(gvfg_audio_player p, bool paused)
{
if (p) { p->pause_requested = paused; p->queued.notify_one(); }
}
void audio_output_rate(gvfg_audio_player p, double ratio)
{
if (p) p->rate_ratio = ratio;
}
@@ -0,0 +1,49 @@
# Public playback DLL; backend libraries remain implementation details.
enable_language(RC)
add_library(gvfg_playback SHARED
gvfg_playback.def
include/gvfg_playback.h
src/gvfg_playback.cpp
src/playback_timing.h
src/signal_card.h
src/signal_card.cpp
src/signal_card.rc
)
set_target_properties(gvfg_playback PROPERTIES AUTOMOC OFF AUTOUIC OFF AUTORCC OFF)
target_include_directories(gvfg_playback
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/include
${CMAKE_CURRENT_SOURCE_DIR}/../gvfg_preview/include
${CMAKE_CURRENT_SOURCE_DIR}/../gvfg_audio_playback/include
PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src
${CMAKE_CURRENT_SOURCE_DIR}/../gvfg_audio_playback/src
${CMAKE_CURRENT_SOURCE_DIR}/../gvfg_preview/src
)
target_compile_definitions(gvfg_playback PRIVATE GVFG_PLAYBACK_BUILD)
target_link_libraries(gvfg_playback PRIVATE gvfg_audio_playback gvfg_preview user32 gdi32 comctl32)
if(MSVC)
target_compile_options(gvfg_playback PRIVATE /utf-8 /EHsc)
endif()
if(MSVC AND GVFG_MINGW_DLLTOOL)
add_custom_command(TARGET gvfg_playback POST_BUILD
COMMAND "${GVFG_MINGW_DLLTOOL}"
-d "${CMAKE_CURRENT_SOURCE_DIR}/gvfg_playback.def"
-D gvfg_playback.dll -l libgvfg_playback.dll.a
WORKING_DIRECTORY "${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}"
COMMENT "Generating MinGW import library for gvfg_playback.dll"
VERBATIM
)
install(FILES "${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}/libgvfg_playback.dll.a"
DESTINATION ${CMAKE_INSTALL_LIBDIR})
endif()
install(TARGETS gvfg_playback
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
# Backend headers supply the frame/format/stat types used by the public API.
install(FILES include/gvfg_playback.h
../gvfg_audio_playback/include/gvfg_audio_playback.h
../gvfg_preview/include/gvfg_preview.h
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
# This README describes private internals. Customer guides are installed by
# the SDK root with the same relative layout as docs/.
+184
View File
@@ -0,0 +1,184 @@
# Playback 維護與同步實作
SDK 2.1.1;客戶整合從 [公開播放手冊](../../../docs/GVFG_PLAYBACK_API.md) 開始,
逐參數契約見 [API Reference](../../../docs/GVFG_Customer_doc/GVFG_CUSTOMER_API_REFERENCE.md)。
本文件供 SDK 維護者,說明目前實作,不作為 Customer Demo 的除錯畫面需求。
`signal_card.cpp` 管理 UI 執行緒上的原生 child overlay;圖片以 bitmap resource
內嵌 DLL,不相依 Qt 或外部圖片。`set_signal_connected()` 只轉交訊號狀態,
不介入播放 worker。Parent subclass 處理 resize/銷毀,detach/destroy 回收 overlay。
預設有訊號;未呼叫時不建立圖卡視窗。相關 API 與 HWND lifecycle 由 UI 執行緒序列化。
## 1. 模組與二進位邊界
```text
Application: read Capture frame → submit Playback → release Capture token
↓
gvfg_playback.dll
gvfg_playback_t: 模式、共同狀態、queue、Clock、AudioTimeline、DriftFilter
↓ ↓
gvfg_preview STATIC gvfg_audio_playback STATIC
D3D upload / conversion / Present PCM / WASAPI / raw frame position
```
Playback 是 SHARED target;兩個 backend 是 PRIVATE 連結的 STATIC target,只有 Playback 函式匯出。
`.def` 在本目錄。客戶標頭包含 backend header 只是重用資料型別,不對外匯出 backend 函式。
Capture DLL 與 Playback DLL 沒有互相接管 handle,SDK source 仍依 target 各自維護。
## 2. 物件與執行緒
| 位置 | 責任 |
|---|---|
| `src/gvfg_playback.cpp` | C ABI、參數驗證、queue、共同 worker、排程與控制 |
| `src/playback_timing.h` | sample_time、Clock、AudioSourceClock、AudioTimeline、DriftFilter |
| `../gvfg_audio_playback/src/audio_output_internal.h` | 同 DLL 內的私有 raw position/pause/rate bridge |
| `../gvfg_preview/src/gvfg_preview.cpp` | D3D upload slots、呈現 worker、完成通知與統計 |
應用程式可有一個 video 與一個 audio producer,submit 時短暫持有 core mutex 並複製。
共用 worker 決定送給 WASAPI 的 PCM 與到期影像;各 backend 另有自己的 worker。
控制 API 不由 Demo 重新實作時鐘。caller 必須序列化控制操作,協調 producer 與 handle/HWND lifetime。
## 3. SDK timestamp 與來源 PTS
Capture video/audio timestamp 來自 SDK 的 steady_clock 交付時刻,時鐘域相同;
不是硬體曝光/收音 timestamp,也不是 UTC。兩路各自嚴格遞增。
影像沿用此值;第一包音訊扣除包長估起點,後續由 AudioSourceClock 建立連續 spans。
名義 sample 數仍提供基礎時長;與 delivery clock 的誤差使用約 500 ms 平滑、5 ms 容忍區,
每包來源時長最多伸縮 0.25%。此 mapping 不丟棄 PCM,也不把 callback jitter 直接套到每包 PTS。
AudioTimeline 將實際 consumed frames 依 span 的起訖 PTS 插值,輸出調速仍由 DriftFilter 處理。
若忽略來源時鐘偏差,只把第一包 PTS 加上永久累計 sample 數,較慢供應會讓 audio horizon
逐漸落後 delivery timestamp,進入共用 buffering 並累積影像佇列;較快供應則可能堆積音訊。
起點並不是把第一筆音影相減後設為永久零誤差,未知 pipeline 延遲仍存在。
`sample_time` 先做整數商與餘數,避免長時間 frames × 1e9 先溢位。
AudioTimeline 在 PCM 成功送入低階輸出時保存來源 spans;先配置 mapping,拒收則 rollback。
Audio backend 只回報 played_frames 與 queued_frames,不知道 video 或來源 PTS。
## 4. Clock 與 master
| 模式 | master |
|---|---|
| Video-only | 強制 External |
| Audio-only | 強制 Audio |
| Audio-video | config 選 External/Audio/Video,預設 External |
Clock 保存 PTS 錨點、steady wall time 與 paused。External 在錨點上加單調經過時間;
Video 在成功呈現或隱藏消化後更新,再於影格間推進。
Audio 以 written_frames 減 WASAPI padding 估算 consumed frames,再由 AudioTimeline 映射來源位置。
它不是實體 speaker 的聲學時鐘;Present 也不代表 scanout 已完成。
共同 PTS 只定義座標;master 決定追趕哪個播放進度。設定 Video master 不會讓缺少的 PCM 提早產生,
也不保證任意 GPU 能以輸入速率呈現全部 frame。
## 5. 緩衝與排程
1. 等所有啟用串流的第一筆資料,取較早來源起點建立 paused clocks。
2. 在仍暫停時完成首次 GPU prepare,避免資源建立消耗正在播放的小段 audio lead。
3. 以 video 最後來源時間及 audio 已接受 sample 結尾的共同 horizon 判斷 preroll,預設 100 ms。
4. 覆蓋足夠後開始;video 保留一張 lookahead,不假設有限資料最後一幀的 duration。
5. 每輪把 audio 補到約 40 ms lead;不是每張影像只准送一包 10 ms PCM。
6. 依 master 提交到期影像;若下一張也已到期,External/Audio master 退休舊張,保留最新到期影格。
7. 若 horizon 用盡或音訊真正 starvation,短暫重新緩衝;超時後改為獨立播放。
過期退休也可在 producer 送入時執行,避免共用 worker 暫時等 GPU 時讓舊預覽堆滿 queue。
正常 buffering 或 Video master 不執行此自動過期退休。
queue 壓力、超過 250 ms 的影音/來源映射誤差、正向音訊交付缺口,或等待超過
max(250 ms, 2 × preroll),都會自動降級。初始永遠收不到音訊也不會永久卡住影像。
降級時 video 立即消化最新可用影格,各種 master 都可退休舊預覽;GPU in-flight 已佔滿
byte budget 時可直接計數略過新輸入,而不超額配置或讓擷取停止。
audio 取消舊 queue,透過 backend 的既有 reset 清除輸出 padding,完成 reset 後才接受新的 frame mapping。
backend position 的 resetting 旗標與 generation 在 mutex 下協調,避免舊 consumed frames 套到新 spans。
音訊以原速獨立播放,保留有界的近期 PCM;軟體 queue 過時資料可丟棄,無資料時不輸出聲音。
降級輸出的短 reserve 最多 20 ms,等待稀疏封包最多 40 ms,不要求影音同時 preroll。
恢復用兩秒 delivery/nominal PCM 的線性回歸估計來源速率,允許 ±0.25%;
使用窗口內所有觀測,避免單一批次交付的端點 jitter 誤判來源不穩。
輸入新鮮、音訊進度與 video clock 差在 150 ms 內且條件持續兩秒後,採納共同位置恢復同步。
恢復不重啟擷取、不 flush 正在輸出的 PCM,但重新對齊可能短暫保留影像。
`gvfg_playback_set_sync_enabled()` 控制 handle 的同步選擇,預設 true,保留到 stop/start 與 reset。
關閉時使用同一套獨立播放排程並禁止恢復;重開會重新觀察穩定條件,不直接跳回 master。
此函式不改 config layout,切換時透過 core mutex 協調;主動關閉不計為 sync_fallbacks。
單筆資料大於設定容量是 EINVAL;普通 queue 壓力不再產生 EQUEUE_FULL。
## 6. GPU 完成與略過
呈現使用 Preview 的自有 upload resources;CPU source 只需維持到 render 返回。
共用 worker 等待該工作退休後才送下一張,因此不把每次 render 接受誤認為成功 Present。
背景 thread 用 `idleCv_` 等待工作完成通知,不逐幀輪詢 Windows 1 ms 計時器。
HWND owner 的同步等待仍服務 sent messages,避免 DXGI 與 UI thread 互等。
初次 prepare 在緩衝期間做;正常每張不再重複 prepare 與前置 idle 等待。
真正後端 failure 導致 EOUTPUT;GPU busy/後端過期是計數略過,不是 Capture failure。
`video_processed` 包含呈現、隱藏消化與略過;`video_dropped` 是過期/busy 略過,不能當 driver drop。
底層 Preview delivery 計數不包含 core 在送 GPU 前已退休的所有 frame。
## 7. 音訊補償
Audio master 不調整音訊速率。其他 master 每約 20 ms 以 audio PTS 減 master PTS 更新 DriftFilter:
- 平滑誤差,暖機 20 次;3 ms 以內的目標速率為 1.0。
- 目標比例限制 0.995~1.005,每次比例變化最多 0.0001。
- 超過 250 ms 的誤差會清 filter 並回到 1.0;不是大幅失步的自動修復機制。
WASAPI 使用 shared-mode AUTOCONVERTPCM、SRC_DEFAULT_QUALITY、RATEADJUST,
透過 `IAudioClockAdjustment::SetSampleRate()` 執行指令;不支援或操作失敗會回報輸出錯誤。
本實作沒有舊 QAudioSink 的兩秒自動重建裝置策略,也沒有無界加速補回未知遺失 samples。
## 8. 與 FFplay 的對應及差異
設計參考 [FFplay 原始碼](https://ffmpeg.org/doxygen/trunk/ffplay_8c_source.html),獨立實作,未引入 FFmpeg/SDL runtime。
| FFplay 概念 | 目前實作 |
|---|---|
| VideoState/Clock/master 選擇 | gvfg_playback_t/Clock/config |
| video_refresh 與 late frame drop | 到期呈現、保留最新到期影格;預設非 Video master 可退休 |
| audio output clock 與 pending buffer | WASAPI consumed frames/padding +來源 spans |
| synchronize_audio/swr compensation | DriftFilter + Windows SetSampleRate |
不是完整 FFplay 移植:沒有 decoder/demuxer、seek、EOS drain 或相同的全部門檻與策略。
共同緩衝、有界 queue、音訊來源時間估計與目前補償上限都是本 SDK 的選擇。
不能宣稱 FFplay 可以做的任意格式/裝置恢復,本 SDK 就全部具備。
## 9. 錯誤、ABI 與回收
core 非同步失敗保存在 last_error,worker 暫停,後續 submit 回報同一錯誤;running 可能仍為 1。
stop/reset 取消 queue,不是無損 drain。reset 沿用舊 config,音訊格式改變應明確 stop/start 新設定。
呼叫端先停止/join read producers、release token,再停止 Playback 與 Capture。
2.0.2 stats 尾端新增 video_dropped;2.0.4 追加 sync_degraded、sync_fallbacks、audio_dropped_frames。
getter 明確接受目前大小、2.0.2/2.0.3 大小及 2.0.0/2.0.1 原始大小,
只回填 caller 提供的範圍;不是對任意 struct_size 都相容。config 仍要求目前完整大小。
公開 API/資料變更需同步標頭、匯入庫、DLL、Reference 與 Demo,避免混版。
## 10. 既有驗證範圍
既有 MSVC build/exports/dependencies/C header 檢查通過;這是靜態與連結證據。
既有實際 Qt Sample 測試為 CH0 1080p YUY2、48 kHz stereo PCM16、External master、120 秒,
含視窗/全螢幕切換:約 60 fps,queue 未持續增長;7166 張輸入,processed 7160、presented 7158、dropped 2。
其餘待播 frame 在 stop 時取消。
慢速輸出模擬為 60 fps 輸入、30 ms/張輸出與 busy:300 張輸入,略過 159、呈現 134、最大 queue 8、無拒收;舊 stats guard 通過。
2.0.3 的決定性模擬使用實際 Playback core,僅替換時鐘/worker 步進與輸出後端:
舊版在 audio source 慢 500 ppm 時,910.084 秒出現 buffering、video queue 32、EQUEUE_FULL。
修正後 External master 的 source ±500/±2000 ppm、output ±300 ppm 與組合案例各模擬 7200 秒,
無 queue rejection,video queue 最高 6~7。另驗證 Audio/Video master、video-only、audio-only;
Audio master 遇到來源較慢時仍會耗盡既有緩衝並重新緩衝,未宣稱音訊裝置成為 master 後仍自動調速。
44.1/48/96 kHz 變動包長、delivery jitter、span 單調及邊界映射檢查通過。
另以未修改的 Release DLL 與實際 WASAPI 輸出測試 60 秒,合成 PCM 供應慢 0.2%、
60 fps 隱藏影像:3600 張提交、3594 張處理、queue 最高 9、拒收 0、重新緩衝 0;
結束時 audio queue 77.73 ms、rate ratio 0.997830。此測試不含 Capture 硬體或 GPU 呈現。
模擬不是實際兩小時硬體播放,也不是聲學/嘴型延遲驗證。
2.0.4 決定性 core 模擬通過:完全無音訊、延後出現、五秒斷音、五秒停影、
來源半速/兩倍速及恢復、各 master、video-only/audio-only、GPU worker 暫停且 video queue 只有兩張。
檢查無拒收、容量不超限、影像持續消化、來源恢復後退出降級,以及兩種既有 stats 大小的尾端 guard。
後端模擬 reset 延遲五毫秒,驗證 reset 完成前不會餵入新 mapping。
正常 ±500 ppm 各模擬兩小時,沒有降級,video queue 最大 6~7。
另以實際 Release DLL/WASAPI、合成 PCM 與隱藏影像跑 60 秒,包含三秒斷音、
五秒兩倍音訊、五秒半速音訊、三秒停影;四次降級均恢復,queue 拒收 0、video queue 最大 22。
3420 張提交、3414 張處理;剩餘待播影格於 stop 取消。
這些測試未使用 Capture 硬體、實體 GPU 呈現或聲學同步量測。臨時測試檔於完成後清除。
同步開關另以實際 Release DLL/WASAPI 驗證啟動前關閉、運行中開啟並恢復、再次關閉,
以及 reset/stop-start 保留關閉選擇;非法參數回傳 EINVAL。
@@ -0,0 +1,20 @@
LIBRARY gvfg_playback
EXPORTS
gvfg_playback_default_config
gvfg_playback_create
gvfg_playback_attach_window
gvfg_playback_set_signal_connected
gvfg_playback_start
gvfg_playback_present_image
gvfg_playback_submit_video
gvfg_playback_submit_audio
gvfg_playback_set_volume
gvfg_playback_set_sync_enabled
gvfg_playback_reset_timeline
gvfg_playback_stop
gvfg_playback_destroy
gvfg_playback_get_stats
gvfg_playback_get_preview_info
gvfg_playback_get_preview_stats
gvfg_playback_get_delivery_stats
gvfg_playback_strerror
@@ -0,0 +1,138 @@
#pragma once
/* Unified playback API, exported by gvfg_playback.dll.
* Audio and preview backends are statically linked into this DLL.
* Capture remains application owned. Submissions COPY data before returning;
* the caller may immediately release its SDK frame. Handles own both outputs.
* Control calls (start/stop/reset/attach/destroy) must be serialized by the
* caller; one video producer and one audio producer may submit concurrently.
*/
#include "gvfg_audio_playback.h"
#include "gvfg_preview.h"
#ifdef _WIN32
#ifdef GVFG_PLAYBACK_BUILD
#define GVFG_PLAYBACK_API __declspec(dllexport)
#else
#define GVFG_PLAYBACK_API __declspec(dllimport)
#endif
#else
#define GVFG_PLAYBACK_API
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef struct gvfg_playback_t *gvfg_playback;
typedef enum {
GVFG_PLAYBACK_OK = 0,
GVFG_PLAYBACK_EINVAL = -1,
GVFG_PLAYBACK_ESTATE = -2,
GVFG_PLAYBACK_EOUTPUT = -3,
GVFG_PLAYBACK_EQUEUE_FULL = -4,
GVFG_PLAYBACK_EDISCONTINUITY = -5,
GVFG_PLAYBACK_EAUDIO = -6 /* A/V audio output disabled; video remains running. */
} gvfg_playback_status_t;
typedef enum {
GVFG_PLAYBACK_VIDEO_ONLY = 1,
GVFG_PLAYBACK_AUDIO_ONLY = 2,
GVFG_PLAYBACK_AUDIO_VIDEO = 3
} gvfg_playback_mode_t;
typedef enum {
GVFG_PLAYBACK_MASTER_EXTERNAL = 0,
GVFG_PLAYBACK_MASTER_AUDIO = 1,
GVFG_PLAYBACK_MASTER_VIDEO = 2
} gvfg_playback_master_t;
typedef struct {
uint32_t struct_size;
gvfg_playback_mode_t mode;
gvfg_playback_master_t master;
gvfg_audio_playback_format_t audio_format;
uint32_t preroll_ms; /* Default 100; required coverage of both streams. */
uint32_t max_video_frames; /* Default 32; late preview frames are retired and counted. */
uint32_t max_audio_ms; /* Default 1000. */
uint64_t max_video_bytes; /* Default 256 MiB, including in-flight copy. */
} gvfg_playback_config_t;
typedef struct {
gvfg_preview_frame_t image;
uint64_t timestamp_ns; /* Common monotonic delivery clock, NOT UTC. */
} gvfg_playback_video_frame_t;
typedef struct {
uint32_t struct_size;
int running;
int buffering;
gvfg_playback_status_t last_error;
uint64_t video_submitted;
uint64_t video_processed; /* Includes hidden frames and counted late/skipped previews. */
uint64_t video_presented;
uint64_t audio_submitted;
uint64_t queue_rejections;
uint64_t rebuffer_count;
uint64_t video_queue_bytes;
uint32_t video_queue_frames;
double audio_queue_ms;
uint64_t video_timestamp_ns;
uint64_t audio_timestamp_ns; /* Estimated output position, NOT acoustic time. */
int64_t av_difference_ns; /* audio - video; valid only with both clocks. */
double audio_rate_ratio;
uint64_t video_dropped; /* Late or GPU-busy preview frames; never audio/recording loss. */
int sync_degraded; /* Independent best-effort playback; capture may continue. */
uint64_t sync_fallbacks;
uint64_t audio_dropped_frames; /* PCM frames discarded from the core queue, not device padding. */
} gvfg_playback_stats_t;
GVFG_PLAYBACK_API void gvfg_playback_default_config(gvfg_playback_config_t *config);
GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_create(gvfg_playback *out);
/* A null HWND hides video while preserving its timeline. Attach on HWND thread. */
GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_attach_window(gvfg_playback p, void *hwnd);
/* Forward Capture's signal.connected (0/1). The helper owns the NO SIGNAL
* overlay; it does not query Capture or infer signal from missing frames.
* Call on the attached HWND thread, serialized with attach/destroy.
* Default connected=1. State persists across stop/start/reset and reattach. */
GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_set_signal_connected(gvfg_playback p, int connected);
GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_start(gvfg_playback p, const gvfg_playback_config_t *config);
/* Monotonic timestamps required per stream. Zero/reversed timestamps rejected.
* Queue pressure triggers bounded best-effort playback; obsolete queued data
* may be discarded even on OK. Never block capture holding an SDK frame.
* A single packet/frame exceeding its configured capacity returns EINVAL.
* Each PCM submission must contain at most 100 ms of audio.
* Audio timestamp is SDK DELIVERY time. The first PCM sample is estimated by
* subtracting packet duration. Following PCM remains continuous while its
* source-time mapping smoothly tracks long-term delivery-clock differences.
* Forward audio delivery gaps recover automatically in best-effort playback.
* Delivery timestamps cannot recover unknown hardware latency or lost samples.
*/
GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_submit_video(gvfg_playback p, const gvfg_playback_video_frame_t *frame);
/* Synchronously present one still image without starting a playback timeline.
* Requires an attached window and a stopped handle. Caller data stays valid
* through return. Used for RAW/DICOM image display; no audio is initialized. */
GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_present_image(gvfg_playback p, const gvfg_preview_frame_t *image);
/* In A/V mode an audio-output failure disables monitoring for this handle,
* preserving video playback. Subsequent audio submissions return EAUDIO.
* Keep capture/recording audio independent; do not retry output on this handle.
* Recreate the handle to retry monitoring. Stop/reset does not clear EAUDIO.
* A/V start may succeed with monitoring disabled; audio-only start still fails
* if its output is unavailable. Other errors retain their normal meaning. */
GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_submit_audio(gvfg_playback p, const void *pcm, uint32_t bytes, uint64_t timestamp_ns);
GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_set_volume(gvfg_playback p, float gain);
/* Default enabled=1. Set 0 for independent best-effort playback with no
* automatic return to synchronization. May be called before start or while
* active. Re-enabling waits for stable input/output before synchronizing.
* This choice persists across stop/start and reset_timeline. */
GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_set_sync_enabled(gvfg_playback p, int enabled);
/* Explicit discontinuity: discards pending output and establishes a new epoch.
* Stop/reset discard queued data; they are NOT lossless end-of-stream drains. */
GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_reset_timeline(gvfg_playback p);
GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_stop(gvfg_playback p);
GVFG_PLAYBACK_API void gvfg_playback_destroy(gvfg_playback p);
GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_get_stats(gvfg_playback p, gvfg_playback_stats_t *stats);
GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_get_preview_info(gvfg_playback p, gvfg_preview_info_t *info);
GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_get_preview_stats(gvfg_playback p, gvfg_preview_stats_t *stats);
GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_get_delivery_stats(gvfg_playback p, gvfg_preview_delivery_stats_t *stats);
GVFG_PLAYBACK_API const char *gvfg_playback_strerror(gvfg_playback_status_t status);
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,630 @@
#include "gvfg_playback.h"
#include "audio_output_internal.h"
#include "preview_output_internal.h"
#include "playback_timing.h"
#include "signal_card.h"
#include <windows.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <cstring>
#include <cstddef>
#include <cstdlib>
#include <deque>
#include <limits>
#include <mutex>
#include <new>
#include <thread>
#include <vector>
using namespace gvfg_playback_detail;
namespace {
uint64_t now_ns() {
return static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count());
}
// HWND owner may be joining a worker inside DXGI. Pump only synchronous sent
// messages, matching the preview helper's teardown contract.
void service_messages() {
MsgWaitForMultipleObjectsEx(0, nullptr, 1, QS_SENDMESSAGE, MWMO_INPUTAVAILABLE);
MSG msg{}; PeekMessageW(&msg, nullptr, 0, 0, PM_NOREMOVE | PM_QS_SENDMESSAGE);
}
}
struct gvfg_playback_t {
struct Video { gvfg_playback_video_frame_t frame{}; std::vector<uint8_t> data; };
struct Audio { uint64_t pts = 0, end = 0; std::vector<uint8_t> data; };
std::mutex mutex;
std::condition_variable changed;
std::thread worker;
std::atomic<bool> exited{true};
bool stopping = false, active = false;
bool sync_enabled = true;
bool audio_output_failed = false;
float gain = 1.0f;
void *hwnd = nullptr;
SignalCard signal_card;
gvfg_preview_handle preview = nullptr;
gvfg_audio_player audio = nullptr;
gvfg_playback_config_t config{};
gvfg_playback_stats_t stats{};
std::deque<Video> videos;
std::deque<Audio> audios;
uint64_t video_bytes = 0, audio_bytes = 0;
uint64_t first_video = 0, last_video = 0, first_audio = 0, audio_end = 0;
uint64_t last_audio_delivery = 0;
uint64_t start_wall = 0, buffering_since = 0;
uint64_t last_video_arrival = 0, last_audio_arrival = 0;
uint64_t stable_since = 0;
RecoveryRate recovery_rate;
bool fallback_audio_primed = false;
uint64_t audio_wait_since = 0;
AudioSourceClock audio_source_clock;
Clock external, video_clock;
DriftFilter drift;
AudioTimeline audio_timeline;
void drop_audio() {
stats.audio_dropped_frames += audio_bytes / (config.audio_format.channels * 2);
audios.clear(); audio_bytes = 0;
}
void reset_audio() {
if (!has_audio()) return;
drop_audio(); audio_source_clock = {}; audio_timeline = {};
first_audio = audio_end = 0;
audio_output_pause(audio, true); audio_output_rate(audio, 1.0);
if (gvfg_audio_player_reset_timeline(audio) != GVFG_AUDIO_PLAYBACK_OK)
fail_audio();
}
void degrade(uint64_t now, bool count_fallback = true) {
stable_since = 0; recovery_rate = {};
if (stats.sync_degraded) return;
stats.sync_degraded = 1;
if (count_fallback) ++stats.sync_fallbacks;
stats.buffering = 0;
const uint64_t live = last_video ? last_video : (audio_end ? audio_end : now);
external.set(live, now, false); video_clock.set(live, now, false);
drift = {}; stats.audio_rate_ratio = 1;
fallback_audio_primed = false; audio_wait_since = 0;
reset_audio();
}
bool has_video() const { return (config.mode & GVFG_PLAYBACK_VIDEO_ONLY) != 0; }
bool has_audio() const { return (config.mode & GVFG_PLAYBACK_AUDIO_ONLY) != 0 && !audio_output_failed; }
void fail_audio() {
if (!has_video()) { fail(GVFG_PLAYBACK_EOUTPUT); return; }
if (audio_output_failed) return;
audio_output_failed = true;
drop_audio();
gvfg_audio_player_destroy(audio); audio = nullptr;
audio_source_clock = {}; audio_timeline = {};
first_audio = audio_end = 0;
stats.audio_timestamp_ns = 0; stats.av_difference_ns = 0;
stats.audio_rate_ratio = 1;
// Retain video packets and move off a failed audio master. Monitoring
// remains disabled across resets; a fresh handle may retry the device.
degrade(now_ns());
}
void fail(gvfg_playback_status_t error) {
stats.last_error = error; stats.buffering = 1;
audio_output_pause(audio, true);
}
uint64_t master_time(uint64_t now) {
if (stats.sync_degraded) return external.get(now);
if (config.master == GVFG_PLAYBACK_MASTER_AUDIO && audio) {
const auto pos = audio_output_position(audio);
const auto pts = audio_timeline.position(pos.played_frames);
if (pts) return pts;
}
return config.master == GVFG_PLAYBACK_MASTER_VIDEO ? video_clock.get(now) : external.get(now);
}
void retire_late_video(uint64_t master) {
// FFplay-style automatic dropping for external/audio master. Keep the
// newest due frame, never a future frame, and account every retirement.
if (stats.buffering || (!stats.sync_degraded && config.master == GVFG_PLAYBACK_MASTER_VIDEO)) return;
while (videos.size() > 1 && (stats.sync_degraded || videos[1].frame.timestamp_ns <= master)) {
video_bytes -= videos.front().data.size(); videos.pop_front();
++stats.video_processed; ++stats.video_dropped;
}
}
void loop();
};
void gvfg_playback_t::loop() {
uint64_t last_control = 0;
bool started = false, preview_ready = false;
for (;;) {
std::unique_lock<std::mutex> lock(mutex);
if (stopping) break;
if (stats.last_error != GVFG_PLAYBACK_OK) {
changed.wait_for(lock, std::chrono::milliseconds(2)); continue;
}
// Warm up the GPU while outputs are still paused. Shader/resource
// creation must not consume the small running audio lead.
if (!preview_ready && hwnd && !videos.empty()) {
const auto image = videos.front().frame.image;
lock.unlock();
const bool ready = gvfg_preview_prepare(preview, image.width, image.height, image.bit_depth) == GVFG_PREVIEW_OK;
lock.lock();
if (!ready) { fail(GVFG_PLAYBACK_EOUTPUT); continue; }
preview_ready = true;
}
auto position = audio_output_position(audio);
if (has_audio() && !position.running) { fail_audio(); continue; }
uint64_t audio_pts = has_audio() ? audio_timeline.position(position.played_frames) : 0;
const uint64_t now = now_ns();
if (stats.sync_degraded) started = true;
uint64_t horizon = (std::numeric_limits<uint64_t>::max)();
if (has_video()) horizon = last_video; // Keep one-frame lookahead.
if (has_audio()) horizon = (std::min)(horizon, audio_end);
if ((!has_video() || first_video) && (!has_audio() || first_audio)) {
if (!started) {
const uint64_t origin = has_video() && has_audio() ? (std::min)(first_video, first_audio) :
(has_video() ? first_video : first_audio);
external.set(origin, now, true);
video_clock.set(origin, now, true);
started = true;
}
}
uint64_t master = external.get(now);
if (!stats.sync_degraded && started && config.master == GVFG_PLAYBACK_MASTER_AUDIO && audio_pts)
master = audio_pts;
else if (!stats.sync_degraded && started && config.master == GVFG_PLAYBACK_MASTER_VIDEO)
master = video_clock.get(now);
// Shared buffering: pause both outputs on starvation, preserve accepted
// data, and resume only after both enabled streams have coverage.
const uint64_t preroll = static_cast<uint64_t>(config.preroll_ms) * 1'000'000;
// An audio clock stops at its last consumed sample. Integer sample/ns
// rounding can leave it just below the horizon forever; starvation
// must also be detected from actual queued frames and feed eligibility.
const bool audio_starved = has_audio() && audio_pts &&
!position.queued_frames && (audios.empty() ||
(has_video() && audios.front().end > horizon));
if (!stats.sync_degraded && started && stats.buffering && horizon >= master && horizon - master >= preroll) {
stats.buffering = 0;
buffering_since = 0;
external.set(master, now, false);
video_clock.set(master, now, false);
} else if (!stats.sync_degraded && started && !stats.buffering && (master >= horizon || audio_starved)) {
++stats.rebuffer_count; stats.buffering = 1;
buffering_since = now;
master = (std::min)(master, horizon);
external.set(master, now, true); video_clock.set(master, now, true);
}
const uint64_t patience = (std::max)(250'000'000ULL, preroll * 2);
if (!stats.sync_degraded &&
((stats.buffering && now - (buffering_since ? buffering_since : start_wall) >= patience) ||
(has_audio() && last_audio_delivery && audio_end &&
std::llabs(difference(last_audio_delivery, audio_end)) > 250'000'000) ||
(has_audio() && audio_pts && started && !stats.buffering &&
std::llabs(difference(audio_pts, master)) > 250'000'000))) {
degrade(now); started = true;
position = audio_output_position(audio); audio_pts = 0;
}
if (stats.sync_degraded) {
master = external.get(now);
const bool fresh_video = !has_video() ||
(last_video_arrival && now - last_video_arrival < 100'000'000);
const bool fresh_audio = !has_audio() ||
(recovery_rate.stable && last_audio_arrival && now - last_audio_arrival < 100'000'000 &&
!position.resetting && audio_pts &&
(!has_video() || std::llabs(difference(audio_pts, master)) < 150'000'000));
if (sync_enabled && fresh_video && fresh_audio) {
if (!stable_since) stable_since = now;
if (now - stable_since >= 2'000'000'000) {
// Outputs already run independently. Adopt their current
// common position without flushing or stopping capture.
stats.sync_degraded = 0; stats.buffering = 0; buffering_since = 0;
master = has_audio() ? (std::min)(master, audio_pts) : master;
external.set(master, now, false); video_clock.set(master, now, false);
drift = {}; stable_since = 0;
}
} else stable_since = 0;
}
if (!started || stats.buffering) {
audio_output_pause(audio, true);
changed.wait_for(lock, std::chrono::milliseconds(2)); continue;
}
// Refill the complete output lead, not one packet per GPU iteration.
// SDK audio packets can be shorter than a single video presentation.
// A one-packet limit throttles 10 ms audio to the video frame rate.
const uint64_t audio_lead_ns = (std::min)(40'000'000ULL,
static_cast<uint64_t>(config.max_audio_ms) * 1'000'000);
uint64_t queued_frames = position.queued_frames;
while (has_audio() && !position.resetting && !audios.empty() &&
sample_time(queued_frames, config.audio_format.sample_rate) < audio_lead_ns) {
const Audio &packet = audios.front();
if (!stats.sync_degraded &&
(packet.pts > master + audio_lead_ns || (has_video() && packet.end > horizon))) break;
const uint64_t frames = packet.data.size() / (config.audio_format.channels * 2);
// Allocate the mapping before accepting PCM, then undo on rejection.
audio_timeline.append(packet.pts, frames, packet.end);
const auto status = gvfg_audio_player_write(audio, packet.data.data(),
static_cast<uint32_t>(packet.data.size()));
if (status != GVFG_AUDIO_PLAYBACK_OK) {
audio_timeline.rollback();
if (status != GVFG_AUDIO_PLAYBACK_EQUEUE_FULL) {
fail_audio(); audio_pts = 0;
}
break;
}
queued_frames += frames;
audio_bytes -= packet.data.size(); audios.pop_front();
}
if (stats.last_error != GVFG_PLAYBACK_OK) continue;
// Starting a stopped device with an empty queue would advance the
// system clock without content. Wait for a packet to actually be fed.
const auto fed_position = audio_output_position(audio);
bool wait_audio = fed_position.resetting || !fed_position.queued_frames;
if (stats.sync_degraded && has_audio() && !fed_position.resetting) {
if (!position.queued_frames) fallback_audio_primed = false;
if (fed_position.queued_frames && !audio_wait_since) audio_wait_since = now;
const uint64_t reserve = (std::min)(20'000'000ULL, audio_lead_ns);
if (sample_time(fed_position.queued_frames, config.audio_format.sample_rate) >= reserve ||
(audio_wait_since && now - audio_wait_since >= 40'000'000)) fallback_audio_primed = true;
wait_audio = !fed_position.queued_frames || !fallback_audio_primed;
if (!fed_position.queued_frames) audio_wait_since = 0;
}
audio_output_pause(audio, has_audio() && wait_audio);
stats.audio_timestamp_ns = audio_pts;
if (has_audio() && audio_pts && now - last_control >= 20'000'000) {
last_control = now;
const int64_t error = difference(audio_pts, master);
const double ratio = stats.sync_degraded || config.master == GVFG_PLAYBACK_MASTER_AUDIO ? 1.0 : drift.update(error);
stats.audio_rate_ratio = ratio;
audio_output_rate(audio, ratio);
}
retire_late_video(master);
if (has_video() && !videos.empty() && (stats.sync_degraded || videos.front().frame.timestamp_ns <= master)) {
Video packet = std::move(videos.front()); videos.pop_front();
packet.frame.image.data = packet.data.data();
const uint64_t pts = packet.frame.timestamp_ns;
void *target = hwnd;
lock.unlock();
bool ok = true, presented = false;
if (target) {
gvfg_preview_delivery_stats_t before{}, after{};
gvfg_preview_get_delivery_stats(preview, &before);
ok = gvfg_preview_render_frame(preview, &packet.frame.image) == GVFG_PREVIEW_OK &&
gvfg_preview_wait_idle(preview, 2000) == GVFG_PREVIEW_OK;
gvfg_preview_get_delivery_stats(preview, &after);
// A busy Present or an expired backend frame is a counted
// preview skip, not a capture/output failure.
ok = ok && after.failed == before.failed;
presented = after.presented == before.presented + 1;
}
lock.lock();
video_bytes -= packet.data.size();
if (!ok) { fail(GVFG_PLAYBACK_EOUTPUT); continue; }
++stats.video_processed;
if (presented) ++stats.video_presented;
else if (target) ++stats.video_dropped;
if (presented || !target) {
stats.video_timestamp_ns = pts;
video_clock.set(pts, now_ns(), false);
if (stats.sync_degraded) external.set(pts, now_ns(), false);
}
}
if (stats.audio_timestamp_ns && stats.video_timestamp_ns)
stats.av_difference_ns = difference(stats.audio_timestamp_ns, video_clock.get(now_ns()));
// Rendering already waited for the GPU. Do not add a timer wait when
// another video frame is due; coarse Windows timers can reduce FPS.
const uint64_t due_clock = stats.sync_degraded ? external.get(now_ns()) :
config.master == GVFG_PLAYBACK_MASTER_AUDIO && audio_pts ? audio_pts :
(config.master == GVFG_PLAYBACK_MASTER_VIDEO ? video_clock.get(now_ns()) : external.get(now_ns()));
if (!videos.empty() && videos.front().frame.timestamp_ns <= due_clock) continue;
changed.wait_for(lock, std::chrono::milliseconds(1));
}
}
extern "C" {
void gvfg_playback_default_config(gvfg_playback_config_t *c) {
if (!c) return;
*c = {}; c->struct_size = sizeof(*c); c->mode = GVFG_PLAYBACK_AUDIO_VIDEO;
c->master = GVFG_PLAYBACK_MASTER_EXTERNAL;
c->audio_format = {48000, 2, 16}; c->preroll_ms = 100;
c->max_video_frames = 32; c->max_audio_ms = 1000; c->max_video_bytes = 256ULL * 1024 * 1024;
}
gvfg_playback_status_t gvfg_playback_create(gvfg_playback *out) {
if (!out) return GVFG_PLAYBACK_EINVAL;
*out = nullptr;
try { *out = new gvfg_playback_t(); } catch (...) { return GVFG_PLAYBACK_EOUTPUT; }
return GVFG_PLAYBACK_OK;
}
gvfg_playback_status_t gvfg_playback_attach_window(gvfg_playback p, void *hwnd) {
if (!p) return GVFG_PLAYBACK_EINVAL;
if (!p->signal_card.on_window_thread() || (hwnd &&
GetWindowThreadProcessId(static_cast<HWND>(hwnd), nullptr) != GetCurrentThreadId()))
return GVFG_PLAYBACK_EINVAL;
// Attach/configure may send HWND messages: no playback mutex held here.
gvfg_preview_handle preview = nullptr;
{ std::lock_guard<std::mutex> lock(p->mutex); preview = p->preview; }
const bool created = hwnd && !preview;
if (created && gvfg_preview_create(&preview) != GVFG_PREVIEW_OK)
return GVFG_PLAYBACK_EOUTPUT;
if (hwnd && gvfg_preview_attach_window(preview, hwnd) != GVFG_PREVIEW_OK) {
if (created) gvfg_preview_destroy(preview);
return GVFG_PLAYBACK_EOUTPUT;
}
{
std::lock_guard<std::mutex> lock(p->mutex);
p->preview = preview; p->hwnd = hwnd;
}
return p->signal_card.attach(static_cast<HWND>(hwnd)) ? GVFG_PLAYBACK_OK : GVFG_PLAYBACK_EOUTPUT;
}
gvfg_playback_status_t gvfg_playback_set_signal_connected(gvfg_playback p, int connected) {
if (!p || (connected != 0 && connected != 1)) return GVFG_PLAYBACK_EINVAL;
if (!p->signal_card.on_window_thread()) return GVFG_PLAYBACK_EINVAL;
return p->signal_card.set_connected(connected != 0) ? GVFG_PLAYBACK_OK : GVFG_PLAYBACK_EOUTPUT;
}
gvfg_playback_status_t gvfg_playback_start(gvfg_playback p, const gvfg_playback_config_t *c) {
if (!p || !c || c->struct_size != sizeof(*c) || c->mode < 1 || c->mode > 3 ||
c->master < 0 || c->master > 2 || !c->max_video_frames || !c->max_video_bytes ||
!c->preroll_ms || c->preroll_ms > 1000 || c->max_audio_ms < c->preroll_ms ||
c->max_audio_ms > 10000 || c->max_video_frames > 600 ||
((c->mode & 2) && (!c->audio_format.sample_rate || c->audio_format.sample_rate > 384000 ||
!c->audio_format.channels || c->audio_format.channels > 32 || c->audio_format.bits_per_sample != 16)))
return GVFG_PLAYBACK_EINVAL;
std::lock_guard<std::mutex> lock(p->mutex);
if (p->active) return GVFG_PLAYBACK_ESTATE;
if (p->audio_output_failed && c->mode == GVFG_PLAYBACK_AUDIO_ONLY)
return GVFG_PLAYBACK_EOUTPUT;
p->config = *c;
if (c->mode == GVFG_PLAYBACK_VIDEO_ONLY) p->config.master = GVFG_PLAYBACK_MASTER_EXTERNAL;
if (c->mode == GVFG_PLAYBACK_AUDIO_ONLY) p->config.master = GVFG_PLAYBACK_MASTER_AUDIO;
p->stats = {}; p->stats.struct_size = sizeof(p->stats); p->stats.buffering = 1;
p->stats.running = 1; p->stats.audio_rate_ratio = 1;
p->stopping = false; p->first_video = p->last_video = p->first_audio = p->audio_end = 0;
p->last_audio_delivery = p->video_bytes = p->audio_bytes = 0;
p->audio_source_clock = {};
p->start_wall = now_ns(); p->buffering_since = 0;
p->last_video_arrival = p->last_audio_arrival = 0;
p->stable_since = p->audio_wait_since = 0;
p->fallback_audio_primed = false;
p->recovery_rate = {};
p->videos.clear(); p->audios.clear(); p->external = {}; p->video_clock = {}; p->drift = {}; p->audio_timeline = {};
if (p->has_audio()) {
try { p->audio = audio_output_create_managed(); }
catch (...) { p->audio = nullptr; }
if (!p->audio || gvfg_audio_player_start(p->audio, &c->audio_format) != GVFG_AUDIO_PLAYBACK_OK) {
if (!p->has_video()) {
gvfg_audio_player_destroy(p->audio); p->audio = nullptr; p->stats.running = 0;
p->stats.last_error = GVFG_PLAYBACK_EOUTPUT; return GVFG_PLAYBACK_EOUTPUT;
}
p->fail_audio();
}
if (p->audio) gvfg_audio_player_set_volume(p->audio, p->gain);
}
p->active = true; p->exited = false;
if (!p->sync_enabled || p->audio_output_failed) p->degrade(now_ns(), false);
try {
p->worker = std::thread([p] {
try { p->loop(); } catch (...) { std::lock_guard<std::mutex> lock(p->mutex); p->fail(GVFG_PLAYBACK_EOUTPUT); }
p->exited = true;
});
} catch (...) {
p->exited = true; p->active = false; p->stats.running = 0;
gvfg_audio_player_destroy(p->audio); p->audio = nullptr; return GVFG_PLAYBACK_EOUTPUT;
}
return GVFG_PLAYBACK_OK;
}
gvfg_playback_status_t gvfg_playback_submit_video(gvfg_playback p, const gvfg_playback_video_frame_t *f) {
if (!p || !f || !f->timestamp_ns || f->timestamp_ns > INT64_MAX || !f->image.data ||
f->image.width <= 0 || f->image.height <= 0 || f->image.row_bytes <= 0) return GVFG_PLAYBACK_EINVAL;
const auto &im = f->image;
const uint64_t row = im.pixel_format == GVFG_PREVIEW_PIXFMT_RGBA16 ? static_cast<uint64_t>(im.width) * 8 :
im.pixel_format == GVFG_PREVIEW_PIXFMT_Y210 ? static_cast<uint64_t>(im.width) * 4 :
im.pixel_format == GVFG_PREVIEW_PIXFMT_GRAY16 ? static_cast<uint64_t>(im.width) * 2 :
im.pixel_format == GVFG_PREVIEW_PIXFMT_YUY2 ? (static_cast<uint64_t>(im.width) + 1) / 2 * 4 :
im.pixel_format == GVFG_PREVIEW_PIXFMT_DICOM_YBR_FULL_422 ? (static_cast<uint64_t>(im.width) + 1) / 2 * 8 : 0;
const uint64_t size = static_cast<uint64_t>(im.row_bytes) * im.height;
if (!row || row > static_cast<uint64_t>(im.row_bytes) || size > im.data_size || size > SIZE_MAX)
return GVFG_PLAYBACK_EINVAL;
std::lock_guard<std::mutex> lock(p->mutex);
if (!p->active || p->stopping || !p->has_video()) return GVFG_PLAYBACK_ESTATE;
if (p->stats.last_error) return p->stats.last_error;
if (p->last_video && f->timestamp_ns <= p->last_video) return GVFG_PLAYBACK_EDISCONTINUITY;
if (size > p->config.max_video_bytes) return GVFG_PLAYBACK_EINVAL;
const uint64_t now = now_ns();
p->retire_late_video(p->master_time(now));
if (p->videos.size() >= p->config.max_video_frames ||
p->video_bytes > p->config.max_video_bytes - size) {
p->degrade(now);
while (!p->videos.empty() && (p->videos.size() >= p->config.max_video_frames ||
p->video_bytes > p->config.max_video_bytes - size)) {
p->video_bytes -= p->videos.front().data.size(); p->videos.pop_front();
++p->stats.video_processed; ++p->stats.video_dropped;
}
if (p->video_bytes > p->config.max_video_bytes - size) {
// An in-flight GPU copy owns the budget. Skip this incoming preview
// rather than allocate beyond the limit or stop the capture source.
p->last_video = f->timestamp_ns; p->last_video_arrival = now;
++p->stats.video_submitted; ++p->stats.video_processed; ++p->stats.video_dropped;
p->changed.notify_one(); return GVFG_PLAYBACK_OK;
}
}
try {
gvfg_playback_t::Video v; v.frame = *f;
const auto *begin = static_cast<const uint8_t *>(im.data);
v.data.assign(begin, begin + static_cast<size_t>(size));
p->videos.push_back(std::move(v));
} catch (...) { return GVFG_PLAYBACK_EOUTPUT; }
p->video_bytes += size; if (!p->first_video) p->first_video = f->timestamp_ns;
p->last_video = f->timestamp_ns; p->last_video_arrival = now;
++p->stats.video_submitted; p->changed.notify_one();
return GVFG_PLAYBACK_OK;
}
gvfg_playback_status_t gvfg_playback_present_image(gvfg_playback p, const gvfg_preview_frame_t *image) {
if (!p || !image || !image->data || image->width <= 0 || image->height <= 0)
return GVFG_PLAYBACK_EINVAL;
gvfg_preview_handle preview;
{
std::lock_guard<std::mutex> lock(p->mutex);
if (p->active || !p->hwnd || !p->preview) return GVFG_PLAYBACK_ESTATE;
preview = p->preview;
}
// Like attach/start/stop, callers serialize this control operation. Do not
// hold the playback mutex while DXGI can send synchronous HWND messages.
if (gvfg_preview_wait_idle(preview, 2000) != GVFG_PREVIEW_OK ||
gvfg_preview_prepare(preview, image->width, image->height, image->bit_depth) != GVFG_PREVIEW_OK ||
gvfg_preview_render_frame(preview, image) != GVFG_PREVIEW_OK ||
gvfg_preview_wait_idle(preview, 2000) != GVFG_PREVIEW_OK)
return GVFG_PLAYBACK_EOUTPUT;
return GVFG_PLAYBACK_OK;
}
gvfg_playback_status_t gvfg_playback_submit_audio(gvfg_playback p, const void *pcm, uint32_t bytes, uint64_t ts) {
if (!p || !pcm || !bytes || !ts || ts > INT64_MAX) return GVFG_PLAYBACK_EINVAL;
std::lock_guard<std::mutex> lock(p->mutex);
if (!p->active || p->stopping) return GVFG_PLAYBACK_ESTATE;
if (p->stats.last_error) return p->stats.last_error;
if (p->audio_output_failed) return GVFG_PLAYBACK_EAUDIO;
if (!p->has_audio()) return GVFG_PLAYBACK_ESTATE;
const uint32_t align = p->config.audio_format.channels * 2;
if (bytes % align) return GVFG_PLAYBACK_EINVAL;
if (p->last_audio_delivery && ts <= p->last_audio_delivery) return GVFG_PLAYBACK_EDISCONTINUITY;
const uint64_t limit = static_cast<uint64_t>(p->config.audio_format.sample_rate) * align * p->config.max_audio_ms / 1000;
if (bytes > limit) return GVFG_PLAYBACK_EINVAL;
const uint64_t frames = bytes / align, duration = sample_time(frames, p->config.audio_format.sample_rate);
if (duration > 100'000'000) return GVFG_PLAYBACK_EINVAL;
if (ts <= duration) return GVFG_PLAYBACK_EINVAL;
const uint64_t now = now_ns();
auto position = audio_output_position(p->audio);
if ((p->last_audio_delivery && ts - p->last_audio_delivery > 250'000'000 + duration) ||
p->audio_bytes + position.queued_frames * align > limit - bytes)
p->degrade(now);
if (p->audio_output_failed) return GVFG_PLAYBACK_EAUDIO;
position = audio_output_position(p->audio);
if (p->stats.sync_degraded) {
const uint64_t device_bytes = position.resetting ? 0 : position.queued_frames * align;
if (device_bytes > limit - bytes) p->reset_audio();
if (p->audio_output_failed) return GVFG_PLAYBACK_EAUDIO;
const uint64_t recent = (std::max)(static_cast<uint64_t>(bytes),
static_cast<uint64_t>(p->config.audio_format.sample_rate) * align * p->config.preroll_ms / 1000);
const uint64_t budget = (std::min)(limit - (device_bytes > limit - bytes ? 0 : device_bytes), recent);
while (!p->audios.empty() && p->audio_bytes > budget - bytes) {
p->stats.audio_dropped_frames += p->audios.front().data.size() / align;
p->audio_bytes -= p->audios.front().data.size(); p->audios.pop_front();
p->stable_since = 0; p->recovery_rate.stable = false;
}
}
// Commit clock state only after the packet has actually been accepted.
auto source_clock = p->stats.sync_degraded ? AudioSourceClock{} : p->audio_source_clock;
auto span = source_clock.advance(ts, frames, p->config.audio_format.sample_rate);
if (!p->stats.sync_degraded && std::llabs(difference(ts, span.end)) > 250'000'000) {
p->degrade(now); source_clock = {};
if (p->audio_output_failed) return GVFG_PLAYBACK_EAUDIO;
span = source_clock.advance(ts, frames, p->config.audio_format.sample_rate);
}
try {
gvfg_playback_t::Audio a; a.pts = span.pts;
a.end = span.end;
const auto *begin = static_cast<const uint8_t *>(pcm); a.data.assign(begin, begin + bytes);
p->audios.push_back(std::move(a));
} catch (...) { return GVFG_PLAYBACK_EOUTPUT; }
p->audio_source_clock = source_clock;
p->first_audio = source_clock.first;
p->audio_end = span.end;
p->last_audio_delivery = ts; p->audio_bytes += bytes; ++p->stats.audio_submitted;
p->last_audio_arrival = now;
if (p->stats.sync_degraded) {
p->recovery_rate.observe(ts, frames, p->config.audio_format.sample_rate);
}
p->changed.notify_one(); return GVFG_PLAYBACK_OK;
}
gvfg_playback_status_t gvfg_playback_set_volume(gvfg_playback p, float gain) {
if (!p || !std::isfinite(gain) || gain < 0 || gain > 2) return GVFG_PLAYBACK_EINVAL;
std::lock_guard<std::mutex> lock(p->mutex);
p->gain = gain;
if (p->audio && gvfg_audio_player_set_volume(p->audio, gain) != GVFG_AUDIO_PLAYBACK_OK) {
p->fail_audio();
return p->audio_output_failed ? GVFG_PLAYBACK_EAUDIO : GVFG_PLAYBACK_EOUTPUT;
}
return GVFG_PLAYBACK_OK;
}
gvfg_playback_status_t gvfg_playback_set_sync_enabled(gvfg_playback p, int enabled) {
if (!p || (enabled != 0 && enabled != 1)) return GVFG_PLAYBACK_EINVAL;
std::lock_guard<std::mutex> lock(p->mutex);
if (p->sync_enabled == (enabled != 0)) return GVFG_PLAYBACK_OK;
p->sync_enabled = enabled != 0;
p->stable_since = 0; p->recovery_rate = {};
if (p->active && !p->sync_enabled) p->degrade(now_ns(), false);
return GVFG_PLAYBACK_OK;
}
gvfg_playback_status_t gvfg_playback_stop(gvfg_playback p) {
if (!p) return GVFG_PLAYBACK_EINVAL;
{ std::lock_guard<std::mutex> lock(p->mutex); p->stopping = true; p->changed.notify_all(); }
while (!p->exited.load()) service_messages();
if (p->worker.joinable()) p->worker.join();
std::lock_guard<std::mutex> lock(p->mutex);
gvfg_audio_player_destroy(p->audio); p->audio = nullptr;
p->active = false; p->stats.running = 0; p->videos.clear(); p->audios.clear();
p->video_bytes = p->audio_bytes = 0;
return GVFG_PLAYBACK_OK;
}
gvfg_playback_status_t gvfg_playback_reset_timeline(gvfg_playback p) {
if (!p) return GVFG_PLAYBACK_EINVAL;
const bool active = p->active; const auto config = p->config;
gvfg_playback_stop(p);
if (p->preview && gvfg_preview_clear(p->preview) != GVFG_PREVIEW_OK) return GVFG_PLAYBACK_EOUTPUT;
return active ? gvfg_playback_start(p, &config) : GVFG_PLAYBACK_OK;
}
void gvfg_playback_destroy(gvfg_playback p) {
if (!p) return;
gvfg_playback_stop(p); p->signal_card.attach(nullptr);
gvfg_preview_destroy(p->preview); delete p;
}
gvfg_playback_status_t gvfg_playback_get_stats(gvfg_playback p, gvfg_playback_stats_t *s) {
// Keep 2.0.0/2.0.1 callers with the original struct size ABI-compatible.
constexpr uint32_t legacy_size = offsetof(gvfg_playback_stats_t, video_dropped);
constexpr uint32_t previous_size = offsetof(gvfg_playback_stats_t, sync_degraded);
if (!p || !s || (s->struct_size != sizeof(*s) && s->struct_size != legacy_size &&
s->struct_size != previous_size)) return GVFG_PLAYBACK_EINVAL;
const uint32_t requested_size = s->struct_size;
std::lock_guard<std::mutex> lock(p->mutex);
auto result = p->stats; result.struct_size = requested_size;
result.video_queue_bytes = p->video_bytes; result.video_queue_frames = static_cast<uint32_t>(p->videos.size());
if (p->has_audio() && p->audio) {
const auto pos = audio_output_position(p->audio);
result.audio_timestamp_ns = p->audio_timeline.position(pos.played_frames);
result.audio_queue_ms = (static_cast<double>(p->audio_bytes) / (p->config.audio_format.channels * 2) + pos.queued_frames) *
1000.0 / p->config.audio_format.sample_rate;
}
std::memcpy(s, &result, requested_size);
return GVFG_PLAYBACK_OK;
}
gvfg_playback_status_t gvfg_playback_get_preview_info(gvfg_playback p, gvfg_preview_info_t *s) {
if (!p || !s) return GVFG_PLAYBACK_EINVAL;
std::lock_guard<std::mutex> lock(p->mutex);
*s = {}; return !p->preview || gvfg_preview_get_info(p->preview, s) == GVFG_PREVIEW_OK ? GVFG_PLAYBACK_OK : GVFG_PLAYBACK_EOUTPUT;
}
gvfg_playback_status_t gvfg_playback_get_preview_stats(gvfg_playback p, gvfg_preview_stats_t *s) {
if (!p || !s) return GVFG_PLAYBACK_EINVAL;
std::lock_guard<std::mutex> lock(p->mutex);
*s = {}; return !p->preview || gvfg_preview_get_stats(p->preview, s) == GVFG_PREVIEW_OK ? GVFG_PLAYBACK_OK : GVFG_PLAYBACK_EOUTPUT;
}
gvfg_playback_status_t gvfg_playback_get_delivery_stats(gvfg_playback p, gvfg_preview_delivery_stats_t *s) {
if (!p || !s) return GVFG_PLAYBACK_EINVAL;
std::lock_guard<std::mutex> lock(p->mutex);
*s = {}; return !p->preview || gvfg_preview_get_delivery_stats(p->preview, s) == GVFG_PREVIEW_OK ? GVFG_PLAYBACK_OK : GVFG_PLAYBACK_EOUTPUT;
}
const char *gvfg_playback_strerror(gvfg_playback_status_t s) {
switch (s) {
case GVFG_PLAYBACK_OK: return "ok";
case GVFG_PLAYBACK_EINVAL: return "invalid playback argument or format";
case GVFG_PLAYBACK_ESTATE: return "playback is not running or stream disabled";
case GVFG_PLAYBACK_EOUTPUT: return "playback output failed; inspect device/window and restart";
case GVFG_PLAYBACK_EQUEUE_FULL: return "playback buffer limit reached; packet not accepted";
case GVFG_PLAYBACK_EDISCONTINUITY: return "timestamp discontinuity; reset timeline";
case GVFG_PLAYBACK_EAUDIO: return "audio output disabled; video continues; recreate playback to retry audio";
default: return "unknown playback error";
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 MiB

@@ -0,0 +1,119 @@
#pragma once
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <deque>
namespace gvfg_playback_detail {
constexpr uint64_t second = 1'000'000'000ULL;
inline uint64_t sample_time(uint64_t frames, uint32_t rate) {
return frames / rate * second + frames % rate * second / rate;
}
inline int64_t difference(uint64_t a, uint64_t b) {
return a >= b ? static_cast<int64_t>(a - b) : -static_cast<int64_t>(b - a);
}
// PCM sample count is nominal media time; SDK video timestamps are delivery
// time. Track slow source-clock differences without assigning callback jitter
// directly to every packet. This cannot recover missing samples or determine
// hardware capture latency. The resulting spans remain contiguous.
struct AudioSourceClock {
uint64_t first = 0, frames = 0, end = 0;
int64_t offset = 0;
double filtered_error = 0;
struct Packet { uint64_t pts, end; };
Packet advance(uint64_t delivery, uint64_t count, uint32_t rate) {
const uint64_t previous = sample_time(frames, rate);
const uint64_t total = sample_time(frames + count, rate);
const uint64_t duration = total - previous;
if (!end) {
first = delivery - duration;
frames += count; end = delivery;
return {first, end};
}
const uint64_t nominal = first + total;
const uint64_t predicted = offset >= 0 ? nominal + offset : nominal - static_cast<uint64_t>(-offset);
const double alpha = (std::min)(1.0, static_cast<double>(duration) / 500'000'000.0);
filtered_error += alpha * (static_cast<double>(difference(delivery, predicted)) - filtered_error);
constexpr double tolerance = 5'000'000; // Ignore small delivery jitter.
const double phase = filtered_error > tolerance ? filtered_error - tolerance :
(filtered_error < -tolerance ? filtered_error + tolerance : 0);
// At most 0.25% source-time stretch per packet; output drift correction
// remains responsible for resampling, independently of this mapping.
const double limit = static_cast<double>(duration) / 400.0;
offset += static_cast<int64_t>(std::clamp(phase, -limit, limit));
const uint64_t begin = end;
end = offset >= 0 ? nominal + offset : nominal - static_cast<uint64_t>(-offset);
frames += count;
return {begin, end};
}
};
// Fit delivered nominal PCM duration against delivery time over a window.
// Using all observations avoids classifying one batched callback's endpoint
// jitter as a sustained source-rate mismatch during recovery.
struct RecoveryRate {
uint64_t first = 0, frames = 0, count = 0;
double x = 0, y = 0, xx = 0, xy = 0;
bool stable = false;
void observe(uint64_t delivery, uint64_t samples, uint32_t rate) {
if (!first || delivery - first > 3'000'000'000) {
*this = {}; first = delivery; return;
}
frames += samples;
const uint64_t elapsed = delivery - first;
const double t = static_cast<double>(elapsed) / second;
const double media = static_cast<double>(frames) / rate;
++count; x += t; y += media; xx += t * t; xy += t * media;
if (elapsed >= 2'000'000'000) {
const double denominator = count * xx - x * x;
stable = denominator > 0 && std::fabs((count * xy - x * y) / denominator - 1.0) <= .0025;
first = delivery; frames = count = 0; x = y = xx = xy = 0;
}
}
};
// Source-time mapping belongs to the shared playback core. The backend only
// reports consumed PCM frames; accepted spans follow the same FIFO order.
struct AudioTimeline {
struct Span { uint64_t end_frame, pts, frames, end_pts; };
std::deque<Span> spans;
uint64_t accepted_frames = 0;
void append(uint64_t pts, uint64_t frames, uint64_t end_pts) {
spans.push_back({accepted_frames + frames, pts, frames, end_pts});
accepted_frames += frames;
}
void rollback() {
accepted_frames -= spans.back().frames;
spans.pop_back();
}
uint64_t position(uint64_t played) {
while (spans.size() > 1 && played >= spans.front().end_frame) spans.pop_front();
if (spans.empty()) return 0;
const auto &span = spans.front();
const uint64_t begin = span.end_frame - span.frames;
const uint64_t offset = played > begin ? (std::min)(played - begin, span.frames) : 0;
return span.pts + offset * (span.end_pts - span.pts) / span.frames;
}
};
struct Clock {
uint64_t pts = 0, wall = 0;
bool paused = true;
uint64_t get(uint64_t now) const { return pts + (!paused && now > wall ? now - wall : 0); }
void set(uint64_t value, uint64_t now, bool stop) { pts = value; wall = now; paused = stop; }
};
// FFplay-style filtered A/V error, implemented independently. Audio output
// rate adjustment is delegated to Windows shared-mode resampling (no FFmpeg
// runtime dependency). Slew limit prevents audible abrupt speed changes.
struct DriftFilter {
double average = 0, ratio = 1;
unsigned count = 0;
double update(int64_t error_ns) {
const double error = static_cast<double>(error_ns) / second;
if (std::fabs(error) > .250) { average = 0; count = 0; ratio = 1; return ratio; }
average = count ? average * .9 + error * .1 : error;
if (++count < 20) return ratio;
const double target = std::fabs(average) < .003 ? 1.0 :
std::clamp(1.0 - average / 2.0, .995, 1.005);
ratio += std::clamp(target - ratio, -.0001, .0001);
return ratio;
}
};
}
@@ -0,0 +1,78 @@
#include "signal_card.h"
SignalCard::~SignalCard() {
detach();
if (bitmap_) DeleteObject(bitmap_);
}
bool SignalCard::on_window_thread() const {
return !parent_ || GetWindowThreadProcessId(parent_, nullptr) == GetCurrentThreadId();
}
void SignalCard::detach() {
if (parent_) RemoveWindowSubclass(parent_, parent_proc, reinterpret_cast<UINT_PTR>(this));
if (view_) DestroyWindow(view_);
parent_ = view_ = nullptr;
}
bool SignalCard::attach(HWND parent) {
if (!on_window_thread() || (parent &&
GetWindowThreadProcessId(parent, nullptr) != GetCurrentThreadId())) return false;
if (parent_ == parent) return set_connected(connected_);
detach();
parent_ = parent;
if (parent_ && !SetWindowSubclass(parent_, parent_proc,
reinterpret_cast<UINT_PTR>(this), reinterpret_cast<DWORD_PTR>(this))) {
parent_ = nullptr;
return false;
}
return set_connected(connected_);
}
bool SignalCard::set_connected(bool connected) {
if (!on_window_thread()) return false;
if (connected_ == connected && (connected || view_)) return true;
connected_ = connected;
if (!parent_) return true;
if (connected) {
if (view_) ShowWindow(view_, SW_HIDE);
return true;
}
if (!view_) {
HMODULE module = nullptr;
if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCWSTR>(&parent_proc), &module)) return false;
if (!bitmap_) bitmap_ = static_cast<HBITMAP>(LoadImageW(module,
MAKEINTRESOURCEW(101), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION));
if (!bitmap_) return false;
view_ = CreateWindowExW(WS_EX_NOACTIVATE, L"STATIC", L"GVFG NO SIGNAL",
WS_CHILD | SS_OWNERDRAW, 0, 0, 0, 0, parent_, nullptr, module, nullptr);
if (!view_) return false;
}
RECT area{}; GetClientRect(parent_, &area);
SetWindowPos(view_, HWND_TOP, 0, 0, area.right, area.bottom, SWP_NOACTIVATE | SWP_SHOWWINDOW);
return true;
}
LRESULT CALLBACK SignalCard::parent_proc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp,
UINT_PTR id, DWORD_PTR data) {
auto *self = reinterpret_cast<SignalCard *>(data);
if (msg == WM_DRAWITEM) {
const auto *draw = reinterpret_cast<DRAWITEMSTRUCT *>(lp);
if (draw && draw->hwndItem == self->view_) {
BITMAP info{}; GetObjectW(self->bitmap_, sizeof(info), &info);
HDC source = CreateCompatibleDC(draw->hDC);
if (!source) return TRUE;
auto old = SelectObject(source, self->bitmap_);
SetStretchBltMode(draw->hDC, HALFTONE);
StretchBlt(draw->hDC, draw->rcItem.left, draw->rcItem.top,
draw->rcItem.right - draw->rcItem.left, draw->rcItem.bottom - draw->rcItem.top,
source, 0, 0, info.bmWidth, info.bmHeight, SRCCOPY);
SelectObject(source, old); DeleteDC(source);
return TRUE;
}
} else if (msg == WM_SIZE && self->view_) {
RECT area{}; GetClientRect(hwnd, &area);
MoveWindow(self->view_, 0, 0, area.right, area.bottom, TRUE);
} else if (msg == WM_NCDESTROY) {
RemoveWindowSubclass(hwnd, parent_proc, id);
self->parent_ = self->view_ = nullptr;
}
return DefSubclassProc(hwnd, msg, wp, lp);
}
@@ -0,0 +1,18 @@
#pragma once
#include <windows.h>
#include <commctrl.h>
// UI-thread-owned overlay. It never changes capture buffers or video timing.
class SignalCard {
public:
~SignalCard();
bool attach(HWND parent);
bool set_connected(bool connected);
bool on_window_thread() const;
private:
static LRESULT CALLBACK parent_proc(HWND, UINT, WPARAM, LPARAM, UINT_PTR, DWORD_PTR);
void detach();
HWND parent_ = nullptr, view_ = nullptr;
HBITMAP bitmap_ = nullptr;
bool connected_ = true;
};
@@ -0,0 +1 @@
101 BITMAP "no_signal.bmp"
+2 -32
View File
@@ -1,8 +1,6 @@
project(gvfg_preview LANGUAGES CXX)
add_library(gvfg_preview SHARED
gvfg_preview.def
add_library(gvfg_preview STATIC
include/gvfg_preview.h
src/preview_output_internal.h
../../sdk/gvfg/src/gpu/d3d_conversion_pipeline.cpp
../../sdk/gvfg/src/gpu/d3d_conversion_pipeline.h
src/gvfg_preview.cpp
@@ -23,7 +21,6 @@ target_include_directories(gvfg_preview
)
target_compile_definitions(gvfg_preview PRIVATE
GVFG_PREVIEW_BUILD
GVFG_INTERNAL_DIAGNOSTICS=$<IF:$<CONFIG:Debug>,1,0>
)
@@ -38,30 +35,3 @@ target_link_libraries(gvfg_preview
if (MSVC)
target_compile_options(gvfg_preview PRIVATE /utf-8 /EHsc)
endif()
if (MSVC AND GVFG_MINGW_DLLTOOL)
add_custom_command(TARGET gvfg_preview POST_BUILD
COMMAND "${GVFG_MINGW_DLLTOOL}"
-d "${CMAKE_CURRENT_SOURCE_DIR}/gvfg_preview.def"
-D gvfg_preview.dll
-l libgvfg_preview.dll.a
WORKING_DIRECTORY "${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}"
COMMENT "Generating MinGW import library for gvfg_preview.dll"
VERBATIM
)
endif()
install(TARGETS gvfg_preview
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
)
install(FILES include/gvfg_preview.h
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
if (MSVC AND GVFG_MINGW_DLLTOOL)
install(FILES "${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}/libgvfg_preview.dll.a"
DESTINATION ${CMAKE_INSTALL_LIBDIR}
)
endif()
@@ -1,9 +1,9 @@
# Preview GPU conversion paths
`gvfg_preview.dll` remains independent of `gvfg.dll`. Both targets compile
one shared private conversion source, `d3d_conversion_pipeline.cpp`, into
their own DLLs. There is no cross-DLL bridge, new public texture API, or
runtime SDK dependency in the preview helper.
The static `gvfg_preview` backend is linked into `gvfg_playback.dll` and remains
independent of `gvfg.dll`. Both playback and capture compile the shared private
conversion source, `d3d_conversion_pipeline.cpp`, into their own DLLs. Preview
functions are internal; applications use `gvfg_playback_*`.
CPU-buffer conversion uses dedicated outputs. YUY2/Y210 to NV12 preserves
native luma and averages chroma vertically; Y210 codes are reduced to 8 bits.
@@ -1,15 +0,0 @@
LIBRARY gvfg_preview
EXPORTS
gvfg_preview_get_delivery_stats
gvfg_preview_wait_idle
gvfg_preview_create
gvfg_preview_destroy
gvfg_preview_attach_window
gvfg_preview_prepare
gvfg_preview_render_frame
gvfg_preview_clear
gvfg_preview_get_info
gvfg_preview_get_stats
gvfg_preview_shutdown
gvfg_preview_strerror
@@ -1,40 +1,8 @@
#pragma once
/*
* Optional GVFG preview helper API.
*
* Standalone preview helper. Applications provide the frame buffer, pixel
* format, and row stride explicitly; gvfg_preview.dll does not depend on
* gvfg.dll.
*/
/* Public image and presentation types used by gvfg_playback.h. */
#include <stdint.h>
#ifdef _WIN32
#ifdef GVFG_PREVIEW_BUILD
#define GVFG_PREVIEW_API __declspec(dllexport)
#else
#define GVFG_PREVIEW_API __declspec(dllimport)
#endif
#else
#define GVFG_PREVIEW_API
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef enum
{
GVFG_PREVIEW_OK = 0,
GVFG_PREVIEW_EINVAL = -1,
GVFG_PREVIEW_ESTATE = -2,
GVFG_PREVIEW_ENOTSUP = -3,
GVFG_PREVIEW_ERENDER = -4
} gvfg_preview_status_t;
typedef struct gvfg_preview_handle_t *gvfg_preview_handle;
typedef enum
{
GVFG_PREVIEW_PIXFMT_YUY2 = 1,
@@ -105,69 +73,3 @@ typedef struct
uint64_t slots_busy;
uint64_t last_busy_id;
} gvfg_preview_delivery_stats_t;
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_get_delivery_stats(
gvfg_preview_handle handle, gvfg_preview_delivery_stats_t *out_stats);
/* Call after stopping submissions. Wait at most timeout_ms for queued work.
* Returns ESTATE if work remains; does not discard or reset counters. */
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_wait_idle(
gvfg_preview_handle handle, uint32_t timeout_ms);
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_create(
gvfg_preview_handle *out_handle);
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_destroy(
gvfg_preview_handle handle);
/*
* Attach a native window handle for preview output.
*
* On Windows, native_window_handle is an HWND.
*/
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_attach_window(
gvfg_preview_handle handle,
void *native_window_handle);
/* Pre-create GPU resources before the first captured frame is held. */
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_prepare(
gvfg_preview_handle handle,
int width,
int height,
int bit_depth);
/*
* Upload one frame to an internal GPU slot and queue it for preview.
*
* The frame memory remains owned by the caller and must remain valid until
* this function returns. GPU conversion and Present continue on the internal
* preview worker. Up to three pending frames are retained in FIFO order.
* Frames waiting longer than 50 ms are discarded; if the queue is full,
* the incoming frame is skipped. No SDK frame is retained for queueing.
* The age limit excludes time spent rendering or waiting inside Present.
*/
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_render_frame(
gvfg_preview_handle handle,
const gvfg_preview_frame_t *frame);
/* Replace the last presented frame with a solid black frame. */
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_clear(
gvfg_preview_handle handle);
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_get_info(
gvfg_preview_handle handle,
gvfg_preview_info_t *out_info);
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_get_stats(
gvfg_preview_handle handle,
gvfg_preview_stats_t *out_stats);
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_shutdown(
gvfg_preview_handle handle);
GVFG_PREVIEW_API const char *gvfg_preview_strerror(
gvfg_preview_status_t status);
#ifdef __cplusplus
}
#endif
@@ -1,4 +1,4 @@
#include "gvfg_preview.h"
#include "preview_output_internal.h"
#include "d3d_conversion_pipeline.h"
@@ -124,7 +124,7 @@ public:
D3D11_MAPPED_SUBRESOURCE mapped{};
if (FAILED(deferred->Map(texture, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped)))
{
lock.lock(); slot.state = SlotState::Free; return false;
lock.lock(); slot.state = SlotState::Free; idleCv_.notify_all(); return false;
}
const size_t rowBytes = frame.pixel_format == GVFG_PREVIEW_PIXFMT_Y210
? static_cast<size_t>(frame.width) * 4u
@@ -150,7 +150,7 @@ public:
ComPtr<ID3D11CommandList> commands;
if (FAILED(deferred->FinishCommandList(FALSE, &commands)))
{
lock.lock(); slot.state = SlotState::Free; return false;
lock.lock(); slot.state = SlotState::Free; idleCv_.notify_all(); return false;
}
lock.lock();
@@ -183,14 +183,20 @@ public:
{
auto lock = lockWithWindowMessages(mutex_);
if (!configured_ || !pipeline_)
return false;
{
// Before the first frame there is no surface to clear.
// Treat an already-empty preview as successfully cleared so
// playback reset can restart its timeline.
clearActiveInfo();
return true;
}
for (UploadSlot &slot : slots_)
{
if (slot.state == SlotState::Pending)
{
++delivery_.cancelled;
slot.commands.Reset();
slot.state = SlotState::Free;
slot.state = SlotState::Free; idleCv_.notify_all();
}
}
}
@@ -233,6 +239,7 @@ public:
clearActiveInfo();
resetPresentStats();
delivery_ = {};
idleCv_.notify_all();
}
bool active() const
@@ -291,6 +298,20 @@ public:
bool waitIdle(uint32_t timeoutMs)
{
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
auto isIdle = [this] {
for (const auto &slot : slots_)
if (slot.state != SlotState::Free) return false;
return true;
};
{
auto lock = lockWithWindowMessages(mutex_);
const bool ownsWindow = hwnd_ && GetWindowThreadProcessId(static_cast<HWND>(hwnd_), nullptr) == GetCurrentThreadId();
// Playback workers do not own the HWND. Wake them directly when
// the GPU job retires, rather than polling a 1 ms Windows timer
// whose effective wait can consume most of a 60 Hz frame period.
if (!ownsWindow) return idleCv_.wait_until(lock, deadline, isIdle);
}
// The HWND owner must keep synchronous DXGI messages flowing.
for (;;)
{
std::unique_lock<std::mutex> lock(mutex_, std::try_to_lock);
@@ -338,7 +359,7 @@ private:
if (slot.state == SlotState::Pending && now - slot.queuedAt > kMaxQueueAge)
{
slot.commands.Reset();
slot.state = SlotState::Free;
slot.state = SlotState::Free; idleCv_.notify_all();
++skippedSubmits_;
++delivery_.replaced; // Retired queued frame: expired, not latest-frame replacement.
}
@@ -579,6 +600,7 @@ private:
if (slot.state == SlotState::Pending)
++delivery_.cancelled;
slots_ = std::move(replacement);
idleCv_.notify_all();
uploadWidth_ = width;
uploadHeight_ = height;
uploadPixelFormat_ = pixelFormat;
@@ -687,6 +709,7 @@ private:
}
slots_[selected].commands.Reset();
slots_[selected].state = SlotState::Free;
idleCv_.notify_all();
workerCv_.notify_all();
}
}
@@ -733,6 +756,7 @@ private:
std::array<UploadSlot, kUploadSlotCount> slots_{};
std::thread worker_;
std::condition_variable workerCv_;
std::condition_variable idleCv_;
bool workerStarted_ = false;
bool workerStopping_ = false;
int uploadWidth_ = 0;
@@ -901,30 +925,4 @@ extern "C"
return handle->renderer.waitIdle(timeout_ms) ? GVFG_PREVIEW_OK : GVFG_PREVIEW_ESTATE;
}
gvfg_preview_status_t gvfg_preview_shutdown(gvfg_preview_handle handle)
{
if (!handle)
return GVFG_PREVIEW_EINVAL;
handle->renderer.shutdown();
return GVFG_PREVIEW_OK;
}
const char *gvfg_preview_strerror(gvfg_preview_status_t status)
{
switch (status)
{
case GVFG_PREVIEW_OK:
return "OK";
case GVFG_PREVIEW_EINVAL:
return "Invalid argument";
case GVFG_PREVIEW_ESTATE:
return "Invalid state";
case GVFG_PREVIEW_ENOTSUP:
return "Unsupported frame format";
case GVFG_PREVIEW_ERENDER:
return "Render failed";
default:
return "Unknown";
}
}
}
@@ -0,0 +1,79 @@
#pragma once
/* Private static backend; not part of the customer API. */
#include "gvfg_preview.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum
{
GVFG_PREVIEW_OK = 0,
GVFG_PREVIEW_EINVAL = -1,
GVFG_PREVIEW_ESTATE = -2,
GVFG_PREVIEW_ENOTSUP = -3,
GVFG_PREVIEW_ERENDER = -4
} gvfg_preview_status_t;
typedef struct gvfg_preview_handle_t *gvfg_preview_handle;
gvfg_preview_status_t gvfg_preview_get_delivery_stats(
gvfg_preview_handle handle, gvfg_preview_delivery_stats_t *out_stats);
/* Call after stopping submissions. Wait at most timeout_ms for queued work.
* Returns ESTATE if work remains; does not discard or reset counters. */
gvfg_preview_status_t gvfg_preview_wait_idle(
gvfg_preview_handle handle, uint32_t timeout_ms);
gvfg_preview_status_t gvfg_preview_create(
gvfg_preview_handle *out_handle);
gvfg_preview_status_t gvfg_preview_destroy(
gvfg_preview_handle handle);
/*
* Attach a native window handle for preview output.
*
* On Windows, native_window_handle is an HWND.
*/
gvfg_preview_status_t gvfg_preview_attach_window(
gvfg_preview_handle handle,
void *native_window_handle);
/* Pre-create GPU resources before the first captured frame is held. */
gvfg_preview_status_t gvfg_preview_prepare(
gvfg_preview_handle handle,
int width,
int height,
int bit_depth);
/*
* Upload one frame to an internal GPU slot and queue it for preview.
*
* The frame memory remains owned by the caller and must remain valid until
* this function returns. GPU conversion and Present continue on the internal
* preview worker. Up to three pending frames are retained in FIFO order.
* Frames waiting longer than 50 ms are discarded; if the queue is full,
* the incoming frame is skipped. No SDK frame is retained for queueing.
* The age limit excludes time spent rendering or waiting inside Present.
*/
gvfg_preview_status_t gvfg_preview_render_frame(
gvfg_preview_handle handle,
const gvfg_preview_frame_t *frame);
/* Replace the last presented frame with a solid black frame. */
gvfg_preview_status_t gvfg_preview_clear(
gvfg_preview_handle handle);
gvfg_preview_status_t gvfg_preview_get_info(
gvfg_preview_handle handle,
gvfg_preview_info_t *out_info);
gvfg_preview_status_t gvfg_preview_get_stats(
gvfg_preview_handle handle,
gvfg_preview_stats_t *out_stats);
#ifdef __cplusplus
}
#endif