Skip to content

Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.

C++

phase-5 work: R3.1a veyra_sinks product library (WASAPI audio extracted verbatim, no behavior regression)

Veyra Goal Agenta041a39770f9
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 13d58c59..85c07729 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -306,6 +306,22 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_link_libraries(veyra_media_probe PRIVATE veyra_media veyra_gfx veyra_ngx veyra_parity psapi)
add_dependencies(veyra_media_probe veyra_shader_yuv_to_rgb)
+ # veyra_sinks: product output sinks (Playbook R3). First member is the
+ # WASAPI audio sink extracted verbatim from player_probe; D3D12PresentSink
+ # currently lives in veyra_gfx and moves here when the migration completes.
+ add_library(veyra_sinks STATIC
+ src/sink/WasapiAudioSink.cpp
+ )
+ veyra_apply_warnings(veyra_sinks)
+ target_compile_options(veyra_sinks PRIVATE /WX-)
+ target_compile_features(veyra_sinks PRIVATE cxx_std_20)
+ target_compile_definitions(veyra_sinks PRIVATE
+ UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)
+ target_include_directories(veyra_sinks PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
+ target_include_directories(veyra_sinks PRIVATE ${FFMPEG_INCLUDE_DIRS})
+ target_link_libraries(veyra_sinks PUBLIC veyra_base ole32 mmdevapi avrt)
+ target_link_libraries(veyra_sinks PRIVATE ${FFMPEG_LIBRARIES})
+
# Phase 6 realtime engine probe: decode -> SR -> NR -> NVOF -> DLSSG -> present.
if(VEYRA_ENABLE_EXPERIMENTAL_DLSSNR AND EXISTS "${VEYRA_NVOF_SDK_ROOT}/NvOFInterface/nvOpticalFlowCommon.h")
add_executable(veyra_player_probe
@@ -319,7 +335,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX
VEYRA_SHADER_DIR="${CMAKE_BINARY_DIR}/shaders")
target_link_libraries(veyra_player_probe PRIVATE
- veyra_media veyra_gfx veyra_ngx veyra_nvof veyra_parity
+ veyra_media veyra_gfx veyra_ngx veyra_nvof veyra_parity veyra_sinks
${FFMPEG_LIBRARIES} psapi ole32 mmdevapi avrt)
add_dependencies(veyra_player_probe
veyra_shader_yuv_to_rgb veyra_shader_parity_encode
diff --git a/include/veyra/sink/WasapiAudioSink.h b/include/veyra/sink/WasapiAudioSink.h
new file mode 100644
index 00000000..e8c619ab
--- /dev/null
+++ b/include/veyra/sink/WasapiAudioSink.h
@@ -0,0 +1,171 @@
+#pragma once
+
+// WasapiAudioSink - product audio playback extracted verbatim from the
+// verified player_probe implementation (Phase 6 audio evidence: event-driven
+// shared mode, PTS-anchored master clock, atomic seek, bounded ring, never
+// dropping decoded audio in player mode).
+//
+// AudioPipeline: FFmpeg audio demux/decode + watermarked bounded ring
+// (low 250ms / prefill 500ms / high 1000ms, 2s hard bound).
+// AudioRenderer: event-driven WASAPI shared-mode endpoint whose device clock
+// is mapped onto media PTS through an explicit anchor set at Start and after
+// every seek restart.
+#include <windows.h>
+#include <mmdeviceapi.h>
+#include <audioclient.h>
+
+#include <atomic>
+#include <chrono>
+#include <condition_variable>
+#include <cstdint>
+#include <deque>
+#include <mutex>
+#include <thread>
+#include <vector>
+
+#include "veyra/Log.h"
+
+struct AVFormatContext;
+struct AVCodecContext;
+struct AVStream;
+struct AVPacket;
+struct SwrContext;
+typedef struct AVFrame AVFrame;
+
+namespace veyra::sink {
+
+constexpr double kAudioLowWatermarkMs = 250.0;
+constexpr double kAudioPrefillMs = 500.0;
+constexpr double kAudioHighWatermarkMs = 1000.0;
+constexpr uint32_t kAudioRate = 48000;
+
+class AudioRenderer; // forward: pipeline thread needs the renderer
+
+class AudioPipeline {
+public:
+ AudioPipeline();
+ ~AudioPipeline();
+
+ bool open(const std::wstring& path);
+
+ double bufferedMs() const;
+ // PTS (ms) of the first unconsumed buffered sample; < 0 when empty.
+ double headPtsMs() const;
+ // Decoded-ahead PTS (ms) of the last buffered sample end; -1 if empty.
+ double tailPtsMs() const;
+
+ uint64_t underruns() const;
+ uint64_t overruns() const; // must stay 0
+ uint64_t seekCount() const;
+ double lastPrefillMs() const;
+ double firstPtsAfterLastSeek() const;
+
+ // Pull up to maxFrames stereo frames; sets the PTS of the first pulled
+ // frame. Returns frames pulled (0 legal; caller writes silence and it is
+ // counted as an underrun by the pump only when the endpoint had space).
+ size_t pull(float* dst, size_t maxFrames, double* firstPtsMs);
+
+ void stopThread();
+
+ // Seek protocol (engine thread calls; audio thread executes). Blocks
+ // until the audio thread finished the atomic re-sequence and prefilled.
+ // Returns the PTS of the first buffered sample after seek.
+ double requestSeek(double targetMs);
+
+ void runOnAudioThread(AudioRenderer* renderer);
+ void startThread(AudioRenderer* renderer);
+
+private:
+ struct Segment {
+ double startPtsMs;
+ size_t frames;
+ };
+
+ void pushDecoded(const AVFrame* frame);
+ void decodeBlock();
+ double bufferedMsLocked() const;
+ void closeAll();
+
+ friend class AudioThread;
+
+ AVFormatContext* fmt_ = nullptr;
+ AVCodecContext* codecCtx_ = nullptr;
+ AVStream* stream_ = nullptr;
+ AVPacket* packet_ = nullptr;
+ SwrContext* swr_ = nullptr;
+ int streamIndex_ = -1;
+ bool havePacket_ = false;
+ bool demuxEof_ = false;
+ double nextPtsMs_ = 0.0; // PTS of the NEXT decoded sample
+ double discardUntilPtsMs_ = -1.0; // seek pruning
+ static constexpr size_t kMaxRingFrames = kAudioRate * 2; // 2s hard bound
+
+ mutable std::mutex mutex_;
+ std::deque<float> ring_{}; // stereo interleaved
+ size_t ringFrames_ = 0;
+ std::deque<Segment> segments_{}; // PTS bookkeeping of ring contents
+
+ std::condition_variable wake_;
+ std::condition_variable seekDoneCv_;
+ std::atomic<bool> stopFlag_{false};
+ bool seekRequested_ = false;
+ bool seekDone_ = true;
+ double seekTargetMs_ = 0.0;
+
+ std::atomic<uint64_t> underruns_{0};
+ std::atomic<uint64_t> overruns_{0};
+ std::atomic<uint64_t> seekCount_{0};
+ std::atomic<double> lastPrefillMs_{0.0};
+ std::atomic<double> firstPtsAfterSeek_{-1.0};
+ std::vector<float> converted_{std::vector<float>(kAudioRate)};
+
+ std::thread thread_;
+};
+
+class AudioRenderer {
+public:
+ bool start();
+
+ // Called by the audio thread after prefill: begins playback anchored at
+ // the PTS of the sample that will be written first.
+ bool startAnchored(double firstBufferPtsMs);
+
+ // Event-driven pump for ONE event cycle. Writes real data when the ring
+ // has it, silence otherwise (underrun counted). Returns false on hard
+ // failure.
+ bool pumpOnce(AudioPipeline& pipeline, double* firstWrittenPtsMs);
+
+ // Master clock: real media PTS of the sample currently being played.
+ double mediaTimeMs() const;
+
+ // Atomic seek support: stop + reset the endpoint; the clock is invalid
+ // until the next startAnchored.
+ void stopAndReset();
+
+ bool started() const;
+ uint64_t underruns() const;
+ uint64_t framesWritten() const;
+
+ void shutdown();
+
+private:
+ IMMDeviceEnumerator* enum_ = nullptr;
+ IMMDevice* device_ = nullptr;
+ IAudioClient* client_ = nullptr;
+ IAudioRenderClient* render_ = nullptr;
+ IAudioClock* clock_ = nullptr;
+ HANDLE event_ = nullptr;
+ UINT32 bufferFrames_ = 0;
+ uint32_t sampleRate_ = kAudioRate;
+ UINT64 clockFrequency_ = 0;
+ UINT64 anchorPos_ = 0;
+ std::atomic<double> anchorPtsMs_{0.0};
+ bool started_ = false;
+ bool running_ = false;
+ bool comInited_ = false;
+ std::atomic<uint64_t> underruns_{0};
+ uint64_t framesWritten_ = 0;
+ std::vector<float> chunk_{std::vector<float>(8192 * 2)};
+};
+
+} // namespace veyra::sink
diff --git a/loop/JOURNAL.md b/loop/JOURNAL.md
index c2f15731..2c81f750 100644
--- a/loop/JOURNAL.md
+++ b/loop/JOURNAL.md
@@ -944,6 +944,31 @@ C staged teardown 定位崩溃=swapChain_.Release,矩阵证明 NVOF+debug layer+
- 新 blocker:L2 GBV runtime id=938 未初始化描述符(待修,非本任务)。
- 未执行:query-heap GPU timestamp(用户明令禁止);Reviewer/checkpoint(未授权)。
+## Cycle 034 — R3.1a veyra_sinks:WASAPI 音频迁出 player_probe(2026-09-06 Goal)
+
+### Before
+
+- Phase: 5(重开,in_progress)
+- 唯一任务: 把 player_probe 中自包含的 AudioPipeline(FFmpeg demux/decode + 水位环形缓冲)与 AudioRenderer(事件驱动 WASAPI + PTS 锚定主时钟)整体迁入新产品库 `veyra_sinks`(include/veyra/sink/WasapiAudioSink.h + src/sink/WasapiAudioSink.cpp,namespace veyra::sink,代码逐字保留已验证语义);player_probe 删除 172-686 行改为 include + 链接;CMake 在 FFmpeg guard 内建立 veyra_sinks;phase5 gate 增加 product:veyra_sinks-target 检查(只加不减)。
+- 可证伪假设: 若迁移引入行为差异,player probe 冒烟的音频计数/exit code 将变化;预期 exit 12(drift FAIL)不变、audioUnderruns/overruns 与迁移前同量级。若 veyra_sinks 只是空壳,gate 新检查暴露。
+- 预计修改文件: include/veyra/sink/WasapiAudioSink.h、src/sink/WasapiAudioSink.cpp、tools/player_probe/main.cpp(删音频段+include)、CMakeLists.txt、scripts/gates/phase5.ps1(加检查)。
+- 快速检查命令: `build x64-debug/-release` → 0;`veyra_player_probe --duration-seconds 20` → exit 12 且 audio 字段存在;`phase5.ps1` → 仍 exit 1 但 product:veyra_sinks-target PASS。
+- 预期新增证据: 双配置构建 + player 冒烟音频计数不回归 + gate 新检查绿。
+
+### After
+
+- 实际修改: include/veyra/sink/WasapiAudioSink.h(AudioPipeline/AudioRenderer 产品头,FFmpeg 类型前置声明)、src/sink/WasapiAudioSink.cpp(实现逐字迁移 + packet_ 构造/析构与 startThread 出类定义)、tools/player_probe/main.cpp(删除 172-686 音频段 → include + `veyra::sink::` 限定,3641→3128 行)、CMakeLists.txt(FFmpeg guard 内 add_library(veyra_sinks) PUBLIC veyra_base/ole32/mmdevapi/avrt + PRIVATE FFMPEG;player_probe 链接 veyra_sinks)、scripts/gates/phase5.ps1(新增 product:veyra_sinks-target / veyra_sources-target / player-links-sinks 三项检查——只增不减;并修复 player-links 检查的跨 target 假阳性:原宽松正则会把任意位置的 veyra_pipeline 误判为 player_probe 链接)。
+- 实际命令与 exit code:
+ - `build x64-release` → 首两轮 exit 6(veyra_sinks 缺 FFMPEG_INCLUDE_DIRS;startThread 声明后缺类外定义)→ 修复后 **exit 0**;`build x64-debug` → exit 0。
+ - player probe 冒烟(r3a-player-175416,1080p 20s)→ **exit 12(drift FAIL 不变)**;mvecSource=nvof;**audioUnderruns=0 audioOverruns=0 audioSeekCount=11** — 音频语义迁移无回归。
+ - `phase5.ps1` → **exit 1,30/45**;product:veyra_sinks-target + player-links-sinks PASS;player-links-pipeline 诚实保持红(player_probe 尚未链接 veyra_pipeline——R3.2/R3.3 任务)。
+- 失败 fingerprint: build|link|6|include-dirs+missing-definition → 两处独立修复,第 1 轮关闭。
+- 是否有进展,依据: 是——WASAPI 音频(事件模式、PTS 锚定主时钟、原子 seek、有界环形)从 probe 私有代码变为产品库 `veyra_sinks` 真实成员,player_probe 3128 行,且运行行为无回归;gate 检查面扩大且更严格。
+- STATE/BACKLOG 更新: cycle.completed=34;nextAction → R3.1b veyra_guidance。
+- 下一唯一动作: R3.1b — 建立 `veyra_guidance`(ZeroGuidanceProvider、NvofGuidanceProvider 包装已验证的 NvOfSession、GuidanceValidator 骨架),真实成员非空壳;nvof_probe/player_probe 改为消费产品库。
+
+---
+
## Cycle 033 — R2.1 pipeline 数据契约迁移(2026-09-06 Goal)
### Before
diff --git a/loop/STATE.json b/loop/STATE.json
index 6f3c5b50..db510b43 100644
--- a/loop/STATE.json
+++ b/loop/STATE.json
@@ -76,14 +76,14 @@
}
],
"cycle": {
- "completed": 33,
+ "completed": 34,
"maximum": 120,
"sameFailureAttempts": 0,
"maximumSameFailureAttempts": 3,
"noProgressCycles": 0,
"maximumNoProgressCycles": 5
},
- "currentTask": "R2.1 complete (Cycle 033): include/veyra/pipeline contract family landed (Rational PTS with negative/unknown, ColorDescription with assumed flags + P010 HDR fail-closed path, 10-bit FrameFlags with breaksHistory, GpuTextureHandle with owner slot/expected state/ready fence, FrameWindow fixed prev/current/next + lookaheadFrames<=2 no vector, GuidanceFrame provenance/age/sourceSequence, ResetCoordinator frame-boundary epoch). PipelineContractTests 50/50 debug+release; legacy unified tests 51/51 no regression. veyra_pipeline static target created.",
+ "currentTask": "R3.1a complete (Cycle 034): WASAPI audio (AudioPipeline watermark ring + AudioRenderer event-driven PTS-anchored clock) extracted verbatim from player_probe into product library veyra_sinks. player_probe 3641->3128 lines, audio behavior verified unchanged (underruns=0 overruns=0 seekCount=11, exit 12 drift FAIL unchanged). Gate gained product:sinks/sources/player-links-sinks checks (45 total, 30 fail) and the player-links-pipeline false positive was fixed.",
"lastGate": {
"name": "phase5",
"status": "invalidated_requires_rebuild",
@@ -106,6 +106,6 @@
"A real DirectShow/UVC 4K60 SDR capture device, HDMI audio, and 4K60 source signal are required before P7 capture gate can pass.",
"Public distribution rights for the experimental DLSSNR runtime and all bundled NVIDIA/model/FFmpeg assets are unresolved; a local release candidate is allowed, public launch is blocked."
],
- "nextAction": "Playbook R3.1: establish the remaining product library targets with real members extracted from tools/player_probe (veyra_sinks: WasapiAudioSink from AudioPipeline/AudioRenderer lines ~194-690 + link D3D12PresentSink; veyra_guidance: NvofGuidanceProvider wrapping NvOfSession + ZeroGuidanceProvider + GuidanceValidator skeleton; veyra_sources: MediaFileSource wrapping FFmpegDemuxer/FFmpegVideoDecoder). No empty/interface-only targets; player_probe must keep compiling and reproduce the same probe behavior. Then R3.2 moves the real GPU chain into EnhanceGraph (src/pipeline/EnhanceGraph.cpp must submit command lists + NGX evaluate per the gate check).",
- "updatedAt": "2026-09-06T17:10:00+08:00"
+ "nextAction": "Playbook R3.1b: create veyra_guidance product library with real members (ZeroGuidanceProvider, NvofGuidanceProvider wrapping the verified NvOfSession with B8G8R8A8/S10.5 grid-4 cost contract, GuidanceValidator with cost/luma-warp-residual/out-of-frame confidence inputs); then R3.1c veyra_sources MediaFileSource. After all four libraries exist: R3.2 move the real GPU chain (upload/YUV/SR/NVOF/parity/NR/FG) into EnhanceGraph so product:enhance-graph-submits-gpu can pass.",
+ "updatedAt": "2026-09-06T17:55:00+08:00"
}
diff --git a/scripts/gates/phase5.ps1 b/scripts/gates/phase5.ps1
index c7b440a7..903677c8 100644
--- a/scripts/gates/phase5.ps1
+++ b/scripts/gates/phase5.ps1
@@ -92,12 +92,23 @@ if (Test-Path -LiteralPath $cmakePath -PathType Leaf) {
}
$hasPipelineTarget = ($cmakeText -match "add_library\s*\(\s*veyra_pipeline\b")
$hasGuidanceTarget = ($cmakeText -match "add_library\s*\(\s*veyra_guidance\b")
+$hasSinksTarget = ($cmakeText -match "add_library\s*\(\s*veyra_sinks\b")
+$hasSourcesTarget = ($cmakeText -match "add_library\s*\(\s*veyra_sources\b")
$hasRunnerTarget = ($cmakeText -match "veyra_quality_probe\b")
-$playerLinksPipeline = ($cmakeText -match "(?s)veyra_player_probe.*?veyra_pipeline") -or ($cmakeText -match "(?s)veyra_pipeline.*?veyra_player_probe")
+# Extract the veyra_player_probe target block so link checks stay scoped to
+# it (a loose whole-file regex would match across unrelated targets).
+$playerBlock = ""
+$playerMatch = [regex]::Match($cmakeText, "(?s)add_executable\(veyra_player_probe.*?(?=\r?\n\s*(?:add_executable|add_library|endif|# ---))")
+if ($playerMatch.Success) { $playerBlock = $playerMatch.Value }
+$playerLinksPipeline = ($playerBlock -match "target_link_libraries\s*\(\s*veyra_player_probe.*?veyra_pipeline") -or ($playerBlock -match "veyra_pipeline")
+$playerLinksSinks = ($playerBlock -match "target_link_libraries\s*\(\s*veyra_player_probe.*?veyra_sinks") -or ($playerBlock -match "veyra_sinks")
Add-GateCheck "product:veyra_pipeline-target" $hasPipelineTarget "CMakeLists add_library(veyra_pipeline ...) present=$hasPipelineTarget"
Add-GateCheck "product:veyra_guidance-target" $hasGuidanceTarget "CMakeLists add_library(veyra_guidance ...) present=$hasGuidanceTarget"
+Add-GateCheck "product:veyra_sinks-target" $hasSinksTarget "CMakeLists add_library(veyra_sinks ...) present=$hasSinksTarget"
+Add-GateCheck "product:veyra_sources-target" $hasSourcesTarget "CMakeLists add_library(veyra_sources ...) present=$hasSourcesTarget"
Add-GateCheck "product:quality-runner-target" $hasRunnerTarget "CMakeLists references veyra_quality_probe present=$hasRunnerTarget"
Add-GateCheck "product:player-links-pipeline" $playerLinksPipeline "player_probe links veyra_pipeline present=$playerLinksPipeline"
+Add-GateCheck "product:player-links-sinks" $playerLinksSinks "player_probe links veyra_sinks present=$playerLinksSinks"
$enhanceGraphSrc = Join-Path $Root "src\pipeline\EnhanceGraph.cpp"
$enhanceOk = $false
diff --git a/src/sink/WasapiAudioSink.cpp b/src/sink/WasapiAudioSink.cpp
new file mode 100644
index 00000000..d6c6db16
--- /dev/null
+++ b/src/sink/WasapiAudioSink.cpp
@@ -0,0 +1,423 @@
+// WasapiAudioSink implementation - moved verbatim from tools/player_probe
+// main.cpp (lines ~172-686, Phase 6 session evidence). Semantics preserved:
+// watermarked bounded production ring, event-driven pump, PTS-anchored master
+// clock, atomic seek re-sequence, player mode never drops decoded audio.
+#include "veyra/sink/WasapiAudioSink.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+#include <format>
+
+extern "C" {
+#include <libavformat/avformat.h>
+#include <libavcodec/avcodec.h>
+#include <libswresample/swresample.h>
+}
+
+namespace veyra::sink {
+
+AudioPipeline::AudioPipeline()
+ : packet_(av_packet_alloc())
+{
+}
+
+AudioPipeline::~AudioPipeline()
+{
+ closeAll();
+ stopThread();
+}
+
+bool AudioPipeline::open(const std::wstring& path)
+{
+ std::string narrow;
+ narrow.assign(path.begin(), path.end());
+ if (avformat_open_input(&fmt_, narrow.c_str(), nullptr, nullptr) != 0) return false;
+ if (avformat_find_stream_info(fmt_, nullptr) < 0) return false;
+ const AVCodec* codec = nullptr;
+ const int si = av_find_best_stream(fmt_, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0);
+ if (si < 0 || codec == nullptr) {
+ veyra::log::info("audio", "no audio stream in source");
+ return false;
+ }
+ streamIndex_ = si;
+ codecCtx_ = avcodec_alloc_context3(codec);
+ if (avcodec_parameters_to_context(codecCtx_, fmt_->streams[si]->codecpar) < 0) return false;
+ if (avcodec_open2(codecCtx_, codec, nullptr) < 0) return false;
+ stream_ = fmt_->streams[si];
+ veyra::log::info("audio", std::format("audio stream idx={} codec={} rate={}",
+ si, codec->name, codecCtx_->sample_rate));
+ return true;
+}
+
+double AudioPipeline::bufferedMs() const
+{
+ std::lock_guard<std::mutex> lock(mutex_);
+ return 1000.0 * static_cast<double>(ringFrames_) / kAudioRate;
+}
+
+double AudioPipeline::headPtsMs() const
+{
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (segments_.empty()) return -1.0;
+ return segments_.front().startPtsMs;
+}
+
+double AudioPipeline::tailPtsMs() const
+{
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (segments_.empty()) return -1.0;
+ const Segment& t = segments_.back();
+ return t.startPtsMs + 1000.0 * static_cast<double>(t.frames) / kAudioRate;
+}
+
+uint64_t AudioPipeline::underruns() const { return underruns_.load(); }
+uint64_t AudioPipeline::overruns() const { return overruns_.load(); } // must stay 0
+uint64_t AudioPipeline::seekCount() const { return seekCount_.load(); }
+double AudioPipeline::lastPrefillMs() const { return lastPrefillMs_.load(); }
+double AudioPipeline::firstPtsAfterLastSeek() const { return firstPtsAfterSeek_.load(); }
+
+size_t AudioPipeline::pull(float* dst, size_t maxFrames, double* firstPtsMs)
+{
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (firstPtsMs) *firstPtsMs = segments_.empty() ? -1.0 : segments_.front().startPtsMs;
+ const size_t take = std::min(maxFrames, ringFrames_);
+ size_t copied = 0;
+ while (copied < take && !segments_.empty()) {
+ Segment& seg = segments_.front();
+ const size_t n = std::min(take - copied, seg.frames);
+ // Ring is a deque of float pairs: copy n frames.
+ for (size_t i = 0; i < n * 2; ++i) {
+ dst[copied * 2 + i] = ring_.front();
+ ring_.pop_front();
+ }
+ copied += n;
+ seg.frames -= n;
+ seg.startPtsMs += 1000.0 * static_cast<double>(n) / kAudioRate;
+ if (seg.frames == 0) segments_.pop_front();
+ }
+ ringFrames_ -= take;
+ return take;
+}
+
+void AudioPipeline::stopThread()
+{
+ stopFlag_ = true;
+ wake_.notify_all();
+ if (thread_.joinable()) thread_.join();
+}
+
+double AudioPipeline::requestSeek(double targetMs)
+{
+ std::unique_lock<std::mutex> lock(mutex_);
+ seekTargetMs_ = targetMs;
+ seekDone_ = false;
+ seekRequested_ = true;
+ wake_.notify_all();
+ // The audio thread signals when the ring is prefilled past target.
+ if (!seekDoneCv_.wait_for(lock, std::chrono::milliseconds(3000), [this] { return seekDone_; })) {
+ veyra::log::error("audio", "seek prefill timed out");
+ }
+ return segments_.empty() ? targetMs : segments_.front().startPtsMs;
+}
+
+void AudioPipeline::pushDecoded(const AVFrame* frame)
+{
+ // Convert to 48k stereo float in converted_.
+ if (swr_ == nullptr) {
+ AVChannelLayout outLayout = AV_CHANNEL_LAYOUT_STEREO;
+ AVChannelLayout inLayout = frame->ch_layout.nb_channels > 0
+ ? frame->ch_layout : outLayout;
+ swr_alloc_set_opts2(&swr_,
+ &outLayout, AV_SAMPLE_FMT_FLT, kAudioRate,
+ &inLayout, static_cast<AVSampleFormat>(frame->format), frame->sample_rate,
+ 0, nullptr);
+ if (swr_ == nullptr || swr_init(swr_) < 0) return;
+ }
+ uint8_t* planes[1] = { reinterpret_cast<uint8_t*>(converted_.data()) };
+ const int outSamples = swr_convert(swr_, planes,
+ static_cast<int>(converted_.size() / 2),
+ const_cast<const uint8_t**>(frame->extended_data), frame->nb_samples);
+ if (outSamples <= 0) return;
+
+ std::unique_lock<std::mutex> lock(mutex_);
+ const size_t addFrames = static_cast<size_t>(outSamples);
+ if (ringFrames_ + addFrames > kMaxRingFrames) {
+ // Player mode: never drop. This is a hard error (bounded ring
+ // should never overflow because production is watermarked).
+ overruns_.fetch_add(1);
+ veyra::log::error("audio", "ring overflow despite watermarks (bug)");
+ return;
+ }
+ ring_.insert(ring_.end(), converted_.data(), converted_.data() + addFrames * 2);
+ ringFrames_ += addFrames;
+ if (!segments_.empty()) {
+ Segment& last = segments_.back();
+ const double lastEnd = last.startPtsMs + 1000.0 * static_cast<double>(last.frames) / kAudioRate;
+ if (std::fabs(lastEnd - nextPtsMs_) < 1.0) {
+ last.frames += addFrames; // contiguous: extend
+ } else {
+ segments_.push_back({ nextPtsMs_, addFrames });
+ }
+ } else {
+ segments_.push_back({ nextPtsMs_, addFrames });
+ }
+ nextPtsMs_ += 1000.0 * static_cast<double>(addFrames) / kAudioRate;
+}
+
+void AudioPipeline::decodeBlock()
+{
+ // Decode until high watermark or EOF; called only when below high.
+ while (bufferedMsLocked() < kAudioHighWatermarkMs && !stopFlag_ && !seekRequested_) {
+ if (!havePacket_) {
+ if (av_read_frame(fmt_, packet_) < 0) {
+ demuxEof_ = true;
+ break;
+ }
+ havePacket_ = true;
+ if (packet_->stream_index != streamIndex_) {
+ av_packet_unref(packet_);
+ havePacket_ = false;
+ continue;
+ }
+ }
+ if (avcodec_send_packet(codecCtx_, havePacket_ ? packet_ : nullptr) == 0 && havePacket_) {
+ av_packet_unref(packet_);
+ havePacket_ = false;
+ }
+ AVFrame* frame = av_frame_alloc();
+ bool enough = false;
+ while (avcodec_receive_frame(codecCtx_, frame) == 0) {
+ const double ptsMs = 1000.0 * frame->pts * stream_->time_base.num / stream_->time_base.den;
+ nextPtsMs_ = ptsMs + 1000.0 * frame->nb_samples / kAudioRate;
+ if (discardUntilPtsMs_ < 0.0 || ptsMs >= discardUntilPtsMs_) {
+ pushDecoded(frame);
+ }
+ av_frame_unref(frame);
+ if (bufferedMsLocked() >= kAudioHighWatermarkMs) { enough = true; break; }
+ }
+ av_frame_free(&frame);
+ if (enough || demuxEof_) break;
+ }
+}
+
+double AudioPipeline::bufferedMsLocked() const
+{
+ return 1000.0 * static_cast<double>(ringFrames_) / kAudioRate;
+}
+
+void AudioPipeline::closeAll()
+{
+ if (swr_ != nullptr) swr_free(&swr_);
+ if (packet_ != nullptr) av_packet_free(&packet_);
+ if (codecCtx_ != nullptr) avcodec_free_context(&codecCtx_);
+ if (fmt_ != nullptr) avformat_close_input(&fmt_);
+}
+
+bool AudioRenderer::start()
+{
+ HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
+ comInited_ = SUCCEEDED(hr);
+ hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL,
+ __uuidof(IMMDeviceEnumerator), reinterpret_cast<void**>(&enum_));
+ if (FAILED(hr)) return false;
+ hr = enum_->GetDefaultAudioEndpoint(eRender, eConsole, &device_);
+ if (FAILED(hr)) return false;
+ hr = device_->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr,
+ reinterpret_cast<void**>(&client_));
+ if (FAILED(hr)) return false;
+ WAVEFORMATEX* mix = nullptr;
+ if (FAILED(client_->GetMixFormat(&mix))) return false;
+ sampleRate_ = mix->nSamplesPerSec;
+ hr = client_->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
+ 10 * 10000, 0, mix, nullptr);
+ const bool initOk = SUCCEEDED(hr);
+ CoTaskMemFree(mix);
+ if (!initOk) return false;
+ if (FAILED(client_->GetBufferSize(&bufferFrames_))) return false;
+ event_ = CreateEventW(nullptr, FALSE, FALSE, nullptr);
+ if (event_ == nullptr || FAILED(client_->SetEventHandle(event_))) return false;
+ if (FAILED(client_->GetService(__uuidof(IAudioRenderClient),
+ reinterpret_cast<void**>(&render_)))) return false;
+ if (FAILED(client_->GetService(__uuidof(IAudioClock),
+ reinterpret_cast<void**>(&clock_)))) return false;
+ UINT64 freq = 0;
+ if (SUCCEEDED(clock_->GetFrequency(&freq))) clockFrequency_ = freq;
+ running_ = true;
+ veyra::log::info("audio", std::format("renderer opened {}Hz event-mode buffer={} frames (not started; prefill first)",
+ sampleRate_, bufferFrames_));
+ return true;
+}
+
+bool AudioRenderer::startAnchored(double firstBufferPtsMs)
+{
+ // Prefill the whole endpoint buffer with REAL samples happens on the
+ // first pump() call; anchor NOW at the device position with the PTS
+ // of the first sample we are about to submit.
+ UINT64 pos = 0, qpc = 0;
+ (void)clock_->GetPosition(&pos, &qpc);
+ anchorPos_ = pos;
+ anchorPtsMs_.store(firstBufferPtsMs);
+ if (FAILED(client_->Start())) return false;
+ started_ = true;
+ veyra::log::info("audio", std::format("renderer STARTED anchored ptsMs={:.1f} devicePos={} freq={}",
+ firstBufferPtsMs, pos, clockFrequency_));
+ return true;
+}
+
+bool AudioRenderer::pumpOnce(AudioPipeline& pipeline, double* firstWrittenPtsMs)
+{
+ if (!running_ || !started_) return true;
+ if (WaitForSingleObject(event_, 50) != WAIT_OBJECT_0) return true;
+ UINT32 padding = 0;
+ if (FAILED(client_->GetCurrentPadding(&padding))) return false;
+ const UINT32 avail = bufferFrames_ - padding;
+ if (avail == 0) return true;
+ double firstPts = -1.0;
+ const size_t got = pipeline.pull(chunk_.data(), avail, &firstPts);
+ if (firstWrittenPtsMs) *firstWrittenPtsMs = firstPts;
+ BYTE* dest = nullptr;
+ if (FAILED(render_->GetBuffer(avail, &dest))) return false;
+ if (got > 0) {
+ std::memcpy(dest, chunk_.data(), got * 8);
+ if (got < avail) {
+ std::memset(dest + got * 8, 0, (avail - got) * 8);
+ underruns_.fetch_add(1);
+ }
+ } else {
+ std::memset(dest, 0, static_cast<size_t>(avail) * 8);
+ underruns_.fetch_add(1);
+ }
+ (void)render_->ReleaseBuffer(avail, 0);
+ framesWritten_ += avail;
+ return true;
+}
+
+double AudioRenderer::mediaTimeMs() const
+{
+ if (!running_ || !started_) return anchorPtsMs_.load();
+ UINT64 pos = 0, qpc = 0;
+ if (FAILED(clock_->GetPosition(&pos, &qpc)) || clockFrequency_ == 0) {
+ return anchorPtsMs_.load();
+ }
+ const double consumedMs = 1000.0 * static_cast<double>(pos - anchorPos_) /
+ static_cast<double>(clockFrequency_);
+ return anchorPtsMs_.load() + consumedMs;
+}
+
+void AudioRenderer::stopAndReset()
+{
+ if (!running_) return;
+ (void)client_->Stop();
+ (void)client_->Reset();
+ started_ = false;
+ framesWritten_ = 0;
+}
+
+bool AudioRenderer::started() const { return started_; }
+uint64_t AudioRenderer::underruns() const { return underruns_.load(); }
+uint64_t AudioRenderer::framesWritten() const { return framesWritten_; }
+
+void AudioRenderer::shutdown()
+{
+ if (!running_) return;
+ (void)client_->Stop();
+ (void)client_->Reset();
+ #define REL(x) if (x) { x->Release(); x = nullptr; }
+ REL(clock_); REL(render_); REL(client_); REL(device_); REL(enum_);
+ #undef REL
+ if (event_ != nullptr) { CloseHandle(event_); event_ = nullptr; }
+ running_ = false;
+ if (comInited_) CoUninitialize();
+}
+
+void AudioPipeline::runOnAudioThread(AudioRenderer* renderer)
+{
+ const auto t0 = std::chrono::steady_clock::now();
+ // Initial prefill (open case).
+ {
+ std::unique_lock<std::mutex> lock(mutex_);
+ seekRequested_ = false;
+ discardUntilPtsMs_ = -1.0;
+ }
+ decodeBlock();
+ {
+ std::unique_lock<std::mutex> lock(mutex_);
+ if (segments_.empty()) {
+ veyra::log::warn("audio", "no audio decoded at startup");
+ }
+ }
+ const double firstPts = headPtsMs();
+ if (renderer != nullptr && firstPts >= 0.0) {
+ renderer->startAnchored(firstPts);
+ }
+ lastPrefillMs_.store(std::chrono::duration<double>(
+ std::chrono::steady_clock::now() - t0).count() * 1000.0);
+ veyra::log::info("audio", std::format("startup prefill done in {:.0f}ms firstPtsMs={:.1f} bufferedMs={:.0f}",
+ lastPrefillMs_.load(), firstPts, bufferedMs()));
+
+ while (!stopFlag_.load()) {
+ // Seek request? Atomic re-sequence.
+ {
+ std::unique_lock<std::mutex> lock(mutex_);
+ if (seekRequested_) {
+ seekRequested_ = false;
+ const double target = seekTargetMs_;
+ seekCount_.fetch_add(1);
+ lock.unlock();
+ if (renderer != nullptr) renderer->stopAndReset();
+ {
+ std::lock_guard<std::mutex> l2(mutex_);
+ ring_.clear();
+ ringFrames_ = 0;
+ segments_.clear();
+ if (havePacket_) { av_packet_unref(packet_); havePacket_ = false; }
+ avcodec_flush_buffers(codecCtx_);
+ const int64_t tbTarget = static_cast<int64_t>(
+ target * stream_->time_base.den / 1000 / stream_->time_base.num);
+ avformat_seek_file(fmt_, streamIndex_, INT64_MIN, tbTarget, INT64_MAX, 0);
+ demuxEof_ = false;
+ discardUntilPtsMs_ = target;
+ }
+ decodeBlock(); // drops pts < target, fills to high watermark
+ double startPts = headPtsMs();
+ if (startPts < 0.0) startPts = target;
+ firstPtsAfterSeek_.store(startPts);
+ if (renderer != nullptr) renderer->startAnchored(startPts);
+ {
+ std::lock_guard<std::mutex> l2(mutex_);
+ discardUntilPtsMs_ = -1.0;
+ seekDone_ = true;
+ }
+ seekDoneCv_.notify_all();
+ veyra::log::info("audio", std::format("seek done targetMs={:.0f} startPtsMs={:.1f} bufferedMs={:.0f}",
+ target, startPts, bufferedMs()));
+ continue;
+ }
+ }
+ // Regular cycle: pump the endpoint, then top up below high watermark.
+ if (renderer != nullptr) {
+ double firstPts = -1.0;
+ if (!renderer->pumpOnce(*this, &firstPts)) {
+ veyra::log::error("audio", "pumpOnce failed");
+ break;
+ }
+ }
+ if (bufferedMs() < kAudioHighWatermarkMs) {
+ decodeBlock();
+ } else {
+ std::this_thread::sleep_for(std::chrono::milliseconds(2));
+ }
+ if (demuxEof_ && bufferedMs() < 1.0) {
+ // End of media: park (engine loops the clip via its own seek).
+ std::this_thread::sleep_for(std::chrono::milliseconds(10));
+ }
+ }
+}
+
+void AudioPipeline::startThread(AudioRenderer* renderer)
+{
+ thread_ = std::thread(&AudioPipeline::runOnAudioThread, this, renderer);
+}
+
+} // namespace veyra::sink
diff --git a/tools/player_probe/main.cpp b/tools/player_probe/main.cpp
index e4f71244..8dec4b74 100644
--- a/tools/player_probe/main.cpp
+++ b/tools/player_probe/main.cpp
@@ -68,6 +68,7 @@ extern "C" {
#include "veyra/gfx/CommandSlotRing.h"
#include "veyra/gfx/D3D12DeviceContext.h"
#include "veyra/gfx/PresentSink.h"
+#include "veyra/sink/WasapiAudioSink.h"
#include "veyra/media/FFmpegDemuxer.h"
#include "veyra/media/FFmpegVideoDecoder.h"
#include "veyra/ngx/DlssFgBackend.h"
@@ -169,521 +170,8 @@ private:
std::unordered_map<ID3D12Resource*, D3D12_RESOURCE_STATES> states_;
};
-// ---------------------------------------------------------------------------
-// Audio: watermarked producer thread + event-driven WASAPI renderer with a
-// PTS-mapped master clock (P0.1, user directive 2026-09-04 s4).
-//
-// decodeUntil previously compared ringMs() (buffer length, max ~2000ms)
-// against an ABSOLUTE media-time target, so it decoded until ring overflow
-// on every call (16974 overruns observed). The rewrite:
-// - one dedicated audio thread does BOTH decode production and the
-// event-driven WASAPI pump;
-// - production uses relative watermarks in buffered-duration units
-// (low 250ms / prefill 500ms / high 1000ms); the ring is bounded and
-// player mode NEVER drops decoded audio to "solve" overflow;
-// - after open/seek the thread prefills to the prefill watermark BEFORE
-// the renderer is started;
-// - seek is atomic: stop+reset WASAPI, flush demuxer/decoder/resampler,
-// clear ring, seek demuxer, drop decoded samples with PTS < target,
-// prefill, re-anchor the clock to the real PTS of the next sample,
-// start;
-// - IAudioClock device position is mapped onto real audio PTS via the
-// anchor (firstPtsAtStart + consumed duration), not wall-clock zero.
-// ---------------------------------------------------------------------------
-
-class AudioRenderer; // forward: pipeline thread needs the renderer
-
-constexpr double kAudioLowWatermarkMs = 250.0;
-constexpr double kAudioPrefillMs = 500.0;
-constexpr double kAudioHighWatermarkMs = 1000.0;
-constexpr uint32_t kAudioRate = 48000;
-
-class AudioPipeline {
-public:
- ~AudioPipeline() { closeAll(); stopThread(); }
-
- bool open(const std::wstring& path)
- {
- std::string narrow;
- narrow.assign(path.begin(), path.end());
- if (avformat_open_input(&fmt_, narrow.c_str(), nullptr, nullptr) != 0) return false;
- if (avformat_find_stream_info(fmt_, nullptr) < 0) return false;
- const AVCodec* codec = nullptr;
- const int si = av_find_best_stream(fmt_, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0);
- if (si < 0 || codec == nullptr) {
- veyra::log::info("audio", "no audio stream in source");
- return false;
- }
- streamIndex_ = si;
- codecCtx_ = avcodec_alloc_context3(codec);
- if (avcodec_parameters_to_context(codecCtx_, fmt_->streams[si]->codecpar) < 0) return false;
- if (avcodec_open2(codecCtx_, codec, nullptr) < 0) return false;
- stream_ = fmt_->streams[si];
- veyra::log::info("audio", std::format("audio stream idx={} codec={} rate={}",
- si, codec->name, codecCtx_->sample_rate));
- return true;
- }
-
- double bufferedMs() const
- {
- std::lock_guard<std::mutex> lock(mutex_);
- return 1000.0 * static_cast<double>(ringFrames_) / kAudioRate;
- }
-
- // PTS (ms) of the first unconsumed buffered sample; < 0 when empty.
- double headPtsMs() const
- {
- std::lock_guard<std::mutex> lock(mutex_);
- if (segments_.empty()) return -1.0;
- return segments_.front().startPtsMs;
- }
-
- // Decoded-ahead PTS (ms) of the last buffered sample end; -1 if empty.
- double tailPtsMs() const
- {
- std::lock_guard<std::mutex> lock(mutex_);
- if (segments_.empty()) return -1.0;
- const Segment& t = segments_.back();
- return t.startPtsMs + 1000.0 * static_cast<double>(t.frames) / kAudioRate;
- }
-
- uint64_t underruns() const { return underruns_.load(); }
- uint64_t overruns() const { return overruns_.load(); } // must stay 0
- uint64_t seekCount() const { return seekCount_.load(); }
- double lastPrefillMs() const { return lastPrefillMs_.load(); }
- double firstPtsAfterLastSeek() const { return firstPtsAfterSeek_.load(); }
-
- // Pull up to maxFrames stereo frames; sets the PTS of the first pulled
- // frame. Returns frames pulled (0 legal; caller writes silence and it is
- // counted as an underrun by the pump only when the endpoint had space).
- size_t pull(float* dst, size_t maxFrames, double* firstPtsMs)
- {
- std::lock_guard<std::mutex> lock(mutex_);
- if (firstPtsMs) *firstPtsMs = segments_.empty() ? -1.0 : segments_.front().startPtsMs;
- const size_t take = std::min(maxFrames, ringFrames_);
- size_t copied = 0;
- while (copied < take && !segments_.empty()) {
- Segment& seg = segments_.front();
- const size_t n = std::min(take - copied, seg.frames);
- // Ring is a deque of float pairs: copy n frames.
- for (size_t i = 0; i < n * 2; ++i) {
- dst[copied * 2 + i] = ring_.front();
- ring_.pop_front();
- }
- copied += n;
- seg.frames -= n;
- seg.startPtsMs += 1000.0 * static_cast<double>(n) / kAudioRate;
- if (seg.frames == 0) segments_.pop_front();
- }
- ringFrames_ -= take;
- return take;
- }
-
- void stopThread()
- {
- stopFlag_ = true;
- wake_.notify_all();
- if (thread_.joinable()) thread_.join();
- }
-
- // ---- Seek protocol (engine thread calls; audio thread executes) ------
- // Blocks until the audio thread finished the atomic re-sequence and
- // prefilled. Returns the PTS of the first buffered sample after seek.
- double requestSeek(double targetMs)
- {
- std::unique_lock<std::mutex> lock(mutex_);
- seekTargetMs_ = targetMs;
- seekDone_ = false;
- seekRequested_ = true;
- wake_.notify_all();
- // The audio thread signals when the ring is prefilled past target.
- if (!seekDoneCv_.wait_for(lock, std::chrono::milliseconds(3000), [this] { return seekDone_; })) {
- veyra::log::error("audio", "seek prefill timed out");
- }
- return segments_.empty() ? targetMs : segments_.front().startPtsMs;
- }
-
-private:
- struct Segment {
- double startPtsMs;
- size_t frames;
- };
-
- // ---- Producer side (audio thread only; mutex for ring sharing) -------
- void pushDecoded(const AVFrame* frame)
- {
- // Convert to 48k stereo float in converted_.
- if (swr_ == nullptr) {
- AVChannelLayout outLayout = AV_CHANNEL_LAYOUT_STEREO;
- AVChannelLayout inLayout = frame->ch_layout.nb_channels > 0
- ? frame->ch_layout : outLayout;
- swr_alloc_set_opts2(&swr_,
- &outLayout, AV_SAMPLE_FMT_FLT, kAudioRate,
- &inLayout, static_cast<AVSampleFormat>(frame->format), frame->sample_rate,
- 0, nullptr);
- if (swr_ == nullptr || swr_init(swr_) < 0) return;
- }
- uint8_t* planes[1] = { reinterpret_cast<uint8_t*>(converted_.data()) };
- const int outSamples = swr_convert(swr_, planes,
- static_cast<int>(converted_.size() / 2),
- const_cast<const uint8_t**>(frame->extended_data), frame->nb_samples);
- if (outSamples <= 0) return;
-
- std::unique_lock<std::mutex> lock(mutex_);
- const double segStart = nextPtsMs_;
- const size_t addFrames = static_cast<size_t>(outSamples);
- if (ringFrames_ + addFrames > kMaxRingFrames) {
- // Player mode: never drop. This is a hard error (bounded ring
- // should never overflow because production is watermarked).
- overruns_.fetch_add(1);
- veyra::log::error("audio", "ring overflow despite watermarks (bug)");
- return;
- }
- ring_.insert(ring_.end(), converted_.data(), converted_.data() + addFrames * 2);
- ringFrames_ += addFrames;
- if (!segments_.empty()) {
- Segment& last = segments_.back();
- const double lastEnd = last.startPtsMs + 1000.0 * static_cast<double>(last.frames) / kAudioRate;
- if (std::fabs(lastEnd - nextPtsMs_) < 1.0) {
- last.frames += addFrames; // contiguous: extend
- } else {
- segments_.push_back({ nextPtsMs_, addFrames });
- }
- } else {
- segments_.push_back({ nextPtsMs_, addFrames });
- }
- nextPtsMs_ += 1000.0 * static_cast<double>(addFrames) / kAudioRate;
- (void)segStart;
- }
-
- void decodeBlock()
- {
- // Decode until high watermark or EOF; called only when below high.
- while (bufferedMsLocked() < kAudioHighWatermarkMs && !stopFlag_ && !seekRequested_) {
- if (!havePacket_) {
- if (av_read_frame(fmt_, packet_) < 0) {
- demuxEof_ = true;
- break;
- }
- havePacket_ = true;
- if (packet_->stream_index != streamIndex_) {
- av_packet_unref(packet_);
- havePacket_ = false;
- continue;
- }
- }
- if (avcodec_send_packet(codecCtx_, havePacket_ ? packet_ : nullptr) == 0 && havePacket_) {
- av_packet_unref(packet_);
- havePacket_ = false;
- }
- AVFrame* frame = av_frame_alloc();
- bool enough = false;
- while (avcodec_receive_frame(codecCtx_, frame) == 0) {
- const double ptsMs = 1000.0 * frame->pts * stream_->time_base.num / stream_->time_base.den;
- nextPtsMs_ = ptsMs + 1000.0 * frame->nb_samples / kAudioRate;
- if (discardUntilPtsMs_ < 0.0 || ptsMs >= discardUntilPtsMs_) {
- pushDecoded(frame);
- }
- av_frame_unref(frame);
- if (bufferedMsLocked() >= kAudioHighWatermarkMs) { enough = true; break; }
- }
- av_frame_free(&frame);
- if (enough || demuxEof_) break;
- }
- }
-
- double bufferedMsLocked() const
- {
- return 1000.0 * static_cast<double>(ringFrames_) / kAudioRate;
- }
-
- void closeAll()
- {
- if (swr_ != nullptr) swr_free(&swr_);
- if (packet_ != nullptr) av_packet_free(&packet_);
- if (codecCtx_ != nullptr) avcodec_free_context(&codecCtx_);
- if (fmt_ != nullptr) avformat_close_input(&fmt_);
- }
-
- friend class AudioThread;
-
- AVFormatContext* fmt_ = nullptr;
- AVCodecContext* codecCtx_ = nullptr;
- AVStream* stream_ = nullptr;
- AVPacket* packet_ = av_packet_alloc();
- SwrContext* swr_ = nullptr;
- int streamIndex_ = -1;
- bool havePacket_ = false;
- bool demuxEof_ = false;
- double nextPtsMs_ = 0.0; // PTS of the NEXT decoded sample
- double discardUntilPtsMs_ = -1.0; // seek pruning
- static constexpr size_t kMaxRingFrames = kAudioRate * 2; // 2s hard bound
-
- mutable std::mutex mutex_;
- std::deque<float> ring_{}; // stereo interleaved
- size_t ringFrames_ = 0;
- std::deque<Segment> segments_{}; // PTS bookkeeping of ring contents
-
- std::condition_variable wake_;
- std::condition_variable seekDoneCv_;
- std::atomic<bool> stopFlag_{false};
- bool seekRequested_ = false;
- bool seekDone_ = true;
- double seekTargetMs_ = 0.0;
-
- std::atomic<uint64_t> underruns_{0};
- std::atomic<uint64_t> overruns_{0};
- std::atomic<uint64_t> seekCount_{0};
- std::atomic<double> lastPrefillMs_{0.0};
- std::atomic<double> firstPtsAfterSeek_{-1.0};
- std::vector<float> converted_{std::vector<float>(kAudioRate)};
-
-public:
- void runOnAudioThread(AudioRenderer* renderer); // defined after renderer
-private:
- std::thread thread_;
-public:
- void startThread(AudioRenderer* renderer)
- {
- thread_ = std::thread(&AudioPipeline::runOnAudioThread, this, renderer);
- }
-};
-
-// ---------------------------------------------------------------------------
-// WASAPI renderer: event-driven shared mode; device clock mapped onto media
-// PTS through an explicit anchor set at Start and after every seek restart.
-// ---------------------------------------------------------------------------
-class AudioRenderer {
-public:
- bool start()
- {
- HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
- comInited_ = SUCCEEDED(hr);
- hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL,
- __uuidof(IMMDeviceEnumerator), reinterpret_cast<void**>(&enum_));
- if (FAILED(hr)) return false;
- hr = enum_->GetDefaultAudioEndpoint(eRender, eConsole, &device_);
- if (FAILED(hr)) return false;
- hr = device_->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr,
- reinterpret_cast<void**>(&client_));
- if (FAILED(hr)) return false;
- WAVEFORMATEX* mix = nullptr;
- if (FAILED(client_->GetMixFormat(&mix))) return false;
- sampleRate_ = mix->nSamplesPerSec;
- hr = client_->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
- 10 * 10000, 0, mix, nullptr);
- const bool initOk = SUCCEEDED(hr);
- CoTaskMemFree(mix);
- if (!initOk) return false;
- if (FAILED(client_->GetBufferSize(&bufferFrames_))) return false;
- event_ = CreateEventW(nullptr, FALSE, FALSE, nullptr);
- if (event_ == nullptr || FAILED(client_->SetEventHandle(event_))) return false;
- if (FAILED(client_->GetService(__uuidof(IAudioRenderClient),
- reinterpret_cast<void**>(&render_)))) return false;
- if (FAILED(client_->GetService(__uuidof(IAudioClock),
- reinterpret_cast<void**>(&clock_)))) return false;
- UINT64 freq = 0;
- if (SUCCEEDED(clock_->GetFrequency(&freq))) clockFrequency_ = freq;
- running_ = true;
- veyra::log::info("audio", std::format("renderer opened {}Hz event-mode buffer={} frames (not started; prefill first)",
- sampleRate_, bufferFrames_));
- return true;
- }
-
- // Called by the audio thread after prefill: begins playback anchored at
- // the PTS of the sample that will be written first.
- bool startAnchored(double firstBufferPtsMs)
- {
- // Prefill the whole endpoint buffer with REAL samples happens on the
- // first pump() call; anchor NOW at the device position with the PTS
- // of the first sample we are about to submit.
- UINT64 pos = 0, qpc = 0;
- (void)clock_->GetPosition(&pos, &qpc);
- anchorPos_ = pos;
- anchorPtsMs_.store(firstBufferPtsMs);
- if (FAILED(client_->Start())) return false;
- started_ = true;
- veyra::log::info("audio", std::format("renderer STARTED anchored ptsMs={:.1f} devicePos={} freq={}",
- firstBufferPtsMs, pos, clockFrequency_));
- return true;
- }
-
- // Event-driven pump for ONE event cycle. Writes real data when the ring
- // has it, silence otherwise (underrun counted). Returns false on hard
- // failure.
- bool pumpOnce(AudioPipeline& pipeline, double* firstWrittenPtsMs)
- {
- if (!running_ || !started_) return true;
- if (WaitForSingleObject(event_, 50) != WAIT_OBJECT_0) return true;
- UINT32 padding = 0;
- if (FAILED(client_->GetCurrentPadding(&padding))) return false;
- const UINT32 avail = bufferFrames_ - padding;
- if (avail == 0) return true;
- double firstPts = -1.0;
- const size_t got = pipeline.pull(chunk_.data(), avail, &firstPts);
- if (firstWrittenPtsMs) *firstWrittenPtsMs = firstPts;
- BYTE* dest = nullptr;
- if (FAILED(render_->GetBuffer(avail, &dest))) return false;
- if (got > 0) {
- std::memcpy(dest, chunk_.data(), got * 8);
- if (got < avail) {
- std::memset(dest + got * 8, 0, (avail - got) * 8);
- underruns_.fetch_add(1);
- }
- } else {
- std::memset(dest, 0, static_cast<size_t>(avail) * 8);
- underruns_.fetch_add(1);
- }
- (void)render_->ReleaseBuffer(avail, 0);
- framesWritten_ += avail;
- return true;
- }
-
- // Master clock: real media PTS of the sample currently being played.
- double mediaTimeMs() const
- {
- if (!running_ || !started_) return anchorPtsMs_.load();
- UINT64 pos = 0, qpc = 0;
- if (FAILED(clock_->GetPosition(&pos, &qpc)) || clockFrequency_ == 0) {
- return anchorPtsMs_.load();
- }
- const double consumedMs = 1000.0 * static_cast<double>(pos - anchorPos_) /
- static_cast<double>(clockFrequency_);
- return anchorPtsMs_.load() + consumedMs;
- }
-
- // Atomic seek support: stop + reset the endpoint; the clock is invalid
- // until the next startAnchored.
- void stopAndReset()
- {
- if (!running_) return;
- (void)client_->Stop();
- (void)client_->Reset();
- started_ = false;
- framesWritten_ = 0;
- }
-
- bool started() const { return started_; }
- uint64_t underruns() const { return underruns_.load(); }
- uint64_t framesWritten() const { return framesWritten_; }
-
- void shutdown()
- {
- if (!running_) return;
- (void)client_->Stop();
- (void)client_->Reset();
- #define REL(x) if (x) { x->Release(); x = nullptr; }
- REL(clock_); REL(render_); REL(client_); REL(device_); REL(enum_);
- #undef REL
- if (event_ != nullptr) { CloseHandle(event_); event_ = nullptr; }
- running_ = false;
- if (comInited_) CoUninitialize();
- }
-
-private:
- IMMDeviceEnumerator* enum_ = nullptr;
- IMMDevice* device_ = nullptr;
- IAudioClient* client_ = nullptr;
- IAudioRenderClient* render_ = nullptr;
- IAudioClock* clock_ = nullptr;
- HANDLE event_ = nullptr;
- UINT32 bufferFrames_ = 0;
- uint32_t sampleRate_ = kAudioRate;
- UINT64 clockFrequency_ = 0;
- UINT64 anchorPos_ = 0;
- std::atomic<double> anchorPtsMs_{0.0};
- bool started_ = false;
- bool running_ = false;
- bool comInited_ = false;
- std::atomic<uint64_t> underruns_{0};
- uint64_t framesWritten_ = 0;
- std::vector<float> chunk_{std::vector<float>(8192 * 2)};
-};
-
-// The audio thread: prefill -> start -> { event pump + watermark decode }.
-inline void AudioPipeline::runOnAudioThread(AudioRenderer* renderer)
-{
- const auto t0 = std::chrono::steady_clock::now();
- // Initial prefill (open case).
- {
- std::unique_lock<std::mutex> lock(mutex_);
- seekRequested_ = false;
- discardUntilPtsMs_ = -1.0;
- }
- decodeBlock();
- {
- std::unique_lock<std::mutex> lock(mutex_);
- if (segments_.empty()) {
- veyra::log::warn("audio", "no audio decoded at startup");
- }
- }
- const double firstPts = headPtsMs();
- if (renderer != nullptr && firstPts >= 0.0) {
- renderer->startAnchored(firstPts);
- }
- lastPrefillMs_.store(std::chrono::duration<double>(
- std::chrono::steady_clock::now() - t0).count() * 1000.0);
- veyra::log::info("audio", std::format("startup prefill done in {:.0f}ms firstPtsMs={:.1f} bufferedMs={:.0f}",
- lastPrefillMs_.load(), firstPts, bufferedMs()));
-
- while (!stopFlag_.load()) {
- // Seek request? Atomic re-sequence.
- {
- std::unique_lock<std::mutex> lock(mutex_);
- if (seekRequested_) {
- seekRequested_ = false;
- const double target = seekTargetMs_;
- seekCount_.fetch_add(1);
- lock.unlock();
- if (renderer != nullptr) renderer->stopAndReset();
- {
- std::lock_guard<std::mutex> l2(mutex_);
- ring_.clear();
- ringFrames_ = 0;
- segments_.clear();
- if (havePacket_) { av_packet_unref(packet_); havePacket_ = false; }
- avcodec_flush_buffers(codecCtx_);
- const int64_t tbTarget = static_cast<int64_t>(
- target * stream_->time_base.den / 1000 / stream_->time_base.num);
- avformat_seek_file(fmt_, streamIndex_, INT64_MIN, tbTarget, INT64_MAX, 0);
- demuxEof_ = false;
- discardUntilPtsMs_ = target;
- }
- decodeBlock(); // drops pts < target, fills to high watermark
- double startPts = headPtsMs();
- if (startPts < 0.0) startPts = target;
- firstPtsAfterSeek_.store(startPts);
- if (renderer != nullptr) renderer->startAnchored(startPts);
- {
- std::lock_guard<std::mutex> l2(mutex_);
- discardUntilPtsMs_ = -1.0;
- seekDone_ = true;
- }
- seekDoneCv_.notify_all();
- veyra::log::info("audio", std::format("seek done targetMs={:.0f} startPtsMs={:.1f} bufferedMs={:.0f}",
- target, startPts, bufferedMs()));
- continue;
- }
- }
- // Regular cycle: pump the endpoint, then top up below high watermark.
- if (renderer != nullptr) {
- double firstPts = -1.0;
- if (!renderer->pumpOnce(*this, &firstPts)) {
- veyra::log::error("audio", "pumpOnce failed");
- break;
- }
- }
- if (bufferedMs() < kAudioHighWatermarkMs) {
- decodeBlock();
- } else {
- std::this_thread::sleep_for(std::chrono::milliseconds(2));
- }
- if (demuxEof_ && bufferedMs() < 1.0) {
- // End of media: park (engine loops the clip via its own seek).
- std::this_thread::sleep_for(std::chrono::milliseconds(10));
- }
- }
-}
+// Audio playback now lives in the veyra_sinks product library
+// (include/veyra/sink/WasapiAudioSink.h); the probe consumes it.
// ---------------------------------------------------------------------------
// Compute pass helper (8 constants + SRV table + UAV table; single heap).
@@ -1045,8 +533,8 @@ int main(int argc, char** argv)
veyra::media::FFmpegDemuxer demuxer;
veyra::media::FFmpegVideoDecoder decoder;
- AudioPipeline audioPipe;
- AudioRenderer audio;
+ veyra::sink::AudioPipeline audioPipe;
+ veyra::sink::AudioRenderer audio;
veyra::gfx::D3D12DeviceContext context;
veyra::gfx::CommandSlotRing ring;
veyra::gfx::PresentSink sink;