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

fix(audio): bound capture synchronization and checkpoint issue repair plan

Veyra Goal Agent6206b5a476fa
diff --git a/apps/veyra/ui/LiveStatusPanel.h b/apps/veyra/ui/LiveStatusPanel.h
index a1482eba..9c80cdcc 100644
--- a/apps/veyra/ui/LiveStatusPanel.h
+++ b/apps/veyra/ui/LiveStatusPanel.h
@@ -135,11 +135,13 @@ inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){
if(!s.capture&&s.audioAvailable)rows.emplace_back(L"声音领先 · 软件估算",std::format(L"{:.1f} ms",s.lateMs));
if(s.capture&&s.audioAvailable){
rows.emplace_back(L"音频格式",std::format(L"{} Hz · {} bit / {} valid{}",s.captureAudio.inputSampleRate,s.captureAudio.inputContainerBits,s.captureAudio.inputValidBits,s.captureAudio.inputFloating?L" · Float":L""));
- rows.emplace_back(L"音画偏差 · 声音领先",ms(s.captureAudio.skewMs));
+ rows.emplace_back(s.captureAudio.syncClockFallback?L"估算偏差 · 本机时钟":L"音画偏差 · 声音领先",ms(s.captureAudio.skewMs));
rows.emplace_back(L"声音补偿",std::format(L"{:.1f} ms{}",s.captureAudio.compensationMs,s.captureAudio.limited?L" · 已达边界":L""));
+ if(s.captureAudio.syncClockFallback)rows.emplace_back(L"同步状态",L"时间戳异常回退 · 本机延迟估算");
rows.emplace_back(L"PCM队列",std::format(L"{:.1f} ms",s.captureAudio.bufferedMs));
rows.emplace_back(L"音频设备队列",std::format(L"{:.1f} ms",s.captureAudio.endpointBufferedMs));
rows.emplace_back(L"音频重锚 / 溢出",std::format(L"{} / {}",s.captureAudio.resets,s.captureAudio.overflows));
+ if(s.captureAudio.recoveryDiscardedFrames)rows.emplace_back(L"恢复时跳过的旧音频",std::format(L"{:.1f} ms",s.captureAudio.recoveryDiscardedFrames/48.0));
rows.emplace_back(L"欠载 / 可测缺口 / 插入静音",std::format(L"{} / {:.1f} / {:.1f} ms",s.captureAudio.underruns,s.captureAudio.underrunFrames/48.0,s.captureAudio.silenceFrames/48.0));
if(s.captureAudio.clockStalledGaps)rows.emplace_back(L"时钟未量出时长的断流",std::to_wstring(s.captureAudio.clockStalledGaps));
rows.emplace_back(L"转换峰值 / 超满幅 / 异常",std::format(L"{:.4f} / {} / {}",s.captureAudio.inputPeak,s.captureAudio.overRangeSamples,s.captureAudio.nonFiniteSamples+s.captureAudio.invalidPaddingSamples));
diff --git a/docs/CAPTURE_VRR_AUDIO_SYNC_AUDIT_2026-09-15.md b/docs/CAPTURE_VRR_AUDIO_SYNC_AUDIT_2026-09-15.md
new file mode 100644
index 00000000..4ad2d8d6
--- /dev/null
+++ b/docs/CAPTURE_VRR_AUDIO_SYNC_AUDIT_2026-09-15.md
@@ -0,0 +1,222 @@
+# Capture VRR report: automatic audio synchronization audit
+
+## Original audit (before repair)
+
+User reports that some players experience seconds of audio delay with PS5 VRR
+and automatic audio compensation; disabling compensation restores normal sound.
+User believes the affected input is a capture card. The affected application
+version, card, actual negotiated HDMI/USB cadence and incident log are unknown.
+
+This audit establishes a software failure mechanism, not a physical VRR root
+cause. Ordinary variable frame arrival with consistent timestamps did not
+produce excessive buffering in the synthetic test. Video-only timestamp offset
+did: the current production audio session interpreted it as additional video
+delay and buffered over one second of real PCM. The same input with compensation
+disabled returned to a short queue. No product synchronization policy changed.
+
+## Code findings
+
+- `src/sink/CaptureAudioSession.cpp` computes automatic delay as
+ `videoHost - videoPts - audioIngressMapping`, clamped to 0..1500 ms.
+ Raw/converting/PCM storage has a separate 2000 ms budget. These limits are not
+ additive measurements of end-to-end latency.
+- Freshness checks whether video presentation was reported in the last 500 ms;
+ they do not validate that video and audio PTS origins/rates remain comparable.
+- A correction error over 60 ms, after the reset cooldown, resets the output
+ anchor. Subsequent startup waits for the calculated mapping. Consequently,
+ an erroneous target can cause real waiting and PCM accumulation, rather than
+ merely displaying an incorrect number.
+- DirectShow capture forwards video and audio sample timestamps. Sharing one
+ graph/reference clock does not by itself validate driver timestamp behavior.
+ The WASAPI input path added locally uses a separate video-ingress mapping;
+ this audit did not exercise that adapter or conclude it has identical behavior.
+- The relevant formula and 1500/2000 ms budgets are also present in tag
+ `v1.2.0`. Recent audio waveform fixes retained this synchronization policy.
+- `ebba6f1` reanchors live FG deadlines, but does not rewrite the source PTS
+ passed to audio synchronization. The prior FG repair therefore does not
+ establish that this audio problem is fixed.
+
+Given only the present-time/PTS difference, true upstream video delay and an
+invalid video timestamp offset can look identical. A robust repair needs input
+arrival/clock evidence, not an arbitrary smaller delay constant.
+
+## Reproduction
+
+Added optional `--sync-clock-audit` to
+`tests/integration/CaptureAudioTests.cpp`, using the production
+`CaptureAudioSession`, synthetic continuous 48 kHz PCM and real WASAPI output at
+gain zero. No microphone, capture device, PS5 connection or loopback was opened.
+Video observations were synthetic; there was no actual video/GPU processing.
+The fixture's video residence was 35 ms with changing observation intervals.
+
+| Scenario | Max compensation | Max software PCM queue | Result |
+| --- | ---: | ---: | --- |
+| Aligned timestamps, variable observation cadence | 35.50 ms | 13.75 ms | PASS |
+| Video PTS shifted back 1200 ms, same synthetic residence | 1235.51 ms | 1214.56 ms | FAIL |
+| Same shifted PTS, compensation disabled | 0 ms | 10 ms | PASS |
+
+Output endpoint capacity was 22 ms. During the offset scenario its queue was
+22 ms while the software held about 1.2 seconds of PCM. No overflow occurred.
+The auto-mode skew eventually looked small (about -15 ms) despite the wrong
+target: internal timestamp agreement is not proof of physical A/V agreement.
+
+The failure is intentional evidence of an unresolved product behavior; the
+diagnostic returns exit 1 and is not registered as an always-passing gate.
+It is neither physical VRR reproduction nor a speaker latency measurement.
+It does not establish the user's exact multi-second duration; automatic target
+alone is capped at 1.5 seconds, and other delays require incident evidence.
+
+Commands executed:
+
+```powershell
+cmd.exe /c out\build\veyra-build-x64-release.cmd
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/acceptance/scheduler-short-test.ps1 -Name capture-sync-clock-audit-20260915 -Exe out/build/audio-continuity-repair-20260915/veyra_capture_audio_tests.exe -TestArgs '--sync-clock-audit'
+git diff --check
+```
+
+Build exit 0, 2/2 incremental targets. Diagnostic exit 1 in 11.60 seconds.
+Evidence: `logs/scheduler-repair-20260910/capture-sync-clock-audit-20260915.stdout.log`
+and `.result.json`; test EXE SHA256
+`3AFEE6EAAA704CD40754513BD6DEE8A494C97CD4FA1D7A5B6C6E29292C93F668`.
+Only the test executable was rebuilt. No runtime/SDK changed, no RTX
+Create/Evaluate, physical capture or audible acceptance ran, and no publication.
+
+## Proposed repair and acceptance
+
+1. Carry matching video ingress/presentation observations, source epoch and
+ original/generated frame identity into the shared synchronization estimator.
+ Record clock validity, raw requested delay, accepted target, actual PCM and
+ endpoint queues, input PTS/arrival trends and reasons for reanchoring.
+2. Accept cross-stream PTS compensation only with a validated clock relationship.
+ When the relationship becomes inconsistent, stop increasing compensation
+ from that evidence and use a bounded fallback based on observed local video
+ residence. A fallback cannot infer unmeasured capture hardware A/V offset;
+ expose the limitation and preserve manual adjustment. Keep real frame times
+ and A/B interpolation lineage; do not replace VRR timestamps by frame count.
+3. Separate audio device rate correction from changes in the video delay target.
+ Apply stable target estimation and explicit discontinuity recovery rather
+ than treating a single presentation outlier as oscillator drift. Preserve
+ continuous resampling history and explicit queue/recovery accounting.
+4. Make this diagnostic pass through the production estimator with consistent
+ provenance. Also test genuine 80/400/900 ms video residence (not offsets),
+ independent video clock drift, common A/V offsets, correct variable PTS,
+ unmarked/marked timestamp jumps, FG toggles and stale video. Preserve the
+ existing audio continuity and +/-1000 ppm tests. Test adapters independently;
+ PS5 network streaming and files must not inherit capture-only assumptions.
+5. Verify the affected card in the same scene with VRR on/off and automatic
+ compensation on/off. Obtain the version and incident log before claiming
+ VRR causality or the user's exact symptom fixed.
+
+Temporary workaround: select compensation off or a small user-calibrated manual
+offset. This removes automatic video-delay following; it does not guarantee
+perfect long-term synchronization and is not the final fix.
+
+## Authorized implementation
+
+The user subsequently authorized the local repair. The failure and unchanged
+policy described above refer to the before-repair executable, not the candidate.
+
+- `CaptureSyncTarget` validates cross-stream PTS against the matching original
+ frame's host arrival-to-presentation residence. A residual above 80 ms or an
+ invalid observation latches fallback to that local residence. Recovery needs
+ residual within 40 ms for two seconds of fresh observations. Five actual
+ observations provide median filtering; repeated audio-thread polls do not
+ become extra video samples. Real 400/900 ms local processing delay is retained.
+- The 80 ms threshold is an explicit confidence policy, not a measurement of
+ capture-card latency. Unknown upstream A/V offset larger than that can be
+ rejected even if physically real. Fallback estimates local synchronization;
+ it cannot calibrate HDMI/card buffering or acoustic output. Manual adjustment
+ remains available. The 1500 ms automatic and 2000 ms queue bounds remain.
+- Engine presentation reports matching arrival only for real, non-cached frames;
+ generated frames cannot shift the synchronization anchor. Existing scheduler
+ cancellation/reset owns stale jobs. Video-only reset invalidates observations
+ while holding the last audio target; it does not reset healthy PCM. Actual
+ audio discontinuities, endpoint recreation and explicit mode changes reset
+ the estimator. No independent source-epoch protocol was introduced.
+- DirectShow retains its PTS with this validation. The separate WASAPI input
+ adapter now uses the matching original arrival on the host axis, replacing
+ the latest unrelated callback's video mapping. The PS5 no-arrival overload
+ retains its separate clock contract; file audio does not use this estimator.
+- The detail panel explicitly labels timestamp fallback and the estimated
+ skew. Logs retain raw requested delay/skew, local residence, accepted target,
+ freshness, matching input arrival, PCM/endpoint queues and fallback changes.
+- Audio oscillator correction retains the existing continuous resampler and
+ bounded controller. The repair filters video targets and rejects inconsistent
+ clock evidence; it is not a new independent oscillator-estimation algorithm.
+
+### Additional startup backlog defect
+
+The first post-repair suite exposed a separate, genuine failure: WASAPI opening
+took about 680 ms, but the session started after converting only roughly 40 ms
+of the raw input backlog. Startup expiry could see only that small converted
+portion. The remaining raw backlog then kept sound about 600 ms behind even
+after repeated reanchors. Initial jitter regression failed at P95 641.452 ms.
+
+A deterministic `--slow-start` case delays this session's own initial endpoint
+open by 650 ms. Before the backlog fix it failed at P95 646.558 ms with four
+additional reanchors. Evidence remains in
+`logs/scheduler-repair-20260910/capture-slow-start-before-20260915.*`;
+test hash `A9958825429C8F2CBF2FA18FA0AD24FFDF05223E3A44976975AA92A75AE77A28`.
+
+Before starting or reanchoring, the session now converts its bounded pending
+input before applying the existing expired-PCM policy. Healthy running playback
+retains the existing fill policy. Recovery discards are counted and logged as
+`capture-audio-reanchor` and exposed separately in details. This is startup/live
+recovery accounting, not steady playback sample dropping to disguise sync.
+
+## Repair verification
+
+Final candidate: `out/build/audio-continuity-repair-20260915/veyra.exe`,
+11,463,168 bytes, SHA256
+`F060238E39311D9E2D3D8B8CB4EA50B0CBB6E4BD24E67BC10D90A249F417BACC`.
+Audio test SHA256:
+`F2DC850D603DE23964C02864AA603704856560DB8A859D70D76DF42C0282CED1`.
+
+Commands executed:
+
+```powershell
+cmd.exe /c out\build\veyra-build-x64-release.cmd
+out/build/audio-continuity-repair-20260915/veyra_repair_contract_tests.exe
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/diagnostics/test-audio-continuity.ps1 -BuildDirectory out/build/audio-continuity-repair-20260915 -LogDirectory logs/capture-sync-repair-20260915/final
+scripts/run-short-test.ps1 -Exe out/build/audio-continuity-repair-20260915/veyra.exe -Arguments @('--smoke-empty','--smoke-seconds','2','--no-nr','--no-sr','--no-fg') -TimeoutSeconds 30 -LogPrefix logs/capture-sync-repair-20260915/gui-smoke
+git diff --check
+```
+
+- Build succeeded (initial repair 60/60; final incremental 4/4), RemotePlay ON,
+ patched FFmpeg/dav1d unchanged. Final output:
+ `logs/capture-sync-repair-20260915/build-final.log`. During the added slow-start
+ test, compilation failed twice because its assertion referenced `kAudioRate`
+ without the defining header. Replaced with the fixture's 24,000-frame
+ half-second threshold, then rebuilt successfully. Failures were not test passes.
+- CPU contract suite: 123 checks, zero failures; output `contracts.log` in the
+ same evidence directory. Covers ten-minute simulated independent clock drift,
+ fallback/recovery, real residence, invalid observations and latency lineage.
+- Final audio short suite: 16 processes, all exit 0; `final/results.json`.
+ This includes 47 DSP checks, 18 WASAPI input-clock checks, stereo/5.1 jitter,
+ real output-endpoint recovery, multichannel, file timeline, manual/off modes,
+ common input offsets, graph reset and queue bounds. The no-arrival legacy
+ clock contract ran separately and passed; no physical PS5 was connected.
+- Final timestamp-offset test: aligned max target 35.4393 ms, queue 23.625 ms;
+ 1200 ms video-only offset max target 35 ms, queue 10 ms; compensation off
+ target 0 ms, queue 10 ms. Offset scenario has only the startup reset.
+- Deterministic slow-start fix: P95 skew 20.1321 ms vs 646.558 ms before;
+ zero additional resets/underruns. Logs show 648.396 ms expired PCM removed at
+ startup. Evidence: `capture-slow-start-fixed-20260915.*` under
+ `logs/scheduler-repair-20260910/`; final full-suite slow-start also passed.
+- GUI empty-start smoke exit 0, `failed=false`, zero processed/generated frames.
+ This checks startup only, not playback or GPU enhancement success.
+- `git diff --check` passed (existing CRLF notices); no tracked DLL/LIB/EXE/model
+ or PYC files. No runtime replacement, version change, push or Release.
+
+Two 120-second real-WASAPI/synthetic-input clock-drift runs completed with exit 0
+using the same script with `-DriftOnly`. At input speed 1.001, P95 skew was
+4.22906 ms; at 0.999, it was 4.23319 ms. Both reported missing=0, resets=1
+(startup only), and queue high water 89.6458 ms. Evidence:
+`logs/capture-sync-repair-20260915/final/drift-results.json` and the adjacent
+`drift-fast.stdout.log` / `drift-slow.stdout.log` files.
+All audio output tests are muted; no acoustic acceptance is
+claimed. No physical capture/WASAPI input recording, VRR on/off comparison,
+RTX Create/Evaluate or full GPU delivery gate ran in this audio-focused repair.
+Next acceptance: affected user's same card/scene with automatic sync and VRR
+on/off, together with the new target/queue logs. Genuine upstream hardware
+offset and actual screen/speaker timing remain unmeasured.
diff --git a/docs/LOCAL_INTEGRATION_STATUS_2026-09-15.md b/docs/LOCAL_INTEGRATION_STATUS_2026-09-15.md
index a3fd2586..fa523c25 100644
--- a/docs/LOCAL_INTEGRATION_STATUS_2026-09-15.md
+++ b/docs/LOCAL_INTEGRATION_STATUS_2026-09-15.md
@@ -36,8 +36,8 @@
候选为本机完整构建目录,不是新的便携发布包。移动EXE时不能遗漏同目录依赖和shader。
- 路径:`out/build/audio-continuity-repair-20260915/veyra.exe`(相对项目根目录)。
-- 大小:11,442,688字节。
-- SHA256:`F26C655DDF7D9CF07FBA35AEA323059B9F65708139AB580015CF788B23D1D552`。
+- 大小:11,463,168字节(本轮自动同步修复候选)。
+- SHA256:`F060238E39311D9E2D3D8B8CB4EA50B0CBB6E4BD24E67BC10D90A249F417BACC`。
- RemotePlay ON;FFmpeg前缀 `C:/veyra-deps/ffmpeg-ps5-dav1d-installed`。SDK、DLL和模型未加入源码Git。
- 前轮最终专项:12组短用例均exit0;离线生产DSP47/47;两组各120秒±1000ppm漂移回归exit0,P95软件偏差4.24594/4.30137ms,missing=0、resets=1(启动),队列高水位89.6458ms。均不冒充用户声学验收。
- 日志:`logs/audio-continuity-repair-20260915/final/`,含 `results.json`、`drift-results.json`、波形/端点/漂移日志;日志被Git忽略,仅本机存在。
@@ -53,3 +53,5 @@
后续发布需要另行授权、完整候选包回归和依赖对应源码审计;不能直接把当前本地EXE标为已发布1.2.0修复包。
WASAPI专项记录见 [WASAPI接入方案与证据](WASAPI_CAPTURE_INPUT_PLAN_2026-09-15.md)。
+
+最新本地候选还包含[采集自动补偿与慢启动积压修复](CAPTURE_VRR_AUDIO_SYNC_AUDIT_2026-09-15.md):以匹配原帧的到达时间校验跨流时间戳,异常时回退本机处理时间估算;启动/恢复时清理已过期音频并明确记录。该候选的测试结果以此专项文档为准,上文合并轮记录仍属历史证据。反馈者实卡VRR原因尚未证实,未发布。根目录旧启动脚本仍指向 `out/build/x64-release`,本轮测试请直接启动上述候选EXE。
diff --git a/docs/USER_ISSUES_REPAIR_PLAN_2026-09-15.md b/docs/USER_ISSUES_REPAIR_PLAN_2026-09-15.md
new file mode 100644
index 00000000..348041c5
--- /dev/null
+++ b/docs/USER_ISSUES_REPAIR_PLAN_2026-09-15.md
@@ -0,0 +1,203 @@
+# 用户集中反馈修复计划(2026-09-15)
+
+状态:方案建立,尚未开始本轮代码施工。
+范围:视频播放器、采集卡、PS5 串流、增强管线、视频导出和颜色管理。
+本计划不授权发布新版本、不替换运行组件、不修改显卡驱动。
+
+## 1. 目标与原则
+
+本轮目标是把用户反馈拆成可复现、可定位、可回归的工程任务。每项修复必须同时具备:
+
+- 现象对应的日志或测试证据;
+- 明确的状态、队列、时间戳和颜色契约;
+- 可独立回归的自动测试或手工验收步骤;
+- 失败时保留真实错误码,不用“回退成功”掩盖后端失败;
+- 不把一台显卡、一个采集卡或一次成功启动当作全设备兼容证明。
+
+播放器、采集卡和串流继续共享 `FrameSource -> EnhanceGraph -> FrameSink`。本轮不复制第二套增强链,也不通过无限队列或阻塞 UI 来掩盖性能问题。
+
+## 2. 当前已知证据
+
+### 已有证据
+
+- 采集音频自动同步和启动积压已有独立修复候选;其测试使用合成采集时序和真实 WASAPI 静音输出,仍需反馈用户的真实采集卡复测。
+- 现有串流异常日志中,视频已收到、D3D12VA 已解码,NVOF、SR、FG 初始化均返回成功;随后出现 `swapchain mode rejected requested=3 actual=4`,会话被取消。当前更像显示交换链模式回退处理错误,不能直接归咎于配对或网络。
+- OBS 捕获兼容模式和窗口 resize 已有历史修复文档,但 1.2.0 后仍需用 1.1.0 对照确认是否回归。
+- HDR/SDR 和 HDR10/5.1 已有颜色合同和施工记录,但用户反馈“都发灰”,必须增加端到端灰阶和色块证据。
+
+### 尚未证明
+
+- Dolby Vision 原生解码、RPU 保留和原生输出;不能用 HDR10 代称 Dolby Vision。
+- RTX 4060/4070/4070 Ti 的真实过载边界;不能用 RTX 5070 或 RTX 50 代替 40 系验收。
+- 用户导出日志中 `completed sample queue overflow` 与 BT.2020 错误的完整上下文;需要原始导出日志和输入媒体信息。
+- “PS5 VRR 导致音频数秒延迟”的因果关系;需同一采集卡 VRR 开/关对照。
+
+## 3. 分阶段施工顺序
+
+### 阶段 A:不可用状态与恢复
+
+优先修复会让用户无法继续使用的错误状态。
+
+#### A1. PS5 串流增强初始化失败
+
+现象:配对成功、收到视频,但点击增强后显示初始化失败或会话被关闭。
+
+实施:
+
+1. 将交换链能力探测、请求模式和实际生效模式分开记录。
+2. SDR、HDR、直播兼容和窗口 resize 使用明确的回退顺序;实际模式改变时重新绑定呈现资源,不直接终止串流。
+3. 把状态拆成“传输连接、视频解码、增强初始化、呈现初始化、运行中”五层。
+4. NGX/NVOF/XeSS 失败只禁用对应后端,基础视频仍可显示。
+5. 为每个阶段记录 HRESULT、NGX/XeSS 返回值、交换链格式、色彩空间和窗口尺寸。
+
+验收:配对成功后无增强、NR、SR、DLSS FG、XeSS FG、HDR/SDR、全屏/窗口各启动一次;任何单项失败都不能关闭基础视频。
+
+#### A2. OBS resize 回归
+
+现象:1.2.0 起使用 OBS 游戏采集,放大缩小窗口后进入错误状态;1.1.0 无此问题。
+
+实施:统一 resize 生命周期:暂停提交,等待旧资源 fence,重建交换链和尺寸相关纹理,原子 reset SR/NR/FG/flow/depth,再恢复提交。禁止旧 backbuffer 在 GPU 使用期间被释放或复用。
+
+验收:连续拖动窗口、最大化/还原、全屏切换、DPI 改变、OBS 同时捕获;检查无黑帧、无错误状态、无旧尺寸资源访问。
+
+#### A3. 采集卡断开自动重连
+
+实施:检测 DirectShow/WASAPI 设备失效、样本停止、端点错误和设备路径变化;进入 `reconnecting`,保留 UI/设置,暂停历史,按递增间隔重试原设备;成功后重新建视频格式、音频时钟和增强历史。多次失败后才进入可重试错误。
+
+验收:拔线/插回、设备被 OBS 占用、设备格式改变、音频端点单独断开、连续断开重连;不切到其他设备,不丢失用户选择。
+
+#### A4. 采集卡选择记忆
+
+实施:以稳定 `DevicePath` 为主键,显示名仅作展示;保存视频格式、帧率、像素格式和音频端点。启动时优先匹配上次设备,设备不存在时显示未连接,不静默选别的设备。
+
+验收:重启软件、拔插设备、同名设备并存、设备顺序改变、旧配置升级;配置文件不得保存临时枚举序号作为唯一标识。
+
+### 阶段 B:颜色与输入格式
+
+#### B1. HDR/SDR 发灰
+
+实施:每帧或每源显式记录 `matrix/range/transfer/format`,统一进入 linear working color;SDR 不走 HDR tone mapping,HDR 根据显示器能力选择 HDR 输出或明确 tone map 到 SDR;禁止重复转换。
+
+验收素材:SDR 黑白灰阶、BT.709 色块、BT.2020/PQ、HLG、full/limited range。验收日志必须能解释输入、工作空间和输出,不以截图肉眼作为唯一证据。
+
+#### B2. 视频导出 BT.2020 转换失败
+
+实施:导出前按颜色合同分流 SDR 与 HDR。SDR 使用 BT.601/709 SDR 转换;HDR 使用 BT.2020 PQ/HLG 到 HDR10,或在用户选择 SDR 时执行明确 tone map。遇到不支持的组合要在导出前报错,不能进入错误转换函数。
+
+验收:导出输出帧数、PTS、颜色元数据和解码回验一致;HDR 输入不得触发 `BT.2020 input is not supported by BT.601/709 SDR conversion`。
+
+#### B3. Dolby Vision
+
+分三层交付:
+
+1. 识别 Profile、基础层和 RPU 是否存在;
+2. 先提供基础层兼容播放,或明确转换为 HDR10/SDR;
+3. 只有确认 RPU 解码、编码器、Windows 显示链和授权后,才评估原生 Dolby Vision 输出。
+
+完成前 UI 必须标明“兼容播放/转换”,不得宣称原生 Dolby Vision。
+
+### 阶段 C:播放器交互和流畅性
+
+#### C1. Seek、全屏进度和快捷键
+
+实施:拖动过程中只更新目标位置,松开后执行一次精确 seek;新 seek 覆盖旧 seek。解码 worker 异步处理,UI 立即显示目标位置。全屏保留进度条、鼠标唤醒和键盘焦点;左右方向键默认前后10秒。
+
+验收:4K 文件连续拖动、拖到末尾、反复前后跳、全屏/窗口切换、音频恢复;不出现先弹回旧位置再跳转的视觉回弹。
+
+#### C2. 播放器流畅性
+
+先测量再优化:记录解码等待、增强等待、GPU fence、呈现 deadline、UI 消息延迟、队列长度和丢弃原因。消除 UI 等待解码、每帧 CPU fence wait、旧 seek 结果提交和无界任务队列。
+
+实时预览可以丢弃过期增强工作,但不能把导出路径改成丢帧,也不能放慢音频制造同步假象。
+
+#### C3. UI 闪烁
+
+排查 Win32 无效区域、交换链重建清屏、DPI resize 和控件重建。改为差异更新控件,画面层与 UI 层分离,交换链重建期间保留上一帧或明确的加载状态。
+
+验收:模式切换、全屏、resize、错误提示、滚动和参数实时修改截图回归;检查无黑屏闪烁和控件跳动。
+
+### 阶段 D:内部处理分辨率和性能
+
+#### D1. NR 内部处理分辨率
+
+增加 `480p / 720p / 900p / 1080p / 1440p` 挡位。它们表示 NR/增强工作尺寸,不改变最终输出尺寸;按源宽高比计算实际 extent,显示源/内部/输出三组分辨率。
+
+每档记录显存、GPU 时间、实际处理 FPS 和丢帧;默认仍保持现有设置兼容,不擅自替换用户已保存的设置。
+
+#### D2. 40 系过载
+
+先区分真实 GPU 超时、队列积压、显存不足和错误阈值。记录每阶段 GPU 时间、显存预算/占用、队列深度、后端和驱动版本。持续过载时按预设降级内部处理分辨率或关闭单个高成本效果,不能直接把目标帧率锁30并伪装成正常。
+
+验收至少覆盖 RTX 4060、4070、4070 Ti;本机没有对应实卡时只做代码和日志验证,不宣称硬件通过。
+
+#### D3. FG/XeSS 计时与冗余
+
+统一 GPU timestamp/fence 接口,分开显示 GPU 执行、CPU 提交、等待和呈现时间。后端不提供硬件时间戳时显示“未提供”,不能把0或未知参与总延迟。审计 NR、SR、光流、FG 是否重复等待或重复计入总延迟。
+
+#### D4. FG 后端失败
+
+按不可用、驱动不足、分辨率不支持、资源不足、初始化失败、运行时 Evaluate 失败分类。UI显示后端和真实错误码;失败只禁用该后端并保留基础播放,不能静默回滚成“已开启”。
+
+### 阶段 E:视频导出队列
+
+#### E1. completed sample queue overflow
+
+导出路径使用独立有界队列和背压;接近上限时暂停生产或等待可复用 slot,不允许无限堆积。`flow=0 fallback=single-image` 只允许在首帧、seek、场景切换等无历史阶段,并在导出报告中统计。
+
+验收:导出长视频、4K、FG 开关、场景切换和 HDR;检查队列峰值、最终归零、帧数、PTS 连续性、取消清理和输出可解码。
+
+## 4. 依赖关系与交付批次
+
+### 批次 1:A1、A2、A3
+
+目标:不再因串流初始化、窗口变化或采集卡断开进入不可恢复状态。
+
+### 批次 2:B1、B2、C1
+
+目标:先统一颜色,再修 seek/全屏交互;否则后续性能对比没有可信画面和时间线。
+
+### 批次 3:A4、C2、C3、D1
+
+目标:改善重复操作、低配置可用性和日常流畅度。
+
+### 批次 4:D2、D3、D4、E1
+
+目标:处理后端失败、40系过载、计时不完整和导出队列问题。
+
+### 批次 5:B3
+
+目标:在兼容播放和 HDR 转换稳定后再评估 Dolby Vision,不把未验证的原生输出塞进主线。
+
+## 5. 每批次固定验收合同
+
+- 构建成功,记录实际构建命令和依赖路径;
+- 相关单元/集成测试通过,失败日志保留;
+- 至少一个真实 GUI 短测;
+- 记录输入、工作、输出分辨率与颜色合同;
+- GPU/NGX/XeSS/NVOF 返回值和 HRESULT 进入日志;
+- 不将运行组件、SDK、模型、用户配置或测试媒体提交源码 Git;
+- 未接用户硬件时明确写“未执行”,不拿合成测试冒充实卡验收;
+- 本轮不自动发布版本,发布需要另行明确授权。
+
+## 6. 当前需要的外部证据
+
+施工前优先收集:
+
+1. 用户提供的完整“串流异常.log”;
+2. 视频导出失败的完整日志、输入文件信息和导出设置;
+3. 4070/4070 Ti 过载日志,包含驱动版本、源分辨率、内部处理分辨率和所有效果开关;
+4. HDR/SDR 发灰各一份源媒体或采集卡颜色日志;
+5. OBS resize 回归的1.1.0与1.2.0日志;
+6. 采集卡断连、重新插入和设备枚举日志。
+
+在这些证据到齐前,可以先施工 A4、C1、C3 和日志/状态框架;不能声称已经解决用户设备上的 B1、D2、E1 或 A1。
+
+## 7. 明确不做的事情
+
+- 不通过增加缓冲解决卡顿;这会把卡顿变成更高延迟。
+- 不用“系统 HDR 没开”解释所有发灰现象;必须先核对颜色合同。
+- 不把 HDR10、HLG 或基础层播放宣称为 Dolby Vision。
+- 不把一台 RTX 50 的结果推广到 RTX 40 全系列。
+- 不用0、未知或软件提交时间伪造 XeSS/FG GPU 耗时。
+- 不把导出队列溢出、flow fallback 和颜色转换错误合并成一个笼统的“性能不足”。
+
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 8b061445..3564b599 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,11 @@
# 2026-09-11 继续修复目标模式执行中
+## 2026-09-15 VRR / 自动音频补偿延迟排查
+
+用户反馈疑似采集卡在PS5开启VRR后自动补偿导致声音延迟、关闭补偿恢复。当前没有反馈者版本/实卡日志,不能认定VRR根因。新增生产CaptureAudioSession诊断`--sync-clock-audit`:正常可变观察间隔下补偿35.50ms、PCM队列13.75ms;保持合成画面延迟35ms而视频PTS后移1200ms时,补偿1235.51ms、PCM队列1214.56ms;同时间戳关闭补偿后0ms/10ms。真实WASAPI、合成PCM且增益0,不是实卡或声学测量。专项exit1保留失败,证明现有自动同步缺少时间戳可比性验证;未修改产品同步策略。
+
+构建`cmd.exe /c out\build\veyra-build-x64-release.cmd` exit0(2/2);诊断用`scripts/acceptance/scheduler-short-test.ps1 -Name capture-sync-clock-audit-20260915 -Exe out/build/audio-continuity-repair-20260915/veyra_capture_audio_tests.exe -TestArgs '--sync-clock-audit'`运行11.60秒。完整失败证据、现有1.5秒目标/2秒队列边界、修改文件和修复方案见[VRR音频同步排查](CAPTURE_VRR_AUDIO_SYNC_AUDIT_2026-09-15.md)。未执行RTX Create/Evaluate、物理VRR或听测,未改DLL/SDK,未发布。下一步是基于同帧入口/呈现时间验证同步时钟关系,并取得反馈者日志确认真实触发机制。
+
## 2026-09-14 采集卡内部 FG 时间线修复
用户反馈 RTX 4070 Ti 开启内部 FG、NR/SR 关闭后很快显示过载。排查确认物理采集的源 PTS 与主机回调时钟存在 59.94/60Hz 长期漂移;旧代码只在会话开始锚定一次,导致补帧截止时间累积落后数百毫秒,软件准入连续拒绝 FG,并非已证实的 GPU OOM 或 NR/SR 负载。已在 `codex/capture-fg-clock-repair-20260914` 分支修复:物理采集/PS5/live replay 按每个 A/B 对重新锚定,保留对内 FG 节奏;新增 `timeline=capture-pair` 诊断,UI 将“过载”改为“补帧受限”。
@@ -2144,3 +2150,25 @@ WASAPI输入使用共享模式事件采集,按 `IAudioCaptureClient::GetBuffer
- 旧 `test-audio-continuity.ps1` 12组音频专项此前已通过;本轮补充脚本中的WASAPI离线时钟项,未重复声学/GPU验收。
候选仍是本地 `out/build/audio-continuity-repair-20260915/veyra.exe`,未更新版本号、未修改运行组件、未push、未发布。WASAPI接入已具备本机候选证据,但反馈者设备的端点是否提供正确采集音频、以及火堆/口哨沙沙声是否改善,均未验收。
+
+## 2026-09-15 采集自动同步异常补偿修复
+
+用户授权修复采集自动同步可能累积数秒声音等待的问题。新增 `CaptureSyncTarget.h`,以同一原始视频帧的到达至呈现时间核对跨音视频时间戳;差异超过80ms时回退本机延迟估算,连续2秒恢复可信才退出回退。80ms是可信度策略,不是硬件实测;真实上游偏移可能需要手动校准。CaptureCardSource、WASAPI输入适配和EngineController传递匹配帧的到达时刻,排除生成/缓存帧;CaptureAudioSession记录原始、接受及回退目标,LiveStatusPanel显示异常回退。PS5无到达时刻的旧接口与文件音频保持原路径。
+
+专项测试另发现慢启动时原始PCM积压未纳入过期处理。修复在输出启动/重新对齐前转换有界待处理输入,让已有恢复策略清理过期声音;正常运行的填充策略保持。新增恢复丢弃计数及650ms慢启动注入。修复前合成慢启动P95偏差646.558ms、额外重置4次,修复后专测20.1321ms、额外重置/欠载0;移除启动时648.396ms过期PCM。最终16组套件中的慢启动P95为15.2911ms。时间戳单独偏移1200ms用例的目标从修复前1235.51ms降为35ms,软件队列从1214.56ms降为10ms;真实400/900ms本机处理等待仍保留。
+
+实际命令及结果:
+
+- `cmd.exe /c out\build\veyra-build-x64-release.cmd`:最终构建成功,增量4/4,RemotePlay ON及patched FFmpeg/dav1d保持;日志 `logs/capture-sync-repair-20260915/build-final.log`。中途测试引用未声明kAudioRate导致两次编译失败,改为测试固定48kHz下的24000帧阈值后通过。
+- `out/build/audio-continuity-repair-20260915/veyra_repair_contract_tests.exe`:123项,失败0;`logs/capture-sync-repair-20260915/contracts.log`。
+- `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/diagnostics/test-audio-continuity.ps1 -BuildDirectory out/build/audio-continuity-repair-20260915 -LogDirectory logs/capture-sync-repair-20260915/final`:16组全部exit0,含立体声/5.1、端点恢复、时间戳异常、慢启动、手动/关闭补偿及文件时间线;证据 `final/results.json`。
+- 上述命令增加 `-DriftOnly`:两组120秒全部exit0。1.001与0.999输入速度的P95偏差分别4.22906/4.23319ms,missing=0、resets=1(仅启动)、队列高水位89.6458ms;`final/drift-results.json`及对应stdout日志。
+- `scripts/run-short-test.ps1 -Exe out/build/audio-continuity-repair-20260915/veyra.exe -Arguments @('--smoke-empty','--smoke-seconds','2','--no-nr','--no-sr','--no-fg') -TimeoutSeconds 30 -LogPrefix logs/capture-sync-repair-20260915/gui-smoke`:空界面启动exit0,处理帧0,不代表媒体或增强验收。`git diff --check`通过;源码Git未跟踪DLL/LIB/EXE/模型/PYC。
+
+当前候选EXE为11,463,168字节,SHA256 `F060238E39311D9E2D3D8B8CB4EA50B0CBB6E4BD24E67BC10D90A249F417BACC`。构建目录仍为 `out/build/audio-continuity-repair-20260915/`;根目录旧启动器未调整。本轮未发布、未修改运行组件或版本号。完整方案、修改文件与证据见 `docs/CAPTURE_VRR_AUDIO_SYNC_AUDIT_2026-09-15.md`。
+
+测试使用合成采集时序与真实WASAPI静音输出,未执行反馈者实卡、VRR开关对照、声音录制或RTX Create/Evaluate/GPU delivery。软件缺陷有复现及修复证据,但不能认定VRR为反馈者根因。下一步唯一验收:反馈者同一采集卡/场景开启自动同步,对照VRR开关并提供新目标/队列日志。
+
+## 2026-09-15 用户集中反馈总修复方案
+
+用户汇总14项问题:采集卡选择记忆、播放器seek/流畅性、UI闪烁、采集断连重连、全屏控制、HDR/SDR发灰、NR内部处理分辨率、OBS resize回归、Dolby Vision、FG后端失败、XeSS计时、同步/增强冗余、40系过载、视频导出队列与BT.2020错误、PS5串流增强初始化失败。已建立 `docs/USER_ISSUES_REPAIR_PLAN_2026-09-15.md`,按“不可用恢复→颜色→交互→性能→导出→Dolby Vision”分批施工,记录每项证据、验收合同和未验证边界。本轮仅建立方案,未修改代码、未构建、未发布;后续按批次逐项更新实际结果,不能把方案文档当作修复完成证明。
diff --git a/include/veyra/sink/CaptureAudioSession.h b/include/veyra/sink/CaptureAudioSession.h
index 46cfe4f8..de00f050 100644
--- a/include/veyra/sink/CaptureAudioSession.h
+++ b/include/veyra/sink/CaptureAudioSession.h
@@ -13,6 +13,9 @@ struct CaptureAudioState {
uint32_t inputSampleRate=0;unsigned inputContainerBits=0,inputValidBits=0;bool inputFloating=false;
double compensationMs=0,bufferedMs=0,bufferHighWaterMs=0,endpointBufferedMs=0;
double driftCorrectionPpm=0;
+ uint64_t recoveryDiscardedFrames=0;
+ bool syncClockFallback=false;
+ double rawCompensationMs=0,localVideoDelayMs=0;
double inputBlockMs=0,inputIntervalMs=0;
double inputPeak=0; // Historical API name: peak AFTER sample conversion.
uint64_t inputBlocks=0;
@@ -31,7 +34,9 @@ public:
bool start();
void stop();
bool push(const void* data,size_t bytes,double ptsMs,bool discontinuity);
- void videoPresented(double ptsMs,int64_t host100ns);
+ // Arrival is the matching original capture frame, not the latest callback.
+ // Omit only for sources with their own existing timestamp contract (PS5).
+ void videoPresented(double ptsMs,int64_t host100ns,std::optional<int64_t> arrival100ns={});
// Invalidate software presentation. A video graph rebuild can preserve
// the audio clock; callers that are actually pausing the transport may
// request the old audio reset explicitly.
diff --git a/include/veyra/sink/CaptureSyncTarget.h b/include/veyra/sink/CaptureSyncTarget.h
new file mode 100644
index 00000000..4a2d05f4
--- /dev/null
+++ b/include/veyra/sink/CaptureSyncTarget.h
@@ -0,0 +1,46 @@
+#pragma once
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <optional>
+
+namespace veyra::sink {
+// Capture callbacks and presentation use the same host clock. Cross-stream
+// PTS may include a small hardware offset, but are not trusted without bounds.
+class CaptureSyncTarget {
+public:
+ struct Result {double targetMs=0,rawMs=0,localMs=0;bool fallback=false,limited=false;};
+ void reset(){*this={};}
+ void invalidate(){count_=cursor_=0;recoverySince_.reset();}
+ Result observe(double rawMs,double hostMs,std::optional<double> arrivalMs){
+ if(!arrivalMs){reset();return {std::isfinite(rawMs)?rawMs:0,rawMs,0,false};}
+ const bool valid=std::isfinite(hostMs)&&std::isfinite(*arrivalMs)&&*arrivalMs>0&&*arrivalMs<=hostMs;
+ const double local=valid?hostMs-*arrivalMs:lastLocal_;
+ // 80 ms is a confidence bound, not measured hardware latency. Larger
+ // upstream A/V offsets require manual calibration, not blind waiting.
+ const double residual=rawMs-local;
+ const bool inconsistent=!valid||!std::isfinite(rawMs)||std::abs(residual)>80;
+ if(inconsistent){fallback_=true;recoverySince_.reset();}
+ else if(fallback_){
+ if(std::abs(residual)<=40){
+ if(!recoverySince_)recoverySince_=hostMs;
+ if(hostMs-*recoverySince_>=2000){fallback_=false;recoverySince_.reset();}
+ }else recoverySince_.reset();
+ }
+ if(valid)lastLocal_=local;
+ const double requested=fallback_?local:rawMs;
+ const double candidate=std::clamp(requested,0.0,1500.0);
+ // Filter actual video observations, never repeated audio-thread polls.
+ samples_[cursor_]=candidate;cursor_=(cursor_+1)%samples_.size();
+ count_=std::min(count_+1,samples_.size());
+ auto sorted=samples_;std::sort(sorted.begin(),sorted.begin()+count_);
+ return {sorted[count_/2],rawMs,valid?local:-1,fallback_,requested<0||requested>1500};
+ }
+private:
+ std::array<double,5> samples_{};
+ size_t count_=0,cursor_=0;
+ double lastLocal_=0;
+ bool fallback_=false;
+ std::optional<double> recoverySince_;
+};
+}
diff --git a/include/veyra/source/CaptureCardSource.h b/include/veyra/source/CaptureCardSource.h
index 06e51d1a..19bebd75 100644
--- a/include/veyra/source/CaptureCardSource.h
+++ b/include/veyra/source/CaptureCardSource.h
@@ -39,7 +39,7 @@ public:
bool start();
bool setAudioGain(float); // call on the graph owner thread; never system volume
CaptureMetrics metrics()const;
- void videoPresented(double ptsMs,int64_t host100ns);
+ void videoPresented(double ptsMs,int64_t host100ns,int64_t arrival100ns);
void videoReset(bool resetAudio=true);
void setAudioSync(unsigned mode,int offsetMs);
sink::CaptureAudioState audioState()const;
diff --git a/include/veyra/source/WasapiAudioInput.h b/include/veyra/source/WasapiAudioInput.h
index 3ad43863..cc91e55f 100644
--- a/include/veyra/source/WasapiAudioInput.h
+++ b/include/veyra/source/WasapiAudioInput.h
@@ -36,7 +36,7 @@ public:
bool configure(std::wstring endpointId);
bool start();void stop();
void setGain(float);void setSync(unsigned,int);
- void videoPresented(double hostAxisPtsMs,int64_t host100ns);
+ void videoPresented(double hostAxisPtsMs,int64_t host100ns,std::optional<int64_t> arrival100ns={});
void videoReset(bool resetAudio);
sink::CaptureAudioState snapshot()const;
WasapiInputMetrics metrics()const;
diff --git a/scripts/diagnostics/test-audio-continuity.ps1 b/scripts/diagnostics/test-audio-continuity.ps1
index 2374100e..91889046 100644
--- a/scripts/diagnostics/test-audio-continuity.ps1
+++ b/scripts/diagnostics/test-audio-continuity.ps1
@@ -14,7 +14,10 @@ $cases=@(
@{Name='queued-empty-pull';Exe='veyra_audio_waveform_tests.exe';Args=@('--endpoint');Seconds=30},
@{Name='true-endpoint-gap';Exe='veyra_audio_waveform_tests.exe';Args=@('--endpoint-gap');Seconds=30},
@{Name='capture-baseline';Exe='veyra_capture_audio_tests.exe';Args=@('--baseline');Seconds=90},
+ @{Name='capture-clock-audit';Exe='veyra_capture_audio_tests.exe';Args=@('--sync-clock-audit');Seconds=30},
+ @{Name='legacy-clock';Exe='veyra_capture_audio_tests.exe';Args=@('--legacy-clock');Seconds=90},
@{Name='jitter-stereo';Exe='veyra_capture_audio_tests.exe';Args=@('--jitter');Seconds=30},
+ @{Name='slow-start';Exe='veyra_capture_audio_tests.exe';Args=@('--slow-start');Seconds=30},
@{Name='jitter-51';Exe='veyra_capture_audio_tests.exe';Args=@('--jitter','--5.1');Seconds=30},
@{Name='transient';Exe='veyra_capture_audio_tests.exe';Args=@('--transient');Seconds=30},
@{Name='transient-comp';Exe='veyra_capture_audio_tests.exe';Args=@('--transient-comp');Seconds=30},
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index ae2d4e25..0e1c9274 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -827,7 +827,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
veyra::log::info("xess-fg-gate",std::format("event={} revision={} lateMs={:.3f}",xessGenerationGate.suppressed()?"suppress":"resume",item.identity.settingsRevision,nowMs()-itemPtsMs));
}
}
- if(didPresent&&physicalCapture)captureSource.videoPresented(double(item.pts100ns)/10000,host100ns());
+ // Real B owns captureArrival. Generated A/B frames and
+ // paused cached frames must not invent input anchors.
+ if(didPresent&&physicalCapture&&!generated&&!rereadCached)captureSource.videoPresented(double(item.pts100ns)/10000,host100ns(),captureArrival);
#ifdef VEYRA_ENABLE_REMOTEPLAY
if(didPresent&&remote)remote->videoPresented(double(item.pts100ns)/10000,host100ns());
#endif
diff --git a/src/sink/CaptureAudioSession.cpp b/src/sink/CaptureAudioSession.cpp
index bfed74c9..302a74ed 100644
--- a/src/sink/CaptureAudioSession.cpp
+++ b/src/sink/CaptureAudioSession.cpp
@@ -2,6 +2,7 @@
#include "veyra/sink/WasapiAudioSink.h"
#include "veyra/sink/ArrivalClockMapping.h"
#include "veyra/sink/CaptureAudioDsp.h"
+#include "veyra/sink/CaptureSyncTarget.h"
#include <algorithm>
#include <cmath>
#include <cstring>
@@ -32,6 +33,8 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
std::atomic<float> gain{1};
std::atomic<unsigned> mode{0};std::atomic<int> offset{0};
double videoPts=0,videoHost=0;bool haveVideo=false;
+ std::optional<int64_t> videoArrival;
+ uint64_t videoObservation=0;
double ingressMapping=0;bool haveIngress=false;
ArrivalClockMapping ingressClock;
int64_t lastArrival=0;
@@ -62,6 +65,8 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
AudioRenderer renderer;
bool endpointReady=false;int64_t retryAt=0;
const bool injectEndpointLoss=GetEnvironmentVariableW(L"VEYRA_TEST_CAPTURE_AUDIO_ENDPOINT_LOSS",nullptr,0)>0;
+ const bool injectSlowStart=GetEnvironmentVariableW(L"VEYRA_TEST_CAPTURE_AUDIO_SLOW_START",nullptr,0)>0;
+ bool startupDelayed=false;
bool injected=false;uint64_t endpointPumps=0;
SwrContext* swr=nullptr;
const auto inputFormat=floating?AV_SAMPLE_FMT_FLT:format.wBitsPerSample==16?AV_SAMPLE_FMT_S16:AV_SAMPLE_FMT_S32;
@@ -85,6 +90,9 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
int64_t nextSyncLog=0;
int64_t nextPeakLog=0;
unsigned appliedMode=mode.load();int appliedOffset=offset.load();
+ CaptureSyncTarget syncTarget;
+ CaptureSyncTarget::Result syncEstimate;
+ uint64_t lastVideoObservation=0;
uint64_t lastUnderruns=0;
uint64_t lastUnderrunFrames=0,lastSilenceFrames=0;
uint64_t lastEmptyPulls=0;
@@ -111,6 +119,11 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
const auto time=hostTime();
if(time<retryAt){std::unique_lock lock(mutex);wake.wait_for(lock,std::chrono::milliseconds(20),[&]{return stop.load();});continue;}
{std::lock_guard lock(mutex);++state.endpointRetries;}
+ if(injectSlowStart&&!startupDelayed){
+ startupDelayed=true;log::info("capture-audio-test","delay owned endpoint startup by 650 ms");
+ std::unique_lock lock(mutex);wake.wait_for(lock,std::chrono::milliseconds(650),[&]{return stop.load();});
+ if(stop)break;
+ }
if(!renderer.start(layout,20.0)){if(!recoverEndpoint())break;continue;}
endpointReady=true;lastUnderruns=renderer.underruns();
lastUnderrunFrames=renderer.underrunFrames();lastSilenceFrames=renderer.silenceFrames();starvationSince=0;
@@ -121,11 +134,13 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
// endpoint wait is available for this fill instead of padded silence.
if(renderer.started()&&!endpointEventReady){if(!renderer.waitForEvent()){if(!recoverEndpoint())break;continue;}endpointEventReady=true;}
Chunk chunk;bool reset=false,syncChanged=false;double vPts=0,vHost=0,ingress=0;bool video=false;int64_t arrival=0;
+ std::optional<int64_t> vArrival;uint64_t observation=0;
{
std::unique_lock lock(mutex);
if(input.empty())wake.wait_for(lock,std::chrono::milliseconds(2));
if(!input.empty()){chunk=std::move(input.front());input.pop_front();inputBytes-=chunk.bytes.size();convertingBytes=chunk.bytes.size();}
reset=pendingReset;pendingReset=false;video=haveVideo;vPts=videoPts;vHost=videoHost;
+ vArrival=videoArrival;observation=videoObservation;
ingress=ingressMapping;
arrival=lastArrival;
}
@@ -135,6 +150,7 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
}
if(syncChanged&&!clearCorrection()){fail(L"音频同步补偿重置失败");break;}
if(reset||chunk.discontinuity){
+ syncTarget.reset();syncEstimate={};lastVideoObservation=0;
renderer.fadeAndReset(*this,stop);clearPcm();swr_close(swr);
if(swr_init(swr)<0){fail(L"音频重采样重置失败");break;}
const int prepared=rateCorrection.prepare(swr,appliedMode==0);
@@ -220,17 +236,27 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
std::lock_guard lock(mutex);
// Drain callback blocks already available before waiting for
// another endpoint event; otherwise silence can build a backlog.
- if(!input.empty()&&1000.0*(pcm.size()/layout.channels)/kAudioRate<renderer.capacityMs()+10)continue;
+ // Before (re)anchoring, include the whole bounded input backlog
+ // so expiry below can remove old sound after a slow device open.
+ if(!input.empty()&&(!renderer.started()||1000.0*(pcm.size()/layout.channels)/kAudioRate<renderer.capacityMs()+10))continue;
}
// Both streams use graph PTS. Relate the latest displayed video PTS
// to host time; the endpoint's own queued frames are not added again.
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 bool fresh=video&&now>=vHost&&now-vHost<500;
+ if(appliedMode==0&&fresh&&observation!=lastVideoObservation){
+ const bool previousFallback=syncEstimate.fallback;
+ syncEstimate=syncTarget.observe(vHost-vPts-ingress,vHost,vArrival?std::optional<double>(double(*vArrival)/10000):std::nullopt);
+ lastVideoObservation=observation;
+ if(previousFallback!=syncEstimate.fallback)
+ log::warn("capture-audio-clock",std::format("fallback={} rawMs={:.3f} localVideoMs={:.3f} acceptedMs={:.3f} basis=matched-original-arrival hardwareOffsetUnmeasured=1",syncEstimate.fallback,syncEstimate.rawMs,syncEstimate.localMs,syncEstimate.targetMs));
+ }
+ if(!fresh)syncTarget.invalidate();
+ const double requested=appliedMode==0?syncEstimate.targetMs:appliedMode==1?double(appliedOffset):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>maxDelay;
+ const bool limited=requested<0||requested>maxDelay||(appliedMode==0&&syncEstimate.limited);
// A temporary video rebuild must not stop a healthy capture audio
// clock. The next presented video sample will refresh the
// mapping; a real PCM discontinuity is handled above instead.
@@ -247,7 +273,8 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
// an obsolete half-second after a GPU stall or graph reset.
const size_t prefill=size_t(std::ceil(startupPrefillMs*kAudioRate/1000));
const size_t expired=std::min(pcm.size()/layout.channels-prefill,size_t(std::max(0.0,(now-mapping-headPts-5)*kAudioRate/1000)));
- {std::lock_guard lock(mutex);discardPcm(expired);}
+ {std::lock_guard lock(mutex);discardPcm(expired);state.recoveryDiscardedFrames+=expired;}
+ if(expired)log::info("capture-audio-reanchor",std::format("expiredFrames={} expiredMs={:.3f} targetMs={:.3f} reason=startup-or-recovery",expired,1000.0*expired/kAudioRate,target));
const bool due=now>=mapping+headPts;
if(due&&!pcm.empty()){
if(!renderer.startAnchored(*this)){if(!recoverEndpoint())break;continue;}
@@ -317,15 +344,18 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
std::lock_guard lock(mutex);state.available=true;state.running=renderer.started();state.limited=limited;
queueChanged();
state.compensationMs=target;state.underruns=renderer.underruns();
+ state.syncClockFallback=appliedMode==0&&syncEstimate.fallback;
+ state.rawCompensationMs=syncEstimate.rawMs;state.localVideoDelayMs=syncEstimate.localMs;
state.underrunFrames=renderer.underrunFrames();state.silenceFrames=renderer.silenceFrames();
state.emptyPulls=renderer.emptyPulls();state.recoveryFades=renderer.recoveryFades();
state.clockStalledGaps=renderer.clockStalledGaps();
state.endpointBufferedMs=renderer.bufferedMs();
const auto audioPts=renderer.mediaTimeMs();
const double observedNow=double(hostTime())/10000;
- state.skewMs=fresh&&std::isfinite(audioPts)?std::optional<double>(audioPts-(vPts+observedNow-vHost)):std::nullopt;
+ state.skewMs=fresh&&std::isfinite(audioPts)?std::optional<double>(audioPts-(state.syncClockFallback?observedNow-mapping:vPts+observedNow-vHost)):std::nullopt;
if(hostTime()>=nextSyncLog){
nextSyncLog=hostTime()+20000000;
+ if(vArrival)log::info("capture-audio-target",std::format("mode={} rawMs={:.3f} localVideoMs={:.3f} acceptedMs={:.3f} fallback={} fresh={} rawSkewMs={:.3f} presentation=original inputArrival100ns={}",appliedMode,syncEstimate.rawMs,syncEstimate.localMs,target,state.syncClockFallback,fresh,fresh&&std::isfinite(audioPts)?audioPts-(vPts+observedNow-vHost):-999,*vArrival));
log::info("live-audio-sync",std::format("videoPtsMs={:.3f} videoHostMs={:.3f} audioIngressMapMs={:.3f} compensationMs={:.3f} pcmMs={:.3f} endpointMs={:.3f} skewMs={:.3f} correctionPpm={:.1f} resets={} underruns={} underrunFrames={} silenceFrames={} emptyPulls={} recoveryFades={} inputBlockMs={:.3f} inputIntervalMs={:.3f} inputBlocks={} format={}Hz/{}bit validBits={} convertedPeak={:.5f} overRange={} clipped={} (local clock alignment, not GPU execution time)",vPts,vHost,ingress,target,state.bufferedMs,state.endpointBufferedMs,state.skewMs.value_or(-999),state.driftCorrectionPpm,state.resets,state.underruns,state.underrunFrames,state.silenceFrames,state.emptyPulls,state.recoveryFades,state.inputBlockMs,state.inputIntervalMs,state.inputBlocks,state.inputSampleRate,state.inputContainerBits,state.inputValidBits,state.inputPeak,state.overRangeSamples,state.clippedSamples));
}
}
@@ -382,7 +412,7 @@ bool CaptureAudioSession::push(const void* data,size_t bytes,double pts,bool dis
Impl::Chunk c;c.bytes.resize(bytes);memcpy(c.bytes.data(),data,bytes);c.pts=pts;c.discontinuity=discontinuity;
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::videoPresented(double pts,int64_t time,std::optional<int64_t> arrival){std::lock_guard lock(p_->mutex);p_->videoPts=pts;p_->videoHost=double(time)/10000;p_->videoArrival=arrival;++p_->videoObservation;p_->haveVideo=true;}
void CaptureAudioSession::videoReset(bool resetAudio){std::lock_guard lock(p_->mutex);p_->haveVideo=false;if(resetAudio&&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);}
diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cpp
index 3b5a3bff..ebef603e 100644
--- a/src/source/CaptureCardSource.cpp
+++ b/src/source/CaptureCardSource.cpp
@@ -1,6 +1,5 @@
#include "veyra/source/CaptureCardSource.h"
#include "veyra/source/WasapiAudioInput.h"
-#include "veyra/sink/ArrivalClockMapping.h"
#include "veyra/source/CaptureTiming.h"
#include "veyra/source/CaptureMediaType.h"
#include "veyra/source/NativeCaptureSink.h"
@@ -127,7 +126,6 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
ComPtr<IBaseFilter> audioSink;ComPtr<IReferenceClock> referenceClock;
std::unique_ptr<sink::CaptureAudioSession> audioSession;
std::unique_ptr<WasapiAudioInput> wasapi;
- sink::ArrivalClockMapping videoIngressClock;double videoIngressMs=0;bool haveVideoIngress=false;
std::wstring audioError;
SourceInfo info;CaptureMediaLayout layout;Clock::time_point lastFrame;
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** pp)override{if(!pp)return E_POINTER;*pp=nullptr;if(id==IID_IUnknown||id==__uuidof(ISampleGrabberCB)){*pp=static_cast<ISampleGrabberCB*>(this);AddRef();return S_OK;}return E_NOINTERFACE;}
@@ -151,11 +149,6 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
pendingDiscontinuity=captureDiscontinuity(pending,pendingDiscontinuity,
sample->IsDiscontinuity()==S_OK,received>0,pendingTime,time,info.averageFps);
pending=true;pendingTime=time;pendingArrival=arrival;
- if(wasapi){
- if(sample->IsDiscontinuity()==S_OK)videoIngressClock.reset();
- videoIngressMs=videoIngressClock.observe(std::chrono::duration<double,std::milli>(arrival.time_since_epoch()).count(),time*1000);
- haveVideoIngress=true;
- }
pendingDuration=captureDuration(sampleStart,sampleEnd,sampleTime,nominalDuration100ns);
if(!received)firstArrival=arrival;
++received;latestArrival=arrival;
@@ -219,9 +212,9 @@ bool CaptureCardSource::setAudioGain(float gain){
if(SUCCEEDED(hr)){long attenuation=gain<=0?-10000:long(std::clamp(2000.0*std::log10(double(gain)),-10000.0,0.0));hr=audio->put_Volume(attenuation);}
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_->wasapi){double mapping=0;{std::lock_guard lock(p_->mutex);if(!p_->haveVideoIngress)return;mapping=p_->videoIngressMs;}p_->wasapi->videoPresented(pts+mapping,time);}
- else if(p_->audioSession)p_->audioSession->videoPresented(pts,time);
+void CaptureCardSource::videoPresented(double pts,int64_t time,int64_t arrival){
+ if(p_->wasapi)p_->wasapi->videoPresented(double(arrival)/10000,time,arrival);
+ else if(p_->audioSession)p_->audioSession->videoPresented(pts,time,arrival);
}
void CaptureCardSource::videoReset(bool resetAudio){if(p_->wasapi)p_->wasapi->videoReset(resetAudio);else if(p_->audioSession)p_->audioSession->videoReset(resetAudio);}
void CaptureCardSource::setAudioSync(unsigned mode,int offset){if(p_->wasapi)p_->wasapi->setSync(mode,offset);else if(p_->audioSession)p_->audioSession->setSync(mode,offset);}
@@ -406,7 +399,7 @@ SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,c
}
void CaptureCardSource::close()noexcept{
auto& p=*p_;if(p.control)p.control->Stop();if(p.grab)p.grab->SetCallback(nullptr,0);
- if(p.wasapi)p.wasapi->stop();p.wasapi.reset();p.videoIngressClock.reset();p.haveVideoIngress=false;p.videoIngressMs=0;
+ if(p.wasapi)p.wasapi->stop();p.wasapi.reset();
if(p.audioSession)p.audioSession->stop();p.audioError.clear();
p.events.Reset();p.control.Reset();p.grab.Reset();p.nullFilter.Reset();p.grabFilter.Reset();p.audioSink.Reset();p.audioFilter.Reset();p.config.Reset();p.device.Reset();p.builder.Reset();p.graph.Reset();p.referenceClock.Reset();p.audioSession.reset();
av_frame_free(&p.frame);av_frame_free(&p.pendingFrame);p.info={};
diff --git a/src/source/WasapiAudioInput.cpp b/src/source/WasapiAudioInput.cpp
index ac4f3ec2..9cb7073d 100644
--- a/src/source/WasapiAudioInput.cpp
+++ b/src/source/WasapiAudioInput.cpp
@@ -44,6 +44,7 @@ struct WasapiAudioInput::Impl {
mutable std::mutex mutex;std::unique_ptr<sink::CaptureAudioSession> session;
std::wstring id,error;std::thread worker;Handle stopEvent;std::atomic<bool> stopping{true};
float gain=1;unsigned mode=0;int offset=0;double videoPts=0;int64_t videoHost=0;bool haveVideo=false;
+ std::optional<int64_t> videoArrival;
WasapiInputMetrics metrics;bool injectedLoss=false;
HRESULT stream(){
ComPtr<IMMDeviceEnumerator> enumerator;ComPtr<IMMDevice> device;ComPtr<IMMEndpoint> endpoint;
@@ -80,7 +81,7 @@ struct WasapiAudioInput::Impl {
if(!session->configure(format)){session.reset();return AUDCLNT_E_UNSUPPORTED_FORMAT;}
session->setGain(gain);session->setSync(mode,offset);
if(!session->start()){session.reset();return E_FAIL;}
- if(haveVideo)session->videoPresented(videoPts,videoHost);
+ if(haveVideo)session->videoPresented(videoPts,videoHost,videoArrival);
}
hr=client->Start();if(!checked(hr,"Start capture"))return hr;
struct StopClient {IAudioClient* client;~StopClient(){checked(client->Stop(),"Stop capture");}} stopClient{client.Get()};
@@ -149,7 +150,7 @@ bool WasapiAudioInput::start(){
void WasapiAudioInput::stop(){p_->stopping=true;if(p_->stopEvent.value)SetEvent(p_->stopEvent.value);if(p_->worker.joinable())p_->worker.join();}
void WasapiAudioInput::setGain(float value){std::lock_guard lock(p_->mutex);p_->gain=std::clamp(value,0.f,1.f);if(p_->session)p_->session->setGain(p_->gain);}
void WasapiAudioInput::setSync(unsigned mode,int offset){std::lock_guard lock(p_->mutex);p_->mode=std::min(mode,2u);p_->offset=std::clamp(offset,-250,250);if(p_->session)p_->session->setSync(p_->mode,p_->offset);}
-void WasapiAudioInput::videoPresented(double pts,int64_t host){std::lock_guard lock(p_->mutex);p_->haveVideo=true;p_->videoPts=pts;p_->videoHost=host;if(p_->session)p_->session->videoPresented(pts,host);}
+void WasapiAudioInput::videoPresented(double pts,int64_t host,std::optional<int64_t> arrival){std::lock_guard lock(p_->mutex);p_->haveVideo=true;p_->videoPts=pts;p_->videoHost=host;p_->videoArrival=arrival;if(p_->session)p_->session->videoPresented(pts,host,arrival);}
void WasapiAudioInput::videoReset(bool resetAudio){std::lock_guard lock(p_->mutex);p_->haveVideo=false;if(p_->session)p_->session->videoReset(resetAudio);}
sink::CaptureAudioState WasapiAudioInput::snapshot()const{std::lock_guard lock(p_->mutex);auto state=p_->session?p_->session->snapshot():sink::CaptureAudioState{};if(!p_->error.empty())state.error=p_->error;return state;}
WasapiInputMetrics WasapiAudioInput::metrics()const{std::lock_guard lock(p_->mutex);return p_->metrics;}
diff --git a/tests/integration/CaptureAudioTests.cpp b/tests/integration/CaptureAudioTests.cpp
index ceffb4b1..f7230b0e 100644
--- a/tests/integration/CaptureAudioTests.cpp
+++ b/tests/integration/CaptureAudioTests.cpp
@@ -21,12 +21,14 @@ 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 slowStart=argc>=2&&std::string_view(argv[1])=="--slow-start";
+ const bool jitterTest=slowStart||(argc>=2&&std::string_view(argv[1])=="--jitter");
const bool transientTest=argc>=2&&std::string_view(argv[1])=="--transient";
const bool compensatedTransientTest=argc>=2&&std::string_view(argv[1])=="--transient-comp";
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");
+ if(slowStart)SetEnvironmentVariableW(L"VEYRA_TEST_CAPTURE_AUDIO_SLOW_START",L"1");
const bool multichannel=argc>=3&&std::string_view(argv[2])=="--5.1";
CaptureAudioSession audio;WAVEFORMATEX f{};f.wFormatTag=WAVE_FORMAT_PCM;f.nChannels=2;f.nSamplesPerSec=transientTest?44100:48000;f.wBitsPerSample=16;f.nBlockAlign=4;f.nAvgBytesPerSec=f.nSamplesPerSec*f.nBlockAlign;
auto extended=floatWave({6,0x60f});extended.SubFormat=KSDATAFORMAT_SUBTYPE_PCM;extended.Format.wBitsPerSample=16;extended.Samples.wValidBitsPerSample=16;extended.Format.nBlockAlign=12;extended.Format.nAvgBytesPerSec=576000;
@@ -34,6 +36,48 @@ int main(int argc,char** argv){
const unsigned channels=multichannel?6:2;std::vector<int16_t> pcm(480*channels);
for(size_t i=0;i<pcm.size()/channels;++i)for(unsigned c=0;c<channels;++c)pcm[i*channels+c]=int16_t(2000*std::sin((i*channels+c)*0.031));
const auto start=Clock::now();
+ const bool legacyClock=argc>=2&&std::string_view(argv[1])=="--legacy-clock";
+ auto present=[&](double pts,int64_t host,double localDelay){
+ audio.videoPresented(pts,host,legacyClock?std::nullopt:std::optional<int64_t>(host-int64_t(localDelay*10000)));
+ };
+ if(argc>=2&&std::string_view(argv[1])=="--sync-clock-audit"){
+ // Synthetic source timestamps with real, muted WASAPI output. A PTS
+ // origin change must not be mistaken for extra video processing time.
+ unsigned sequence=0;
+ auto phase=[&](const char* name,unsigned mode,double videoOffset,unsigned blocks){
+ audio.setSync(mode,0);
+ unsigned nextVideo=sequence;
+ double maxCompensation=0,maxQueue=0;unsigned observations=0;
+ for(unsigned j=0;j<blocks;++j,++sequence){
+ pacer.until(start+std::chrono::milliseconds(sequence*10));
+ if(!audio.push(pcm.data(),pcm.size()*2,sequence*10.0,sequence==0))return false;
+ const auto host=std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;
+ if(sequence>=nextVideo){
+ audio.videoPresented(sequence*10.0-35-videoOffset,host,host-350000);
+ nextVideo=sequence+1+(sequence%3);
+ }
+ if(j+100>=blocks){
+ const auto s=audio.snapshot();
+ maxCompensation=std::max(maxCompensation,s.compensationMs);
+ maxQueue=std::max(maxQueue,s.bufferedMs);
+ if(s.running)++observations;
+ }
+ }
+ const auto s=audio.snapshot();
+ const bool pass=observations>=80&&maxCompensation<100&&maxQueue<200;
+ std::cout<<(pass?"PASS ":"FAIL ")<<name<<" videoPtsOffsetMs="<<videoOffset
+ <<" actualVideoDelayMs=35 maxCompensationMs="<<maxCompensation
+ <<" maxQueuedMs="<<maxQueue<<" runningSamples="<<observations
+ <<" resets="<<s.resets<<" overflows="<<s.overflows<<std::endl;
+ return pass;
+ };
+ const bool jitter=phase("aligned_variable_cadence",0,0,400);
+ const bool offset=phase("video_timestamp_offset",0,1200,500);
+ const bool off=phase("same_offset_compensation_off",2,1200,250);
+ audio.stop();
+ std::cout<<"Synthetic clock-axis audit only; not physical VRR or acoustic measurement.\n";
+ return jitter&&offset&&off?0:1;
+ }
if(transientTest){
const size_t frames=441;std::vector<int16_t> block(frames*2);
for(unsigned blockIndex=0;blockIndex<30;++blockIndex){
@@ -54,7 +98,7 @@ int main(int argc,char** argv){
std::fill(block.begin(),block.end(),blockIndex>=300&&blockIndex<310?int16_t(32767):int16_t(0));
if(!audio.push(block.data(),block.size()*sizeof(int16_t),blockIndex*10.0,blockIndex==0))return 11;
const auto host=std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;
- audio.videoPresented(blockIndex*10.0-80,host);
+ present(blockIndex*10.0-80,host,80);
}
std::this_thread::sleep_for(std::chrono::milliseconds(150));
const auto state=audio.snapshot();audio.stop();
@@ -70,7 +114,7 @@ int main(int argc,char** argv){
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);
+ if(i>=4&&i%3==0)present(i*10.0-((i/3)%2?30:35),now,(i/3)%2?30:35);
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;}
@@ -78,7 +122,7 @@ int main(int argc,char** argv){
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 inputTelemetry=s.inputBlocks==500&&std::abs(s.inputBlockMs-10)<.001&&s.inputIntervalMs>=0&&s.inputIntervalMs<100&&s.inputPeak>.01&&s.nonFiniteSamples==0&&s.clippedSamples==0;
- const bool pass=inputTelemetry&&missing==0&&s.resets==settledResets&&s.underruns==settledUnderruns&&s.overflows==0&&p95<35;
+ const bool pass=inputTelemetry&&missing==0&&s.resets==settledResets&&s.underruns==settledUnderruns&&s.overflows==0&&p95<35&&(!slowStart||s.recoveryDiscardedFrames>24000);
std::cout<<(pass?"PASS ":"FAIL ")<<"CAPTURE_JITTER additionalResets="<<s.resets-settledResets<<" additionalUnderruns="<<s.underruns-settledUnderruns<<" missing="<<missing<<" p95SkewMs="<<p95<<" inputBlocks="<<s.inputBlocks<<" inputBlockMs="<<s.inputBlockMs<<" inputIntervalMs="<<s.inputIntervalMs<<" peak="<<s.inputPeak<<" nonFinite="<<s.nonFiniteSamples<<" clipped="<<s.clippedSamples<<'\n';
return pass?0:1;
}
@@ -89,7 +133,7 @@ int main(int argc,char** argv){
pacer.until(start+std::chrono::microseconds(int64_t(i*10000/speed)));
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,i*10.0,i==0))return 6;
- if(i>=8)audio.videoPresented(i*10.0-80,host);
+ if(i>=8)present(i*10.0-80,host,80);
const auto s=audio.snapshot();if(i>1000){if(s.running&&s.skewMs)errors.push_back(std::abs(*s.skewMs));else ++missing;}
if(i&&i%2000==0)std::cout<<"DRIFT seconds="<<i/100<<" skewMs="<<s.skewMs.value_or(-999)<<" resets="<<s.resets<<" queueMs="<<s.bufferedMs<<" correctionPpm="<<s.driftCorrectionPpm<<std::endl;
}
@@ -103,7 +147,7 @@ int main(int argc,char** argv){
const auto due=start+std::chrono::milliseconds(i*10);pacer.until(due);
const auto time=std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;
if(!audio.push(pcm.data(),pcm.size()*2,i*10.0,i==0))return 3;
- if(i>=8)audio.videoPresented(i*10.0-80,time);
+ if(i>=8)present(i*10.0-80,time,80);
const auto s=audio.snapshot();bounded&=s.bufferedMs<=520;
sawReconnecting|=!s.error.empty();
if(i>(endpointTest?240u:70u)&&s.running&&s.skewMs){sum+=std::abs(*s.skewMs);++count;}
@@ -121,7 +165,7 @@ int main(int argc,char** argv){
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-commonInputMs,j==0&&commonInputMs!=0))return false;
- audio.videoPresented(sequence*10.0-commonInputMs-delay,host);const auto s=audio.snapshot();
+ present(sequence*10.0-commonInputMs-delay,host,delay);const auto s=audio.snapshot();
boundedPhase&=s.bufferedMs<=2000;
if(j>steps-80&&s.running&&s.skewMs){error+=std::abs(*s.skewMs-expectedSkew);++samples;}
}
diff --git a/tests/integration/CaptureSourceTests.cpp b/tests/integration/CaptureSourceTests.cpp
index 30da088a..5cca1721 100644
--- a/tests/integration/CaptureSourceTests.cpp
+++ b/tests/integration/CaptureSourceTests.cpp
@@ -44,7 +44,7 @@ int wmain(int argc,wchar_t** argv){
source.setAudioSync(wasapiTest?0:2,0);
const AVFrame* frame=nullptr;veyra::pipeline::FramePacket packet;
auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(2);
- auto readFrame=[&](){while(std::chrono::steady_clock::now()<deadline){auto r=source.read(packet,&frame);if(r==veyra::source::SourceReadStatus::Frame){if(wasapiTest)source.videoPresented(packet.pts.toDouble()*1000,std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count()/100);return true;}if(r==veyra::source::SourceReadStatus::Error)return false;}return false;};
+ auto readFrame=[&](){while(std::chrono::steady_clock::now()<deadline){auto r=source.read(packet,&frame);if(r==veyra::source::SourceReadStatus::Frame){if(wasapiTest)source.videoPresented(packet.pts.toDouble()*1000,std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count()/100,packet.arrivalHost100ns);return true;}if(r==veyra::source::SourceReadStatus::Error)return false;}return false;};
if(!readFrame()){printf("FAIL first frame\n");return 5;}
const auto initialPts=packet.pts.toDouble();const auto initialReceived=source.metrics().received;
const int rowBytes=av_image_get_linesize(AVPixelFormat(frame->format),frame->width,0);
diff --git a/tests/unit/RepairContractTests.cpp b/tests/unit/RepairContractTests.cpp
index 2633c999..9a0a85a0 100644
--- a/tests/unit/RepairContractTests.cpp
+++ b/tests/unit/RepairContractTests.cpp
@@ -18,6 +18,7 @@
#include "veyra/Log.h"
#include "veyra/sink/AudioFrameTimeline.h"
#include "veyra/sink/ArrivalClockMapping.h"
+#include "veyra/sink/CaptureSyncTarget.h"
int main(){
using namespace veyra;int failures=0,checks=0;
auto check=[&](bool ok,const char* name){++checks;if(!ok)++failures;std::cout<<(ok?"PASS ":"FAIL ")<<name<<'\n';};
@@ -40,6 +41,41 @@ int main(){
for(int i=0;i<60000;++i)mapping=ingressClock.observe(1000+i*10.01+(i%13==5?4:0),i*10.0);
check(std::abs(mapping-(1000+59999*.01))<2.1,"ten-minute audio ingress mapping ages oscillator drift instead of retaining startup minimum");
ingressClock.reset();check(ingressClock.observe(100,0)==100,"audio discontinuity replaces prior ingress mapping");
+ {
+ sink::CaptureSyncTarget sync;bool valid=true;
+ for(int i=0;i<300;++i){
+ const double host=10000+i*17+(i%3)*3,delay=30+(i%2)*5;
+ const auto r=sync.observe(delay,host,host-delay);
+ valid&=!r.fallback&&r.targetMs>=30&&r.targetMs<=35;
+ }
+ check(valid,"capture sync accepts variable cadence with consistent clocks");
+ auto r=sync.observe(1235,16000,15965);
+ check(r.fallback&&r.targetMs<=35,"capture timestamp jump cannot create a second of audio waiting");
+ sync.invalidate();r=sync.observe(935,16020,15985);
+ check(r.fallback&&r.targetMs==35,"video history reset retains clock fallback");
+ for(int i=0;i<90;++i)r=sync.observe(35,17000+i*17,16965+i*17);
+ check(r.fallback,"clock fallback requires sustained matching evidence");
+ r=sync.observe(35,19100,19065);
+ check(!r.fallback,"consistent clocks recover after two seconds");
+ sync.reset();bool bounded=true;
+ for(int i=0;i<60000;++i){const double host=10000+i*10.;r=sync.observe(35+i*.03,host,host-35);bounded&=r.targetMs<=115;}
+ check(bounded&&r.fallback&&r.targetMs==35,"independent video clock drift cannot accumulate seconds of compensation");
+ for(double delay:{80.,400.,900.}){
+ sync.reset();r=sync.observe(delay,10000,10000-delay);
+ check(!r.fallback&&r.targetMs==delay,"genuine measured video residence retains automatic synchronization");
+ }
+ sync.reset();for(int i=0;i<5;++i)sync.observe(35,10000+i*20,9965+i*20);
+ r=sync.observe(400,10100,9700);
+ check(r.targetMs==35,"one real presentation stall does not change the audio target");
+ r=sync.observe(35,10120,10121);
+ check(r.fallback&&std::isfinite(r.targetMs),"invalid future ingress triggers fallback");
+ sync.reset();r=sync.observe(std::numeric_limits<double>::quiet_NaN(),11000,10965);
+ check(r.fallback&&r.targetMs==35,"nonfinite cross-stream timestamp cannot poison audio target");
+ sync.reset();r=sync.observe(900,10000,std::nullopt);
+ check(!r.fallback&&r.targetMs==900,"sources without capture provenance retain their separate clock contract");
+ r=sync.observe(2000,12000,10000);
+ check(r.limited&&r.targetMs==1500,"real excessive residence retains explicit compensation limit");
+ }
sink::AudioFrameTimeline pcmTime;
check(pipeline::ResolutionPlan::make({1920,1080},true,pipeline::NrSizePolicy::Native,false,1,pipeline::SrTarget::Uhd4K,true).nr==pipeline::Extent{1920,1080},"NR-first preview uses source resolution");
check(pipeline::ResolutionPlan::make({1920,1080},true,pipeline::NrSizePolicy::Native,true,1,pipeline::SrTarget::Uhd4K,true).nr==pipeline::Extent{3840,2160},"export ignores low latency preview order");