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++

release: publish 0.0.4 with synchronized and continuous audio

Veyra Goal Agentcecf34e1f88e
diff --git a/AGENTS.md b/AGENTS.md
index e0fdb671..9b16f50f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,5 +1,7 @@
# Veyra 项目 Agent 执行规则
+> 2026-09-11 用户授权发布 0.0.4:当前音画同步与音频连续性修复推送到 `Likely7/Veyra-NRVideo`,更新中英文 README 并发布完整便携包。运行组件沿用 0.0.3 的七文件白名单及双 NR 原件身份,不新增或替换运行时;社区版继续记录 `HashMismatch`。源码 Git 禁止 SDK/DLL/模型,软件允许用户替换 DLL 的决定不变。
+
> 2026-09-11 用户授权发布当前0.0.3:源码推送到`Likely7/Veyra-NRVideo`,完整便携Release包含当前双NR运行版本和直播实验选项。此前用户指定的RTX40/50社区DLL可原样进入本次Release的`runtime/experimental/nr-community/`,身份沿用下条SHA256、310.8.0.0、165840496字节、`HashMismatch`,必须逐文件列入manifest并明确社区修改版;这是本次发布范围的扩展,不允许自动加入其他版本或修改文件。源码Git仍绝不包含SDK/DLL/模型。软件不恢复运行时哈希锁。OBS捕获说明按用户要求仅补README,不继续改软件提示。
> 2026-09-11 用户指定RTX40/50社区NR运行时接入:允许把用户明确提供的`E:/Ai/mg/DLSSNR-DLL-Options-310.8.0.0/Community-RTX40-RTX50/nvngx_dlssnr.dll`原样复制到忽略的`runtime_local/nvidia/nr-community/`进行本机切换测试。该文件SHA256为`984BEE0F775C277D5829B8FD6775D53A7B0F75396C852B3AAF06A18375F81014`,签名状态`HashMismatch`,必须标注社区修改/实验,不能称为有效NVIDIA签名原版。用户指定此文件取代旧“仅根目录原版可本机加载”的限制;不授予Agent修改/重签名文件的权限,不自动扩大Release默认白名单,不上传DLL到源码Git。
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 19b24947..9f7c78e0 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,6 +1,6 @@
cmake_minimum_required(VERSION 3.24)
-project(veyra VERSION 0.0.3 LANGUAGES CXX RC)
+project(veyra VERSION 0.0.4 LANGUAGES CXX RC)
# Match the compiler's actual bytes, including on localized Windows installs.
# CMake's cached, decoded prefix can leave Ninja with zero header dependencies.
diff --git a/README.md b/README.md
index 80de7ba8..55909fcb 100644
--- a/README.md
+++ b/README.md
@@ -12,7 +12,7 @@
Windows 视频播放器与采集卡增强工具。支持视频、图片和采集卡实时预览,可组合使用超分辨率、NR 画面增强与补帧。
-[下载 0.0.3 免安装版](https://github.com/Likely7/Veyra-NRVideo/releases/tag/v0.0.3) · [更新记录](docs/RELEASE_NOTES_0.0.3.md) · [反馈问题](https://github.com/Likely7/Veyra-NRVideo/issues)
+[下载 0.0.4 免安装版](https://github.com/Likely7/Veyra-NRVideo/releases/tag/v0.0.4) · [更新记录](docs/RELEASE_NOTES_0.0.4.md) · [反馈问题](https://github.com/Likely7/Veyra-NRVideo/issues)
## 功能
@@ -28,11 +28,11 @@ Windows 视频播放器与采集卡增强工具。支持视频、图片和采集
日常模式以观看为主;专业模式展开增强参数、诊断和导出工具。切换模式不需要重新打开视频。
-0.0.3 新增 NR 运行版本切换:NVIDIA 原版默认启用,另附 RTX 40/50 社区兼容实验版。RTX 40 尚未完成实机验证;专业模式布局重排仍在规划中。
+0.0.4 修复增强处理造成的音画不同步,以及 NR 耗时轻微波动时的音频卡顿;同时修正 XeSS 补帧下的音频播放时序。
## 下载与运行
-1. 在 [Releases](https://github.com/Likely7/Veyra-NRVideo/releases) 下载 **Veyra-0.0.3-win64-portable.zip**,不要下载 Source code。
+1. 在 [Releases](https://github.com/Likely7/Veyra-NRVideo/releases) 下载 **Veyra-0.0.4-win64-portable.zip**,不要下载 Source code。
2. 完整解压到一个可写文件夹,双击 **Veyra.exe**。无需安装 SDK、Python 或开发工具。
3. 使用当前显卡驱动。要使用 NVIDIA NR、DLSS、RTX Video SR 和 NVENC,需兼容的 NVIDIA RTX 显卡;本版本主要在 RTX 5070 上验证。
@@ -59,6 +59,8 @@ Windows 视频播放器与采集卡增强工具。支持视频、图片和采集
处理跟不上时降低画质、倍率或目标尺寸。软件延迟指采集回调到 Present 返回,不包含完整采集卡和屏幕扫描延迟;补帧不能降低游戏输入延迟。
+音画同步自动跟随软件处理链路,采集卡音视频共同的输入延迟不会重复补偿。轻微耗时波动不会逐帧停放声音;如果 GPU 持续处理不过来,仍可能等待视频,需要降低增强负载。
+
### 导出与运行组件
在专业模式选择图片保存或视频导出、格式与输出位置。XeSS 目前仅用于预览;视频导出使用已支持的 DLSS 路径。
@@ -87,6 +89,6 @@ NR 与 DLSS 帧生成属于 **community experimental / 社区实验集成**,
## 开发与许可
-[构建说明](docs/BUILD.md) · [组件清单](docs/RUNTIME_COMPONENTS_0.0.3.md) · [第三方许可](THIRD_PARTY_NOTICES.md)
+[构建说明](docs/BUILD.md) · [组件清单](docs/RUNTIME_COMPONENTS_0.0.4.md) · [第三方许可](THIRD_PARTY_NOTICES.md)
源码采用 [GPLv3](LICENSE)。SDK、模型和运行时不进入源码仓库;Release 组件按各自许可与实验发布范围单独提供。
diff --git a/README_EN.md b/README_EN.md
index 47e92ed6..579451c8 100644
--- a/README_EN.md
+++ b/README_EN.md
@@ -12,7 +12,7 @@ English | [简体中文](README.md)
A Windows video player and capture-card enhancement tool. Play videos, process images, and preview capture devices with optional super resolution, NR enhancement, and frame generation.
-[Download 0.0.3 Portable](https://github.com/Likely7/Veyra-NRVideo/releases/tag/v0.0.3) · [Release Notes](docs/RELEASE_NOTES_0.0.3.md) · [Report an Issue](https://github.com/Likely7/Veyra-NRVideo/issues)
+[Download 0.0.4 Portable](https://github.com/Likely7/Veyra-NRVideo/releases/tag/v0.0.4) · [Release Notes](docs/RELEASE_NOTES_0.0.4.md) · [Report an Issue](https://github.com/Likely7/Veyra-NRVideo/issues)
## Features
@@ -28,11 +28,11 @@ A Windows video player and capture-card enhancement tool. Play videos, process i
Daily mode focuses on watching. Professional mode expands the controls, diagnostics, and export tools without reopening the video. The application currently uses a Chinese interface.
-Version 0.0.3 adds NR runtime selection: the NVIDIA original remains the default, with an optional community RTX 40/50 experimental variant included. RTX 40 hardware validation is pending. The proposed Professional-mode layout redesign is not implemented yet.
+Version 0.0.4 fixes audio/video drift caused by enhancement processing, audio interruptions during small NR timing fluctuations, and audio scheduling with XeSS frame generation.
## Download and Run
-1. Download **Veyra-0.0.3-win64-portable.zip** from [Releases](https://github.com/Likely7/Veyra-NRVideo/releases). The Source code archives are for developers.
+1. Download **Veyra-0.0.4-win64-portable.zip** from [Releases](https://github.com/Likely7/Veyra-NRVideo/releases). The Source code archives are for developers.
2. Extract the entire archive into a writable directory and run **Veyra.exe**. No SDK, Python, or development tools are needed.
3. Use a current GPU driver. NVIDIA NR, DLSS, RTX Video SR, and NVENC require compatible NVIDIA RTX hardware; this version was primarily tested on an RTX 5070.
@@ -59,6 +59,8 @@ Enable NR, super resolution, and frame generation independently in Professional
Start with realtime NR, a lower RTX Video SR quality, and 2X frame generation. Compare the image and watch the diagnostics. Reduce quality, multiplier, or target size if processing falls behind. Software latency measures capture callback to Present return, not complete capture-to-display latency. Frame generation does not reduce game input latency.
+Audio synchronization follows the software processing chain without counting the capture card's shared input delay twice. Small timing fluctuations no longer stop audio on each frame. Sustained GPU overload can still require waiting for video; lower the enhancement workload if that happens.
+
### Export and Runtime Replacement
Use Professional mode to save an image or export a video, then choose the format and destination. XeSS is preview-only; supported video frame-generation export uses DLSS.
@@ -87,6 +89,6 @@ NR and DLSS frame generation are **community-experimental integrations**, not NV
## Development and License
-[Build Instructions](docs/BUILD.md) · [Runtime Components](docs/RUNTIME_COMPONENTS_0.0.3.md) · [Third-Party Notices](THIRD_PARTY_NOTICES.md)
+[Build Instructions](docs/BUILD.md) · [Runtime Components](docs/RUNTIME_COMPONENTS_0.0.4.md) · [Third-Party Notices](THIRD_PARTY_NOTICES.md)
Source code is licensed under [GPLv3](LICENSE). SDKs, models, and runtimes are excluded from this source repository. Release components retain their separate licenses and experimental distribution boundaries.
diff --git a/docs/BUILD.md b/docs/BUILD.md
index a362a0f4..b83d8823 100644
--- a/docs/BUILD.md
+++ b/docs/BUILD.md
@@ -5,7 +5,7 @@
## Requirements
- Windows 11 x64, Visual Studio 2022 C++ tools, Windows SDK, CMake 3.24+, Ninja.
-- Local FFmpeg development libraries matching avcodec63 / avformat63 / avutil61 / swresample7 / swscale10. Release 0.0.3 uses the vcpkg FFmpeg 9.0.1#1 build (LGPL configuration).
+- Local FFmpeg development libraries matching avcodec63 / avformat63 / avutil61 / swresample7 / swscale10. Release 0.0.4 uses the vcpkg FFmpeg 9.0.1#1 build (LGPL configuration).
- NVIDIA DLSS SDK 310.7.0, Optical Flow SDK 5.0.7, RTX Video SDK 1.1.0, and nv-codec-headers. Prepare these under their respective licenses in ignored local directories.
- Intel XeSS SDK 3.0.2 for the XeSS presenter; AMD FidelityFX SDK 1.1.4 optical-flow/backend static libraries for the AMD flow option.
- Local NR runtime and NGX project configuration for experimental NR. The source repository intentionally does not contain them.
@@ -35,7 +35,7 @@ The NGX configuration lives in `runtime_local/config/ngx-local.json` for develop
## Dependency Sources
-Release 0.0.3 includes `Veyra-0.0.3-FFmpeg-source.zip` separately: the patched FFmpeg source, SPDX-verified vcpkg port and patches, notices, and configuration queried from the shipped DLL. It is not needed to run Veyra.
+Release 0.0.4 includes `Veyra-0.0.4-FFmpeg-source.zip` separately: the patched FFmpeg source, SPDX-verified vcpkg port and patches, notices, and configuration queried from the shipped DLL. It is not needed to run Veyra.
- FFmpeg: https://github.com/FFmpeg/FFmpeg/tree/n9.0.1 ; vcpkg port source recorded in the distributed `licenses/FFMPEG-SPDX.json`.
- vcpkg FFmpeg port: https://github.com/microsoft/vcpkg/tree/55cd8b8a4f19d8e6ba2ad114c8acacc4af5915a0/ports/ffmpeg . Its patches and the LGPL notices are part of the corresponding-source material.
@@ -51,7 +51,7 @@ Veyra and FidelityFX code are compiled into the executable; FFmpeg is dynamicall
Run targeted tests and `scripts/gates/delivery.ps1`; each individual test must stay below300seconds. Physical capture and screen scanout require separate hardware verification. The legacy Loop gate is not part of the current process.
```powershell
-powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/package-portable.ps1 -Root . -Version 0.0.3 -OutputDirectory out/releases/0.0.3
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/package-portable.ps1 -Root . -Version 0.0.4 -OutputDirectory out/releases/0.0.4
```
The packager accepts `-BuildDirectory` for an isolated build, checks the publisher's fixed input files, copies an explicit payload, and emits a ZIP, checksums, and component manifests. It refuses to overwrite an existing candidate. This build-time audit does not restrict user DLL replacement. Do not upload SDK headers, samples, libraries, private media, logs, or development archives with the source.
diff --git a/docs/RELEASE_0.0.4_EXECUTION.md b/docs/RELEASE_0.0.4_EXECUTION.md
new file mode 100644
index 00000000..cb08d623
--- /dev/null
+++ b/docs/RELEASE_0.0.4_EXECUTION.md
@@ -0,0 +1,52 @@
+# 0.0.4 发布执行记录
+
+状态:候选构建及发布前验证通过,待推送并公开 Release。用户 2026-09-11 明确要求当前版本更新到 GitHub,版本号 0.0.4。目标为 `Likely7/Veyra-NRVideo` 的 `main` 与 `v0.0.4`,保留旧版标签和资产。
+
+## 范围
+
+收录文件与采集的软件处理延迟同步修复,以及 NR 波动、XeSS 帧覆盖引起的音频停顿修复。具体实现、原先失败和针对性回归见 [音画同步修复记录](SOFTWARE_AV_SYNC_REPAIR_2026-09-11.md)。不修改导出完整性检查,不把持续 GPU 过载或采集卡共同输入延迟当成本轮已经消除的问题。
+
+同步 CMake/EXE 版本、中英文 README、更新说明、组件清单及构建文档;保留 README 开头自动播放的 GIF。FFmpeg 源码打包脚本改为显式要求版本参数,避免沿用旧版本号。便携测试显式加载执行宿主的 PowerShell Utility 模块,修复跨 PowerShell 版本调用时报告写入失败。
+
+## 打包与身份
+
+全新 `out/build/release-0.0.4` 构建 174 个目标,exit 0。EXE 产品版本 `0.0.4`,SHA256 `455B17D533D837A88B1A9D8BC27F452677A7D1010033E91EB9B37BF6353DFD9E`。未覆盖用户原开发目录中的进程。
+
+沿用 0.0.3 七个运行文件,发布者检查 SHA256、签名、版本和指定文件大小;无新增运行组件。六个原件签名 Valid,指定社区 NR 为 HashMismatch,分放在 `runtime/experimental/nr-community/`。来源类别、完整哈希、版本、许可证位置及移除方法见 [组件清单](RUNTIME_COMPONENTS_0.0.4.md) 和包内 manifest;清单不作为程序加载锁。NVIDIA/Intel DLL、SDK、模型不进入源码 Git。
+
+项目外新目录 `%TEMP%/Veyra portable 004 verified/` 解压后,51 个 manifest 条目的大小与 SHA256 全匹配,加 manifest 自身恰为 52 个文件。打包 `forbiddenFiles=0`;不包含 SDK 头文件、库、PDB、日志、模型或测试媒体。证据 `logs/release-0.0.4/extracted-audit.json`、`out/releases/0.0.4/package-audit.json`。
+
+| 资产 | 字节数 | SHA256 |
+| --- | --- | --- |
+| Veyra-0.0.4-win64-portable.zip | 299001834 | F788E8EFDE257953166C871267C63597CF13325D0433FD620551C7F4E655E04F |
+| Veyra-0.0.4-FFmpeg-source.zip | 23248643 | B08C43EB78AF709034835D4CF255D67DAB368B25D47967FD2F3B99D529CC3D38 |
+
+两个 ZIP 各附 `.sha256`。FFmpeg 对应源码 10442 条,vcpkg port/patch 与已安装 SPDX 匹配,许可证与构建参数取自实际分发 DLL(LGPL 2.1 or later),未混入 NVIDIA SDK。
+
+## 实际命令
+
+从项目根目录执行,PowerShell 进程测试均用 `scripts/run-short-test.ps1` 包装,单次外部超时不超过 300 秒。
+
+```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root . -Preset x64-release -BuildDirectory out/build/release-0.0.4
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/package-portable.ps1 -Root . -Version 0.0.4 -BuildDirectory out/build/release-0.0.4 -OutputDirectory out/releases/0.0.4
+python scripts/package-ffmpeg-source.py --version 0.0.4 --prefix C:/veyra-deps/installed/x64-windows --vcpkg C:/veyra-deps/vcpkg --source C:/veyra-deps/vcpkg/buildtrees/ffmpeg/src/n9.0.1-1250e74153.clean --output out/releases/0.0.4/Veyra-0.0.4-FFmpeg-source.zip
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/acceptance/portable-smoke.ps1 -PackageDirectory "$env:TEMP/Veyra portable 004 verified/Veyra-0.0.4-win64-portable" -InputFile loop/local/fixed_clips/test_av_1080p.mp4 -OutputDirectory logs/release-0.0.4/portable-final
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/release-0.0.4 -PlayerExe "$env:TEMP/Veyra portable 004 verified/Veyra-0.0.4-win64-portable/Veyra.exe" -PortablePlayer
+out/build/release-0.0.4/veyra_audio_timeline_tests.exe logs/release-0.0.4/audio-fixtures
+out/build/release-0.0.4/veyra_live_presentation_tests.exe "$PWD/logs/audio-jitter-20260911/4k30fps.mp4" "$PWD/logs/release-0.0.4/xess-native4k" --file-continuity
+out/build/release-0.0.4/veyra_capture_audio_tests.exe --jitter
+```
+
+日志目录 `logs/release-0.0.4/`,包括 `build.log`、`package.log`、`ffmpeg-source.log`、`portable-final-run.*.log` 和 `delivery.*.log`。
+
+## 验证与失败记录
+
+- 便携验证清除开发 PATH、临时移走 manifest、从包外工作目录启动:空窗口、基础播放、社区 SR+NR+FG、原版 SR+NR+FG、Video SR+NR+FG 五组通过,`portable-final/result.json`。三组增强分别产生 224/222/227 个生成帧,NR 原版/社区的实际模块路径与选择匹配。
+- Feature18 Create `0x1`、SEH 0;VSR Create `0x1`、SEH 0,有实际 GPU 执行计时和输出图片。VSR 本机可由驱动 NGX 提供,不将成功扩称为包内 VSR DLL 一定被映射。
+- 解压后的正式 EXE 参与 delivery,23 项 PASS、44.899 秒,`logs/delivery/f0ab3a10a1ea44e99f8b20e619fbdbdc/result.json`,EXE SHA 与发布包相同。覆盖实际 NR/NVOF、原生 4K 正确性、播放/暂停/seek/图像、NVENC H264/HEVC 音轨/帧数/时间戳/取消。
+- 独立 Release 构建的音频完整回归 68 PASS,`audio-full.stdout.log`;原生 4K30 NR+XeSS 连续性 6 PASS,100 张真实帧前进 3.33333 秒/耗时 3.33291 秒,额外音频暂停 0,末次软件偏差 1.5ms,真实 XeSS PresentStatus `0`。采集音频 `--jitter` 30/35ms 波动回归 exit 0(合成输入、真实 WASAPI),`capture-jitter.stdout.log`。
+- 第一轮上述五组软件检查通过,但测试最后写报告时 `Get-FileHash` 无法解析,包装 exit 1,保留 `portable-run.*.log` 与 `portable/`。补显式导入 Utility 后完整重跑通过,不改 EXE、不降低断言。
+- 复核先前 XeSS 两份测试的 stdout,各为 6 个 PASS,修正文档原误记的 7 个;原始结果与通过/失败状态未改动。
+
+本版未新增 RTX40 实机、物理采集卡端到端音画、屏幕扫描/扬声器声学测量或长期直播测试。短测不保证持续过载下仍保持一倍速且绝对同步。
diff --git a/docs/RELEASE_NOTES_0.0.4.md b/docs/RELEASE_NOTES_0.0.4.md
new file mode 100644
index 00000000..f025bd04
--- /dev/null
+++ b/docs/RELEASE_NOTES_0.0.4.md
@@ -0,0 +1,49 @@
+# Veyra 0.0.4
+
+## 中文
+
+### 更新
+
+- 修复视频导入播放时,声音先于首张增强画面开始的问题。打开文件、跳转、暂停恢复和调整增强设置后,音视频会重新对齐。
+- 修复 NR 处理耗时轻微波动时声音反复停顿的问题,为短暂抖动保留容差;持续过载时仍限制声音领先,避免越播越不同步。
+- 修正 XeSS 补帧和原画对比下的音频时序,避免将完整源帧时长错误缩短为补帧间隔。
+- 修复采集卡在较长软件处理延迟下的同步补偿上限,并在暂停及重建增强管线时清除过期同步状态。只补偿软件新增的视频等待,不重复计算采集卡音视频共同的输入延迟。
+- 增加音频连续性、跳转恢复、处理波动和过载恢复回归检查;更新中英文使用说明。
+
+### 下载与升级
+
+下载 **Veyra-0.0.4-win64-portable.zip**,完整解压后运行 **Veyra.exe**。运行组件已包含,无需安装 SDK。升级请退出旧版并解压到新目录;保留设置时只复制旧版 `runtime_local/*.v1` 和 `veyra.ini`。
+
+**FFmpeg-source.zip** 是开源依赖的对应源码,普通用户不需要下载。OBS 窗口采集仍应手动选择 **Windows 10(1903及以上)**,避免“自动”选到只能捕获 UI 的 BitBlt。
+
+### 验证与边界
+
+RTX 5070 上的 1080p30、原生 4K30 NR+XeSS 短测中,观测到的额外音频暂停均为 0;30/35ms 处理波动的合成采集音频测试未出现额外重置或欠载。文件跳转、暂停恢复及故意过载后的恢复回归通过。上述是软件短测,不代表长时间直播或屏幕/扬声器物理同步的测量。
+
+本版不降低 NR 本身的运算量。GPU 持续处理不过来时,声音仍可能等待视频,请降低画质、倍率或目标分辨率。
+
+继续提供 NVIDIA 原版 NR 与 RTX 40/50 社区实验版切换,并允许自行替换 DLL。社区版为修改文件,签名状态 **HashMismatch**;RTX 40 实机验证仍待完成。NR 与 DLSS 补帧属于 **community experimental / 社区实验集成**,不是 NVIDIA 官方认证。SDK、运行时和模型不进入源码 Git;组件来源、哈希、许可证及移除方法见包内 `docs/RUNTIME_COMPONENTS_0.0.4.md` 与清单。
+
+## English
+
+### Changes
+
+- Fixed file audio starting before the first enhanced video frame. Playback now re-establishes synchronization after opening, seeking, resuming, and rebuilding enhancement settings.
+- Fixed repeated audio interruptions caused by small NR processing-time fluctuations. Brief jitter has a tolerance window; sustained overload still limits audio lead to prevent accumulating drift.
+- Corrected audio coverage with XeSS frame generation and original-image comparison, preserving the full source-frame interval.
+- Raised the capture synchronization compensation limit for longer software processing delays and cleared stale synchronization state on pause or graph rebuild. The capture card's shared audio/video input delay is not compensated twice.
+- Added regression coverage for audio continuity, seeks, timing fluctuations, and overload recovery; updated both READMEs.
+
+### Download and Upgrade
+
+Download **Veyra-0.0.4-win64-portable.zip**, extract it fully, and run **Veyra.exe**. Application runtimes are included; no SDK installation is needed. Close the old version and extract into a new directory. To retain settings, copy only the old `runtime_local/*.v1` files and `veyra.ini`.
+
+**FFmpeg-source.zip** contains corresponding source for an open-source dependency and is not required to run Veyra. In OBS Window Capture, explicitly choose **Windows 10 (1903 and up)**; Automatic may select BitBlt and capture only the controls.
+
+### Validation and Limits
+
+Short RTX 5070 tests with NR + XeSS at 1080p30 and native 4K30 recorded zero additional audio pauses. Synthetic capture audio with 30/35ms processing fluctuations recorded no additional resets or underruns. File seek/resume and deliberate overload-recovery regressions passed. These are software tests, not long-session streaming validation or physical display/speaker synchronization measurements.
+
+This release does not reduce NR's computational cost. Sustained GPU overload can still require waiting for video; reduce quality, multiplier, or resolution if needed.
+
+The NVIDIA original and community RTX 40/50 NR variants remain selectable, and DLL replacement remains permitted. The community variant is modified and reports **HashMismatch**; RTX 40 hardware validation is pending. NR and DLSS frame generation are community-experimental integrations, not NVIDIA certification. SDKs, runtimes, and models remain outside source Git. See `docs/RUNTIME_COMPONENTS_0.0.4.md` and the included manifests for provenance, hashes, licenses, and removal instructions.
diff --git a/docs/RUNTIME_COMPONENTS_0.0.4.md b/docs/RUNTIME_COMPONENTS_0.0.4.md
new file mode 100644
index 00000000..1fc51459
--- /dev/null
+++ b/docs/RUNTIME_COMPONENTS_0.0.4.md
@@ -0,0 +1,51 @@
+# Veyra 0.0.4 Runtime Components
+
+发布包组件清单 / Shipped components. NVIDIA/Intel DLLs are separate Release assets, never source Git content. NR and DLSS FG are community-experimental integrations, not vendor endorsement or certification.
+
+## Locations and Replacement
+
+NVIDIA components: `runtime/experimental/`. XeSS/XeLL: `runtime_local/intel/experimental/`. Exit Veyra before replacing a DLL and preserve its filename. No runtime hash, signature, or manifest lock is enforced. Manifests describe the original package only; users do not need to edit them after replacement. ABI/API and hardware compatibility still determine whether a feature works.
+
+允许自行替换DLL,但替换不代表兼容。出现初始化错误时还原原件或关闭对应增强。清单是发布记录,不是加载锁。退出软件并删除解压目录即可卸载;需要保留设置时先备份`runtime_local`中的设置文件。移除某个增强DLL会使对应功能不可用。
+
+## NVIDIA and Intel
+
+The six original publisher-provided DLLs below have valid Authenticode signatures. The additional community NR variant does NOT: its recorded status is `HashMismatch`. Names and SHA256 describe the approved files used to build this release. The JSON manifests also record file size, signer, source category, and removability.
+
+| File | Fixed file version | Source / use |
+| --- | --- | --- |
+| nvngx_dlss.dll | 310.7.0.0 | Official DLSS SDK 310.7.0 release runtime; DLSS SR |
+| nvngx_dlssg.dll | 310.7.0.0 | DLSS SDK release runtime; experimental Veyra DLSS FG integration |
+| nvngx_dlssnr.dll | 310.8.0.0 | User-provided pinned experimental NR runtime; 165840496 bytes |
+| nvngx_vsr.dll | 1.6.0.0 | RTX Video SDK 1.1.0; RTX Video SR |
+| libxess_fg.dll | 1.3.1.78 | Official Intel XeSS SDK 3.0.2; preview FG |
+| libxell.dll | 1.3.2.10 | Official Intel XeSS SDK 3.0.2; XeLL timing |
+
+```text
+nvngx_dlss.dll BE6E434A94CA32499515EB62CA0E6C274526055D568D0426E4C652DCDFB6EE6E
+nvngx_dlssg.dll 135EAF0733C1E37381A8C28ABCF7A862404A54132B81787C04E35D09EFC5E36F
+nvngx_dlssnr.dll E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E
+nvngx_vsr.dll C3D88EEA5FF7A548EDEFA66414CF6E77464D0947277C904F324DD23ABF58A1ED
+libxess_fg.dll EC5E0C65E075570C6EDE72618BB666D0BE0C2E10B2EA9762C0FE8CB8E375AB27
+libxell.dll D2030DCD694FDA8F2EC7E044B13E6DB8F0B56D4BA9113A5EFAD334E3F3DED8C7
+```
+
+NVIDIA license files: `licenses/NVIDIA_RTX_SDK_LICENSE.txt`, `NVIDIA_RTX_VIDEO_SDK_LICENSE.pdf`, `NVIDIA_OPTICAL_FLOW_SDK_LICENSE.pdf`. Intel terms: `licenses/INTEL_XESS_LICENSE.txt`, `INTEL_THIRD_PARTY_PROGRAMS.txt`. Experimental NR distribution follows the publisher's explicitly approved Release-only policy; the included official SDK terms are not a claim that the experimental runtime has a general redistribution grant.
+
+## Community NR Variant
+
+The user-selected community NR file is also included, unmodified, in `runtime/experimental/nr-community/nvngx_dlssnr.dll`. Source category: user-provided community-modified RTX40/RTX50 runtime. File version: 310.8.0.0. Size: 165840496 bytes. SHA256: `984BEE0F775C277D5829B8FD6775D53A7B0F75396C852B3AAF06A18375F81014`. Authenticode: **HashMismatch**; retained signer metadata does not make this a valid NVIDIA signature.
+
+社区版为用户指定的实验文件,本次明确授权随Release分发;与原版独立存放,默认仍选原版。不能把NVIDIA SDK许可证解释为对社区修改文件的通用授权。未修改、重签名或隐藏该文件。要移除社区版,先切回原版、退出Veyra,再删除`nr-community`目录;主包manifest仅为发布记录,无需修改。RTX40实机兼容性未验证,不将本机RTX5070结果扩大为全系列支持。
+
+Both variants are recorded with distinct paths in `runtime/experimental/release-runtime-manifest.json`. Delete only the community subdirectory to remove that variant. Neither DLL, the SDKs, nor models are part of source Git history.
+
+## Other Dependencies
+
+- FFmpeg 9.0.1#1: `avcodec-63.dll`, `avformat-63.dll`, `avutil-61.dll`, `swresample-7.dll`, `swscale-10.dll`; LGPL configuration. Full notices and source provenance are in `licenses/FFMPEG-COPYRIGHT.txt`, `FFMPEG-SPDX.json`, and [BUILD.md](BUILD.md).
+- Microsoft `vcruntime140.dll`, `vcruntime140_1.dll`, `msvcp140.dll`: application-local x64 Visual C++ redistributables from the Visual Studio Redistributables directory; needed by FFmpeg and XeSS. Windows11 supplies UCRT.
+- AMD FidelityFX optical flow: linked into Veyra, no AMD runtime DLL or NR model required. MIT terms in `licenses/AMD_FIDELITYFX_LICENSE.txt`.
+- Lucide icon paths: built into Veyra, with ISC/MIT terms in `licenses/LUCIDE-LICENSE.txt`.
+- Own compiled shader files: `shaders/*.dxil`. No local SDK headers or samples are required at runtime.
+
+GPU drivers supply `nvofapi64.dll` and `nvEncodeAPI64.dll`; they are not redistributed. ReShade/RenoDX add-ons, FRUC, SDK archives, development libraries, depth weights, and AMD NR networks are not part of this package.
diff --git a/docs/SOFTWARE_AV_SYNC_REPAIR_2026-09-11.md b/docs/SOFTWARE_AV_SYNC_REPAIR_2026-09-11.md
new file mode 100644
index 00000000..603f6000
--- /dev/null
+++ b/docs/SOFTWARE_AV_SYNC_REPAIR_2026-09-11.md
@@ -0,0 +1,94 @@
+# 软件处理链路音画同步修复
+
+> 后续用户验收发现声音随 30/35ms 处理波动卡顿。第一版以下短测只证明时钟偏差有界,没有证明音频连续;当前继续修复见文末“音频连续性修订”,第一版不能视为用户验收通过。
+
+## 本次范围
+
+补偿 Veyra 内部解码、SR、NR、FG、GPU 等待和呈现调度增加的视频等待。采集卡共同的输入音视频延迟不额外计入;不估算 HDMI 到屏幕物理延迟,不修改导出。
+
+## 已核对的问题
+
+- 文件在首张有效视频 Present 前启动 WASAPI;seek、暂停恢复、设置重建也可能先放声音。
+- 文件过载只在视频线程完成 GPU 等待后,才按领先 80ms/回到 20ms 暂停/恢复音频。GPU 或设置重建阻塞时这段代码无法工作。
+- 采集自动补偿按 `视频 Present host − 视频 PTS − 音频 ingress 映射` 计算,能抵消共同输入延迟。但补偿被截在 250ms;重建及暂停没有主动失效旧视频映射。
+- Present 返回是提交时刻,当前没有屏幕扫描或扬声器声学测量,不宣称绝对物理同步。
+
+## 实施
+
+1. 文件音频预解码及 WASAPI 预填充保留,但首帧呈现前停止设备时钟。seek/设置/暂停恢复复用视频等待状态。
+2. 音频线程根据可呈现视频的 PTS 上限自行停表;即使视频线程卡在 NR/FG 或重建中,声音也不能持续跑远。GPU 就绪帧允许共同时钟前进到该帧,真正 Present 后再允许下一个帧间隔;不丢文件源帧,不按 GPU 平均耗时硬加固定延迟。
+3. 采集自动音频等待首次有效视频及重置后的新呈现。自动补偿上限扩至 1500ms、PCM 总预算 2000ms,仍有硬上限和超限状态;手动偏移保持 ±250ms。真实输入/输出 PTS 决定补偿,不加采集卡硬件延迟。
+4. 使用真实 WASAPI 验证首帧/停顿/seek/恢复、延迟变化、共同输入延迟抵消;Engine 测试覆盖实际 NR/SR/FG、设置、暂停和 seek。每个测试有不超过 300 秒外部超时。
+
+## 状态
+
+代码及本机短测完成,用户实际听看验收待执行。根目录 `Veyra.cmd` 启动本次构建的 `out/build/x64-release/veyra.exe`。
+
+## 改动文件
+
+- `src/engine/EngineController.cpp`:首帧/seek/恢复/设置的共同锚点、GPU 就绪到呈现的音频许可范围;取消视频线程的 80/20ms 事后追赶。
+- `src/sink/WasapiAudioSink.cpp`、对应头文件:音频线程独立执行视频等待,保留 PCM 和设备时钟;恢复端点也保留该等待。
+- `src/sink/CaptureAudioSession.cpp`、`src/source/CaptureCardSource.cpp` 和对应头文件:失效旧呈现锚点、扩大有界自动补偿范围。
+- `include/veyra/engine/EngineController.h`:真实视频等待次数诊断。
+- `tests/integration/{AudioTimelineTests,CaptureAudioTests,LivePresentationTests}.cpp`:真实设备时钟与实际产品图回归。
+
+## 实际验证(2026-09-11)
+
+以下路径均相对项目根目录;所有日志在 gitignore 范围。
+
+| 检查 | 实际命令 / 关键参数 | 结果与证据 |
+| --- | --- | --- |
+| Release 构建 | `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root <项目绝对路径> -Preset x64-release` | `logs/software-av-sync-20260911/build4.log` exit 0 |
+| 文件音频 PCM / WASAPI | `scripts/run-short-test.ps1 -Exe out/build/x64-release/veyra_audio_timeline_tests.exe -Arguments logs/software-av-sync-20260911/audio-fixtures -TimeoutSeconds 60 -LogPrefix logs/software-av-sync-20260911/audio-timeline3` | 68 PASS,exit 0。首帧等待 350ms 时 PCM 时钟不走;视频覆盖到 100ms 后故意再阻塞 350ms,音频停在 120ms 且不再增长;含首帧、设置、seek、暂停恢复和设备失效 |
+| 真实 NR/SR/FG 文件播放 | `scripts/run-short-test.ps1 -Exe out/build/x64-release/veyra_live_presentation_tests.exe -Arguments @(<test_av_1080p.mp4绝对路径>,<logs/software-av-sync-20260911/file-overload绝对路径>,'--file-overload') -TimeoutSeconds 180 -LogPrefix logs/software-av-sync-20260911/file-overload` | 10 PASS,exit 0。RTX 5070、1080 输入、4K 超分/原生 NR/FG4;100 源帧及 FG4→2 重建/播放中 seek/暂停 seek/恢复。Present 时最大观测音频领先 26.667ms。实际 Create Feature18 / DLSSG 与 Evaluate `0x1`、SEH 0;完整 `file-overload/engine.log` |
+| 文件端点恢复 | 同上测试 EXE,参数 `--file-endpoint`,日志目录及前缀 `file-endpoint`,外部超时 60s | 7 PASS,exit 0。端点离线保持共同时钟,重连、暂停 seek 和恢复通过 |
+| 采集软件延迟 | `scripts/run-short-test.ps1 -Exe out/build/x64-release/veyra_capture_audio_tests.exe -Arguments --software-delay -TimeoutSeconds 60 -LogPrefix logs/software-av-sync-20260911/capture-audio2` | 16 PASS,exit 0。合成 DirectShow 风格 PTS + 真实 WASAPI。自动 80/160/400/900ms;共同输入偏移 900ms 时软件额外 400ms 仅补 400.485ms,额外 900ms 补 900.082ms。自动稳态平均软件偏差约 18–23ms;重建等待、手动/关闭、断流、重开及 2000ms 总队列硬上限通过 |
+| 采集端点恢复 | 同上 EXE,参数 `--endpoint-loss`,前缀 `capture-endpoint`,外部超时 30s | exit 0,2 次端点打开,平均软件偏差 16.335ms,无溢出 |
+| 完整交付短测 | 通过 `run-short-test.ps1` 以 300s 外部超时执行 `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root <项目绝对路径>` | 23 PASS,48.892s;`logs/delivery/ab1cf0c67a174cc3845c0eb1336c1bae/result.json`。含实际 NR/NVOF、原生 4K、播放、图像、NVENC H264/HEVC 带音轨/帧数/时间戳及取消。导出完整性 gate 未修改 |
+
+`file-overload` 使用最终端点回退小修前的构建(build3);其后仅修正无有效音频时钟时仍保留视频等待上限。最终 build4 已通过 68 项音频、文件端点恢复、采集合成及完整 delivery,不把先前测试冒充同一 EXE。
+
+最终 EXE SHA256:`CD4E5EDA37CEACE83C09D327E123A160A0AE814E84729C5D18BD9D4FA68548EE`。原版 NR SHA256 仍为 `E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E`;未改任何运行时文件。
+
+## 失败与修正
+
+- `audio-timeline` / `audio-timeline2` exit 1:新增检查最初要求 `stalled < 120ms`,真实 100ms 视频许可在此 WASAPI 22ms 端点上停止于恰好 120ms;第二次观测 350ms 后仍为 120ms。并发现等待标记早于实际 Stop 发布,已改为执行暂停后发布。验收明确为覆盖上限后 30ms 内且之后时钟不再增长(最终 120→120,通过),不冒充零误差。
+- 首次无参数调用 `run-short-test.ps1` 被现有空 `ArgumentList` 包装器拒绝;改用测试标识参数 `--software-delay`,未改检查脚本或产品逻辑。
+- `build2.log` exit 6:测试仍运行时重链接该测试 EXE,Windows 返回 LNK1104 文件占用。等待退出后顺序执行 build3/build4 均 exit 0;非源代码编译错误。
+
+## 边界与下一步
+
+- 未执行物理采集卡音画录制对照、扬声器到屏幕测量、长时间漂移或 XeSS 内部呈现延迟验证。当前证据是本机 WASAPI 消费时钟和 Present 提交时间,不能保证所有声卡/显示器的固定物理偏移都为零。
+- GPU 吞吐持续不足时,文件音频会跟随画面停顿;此修复消除持续跑远,不把过载伪装成实时播放。实时采集自动补偿最多 1500ms,超过边界仍明确标记受限;2000ms 为音频容量上限,不是固定新增等待。
+- 未提交或上传 SDK、DLL、模型;没有 push、发布或改写 0.0.3 Release。
+- 下一步:用户使用本机 `Veyra.cmd`,分别以文件播放和真实采集测试 NR/超分/FG 开关与切换后的音画同步,按实际反馈继续校准。
+
+## 音频连续性修订(2026-09-11,代码及针对性回归完成)
+
+- 用户日志 `logs/audio-jitter-20260911/user-session-before.log` 是 4K30 文件,含 XeSS 与 DLSS。XeSS 每真实源帧 33.3ms,而上一版给音频的许可范围除以 2,只有 16.7ms;SDK 内部生成帧不会回调延长这个范围。修正为源帧间隔,对比模式也不按隐藏插帧划分。
+- 旧文件音频一达到许可 PTS 就 Stop,不给线程唤醒、声卡事件或 GPU 完成抖动留容差。新策略保持首帧/seek/设置/暂停的显式等待;普通播放使用 20ms 死区,领先持续超过死区 100ms 或达到 80ms 才重缓冲,追上许可范围再恢复。这个容差是瞬时软件音画偏差预算,不是给采集卡硬件延迟补偿,也不是新增固定音频延迟。
+- 新增真实 WASAPI、真实 PCM 的 30fps + 5ms 抖动测试,覆盖真实帧和显式 2×/4× 子帧。检查额外音频停止次数为 0、时钟持续以一倍速走、无缺音填零;不再仅以 Present 时偏差小作为通过条件。先执行旧版作为失败对照,证据 `jitter-before`。
+- 采集现有连续重采样路径不使用文件的逐帧 gate;增加同类抖动检查,若通过则不做无关改造。旧正常低延迟及长阻塞测试随新容差要求保留同步有界检查。
+
+### 第二轮实际证据
+
+新增生产文件 `include/veyra/sink/AudioVideoContinuity.h`,由 `WasapiAudioSink.cpp` 的音频 owner 调用;`EngineController.cpp` 修正 XeSS 与对比模式的覆盖间隔。没有新增视频帧队列、固定播放延迟或改动采集重采样算法。`AudioTimelineTests.cpp`、`CaptureAudioTests.cpp`、`LivePresentationTests.cpp` 增加连续性和过载后恢复检查。
+
+构建仍使用前述 `scripts/build.ps1`,最终 `logs/audio-jitter-20260911/build3.log` exit0。下面测试均经 `scripts/run-short-test.ps1` 外部超时包装,输出分别保存在所列前缀的 `.stdout.log/.stderr.log`;每次远低于300s:
+
+| 测试 | EXE / Arguments / 超时 | 结果 |
+| --- | --- | --- |
+| 新旧连续性对照 | `veyra_audio_timeline_tests.exe`,`@('logs/audio-jitter-20260911/fixtures','--jitter')`,60s | `jitter-before` exit1:2×/4× 各有一次额外停表,3秒内音频分别只前进2964.25/2959.25ms。`jitter-after` exit0、15 PASS:1×/2×/4× 全为0额外停表、0underrun;约3秒内媒体进度分别2992.31/2999.12/2990.12ms,保持一倍速,未用静音填缺口 |
+| 完整音频回归 | `veyra_audio_timeline_tests.exe`,`@('logs/audio-jitter-20260911/full-audio-fixtures')`,60s | `audio-full` exit0,68 PASS;含首帧、seek、暂停恢复、端点断开、长阻塞及 PCM 时间线。长阻塞时100ms视频许可的音频停在200ms并保持不动,符合80ms硬领先阈值加声卡事件响应的范围 |
+| 原生1080 NR+XeSS | `veyra_live_presentation_tests.exe`,`@(<30fps.mp4绝对路径>,<xess-continuity2日志目录绝对路径>,'--file-continuity')`,60s | 6 PASS、exit0,100张真实帧前进3.33333秒/耗时3.33751秒;额外音频等待0,采样末偏差1.167ms |
+| 原生4K NR+XeSS | 同上,输入`logs/audio-jitter-20260911/4k30fps.mp4`、目录/前缀`xess-native4k`,60s | 6 PASS、exit0;日志确认 source/base/NR/flow均3840×2160。100张真实帧前进3.33333秒/耗时3.33008秒,额外音频等待0,末次偏差0.896ms。NR P95约24.24ms、GPU就绪P95约29.20ms;实际Feature18 Create `0x1`、SEH0,XeSS Init/PresentStatus `0`且实际产生SDK生成帧 |
+| 采集30/35ms交替 | `veyra_capture_audio_tests.exe`,`--jitter`,30s | `capture-jitter` exit0,5秒合成采集PTS+真实WASAPI。稳定后额外reset/underrun/missing均0,P95软件偏差24.997ms。验证通过,未改采集生产算法 |
+| 原生4K SR/NR/DLSS4过载及恢复 | `veyra_live_presentation_tests.exe`,`@(<test_av_1080p.mp4绝对路径>,<file-overload2日志目录绝对路径>,'--file-overload')`,180s | `file-overload2` exit0、12 PASS;持续过载最大观测领先96.667ms;FG重建、播放/暂停seek及恢复通过。恢复可实时处理的配置后偏差重新小于35ms,没有保留过载固定偏移 |
+
+30fps测试输入由本机ffmpeg `testsrc2`+`sine`生成8秒H264/AAC(1920×1080、3840×2160),证据`fixture/fixture4k`;没有读取新的用户私人素材或把测试媒体放进Git。第一份实际XeSS测试`xess-continuity` exit1必须保留:当时测试退出后GPU仍90–93%/约250W,Magpie正在运行;NR完成P95达81.9ms。用户回复“已停用,可以测试”后,开测前GPU5%/37.5W,再执行上述原生1080及4K,两项通过。这项外部争用不改变已经确认的Veyra逐帧停表及XeSS覆盖错误。
+
+`file-overload`第一次exit1:只有“重建后4帧仍要求偏差<35ms”失败,因为它仍处于故意制造的持续过载。根据事先定义的连续性容差将该项改为有界120ms,并增加关闭高负荷配置后的独立<35ms恢复检查;不能把重建当成性能恢复,也不能将新的96.667ms过载偏差宣传成零偏差。
+
+最终EXE SHA256:`93F9C4D7D596D833B7E3E347FBC225D77626810F42638E9B57BE88FBED949AC1`。根目录`Veyra.cmd`启动此构建。正常小抖动优先保持声音连续;超过吞吐能力的持续过载仍有有界等待,不能保证同时不丢文件帧、一倍速、音画同步且声音绝不断续。未执行实卡声学/屏幕录制对照或长期听感验收,未push或发布。
+
+本轮最终交付短测:`run-short-test.ps1` 以300s外部上限执行 `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root <项目绝对路径>`,`logs/delivery/c2d5b549af744590b66188aff1dd7cbc/result.json` 为23 PASS、45.421s、EXE哈希与上述一致。包括实际NR/NVOF/原生4K/播放器以及保持现状的图像与NVENC音视频导出检查。`git diff --check`通过;新增头文件和文档为自有文本,无SDK、DLL、模型或测试媒体进入源码变更。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index ca5d42d9..aa1b9943 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1536,3 +1536,33 @@ FRUC候选bSkipWarp/延后重建/时间归零/首对预热均未通过新增rese
用户提供 `REAMDE MP4.mp4` 作为项目 README 开头的演示视频。文件为 28,200,658 bytes,H.264 1920x1080 60fps、AAC、14.048 秒;未涉及 NVIDIA SDK/runtime、抓帧或测试输入。由于 GitHub README 不保证仓库 MP4 的 HTML5 `<video>` 标签会渲染,使用 ffmpeg 生成 `assets/readme-demo.gif`(480x270、10fps、14秒、约 7.5 MB),中英文 README 均在顶部直接展示自动循环 GIF,并链接到原始 MP4。未创建新 Release;本轮未运行产品构建或 GPU/实卡测试。
+## 2026-09-11 软件 NR/SR/FG 音画同步修复
+
+按用户纠正,本次只处理软件增加的视频等待,不额外补偿采集卡音视频共同硬件延迟。实施、文件清单、全部命令及失败证据见 `docs/SOFTWARE_AV_SYNC_REPAIR_2026-09-11.md`。文件音频预填充后等首帧 Present;音频线程按可呈现 PTS 自行停止设备时钟,替代视频线程等 GPU 完成后才以 80/20ms 追赶的旧逻辑。设置重建/seek/暂停恢复保留等待状态;文件普通播放不靠丢源帧或跳过 PCM 追赶。采集重建/暂停失效旧视频锚点,自动补偿上限 250→1500ms、原始+转换中+PCM 总预算 2000ms;手动范围不变。
+
+实际构建 `scripts/build.ps1 -Root <root> -Preset x64-release`,最终 `logs/software-av-sync-20260911/build4.log` exit0。`run-short-test.ps1` 包装运行:audio_timeline 68 PASS(60s超时)、capture_audio 16 PASS(60s超时,80/160/400/900ms 软件延迟、共同900ms输入偏移、重建/断流/边界)、file-endpoint 7 PASS(60s超时)、capture-endpoint PASS(30s超时)。实际 RTX5070 超分4K+原生NR+FG4 文件 Engine 测试10 PASS(180s超时),Present 时最大音频领先26.667ms,包含FG4→2重建与播放/暂停seek;该项为build3,最终端点时钟回退修正后由音频68项、endpoint及delivery覆盖。Feature18/DLSSG Create/Evaluate `0x1`、SEH0;证据 `file-overload/engine.log`。
+
+最终 delivery `logs/delivery/ab1cf0c67a174cc3845c0eb1336c1bae/result.json`:23 PASS、48.892s,包含实际NR/NVOF、4K播放/图像和NVENC H264/HEVC音轨/帧数/时间戳/取消。最终EXE SHA256 `CD4E5EDA37CEACE83C09D327E123A160A0AE814E84729C5D18BD9D4FA68548EE`;根目录 `Veyra.cmd` 指向该本机构建。未改导出完整性gate。
+
+失败记录保留:两次新增音频检查exit1,真实停在120ms并在350ms后保持120ms,最初断言`<120`不含边界;同时修正等待标记在Stop前发布的时序。最终按22ms端点采用覆盖范围后30ms内、不持续增长的验收标准。一次空参数测试包装失败、一次测试运行期间重链接LNK1104;后续顺序构建及检查通过。未执行物理采集/屏幕扬声器对照、长期漂移或XeSS内部延迟验证;不宣称零物理偏差或解决GPU吞吐不足。源码改动均为自有代码/测试/文档,无SDK/DLL/模型变更,无push或Release。下一项为用户本机文件与实卡验收。
+
+## 2026-09-11 音频连续性二次修复(处理30/35ms正常波动)
+
+用户验收指出第一版仍会把正常NR波动变成声音卡顿。核对最新实际会话:4K30文件、XeSS/DLSS;上一版XeSS每33.3ms真实帧却只给音频16.7ms许可,而且任何越界立即Stop。新增 `AudioVideoContinuity.h`,音频owner保留20ms死区、持续100ms或硬领先80ms才重缓冲;显式首帧/seek/重建/暂停仍保持。引擎修正XeSS及对比模式的源帧覆盖,不按不可见子帧停声音。没有新增长期队列或固定延迟,不处理采集卡共同硬件延迟。具体文件、完整命令及证据见 `docs/SOFTWARE_AV_SYNC_REPAIR_2026-09-11.md` 末节。
+
+`scripts/build.ps1 -Root <root> -Preset x64-release` 最终build3 exit0。`run-short-test.ps1`包装:真实PCM/WASAPI抖动before exit1,2X/4X都出现额外停表与速度损失;after 15 PASS、0额外停表/0underrun。完整audio-full 68 PASS。采集30/35ms交替5秒,稳定段额外reset/underrun/missing均0、P95偏差24.997ms;因此本轮不改采集生产算法。日志统一 `logs/audio-jitter-20260911/`。
+
+实际原生1080及原生4K NR+XeSS分别6 PASS:原生4K source/base/nr/flow=3840×2160,100真实帧前进3.33333秒/耗时3.33008秒,音频额外等待0,末次软件偏差0.896ms;真实Feature18 Create `0x1`/SEH0、XeSS Init/PresentStatus `0`且有生成帧。第一份1080测试因外部GPU争用失败(测试退出GPU仍90–93%、Magpie运行),用户停用增强后开测GPU5%,重测上述两项通过;失败记录没有删除。原生4K SR/NR/DLSS4故意过载12项通过,最大观测领先96.667ms;接受连续性容差后旧“仍过载的重建后<35ms”断言调整为有界检查,并新增性能恢复后独立<35ms检查,防止仅放宽断言掩盖固定偏移。
+
+最终delivery `logs/delivery/c2d5b549af744590b66188aff1dd7cbc/result.json`:23 PASS、45.421s,EXE SHA256 `93F9C4D7D596D833B7E3E347FBC225D77626810F42638E9B57BE88FBED949AC1`。所有单次测试有30/60/180/300s外部上限,导出gate未改。`git diff --check`通过,无SDK/DLL/模型/媒体进入源码变更,无push或发布。实卡听感/声学扫描、长期连续性仍未执行;本轮保证的是被测小波动下不中断音频,不承诺GPU持续过载也能无限保持一倍速与同步。用户重开根目录Veyra.cmd使用本机构建继续验收。
+
+
+## 2026-09-11 0.0.4 发布候选
+
+用户要求更新 GitHub 并指定 0.0.4。收录两轮软件音画同步及音频连续性修复;中英文 README、构建说明、版本日志、组件说明和 AGENTS 发布授权已同步。完整命令、文件身份、候选资产 SHA256 与验证边界见 `docs/RELEASE_0.0.4_EXECUTION.md`。保留 README 顶部自动播放演示与 WGC 捕获教程。
+
+全新 `scripts/build.ps1 -Preset x64-release -BuildDirectory out/build/release-0.0.4` 构建174目标exit0,正式EXE版本0.0.4、SHA256 `455B17D533D837A88B1A9D8BC27F452677A7D1010033E91EB9B37BF6353DFD9E`。`package-portable.ps1 -Version 0.0.4`沿用七个既有运行文件,发布者身份/签名检查通过,社区版明确HashMismatch;程序仍无manifest加载锁。新解压目录51个清单条目逐文件核验通过,总52文件、forbiddenFiles=0。FFmpeg源码资料10442条,SPDX及实际DLL的LGPL配置匹配。运行组件/SDK/模型不进入源码Git。
+
+`portable-smoke.ps1`清洁PATH、无manifest、包外工作目录的五组检查通过,日志`logs/release-0.0.4/portable-final/result.json`;基础、双NR、DLSS/VideoSR/FG均真实执行,三组分别224/222/227个生成帧。首次测试在最后写报告时Get-FileHash模块无法加载而exit1;显式导入执行宿主Utility后完整重跑成功,保留失败日志,不改产品或断言。先前XeSS各6项PASS被误记7项的文档计数已依stdout纠正。
+
+最终解压EXE的delivery `logs/delivery/f0ab3a10a1ea44e99f8b20e619fbdbdc/result.json`,23 PASS、44.899秒;包含真实NR/NVOF、4K播放/图像/NVENC双编码音轨和完整性。独立发布构建音频完整回归68 PASS、原生4K30 NR+XeSS连续性6 PASS(额外音频暂停0;3.33333秒媒体/3.33291秒墙钟)、合成采集30/35ms抖动回归exit0。所有单次超时30/60/240/300秒,日志`logs/release-0.0.4/`。未新增实卡声学同步、RTX40或长期直播验证。下一步为原子推送源码/标签、上传并核对四个Release附件后公开发布。
\ No newline at end of file
diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.h
index b70cb3d7..fc0b0b61 100644
--- a/include/veyra/engine/EngineController.h
+++ b/include/veyra/engine/EngineController.h
@@ -30,6 +30,7 @@ struct PlayerSnapshot {
std::wstring backendWarning;
sink::CaptureAudioState captureAudio;
bool audioRebuffering=false;
+ uint64_t audioVideoWaits=0;
bool audioEndpointRecovering=false;HRESULT audioEndpointError=S_OK;uint64_t audioEndpointRecoveries=0;
double position=0,duration=0,fps=0,lateMs=0,lateP95Ms=0;
diagnostics::FrameMetrics metrics;
diff --git a/include/veyra/sink/AudioVideoContinuity.h b/include/veyra/sink/AudioVideoContinuity.h
new file mode 100644
index 00000000..f81a42dc
--- /dev/null
+++ b/include/veyra/sink/AudioVideoContinuity.h
@@ -0,0 +1,31 @@
+#pragma once
+#include <chrono>
+#include <cmath>
+#include <optional>
+
+namespace veyra::sink {
+// Audio-owner policy. A presentation deadline is not a hard PCM stop boundary:
+// short GPU jitter must leave a continuous endpoint running. Explicit transport
+// resets still hold immediately; persistent lag and a hard lead bound rebuffer.
+class AudioVideoContinuity {
+public:
+ using Clock=std::chrono::steady_clock;
+ bool blocked(bool explicitHold,double audioPts,double coverage,Clock::time_point now) {
+ if(explicitHold){lateSince_.reset();buffering_=false;return true;}
+ if(!std::isfinite(audioPts)||!std::isfinite(coverage)){reset();return false;}
+ const double lead=audioPts-coverage;
+ if(buffering_){
+ if(lead<=0)reset();
+ return buffering_;
+ }
+ if(lead<=20){lateSince_.reset();return false;}
+ if(!lateSince_)lateSince_=now;
+ buffering_=lead>=80||now-*lateSince_>=std::chrono::milliseconds(100);
+ return buffering_;
+ }
+ void reset(){lateSince_.reset();buffering_=false;}
+private:
+ bool buffering_=false;
+ std::optional<Clock::time_point> lateSince_;
+};
+}
diff --git a/include/veyra/sink/CaptureAudioSession.h b/include/veyra/sink/CaptureAudioSession.h
index b63236c4..2cac0df4 100644
--- a/include/veyra/sink/CaptureAudioSession.h
+++ b/include/veyra/sink/CaptureAudioSession.h
@@ -23,6 +23,8 @@ public:
void stop();
bool push(const void* data,size_t bytes,double ptsMs,bool discontinuity);
void videoPresented(double ptsMs,int64_t host100ns);
+ // Invalidate only software presentation; preserve the shared input mapping.
+ void videoReset();
void setGain(float);
// 0 automatic, 1 manual, 2 off. Positive offset delays sound.
void setSync(unsigned mode,int offsetMs);
diff --git a/include/veyra/sink/WasapiAudioSink.h b/include/veyra/sink/WasapiAudioSink.h
index cac1f195..f692b903 100644
--- a/include/veyra/sink/WasapiAudioSink.h
+++ b/include/veyra/sink/WasapiAudioSink.h
@@ -16,6 +16,7 @@
#include <deque>
#include <format>
#include <mutex>
+#include <limits>
#include <thread>
#include <vector>
@@ -68,6 +69,15 @@ public:
void stopThread();
void setPaused(bool value) { paused_.store(value); }
+ // File playback: prefill while held, then let the device clock advance
+ // with a bounded jitter allowance beyond video coverage. Enforced on the audio owner even
+ // while the GPU owner is blocked in feature creation/evaluation.
+ void holdForVideo();
+ void videoReady(double ptsMs);
+ void videoPresented(double nextPtsMs);
+ bool waitingForVideo() const { return videoWaiting_.load(); }
+ uint64_t videoWaitCount() const { return videoWaitCount_.load(); }
+
// 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.
@@ -133,6 +143,9 @@ private:
std::atomic<bool> endpointRecovering_{false},clockExhausted_{false},endpointLossForTest_{false};
std::atomic<HRESULT> endpointError_{S_OK};
std::atomic<uint64_t> endpointRecoveries_{0};
+ std::atomic<bool> videoSync_{false},videoHold_{false},videoWaiting_{false};
+ std::atomic<double> videoLimitMs_{std::numeric_limits<double>::infinity()};
+ std::atomic<uint64_t> videoWaitCount_{0};
};
class AudioRenderer {
diff --git a/include/veyra/source/CaptureCardSource.h b/include/veyra/source/CaptureCardSource.h
index fd7bb65e..88ab53a7 100644
--- a/include/veyra/source/CaptureCardSource.h
+++ b/include/veyra/source/CaptureCardSource.h
@@ -22,6 +22,7 @@ public:
bool setAudioGain(float); // call on the graph owner thread; never system volume
CaptureMetrics metrics()const;
void videoPresented(double ptsMs,int64_t host100ns);
+ void videoReset();
void setAudioSync(unsigned mode,int offsetMs);
sink::CaptureAudioState audioState()const;
const SourceInfo& info()const override;
diff --git a/scripts/acceptance/portable-smoke.ps1 b/scripts/acceptance/portable-smoke.ps1
index f7fbdbcc..4a74011f 100644
--- a/scripts/acceptance/portable-smoke.ps1
+++ b/scripts/acceptance/portable-smoke.ps1
@@ -1,5 +1,8 @@
param([Parameter(Mandatory=$true)][string]$PackageDirectory,[Parameter(Mandatory=$true)][string]$InputFile,[Parameter(Mandatory=$true)][string]$OutputDirectory)
$ErrorActionPreference='Stop'
+# A PowerShell 7 parent may omit Windows PowerShell's Utility module from the
+# inherited module paths. Load this host's hashing/JSON cmdlets explicitly.
+Import-Module (Join-Path $PSHOME 'Modules/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1') -Force
$package=(Resolve-Path -LiteralPath $PackageDirectory).Path
$inputPath=(Resolve-Path -LiteralPath $InputFile).Path
$output=[IO.Path]::GetFullPath($OutputDirectory)
diff --git a/scripts/package-ffmpeg-source.py b/scripts/package-ffmpeg-source.py
index d3fde3ca..4883354a 100644
--- a/scripts/package-ffmpeg-source.py
+++ b/scripts/package-ffmpeg-source.py
@@ -12,7 +12,7 @@ parser.add_argument('--prefix', type=Path, required=True)
parser.add_argument('--vcpkg', type=Path, required=True)
parser.add_argument('--source', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
-parser.add_argument('--version', default='0.0.3')
+parser.add_argument('--version', required=True)
args = parser.parse_args()
if args.output.exists():
raise SystemExit('Output exists; choose a new candidate')
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index ce38d347..e2f40e9f 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -148,7 +148,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
if(physicalCapture&&!captureSource.start()){status(L"无法启动采集,请查看诊断",true);break;}
{std::lock_guard lock(mutex_);snapshot_.duration=duration;snapshot_.running=true;snapshot_.transport=TransportState::Playing;snapshot_.image=isImage;snapshot_.capture=isCapture;snapshot_.applied=options.snapshot();snapshot_.desired=desired_;}
status(isImage?L"图片已增强,可保存PNG/JPEG":std::format(L"{} | 输入 {}×{} / 底图 {}×{} / NR {}×{} / 光流 {}×{} / FG与输出 {}×{} | {}",isCapture?L"实时采集":L"播放",width,height,gd.workWidth,gd.workHeight,gd.nrWidth,gd.nrHeight,gd.flowWidth,gd.flowHeight,gd.workWidth,gd.workHeight,gd.nrWidth<gd.workWidth?L"实时内部处理并回填":L"原生NR(性能成本较高)"));
- pipeline::EnhanceGraph::FrameOutputs out;bool reset=true,hasOutput=false,audioRebuffering=false,seekPreviewPending=false;std::deque<double> latenessSamples;
+ pipeline::EnhanceGraph::FrameOutputs out;bool reset=true,hasOutput=false,audioRebuffering=false,seekPreviewPending=false;
+ bool fileAwaitingVideo=true,fileAudioAlignPending=true;std::deque<double> latenessSamples;
+ if(!isImage&&!isCapture&&audioPipe.open(path)){
+ audioPipe.holdForVideo();audioPipe.startThread(&audio,true);audioStarted=true;
+ std::lock_guard lock(mutex_);snapshot_.audioAvailable=true;
+ }
+ auto holdFileAudio=[&]{if(audioStarted)audioPipe.holdForVideo();fileAwaitingVideo=true;};
TimingWindow captureAges,scheduleWaits,processTimes,presentTimes,decodeTimes,gpuReadyTimes;
std::array<TimingWindow,size_t(diagnostics::GpuStage::Count)> gpuStageTimes;
std::array<uint64_t,size_t(diagnostics::GpuStage::Count)> lastGpuSampleEnd{};
@@ -160,6 +166,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
bool fileEndpointLossInjected=false;
auto publishAudioStatus=[&]{
const bool recovering=audioPipe.endpointRecovering();const auto error=audioPipe.endpointError();const auto count=audioPipe.endpointRecoveries();
+ {std::lock_guard lock(mutex_);snapshot_.audioRebuffering=audioPipe.waitingForVideo();snapshot_.audioVideoWaits=audioPipe.videoWaitCount();}
if(recovering!=publishedAudioRecovery||error!=publishedAudioError||count!=publishedAudioRecoveries){
publishedAudioRecovery=recovering;publishedAudioError=error;publishedAudioRecoveries=count;
std::lock_guard lock(mutex_);snapshot_.audioEndpointRecovering=recovering;snapshot_.audioEndpointError=error;snapshot_.audioEndpointRecoveries=count;
@@ -293,6 +300,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
}
const auto previous=options.snapshot();const auto previousDesc=gd;bool transaction=false;
if(requested.revision!=previous.revision){
+ holdFileAudio();
finishReset(diagnostics::ResetOutcome::Cancelled);
resetStart=resetStageStart=Clock::now();
resetRecord=diagnostics::FrameFlowMetrics::ResetRecord{};
@@ -300,6 +308,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
resetRecord->reason=static_cast<uint8_t>(pipeline::ResetReason::Settings);
if(frameFlow)frameFlow->resetLifecycle(*resetRecord);
drainLivePresentation();
+ if(physicalCapture)captureSource.videoReset();
// A drain may outlive several slider notifications. Build
// only the latest pending configuration at this boundary.
{std::lock_guard lock(mutex_);requested=desired_;}
@@ -338,18 +347,20 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
if(stop_)break;
const double seek=seekSeconds_.exchange(-1);
if(seek>=0&&!isImage&&!isCapture){
+ holdFileAudio();fileAudioAlignPending=true;
if(!ring.drainQueue()||!activeSource->seek({static_cast<int64_t>(seek*1000000),1000000})){status(L"跳转失败",true);break;}
discardBefore=seek*1000;seekPreviewPending=true;reset=true;pendingResetCause=pipeline::ResetReason::Seek;anchorMs=discardBefore;anchor=Clock::now();lastAudioClockMs=discardBefore;audioClockExhausted=false;audioRebuffering=false;if(audioStarted){audioPipe.setPaused(paused_);audioPipe.requestSeek(discardBefore);}
}
if(!transaction&&((paused_&&!seekPreviewPending)||(isImage&&hasOutput))){
drainLivePresentation();
+ if(!wasPaused){holdFileAudio();if(physicalCapture)captureSource.videoReset();}
if(audioStarted)audioPipe.setPaused(true);wasPaused=true;
const bool referencesValid=hasOutput&&out.batch.count&&out.batch.frames[out.batch.count-1].lease&&out.batch.frames[out.batch.count-1].lease->referencesValid;
if(hasOutput&&!presenter.present(ctx,ring,graph,out.videoSlot,false,referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,out.batch.identity,previewView())){status(L"画面呈现失败",true);break;}
if(hasOutput&&graph.resolveGeneration(out))completeReset(out.batch.identity);
std::this_thread::sleep_for(std::chrono::milliseconds(16));continue;
}
- if(wasPaused&&!paused_){audioRebuffering=false;if(audioStarted)audioPipe.setPaused(false);anchor=Clock::now();anchorMs=out.ptsMs;reset=true;pendingResetCause=pipeline::ResetReason::PauseResume;wasPaused=false;}
+ if(wasPaused&&!paused_){holdFileAudio();audioRebuffering=false;if(audioStarted)audioPipe.setPaused(false);anchor=Clock::now();anchorMs=out.ptsMs;reset=true;pendingResetCause=pipeline::ResetReason::PauseResume;wasPaused=false;}
// Backpressure before reading the capacity-one source mailbox:
// when a lease frees we consume the newest available sample.
if(liveScheduler&&!transaction){
@@ -495,7 +506,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
veyra::log::info("capture-timeline",std::format("interval100ns={} packetDurationKnown={} packetDurationPositive={} nominalFps={} FG={} pacing={}",duration100ns,!pkt.duration.isUnknown(),pkt.duration.num>0,activeSource->info().averageFps,options.fg,paceSourcePts?"source-pts":"capture-ready"));
liveTimeline.reset(out.batch.identity.epoch,out.batch.b100ns,captureArrival,options.fg?duration100ns:0,paceSourcePts);
}
- if(!audioStarted&&!isImage&&!isCapture&&frames==0){if(audioPipe.open(path)){audioPipe.startThread(&audio,true);audioStarted=true;{std::lock_guard lock(mutex_);snapshot_.audioAvailable=true;}}anchor=Clock::now();anchorMs=lastAudioClockMs=pts;}
+ if(!isImage&&!isCapture&&frames==0){anchor=Clock::now();anchorMs=lastAudioClockMs=pts;}
auto nowMs=[&](){
if(!audioStarted)return anchorMs+std::chrono::duration<double,std::milli>(Clock::now()-anchor).count();
publishAudioStatus();const double a=audio.mediaTimeMs();
@@ -585,13 +596,17 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
if(!rereadCached&&!isImage)completedProcessing(out.batch.identity);
gpuWaitMs=elapsedMs(readyStart);gpuReadyTimes.add(gpuWaitMs);
frameFlow->cpu(diagnostics::CpuStage::ReadyWait,gpuWaitMs,host100ns());
- if(audioStarted&&!isCapture&&!paused_){
+ // WASAPI prefill is allowed before video; device-clock playback
+ // is not. Align only open/seek, never discard audio to catch up
+ // with a slow graph during ordinary playback or settings edits.
+ if(audioStarted&&fileAudioAlignPending){
+ while(!stop_&&audioPipe.endpointRecovering()){publishAudioStatus();deadlineWait.slice();}
const double media=audio.mediaTimeMs();
- if(std::isfinite(media)){
- const double lead=media-pts;
- if(!audioRebuffering&&lead>80){audioRebuffering=true;audioPipe.setPaused(true);veyra::log::info("audio-sync",std::format("video overload: holding audio clock leadMs={:.2f}",lead));}
- else if(audioRebuffering&&lead<=20){audioRebuffering=false;audioPipe.setPaused(false);veyra::log::info("audio-sync",std::format("video caught up: resume common timeline leadMs={:.2f}",lead));}
+ if(std::isfinite(media)&&media+1.0<pts){
+ const double aligned=audioPipe.requestSeek(pts);
+ if(!std::isfinite(aligned)){status(L"音频时间线对齐失败",true);break;}
}
+ fileAudioAlignPending=false;
}
bool interrupted=false,presentFailed=false;
for(uint32_t i=0;i<out.batch.count;++i){
@@ -599,8 +614,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
if(generated&&item.validity!=pipeline::GenerationValidity::Valid){++handled;continue;}
if(generated&&comparisonMode_!=0)continue;
if(isCapture&&generated&&liveTimeline.expired(item.pts100ns,host100ns(),100000)){++expired;++handled;frameFlow->update([](auto& m){++m.counters.generatedExpiredAfterEval;});continue;}
+ const double itemPtsMs=item.pts100ns/10000.0;
+ if(audioStarted&&!fileAwaitingVideo)audioPipe.videoReady(itemPtsMs);
const auto waitStart=Clock::now();
- while(!stop_&&!paused_&&seekSeconds_<0&&(isCapture?host100ns()<liveTimeline.deadline(item.pts100ns):nowMs()+0.25<item.pts100ns/10000.0))deadlineWait.slice();
+ while(!stop_&&!paused_&&seekSeconds_<0&&(isCapture?host100ns()<liveTimeline.deadline(item.pts100ns):!fileAwaitingVideo&&nowMs()+0.25<itemPtsMs))deadlineWait.slice();
frameWaitMs+=elapsedMs(waitStart);
frameFlow->cpu(diagnostics::CpuStage::DeadlineWait,elapsedMs(waitStart),host100ns());
if(stop_||(paused_&&!seekPreviewPending)||seekSeconds_>=0){interrupted=true;break;}
@@ -612,6 +629,19 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
item.lease->consumerFence=ring.lastSignaledValue();
if(presenter.submittedCount()>before)traceFrame(diagnostics::TraceKind::Present,item.identity,out.batch.batchId,item.lease->consumerFence,item.pts100ns,item.subframe,1,elapsedMs(begin));
if(presenter.submittedCount()>before){++handled;frameFlow->presented(generated,item.lease->consumerFence,host100ns());}
+ if(presenter.submittedCount()>before&&!isCapture&&!isImage){
+ const double intervalMs=double(liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps))/10000.0;
+ // XeSS owns generated frames inside its swapchain. The
+ // engine sees only real B frames, so its audio coverage
+ // must last a SOURCE interval, never a hidden subframe.
+ const bool callerPresentsGenerated=options.fg&&!graph.xessEnabled()&&comparisonMode_==0;
+ double nextPtsMs=itemPtsMs+intervalMs/(callerPresentsGenerated?options.fgMultiplier:1);
+ for(uint32_t next=i+1;next<out.batch.count;++next){const auto& candidate=out.batch.frames[next];
+ if(candidate.kind!=pipeline::FrameKind::Generated||(candidate.validity==pipeline::GenerationValidity::Valid&&comparisonMode_==0)){nextPtsMs=candidate.pts100ns/10000.0;break;}}
+ if(audioStarted){audioPipe.videoPresented(nextPtsMs);audioPipe.setPaused(paused_);}
+ if(fileAwaitingVideo)veyra::log::info("audio-sync",std::format("video anchor presented ptsMs={:.3f} audioPtsMs={:.3f} nextPtsMs={:.3f} paused={} (Present return, scanout unmeasured)",itemPtsMs,audio.mediaTimeMs(),nextPtsMs,paused_.load()));
+ fileAwaitingVideo=false;anchor=Clock::now();anchorMs=itemPtsMs;
+ }
if(presenter.submittedCount()>before&&!generated&&!rereadCached)frameFlow->latency(std::chrono::duration_cast<std::chrono::nanoseconds>(decodeStart.time_since_epoch()).count()/100,host100ns());
if(presenter.submittedCount()>before&&generated&&lineage)frameFlow->generatedLatency(*lineage,host100ns());
if(presenter.submittedCount()>before){++submitted;const auto time=host100ns();submissionTimes.push_back(time);while(submissionTimes.size()>1&&time-submissionTimes.front()>10000000)submissionTimes.pop_front();if(veyra::log::verboseFrameLogs())veyra::log::info("submit",std::format("batch={} epoch={} revision={} subframe={} pts100ns={} host100ns={} fence={} (submission, display unmeasured)",out.batch.batchId,item.identity.epoch,item.identity.settingsRevision,item.subframe,item.pts100ns,host100ns(),item.lease->consumerFence));}
@@ -621,6 +651,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
seekPreviewPending=false;
}
if(!liveScheduler){scheduleWaits.add(frameWaitMs);presentTimes.add(framePresentMs);}
+ audioRebuffering=audioStarted&&audioPipe.waitingForVideo();
const double lateness=isCapture?0:nowMs()-pts;
if(!paused_&&!isCapture){latenessSamples.push_back(std::abs(lateness));if(latenessSamples.size()>1200)latenessSamples.pop_front();}
std::vector<double> sorted(latenessSamples.begin(),latenessSamples.end());std::sort(sorted.begin(),sorted.end());
@@ -646,6 +677,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
++frames;{std::lock_guard lock(mutex_);snapshot_.metrics=measured;snapshot_.position=pts/1000;snapshot_.frames=sourceFrames;snapshot_.generated=graphStats.fgGeneratedFrames;snapshot_.lateMs=lateness;snapshot_.lateP95Ms=sorted.empty()?0:sorted[size_t((sorted.size()-1)*0.95)];
snapshot_.nrActive=graph.nrEnabled()&&graphStats.nrEvaluateCount>0;
snapshot_.audioRebuffering=audioRebuffering;
+ snapshot_.audioVideoWaits=audioPipe.videoWaitCount();
snapshot_.srActive=gd.enableSr&&graphStats.srEvaluateCount>0;
snapshot_.fgActive=options.fg&&(graph.xessEnabled()?presenter.xessActive()&&graphStats.fgGeneratedFrames>0:graph.fgEnabled()&&measured.flow.counters.fgReadyValid>0);
if(transaction&&nvidiaAdapter&&(!graph.xessEnabled()||presenter.xessActive()))snapshot_.backendWarning.clear();
diff --git a/src/sink/CaptureAudioSession.cpp b/src/sink/CaptureAudioSession.cpp
index 5647dc60..11e2b0e5 100644
--- a/src/sink/CaptureAudioSession.cpp
+++ b/src/sink/CaptureAudioSession.cpp
@@ -32,7 +32,7 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
int64_t lastArrival=0;
CaptureAudioState state;
std::thread thread;
- static constexpr double maxQueuedMs=500;
+ static constexpr double maxAutoDelayMs=1500,maxQueuedMs=2000;
double queuedMs()const{return 1000.0*(pcm.size()/2)/kAudioRate+1000.0*(inputBytes+convertingBytes)/format.nAvgBytesPerSec;}
void queueChanged(){state.bufferedMs=queuedMs();state.bufferHighWaterMs=std::max(state.bufferHighWaterMs,state.bufferedMs);}
void clearPcmLocked(){pcm.clear();haveHead=false;pcmTimeline.clear();pcmHead=pcmTail=0;pullEnd.reset();}
@@ -156,9 +156,14 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
const double now=double(hostTime())/10000;
const bool fresh=video&&now-vHost<500;
const double requested=appliedMode==0&&fresh?vHost-vPts-ingress:appliedMode==1?double(appliedOffset):0;
- const double target=std::clamp(requested,0.0,250.0);
+ const double maxDelay=appliedMode==0?maxAutoDelayMs:250.0;
+ const double target=std::clamp(requested,0.0,maxDelay);
const double mapping=ingress+target;
- const bool limited=requested<0||requested>250;
+ const bool limited=requested<0||requested>maxDelay;
+ if(appliedMode==0&&!fresh&&renderer.started()){
+ renderer.fadeAndReset(*this,stop);endpointEventReady=false;
+ std::lock_guard lock(mutex);++state.resets;
+ }
bool justStarted=false;
const double startupPrefillMs=std::min(renderer.capacityMs(),10.0);
if(!renderer.started()&&haveHead&&1000.0*(pcm.size()/2)/kAudioRate>=startupPrefillMs&&(appliedMode!=0||fresh)){
@@ -258,6 +263,7 @@ bool CaptureAudioSession::push(const void* data,size_t bytes,double pts,bool dis
p.inputBytes+=bytes;p.input.push_back(std::move(c));p.queueChanged();p.wake.notify_one();return true;
}
void CaptureAudioSession::videoPresented(double pts,int64_t time){std::lock_guard lock(p_->mutex);p_->videoPts=pts;p_->videoHost=double(time)/10000;p_->haveVideo=true;}
+void CaptureAudioSession::videoReset(){std::lock_guard lock(p_->mutex);p_->haveVideo=false;if(p_->mode==0)p_->pendingReset=true;p_->wake.notify_all();}
void CaptureAudioSession::setGain(float value){p_->gain=std::clamp(value,0.0f,1.0f);}
void CaptureAudioSession::setSync(unsigned mode,int offset){p_->mode=std::min(mode,2u);p_->offset=std::clamp(offset,-250,250);}
CaptureAudioState CaptureAudioSession::snapshot()const{std::lock_guard lock(p_->mutex);return p_->state;}
diff --git a/src/sink/WasapiAudioSink.cpp b/src/sink/WasapiAudioSink.cpp
index 63428198..e0fa032f 100644
--- a/src/sink/WasapiAudioSink.cpp
+++ b/src/sink/WasapiAudioSink.cpp
@@ -1,4 +1,5 @@
#include "veyra/sink/AudioGain.h"
+#include "veyra/sink/AudioVideoContinuity.h"
#include "veyra/sink/WasapiAudioSink.h"
#include <algorithm>
@@ -109,6 +110,7 @@ void AudioPipeline::stopThread()
double AudioPipeline::requestSeek(double targetMs)
{
+ if(videoSync_)holdForVideo();
std::unique_lock<std::mutex> lock(mutex_);
seekTargetMs_ = targetMs;
seekDone_ = false;
@@ -159,6 +161,25 @@ void AudioPipeline::pushDecoded(const AVFrame* frame)
pushConverted(outSamples);
}
+void AudioPipeline::holdForVideo()
+{
+ videoHold_=true;videoSync_=true;wake_.notify_all();
+}
+
+void AudioPipeline::videoReady(double ptsMs)
+{
+ // Initial/reset prefill must wait for an actual Present, not GPU readiness.
+ if(videoSync_&&!videoHold_&&std::isfinite(ptsMs))
+ videoLimitMs_=std::max(videoLimitMs_.load(),ptsMs+2.0);
+ wake_.notify_all();
+}
+
+void AudioPipeline::videoPresented(double nextPtsMs)
+{
+ if(!videoSync_||!std::isfinite(nextPtsMs))return;
+ videoLimitMs_=nextPtsMs;videoHold_=false;wake_.notify_all();
+}
+
void AudioPipeline::pushConverted(int frames)
{
if (frames <= 0) return;
@@ -486,6 +507,14 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint)
bool endpointReady = renderer && (!ownEndpoint || renderer->start());
double lastClockMs = 0, recoveryTargetMs = 0;
auto retryAt = t0;
+ AudioVideoContinuity continuity;
+ auto videoBlocked=[&]{
+ const double observed=endpointReady?renderer->mediaTimeMs():lastClockMs;
+ const double current=std::isfinite(observed)?observed:lastClockMs;
+ return videoSync_&&continuity.blocked(videoHold_,current,videoLimitMs_,std::chrono::steady_clock::now());
+ };
+ auto shouldPause=[&]{return paused_.load()||videoBlocked();};
+ auto publishVideoWait=[&](bool paused){const bool waiting=paused&&videoBlocked();if(videoWaiting_.exchange(waiting)!=waiting&&waiting)++videoWaitCount_;};
auto recovering = [&](HRESULT error) {
endpointError_ = FAILED(error) ? error : E_FAIL;
endpointRecovering_ = true;
@@ -529,8 +558,9 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint)
}
const double firstPts = headPtsMs();
clockExhausted_=decodedEof_&&firstPts<0;
+ bool pauseApplied = shouldPause();
if (endpointReady && firstPts >= 0.0) {
- if (!renderer->startAnchored(*this,paused_)) recovering(renderer->lastError());
+ if (!renderer->startAnchored(*this,pauseApplied)) recovering(renderer->lastError());
else endpointRecovering_=false;
}
lastPrefillMs_.store(std::chrono::duration<double>(
@@ -538,9 +568,8 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint)
veyra::log::info("audio", std::format("startup prefill done in {:.0f}ms firstPtsMs={:.1f} bufferedMs={:.0f}",
lastPrefillMs_.load(), firstPts, bufferedMs()));
- bool pauseApplied = paused_;
while (!stopFlag_.load()) {
- const bool pauseNow = paused_.load();
+ const bool pauseNow = shouldPause();
if(endpointReady){
const double current=renderer->mediaTimeMs();
if(std::isfinite(current))lastClockMs=current;
@@ -551,6 +580,7 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint)
}
if (pauseNow != pauseApplied && endpointReady) renderer->setPaused(pauseNow);
pauseApplied = pauseNow;
+ publishVideoWait(pauseApplied);
// Seek request? Atomic re-sequence.
{
std::unique_lock<std::mutex> lock(mutex_);
@@ -567,7 +597,8 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint)
firstPtsAfterSeek_.store(startPts);
if(!seekOk&&renderer)recovering(E_FAIL);
if (seekOk&&endpointReady && !clockExhausted_) {
- if (!renderer->startAnchored(*this,pauseNow)) recovering(renderer->lastError());
+ pauseApplied=shouldPause();
+ if (!renderer->startAnchored(*this,pauseApplied)) recovering(renderer->lastError());
}
{
std::lock_guard<std::mutex> l2(mutex_);
@@ -586,7 +617,8 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint)
if(renderer->start()){
endpointReady=true;
const bool rewound=rewind(recoveryTargetMs);
- if(rewound&&(clockExhausted_||renderer->startAnchored(*this,pauseNow))){
+ pauseApplied=shouldPause();
+ if(rewound&&(clockExhausted_||renderer->startAnchored(*this,pauseApplied))){
endpointRecovering_=false;++endpointRecoveries_;
log::info("audio-recovery",std::format("restored mediaPtsMs={:.3f} paused={} recoveries={}",recoveryTargetMs,pauseNow,endpointRecoveries_.load()));
}else recovering(renderer->lastError());
@@ -596,11 +628,18 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint)
wake_.wait_for(lock,std::chrono::milliseconds(5),[&]{return stopFlag_||seekRequested_;});
continue;
}
- if (pauseNow) { std::this_thread::sleep_for(std::chrono::milliseconds(5)); continue; }
+ if (pauseNow) { std::unique_lock lock(mutex_);wake_.wait_for(lock,std::chrono::milliseconds(2));continue; }
// Regular cycle: pump the endpoint, then top up below high watermark.
if (renderer != nullptr) {
double firstPts = -1.0;
- if (!renderer->pumpOnce(*this, &firstPts)) {
+ // Re-check after the endpoint wait: a video hold/seek can arrive
+ // during it. Do not submit another block before applying the hold.
+ if(!renderer->waitForEvent()){
+ if(!ownEndpoint)break;
+ recovering(renderer->lastError());continue;
+ }
+ if(shouldPause())continue;
+ if (!renderer->pumpOnce(*this, &firstPts,false)) {
if(!ownEndpoint){log::error("audio","pumpOnce failed");break;}
recovering(renderer->lastError());continue;
}
diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cpp
index 7244213a..0bdf6dff 100644
--- a/src/source/CaptureCardSource.cpp
+++ b/src/source/CaptureCardSource.cpp
@@ -96,6 +96,7 @@ bool CaptureCardSource::setAudioGain(float gain){
p.lastAudioGain=gain;p.audioGainSupported=SUCCEEDED(hr);log::info("capture-audio",std::format("application gain={} hr=0x{:X}",gain,unsigned(hr)));return p.audioGainSupported;
}
void CaptureCardSource::videoPresented(double pts,int64_t time){if(p_->audioSession)p_->audioSession->videoPresented(pts,time);}
+void CaptureCardSource::videoReset(){if(p_->audioSession)p_->audioSession->videoReset();}
void CaptureCardSource::setAudioSync(unsigned mode,int offset){if(p_->audioSession)p_->audioSession->setSync(mode,offset);}
sink::CaptureAudioState CaptureCardSource::audioState()const{auto state=p_->audioSession?p_->audioSession->snapshot():sink::CaptureAudioState{};if(!p_->audioError.empty())state.error=p_->audioError;return state;}
bool CaptureCardSource::open(const SourceOpenDesc& desc){return configure(desc)&&start();}
diff --git a/tests/integration/AudioTimelineTests.cpp b/tests/integration/AudioTimelineTests.cpp
index 18a5501a..037c62a1 100644
--- a/tests/integration/AudioTimelineTests.cpp
+++ b/tests/integration/AudioTimelineTests.cpp
@@ -49,10 +49,42 @@ void decode(const std::filesystem::path& file) {
check(pipe.overruns()==0, "bounded PCM ring did not overflow");
pipe.stopThread();
}
+int jitter(const std::filesystem::path& dir) {
+ const auto file=dir/"video-jitter.wav";fixture(file,48000,6000);
+ // Alternating 0/5ms completion jitter around 30fps. Real/generated frames
+ // are announced exactly as their owner can observe them; XeSS has only B.
+ for(unsigned multiplier:{1u,2u,4u}){
+ AudioPipeline pipe;AudioRenderer renderer;renderer.setGain(0);
+ check(pipe.open(file.wstring()),"open continuous-audio jitter fixture");
+ pipe.holdForVideo();pipe.startThread(&renderer,true);
+ check(until([&]{return renderer.started()&&!pipe.endpointRecovering()&&pipe.waitingForVideo();}),"prefill held before jitter replay");
+ const auto waits=pipe.videoWaitCount();
+ const auto begin=std::chrono::steady_clock::now();
+ pipe.videoPresented(1000.0/30/multiplier);
+ for(unsigned i=1;i<=90;++i){
+ const double pts=i*1000.0/30;
+ std::this_thread::sleep_until(begin+std::chrono::microseconds(int64_t((pts+(i%2?5.0:0.0))*1000)));
+ for(unsigned sub=1;sub<multiplier;++sub){
+ const double generated=pts-1000.0/30+sub*1000.0/30/multiplier;
+ pipe.videoReady(generated);pipe.videoPresented(generated+1000.0/30/multiplier);
+ }
+ pipe.videoReady(pts);pipe.videoPresented(pts+1000.0/30/multiplier);
+ }
+ const double elapsed=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-begin).count();
+ const double media=renderer.mediaTimeMs();const auto stops=pipe.videoWaitCount()-waits;
+ std::cout<<"JITTER multiplier="<<multiplier<<" wallMs="<<elapsed<<" audioMs="<<media<<" additionalVideoPauses="<<stops<<" underruns="<<renderer.underruns()<<'\n';
+ check(stops==0,"5ms video jitter never stops continuous audio");
+ check(std::abs(media-elapsed)<35,"real endpoint keeps one-times audio playback through jitter");
+ check(renderer.underruns()==0&&pipe.overruns()==0,"jitter does not drop PCM or insert silent underruns");
+ pipe.stopThread();
+ }
+ return failures?1:0;
+}
}
int wmain(int argc, wchar_t** argv) {
- if (argc!=2) return 2;
+ if (argc!=2&&!(argc==3&&wcscmp(argv[2],L"--jitter")==0)) return 2;
const std::filesystem::path dir=argv[1]; std::filesystem::create_directories(dir);
+ if(argc==3)return jitter(dir);
for(uint32_t rate:{48000u,44100u}) { const auto file=dir/(std::to_string(rate)+".wav"); fixture(file,rate); decode(file); }
AudioRenderer renderer;
check(!std::isfinite(renderer.mediaTimeMs()), "unstarted clock is invalid");
@@ -151,5 +183,37 @@ int wmain(int argc, wchar_t** argv) {
check(reads>10&&!std::isfinite(recoveryRenderer.mediaTimeMs()),"concurrent clock readers survive endpoint releases and shutdown");
check(recoveryPipe.overruns()==0,"endpoint outages preserve bounded file PCM queue");
recoveryRenderer.shutdown();
+ // Real PCM and a real WASAPI clock with a deliberately stalled video owner.
+ // No GPU-duration estimate and no physical capture delay are fed to audio.
+ AudioPipeline gated;AudioRenderer gatedRenderer;gatedRenderer.setGain(0);
+ check(gated.open(longFile.wstring()),"open software video-delay fixture");
+ gated.holdForVideo();gated.startThread(&gatedRenderer,true);
+ check(until([&]{return gatedRenderer.started()&&!gated.endpointRecovering();}),"video gate prefills endpoint without playing it");
+ const double initial=gatedRenderer.mediaTimeMs();
+ gated.videoReady(0);std::this_thread::sleep_for(350ms);
+ check(std::abs(gatedRenderer.mediaTimeMs()-initial)<.1,"350ms NR startup and GPU-ready alone cannot advance sound");
+ gated.videoPresented(100);
+ check(until([&]{return gated.waitingForVideo()&&gatedRenderer.mediaTimeMs()>=100;}),"audio owner stops at video coverage while GPU owner is blocked");
+ const double stalled=gatedRenderer.mediaTimeMs();std::this_thread::sleep_for(350ms);
+ std::cout<<"VIDEO_GATE stallStartMs="<<stalled<<" stallEndMs="<<gatedRenderer.mediaTimeMs()<<'\n';
+ check(stalled<=210&&std::abs(gatedRenderer.mediaTimeMs()-stalled)<.1,"long GPU stall stays bounded after jitter grace and clock stops accumulating lead");
+ gated.videoReady(260);
+ check(until([&]{return gatedRenderer.mediaTimeMs()>=260;}),"ready later frame can reach its deadline after missing FG candidates");
+ gated.videoPresented(310);
+ check(until([&]{return gatedRenderer.mediaTimeMs()>=290;}),"actual next video releases audio clock");
+ gated.holdForVideo();std::this_thread::sleep_for(70ms);
+ const double rebuilding=gatedRenderer.mediaTimeMs();std::this_thread::sleep_for(250ms);
+ check(std::abs(gatedRenderer.mediaTimeMs()-rebuilding)<.1,"settings rebuild freezes PCM position without skipping samples");
+ const auto target=gated.requestSeek(1200);
+ gated.videoReady(1200);std::this_thread::sleep_for(200ms);
+ check(std::abs(target-1200)<.1&&std::abs(gatedRenderer.mediaTimeMs()-1200)<.1,"playing seek stays held until new video is presented");
+ gated.setPaused(true);gated.videoPresented(1300);std::this_thread::sleep_for(70ms);
+ check(std::abs(gatedRenderer.mediaTimeMs()-1200)<.1,"paused seek preview cannot start audio");
+ gated.holdForVideo();gated.setPaused(false);std::this_thread::sleep_for(150ms);
+ check(std::abs(gatedRenderer.mediaTimeMs()-1200)<.1,"resume waits for video history warmup");
+ gated.videoPresented(1300);
+ check(until([&]{return gatedRenderer.mediaTimeMs()>1250;}),"resume uses real retained PCM after video anchor");
+ check(gated.videoWaitCount()>=4&&gated.overruns()==0,"software video holds are observed and PCM queue remains bounded");
+ gated.stopThread();
return failures ? 1 : 0;
}
diff --git a/tests/integration/CaptureAudioTests.cpp b/tests/integration/CaptureAudioTests.cpp
index fe451771..079efba8 100644
--- a/tests/integration/CaptureAudioTests.cpp
+++ b/tests/integration/CaptureAudioTests.cpp
@@ -20,12 +20,32 @@ int main(int argc,char** argv){
}
} pacer;
const bool endpointTest=argc==2&&std::string_view(argv[1])=="--endpoint-loss";
+ const bool jitterTest=argc==2&&std::string_view(argv[1])=="--jitter";
const bool fastDrift=argc==2&&std::string_view(argv[1])=="--drift-fast";
const bool driftTest=fastDrift||(argc==2&&std::string_view(argv[1])=="--drift-slow");
if(endpointTest)SetEnvironmentVariableW(L"VEYRA_TEST_CAPTURE_AUDIO_ENDPOINT_LOSS",L"1");
CaptureAudioSession audio;WAVEFORMATEX f{};f.wFormatTag=WAVE_FORMAT_PCM;f.nChannels=2;f.nSamplesPerSec=48000;f.wBitsPerSample=16;f.nBlockAlign=4;f.nAvgBytesPerSec=192000;
if(!audio.configure(f)||!audio.start())return 2;audio.setGain(0);
std::vector<int16_t> pcm(960,0);const auto start=Clock::now();
+ if(jitterTest){
+ uint64_t settledResets=0,settledUnderruns=0;unsigned missing=0;std::vector<double> errors;
+ for(unsigned i=0;i<500;++i){
+ pacer.until(start+std::chrono::milliseconds(i*10));
+ if(!audio.push(pcm.data(),pcm.size()*2,i*10.0,i==0))return 9;
+ const auto now=std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;
+ // Callback every 10ms; video updates at ~30fps with 30/35ms
+ // software delay. Both share the original input PTS time base.
+ if(i>=4&&i%3==0)audio.videoPresented(i*10.0-((i/3)%2?30:35),now);
+ const auto s=audio.snapshot();
+ if(i==100){settledResets=s.resets;settledUnderruns=s.underruns;}
+ if(i>100){if(s.running&&s.skewMs)errors.push_back(std::abs(*s.skewMs));else ++missing;}
+ }
+ const auto s=audio.snapshot();audio.stop();std::sort(errors.begin(),errors.end());
+ const double p95=errors.empty()?999:errors[(errors.size()*95+99)/100-1];
+ const bool pass=missing==0&&s.resets==settledResets&&s.underruns==settledUnderruns&&s.overflows==0&&p95<35;
+ std::cout<<(pass?"PASS ":"FAIL ")<<"CAPTURE_JITTER additionalResets="<<s.resets-settledResets<<" additionalUnderruns="<<s.underruns-settledUnderruns<<" missing="<<missing<<" p95SkewMs="<<p95<<'\n';
+ return pass?0:1;
+ }
if(driftTest){
std::vector<double> errors;unsigned missing=0;
const double speed=fastDrift?1.001:.999;
@@ -58,20 +78,35 @@ int main(int argc,char** argv){
if(endpointTest){ok=ok&&sawReconnecting&&state.error.empty()&&state.endpointRetries>=2&&state.running;audio.stop();std::cout<<(ok?"PASS ":"FAIL ")<<"owned WASAPI endpoint recovered without reopening capture retries="<<state.endpointRetries<<'\n';return ok?0:1;}
std::cout<<(ok?"PASS":"FAIL")<<" synthetic capture PTS with 80ms video delay; real WASAPI, no physical capture\n";
unsigned sequence=160;
- auto phase=[&](unsigned mode,int offset,double delay,double expectedComp,double expectedSkew){
+ auto phase=[&](unsigned mode,int offset,double delay,double expectedComp,double expectedSkew,double commonInputMs=0){
audio.setSync(mode,offset);double error=0;unsigned samples=0;bool boundedPhase=true;
- for(unsigned j=0;j<150;++j,++sequence){
+ const unsigned steps=delay>500?300:150;
+ for(unsigned j=0;j<steps;++j,++sequence){
pacer.until(start+std::chrono::milliseconds(sequence*10));
const auto host=std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;
- if(!audio.push(pcm.data(),pcm.size()*2,sequence*10.0,false))return false;
- audio.videoPresented(sequence*10.0-delay,host);const auto s=audio.snapshot();
- boundedPhase&=s.bufferedMs<=520;
- if(j>70&&s.running&&s.skewMs){error+=std::abs(*s.skewMs-expectedSkew);++samples;}
+ if(!audio.push(pcm.data(),pcm.size()*2,sequence*10.0-commonInputMs,j==0&&commonInputMs!=0))return false;
+ audio.videoPresented(sequence*10.0-commonInputMs-delay,host);const auto s=audio.snapshot();
+ boundedPhase&=s.bufferedMs<=2000;
+ if(j>steps-80&&s.running&&s.skewMs){error+=std::abs(*s.skewMs-expectedSkew);++samples;}
}
const auto s=audio.snapshot();const bool pass=samples>=60&&error/samples<28&&std::abs(s.compensationMs-expectedComp)<15&&boundedPhase&&s.overflows==0;
- std::cout<<(pass?"PASS ":"FAIL ")<<"capture phase mode="<<mode<<" delay="<<delay<<" compensation="<<s.compensationMs<<" meanSkewError="<<(samples?error/samples:-1)<<" resets="<<s.resets<<" queueMs="<<s.bufferedMs<<" endpointMs="<<s.endpointBufferedMs<<" underruns="<<s.underruns<<" correctionPpm="<<s.driftCorrectionPpm<<'\n';return pass;
+ std::cout<<(pass?"PASS ":"FAIL ")<<"capture phase mode="<<mode<<" delay="<<delay<<" commonInputMs="<<commonInputMs<<" compensation="<<s.compensationMs<<" meanSkewError="<<(samples?error/samples:-1)<<" resets="<<s.resets<<" queueMs="<<s.bufferedMs<<" endpointMs="<<s.endpointBufferedMs<<" underruns="<<s.underruns<<" correctionPpm="<<s.driftCorrectionPpm<<'\n';return pass;
};
ok=phase(0,0,160,160,0)&&ok;
+ ok=phase(0,0,400,400,0)&&ok;
+ ok=phase(0,0,400,400,0,900)&&ok;
+ ok=phase(0,0,900,900,0,900)&&ok;
+ // Start a fresh ingress epoch after the shared-input offset fixture.
+ audio.stop();if(!audio.start())return 7;
+ ok=phase(0,0,80,80,0)&&ok;
+ audio.videoReset();
+ for(unsigned i=0;i<35;++i,++sequence){
+ pacer.until(start+std::chrono::milliseconds(sequence*10));
+ if(!audio.push(pcm.data(),pcm.size()*2,sequence*10.0,i==0))return 8;
+ }
+ const bool heldForGraph=!audio.snapshot().running;
+ std::cout<<(heldForGraph?"PASS ":"FAIL ")<<"graph reset waits for new video while input PCM continues\n";ok=heldForGraph&&ok;
+ ok=phase(0,0,80,80,0)&&ok;
ok=phase(1,100,80,100,-20)&&ok;
ok=phase(2,0,80,0,80)&&ok;
ok=phase(1,-100,80,0,80)&&ok;
@@ -92,7 +127,7 @@ int main(int argc,char** argv){
for(unsigned i=0;i<600;++i)burstAccepted=audio.push(pcm.data(),pcm.size()*2,i*10.0,i==0)&&burstAccepted;
std::this_thread::sleep_for(std::chrono::milliseconds(80));
const auto burst=audio.snapshot();
- const bool burstBound=burstAccepted&&burst.bufferHighWaterMs<=500&&burst.overflows>0;
+ const bool burstBound=burstAccepted&&burst.bufferHighWaterMs<=2000&&burst.overflows>0;
std::cout<<(burstBound?"PASS ":"FAIL ")<<"combined raw/converting/PCM burst budget highWaterMs="<<burst.bufferHighWaterMs<<" overflows="<<burst.overflows<<'\n';ok=burstBound&&ok;
audio.stop();
return ok?0:1;
diff --git a/tests/integration/LivePresentationTests.cpp b/tests/integration/LivePresentationTests.cpp
index a2d5e28d..69336aaf 100644
--- a/tests/integration/LivePresentationTests.cpp
+++ b/tests/integration/LivePresentationTests.cpp
@@ -9,7 +9,7 @@ using namespace veyra;
using namespace std::chrono_literals;
int wmain(int argc,wchar_t**argv){
SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",L"1");
- if(argc!=3&&!(argc==4&&(wcscmp(argv[3],L"--half-rate")==0||wcscmp(argv[3],L"--overload")==0||wcscmp(argv[3],L"--overload-baseline")==0||wcscmp(argv[3],L"--file-overload")==0||wcscmp(argv[3],L"--source-gap")==0||wcscmp(argv[3],L"--file-endpoint")==0||wcscmp(argv[3],L"--reset-rollback")==0)))return 2;SetProcessDPIAware();CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ if(argc!=3&&!(argc==4&&(wcscmp(argv[3],L"--half-rate")==0||wcscmp(argv[3],L"--overload")==0||wcscmp(argv[3],L"--overload-baseline")==0||wcscmp(argv[3],L"--file-overload")==0||wcscmp(argv[3],L"--source-gap")==0||wcscmp(argv[3],L"--file-endpoint")==0||wcscmp(argv[3],L"--file-continuity")==0||wcscmp(argv[3],L"--reset-rollback")==0)))return 2;SetProcessDPIAware();CoInitializeEx(nullptr,COINIT_MULTITHREADED);
std::filesystem::create_directories(argv[2]);Logger::instance().openFile((std::filesystem::path(argv[2])/"engine.log").wstring());Logger::instance().setConsoleEnabled(false);
HWND window=CreateWindowExW(0,L"STATIC",L"Live scheduler replay",WS_POPUP,0,0,960,540,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
if(!window)return 3;engine::EngineController engine;engine::PlayerOptions options;options.nr=false;options.fg=false;options.captureReplayForTest=true;
@@ -19,6 +19,8 @@ int wmain(int argc,wchar_t**argv){
const bool overload=(argc==4&&std::wstring(argv[3]).find(L"--overload")==0);
const bool fileOverload=argc==4&&wcscmp(argv[3],L"--file-overload")==0;
const bool fileEndpoint=argc==4&&wcscmp(argv[3],L"--file-endpoint")==0;
+ const bool fileContinuity=argc==4&&wcscmp(argv[3],L"--file-continuity")==0;
+ if(fileContinuity){options.captureReplayForTest=false;options.nr=options.fg=true;options.realtime=false;options.settings.frameGenerationBackend=engine::FrameGenerationBackend::XeSS;engine.setVolume(0,true);}
if(fileEndpoint){options.captureReplayForTest=false;SetEnvironmentVariableW(L"VEYRA_TEST_FILE_ENDPOINT_LOSS",L"1");engine.setVolume(0,true);}
if(overload){options.nr=options.sr=options.fg=true;options.realtime=false;options.fgMultiplier=4;options.settings.videoSrQuality=4;options.captureReplayDisableFgAdmissionForTest=std::wstring(argv[3]).ends_with(L"-baseline");SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",nullptr);}
if(halfRate)options.settings.content=engine::ContentRate::Capture60To30;
@@ -26,6 +28,18 @@ int wmain(int argc,wchar_t**argv){
int failures=0;auto check=[&](bool pass,const char* s){std::cout<<(pass?"PASS ":"FAIL ")<<s<<std::endl;if(!pass)++failures;};
auto until=[&](auto predicate,int seconds=8){auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(seconds);while(std::chrono::steady_clock::now()<deadline){MSG msg;while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}auto s=engine.snapshot();if(s.failed){std::wcerr<<s.status<<'\n';return false;}if(predicate(s))return true;std::this_thread::sleep_for(5ms);}return false;};
engine.open(window,argv[1],options);
+ if(fileContinuity){
+ check(until([](const auto& s){return s.frames>=20;}),"XeSS/NR file starts with actual audio");
+ const auto before=engine.snapshot();const auto begin=std::chrono::steady_clock::now();
+ check(until([&](const auto& s){return s.frames>=before.frames+100;},15),"XeSS/NR advances one hundred real source frames");
+ const auto after=engine.snapshot();const double wall=std::chrono::duration<double>(std::chrono::steady_clock::now()-begin).count();
+ std::cout<<"CONTINUITY audioWaits="<<after.audioVideoWaits-before.audioVideoWaits<<" mediaAdvance="<<after.position-before.position<<" wall="<<wall<<" lateMs="<<after.lateMs<<'\n';
+ check(after.audioVideoWaits==before.audioVideoWaits,"SDK-owned XeSS subframes never repeatedly stop audio");
+ check(std::abs(after.position-before.position-wall)<.15,"file maintains continuous one-times playback");
+ check(after.nrEvaluated>50&&after.generated>20&&after.fgActive,"NR and XeSS execute real evaluations during continuity test");
+ engine.stop();check(until([&](const auto&){return engine.idle();},5),"continuous file closes cleanly");
+ DestroyWindow(window);CoUninitialize();return failures?1:0;
+ }
if(fileEndpoint){
check(until([](const auto& s){return s.frames>=20&&s.audioEndpointRecovering;}),"actual player exposes endpoint recovery");
const auto held=engine.snapshot();
@@ -59,11 +73,21 @@ int wmain(int argc,wchar_t**argv){
}
if(fileOverload){
engine.setVolume(0,true);bool held=false,resumed=false;double maxLead=0;
- check(until([&](const auto& s){held|=s.audioRebuffering;resumed|=held&&!s.audioRebuffering&&s.frames>10;maxLead=std::max(maxLead,s.lateMs);return s.frames>=100;},35),"overloaded file keeps advancing without dropping source frames or deadlocking");
+ check(until([&](const auto& s){held|=s.audioVideoWaits>1;resumed|=held&&!s.audioRebuffering&&s.frames>10;maxLead=std::max(maxLead,s.lateMs);return s.frames>=100;},90),"overloaded file keeps advancing without dropping source frames or deadlocking");
check(held&&resumed,"actual GPU overload holds audio and resumes after video catches up");
+ check(maxLead<120,"sustained GPU overload stays within hard audio lead bound plus source/endpoint interval");
+ check(engine.snapshot().nrEvaluated>50&&engine.snapshot().srActive&&engine.snapshot().generated>0,"sync test actually executes NR, SR and generated frames");
+ auto settings=engine.snapshot().desired;settings.multiplier=2;engine.requestSettings(settings);
+ check(until([](const auto& s){return !s.applying&&s.applied.multiplier==2&&s.metrics.flow.counters.realPresented>4;},30),"file audio resumes after FG backend rebuild");
+ check(std::abs(engine.snapshot().lateMs)<120,"rebuilt overloaded graph retains the bounded continuity allowance");
+ engine.seek(.3);
+ check(until([](const auto& s){return s.position>=.3&&s.position<.6&&std::abs(s.lateMs)<35;}),"playing seek warms video before releasing audio");
const auto before=engine.snapshot();engine.pause(true);engine.seek(.5);
check(until([](const auto& s){return s.transport==engine::TransportState::Paused&&s.position>=.49&&s.position<.6;}),"paused seek survives an audio overload hold");
engine.pause(false);check(until([&](const auto& s){return s.frames>before.frames+8;}),"file resumes after overload and seek");
+ settings=engine.snapshot().desired;settings.nr=false;settings.sr=false;settings.multiplier=1;engine.requestSettings(settings);
+ check(until([](const auto& s){return !s.applying&&!s.applied.nr&&!s.applied.sr&&s.applied.multiplier==1&&s.metrics.flow.counters.realPresented>=30;}),"leave overload and restore a sustainable video graph");
+ check(std::abs(engine.snapshot().lateMs)<35,"recovered graph has no retained overload offset");
engine.stop();check(until([&](const auto&){return engine.idle();},5),"file overload shutdown");
std::cout<<"FILE_OVERLOAD held="<<held<<" resumed="<<resumed<<" maxObservedLeadMs="<<maxLead<<'\n';
DestroyWindow(window);CoUninitialize();return failures?1:0;