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 seven decode, capture and subtitle audit findings

Veyra Goal Agent43b8a4a9cf68
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 34191306..e2a49980 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -798,6 +798,11 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_include_directories(veyra_ui_contract_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
add_executable(veyra_popup_selector_tests tests/integration/PopupSelectorTests.cpp)
add_executable(veyra_subtitle_panel_tests tests/integration/SubtitlePanelTests.cpp)
+ add_executable(veyra_subtitle_overlay_tests tests/integration/SubtitleOverlayTests.cpp)
+ target_compile_features(veyra_subtitle_overlay_tests PRIVATE cxx_std_20)
+ target_compile_options(veyra_subtitle_overlay_tests PRIVATE /utf-8)
+ target_compile_definitions(veyra_subtitle_overlay_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN UNICODE _UNICODE)
+ target_link_libraries(veyra_subtitle_overlay_tests PRIVATE veyra_engine gdiplus comctl32)
target_compile_features(veyra_subtitle_panel_tests PRIVATE cxx_std_20)
target_compile_options(veyra_subtitle_panel_tests PRIVATE /utf-8)
target_compile_definitions(veyra_subtitle_panel_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN UNICODE _UNICODE)
diff --git a/apps/veyra/ui/SubtitleOverlay.cpp b/apps/veyra/ui/SubtitleOverlay.cpp
index 0ae9b4ad..f6d8dc1f 100644
--- a/apps/veyra/ui/SubtitleOverlay.cpp
+++ b/apps/veyra/ui/SubtitleOverlay.cpp
@@ -32,11 +32,13 @@ std::wstring signatureOf(const std::vector<SubtitleLine>& lines,const SubtitleVi
std::wstring signature;
signature.reserve(lines.size()*64);
for(const auto& line:lines){
- signature+=std::format(L"{}|{:08X}|{:08X}|{}|{:.1f}|{}|{}|{}|",line.text,line.style.primary,line.style.outline,line.style.font,
+ signature+=std::format(L"{}:{}|{:08X}|{:08X}|{}:{}|{}|{}|{}|{}|",line.text.size(),line.text,line.style.primary,line.style.outline,line.style.font.size(),line.style.font,
line.style.size,line.style.alignment,line.alignOverride,line.secondary?1:0);
- signature+=std::format(L"{}:{:.4f}:{:.4f}|",reinterpret_cast<uintptr_t>(line.bitmap.get()),line.posX,line.posY);
+ signature+=std::format(L"{}:{}:{}|",reinterpret_cast<uintptr_t>(line.bitmap.get()),line.posX,line.posY);
+ const auto& s=line.style;
+ signature+=std::format(L"{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|",s.back,s.outlineWidth,s.shadow,s.marginL,s.marginR,s.marginV,s.bold,s.italic,s.background,s.font.size());
}
- signature+=std::format(L"#{:.2f}|{}|{}|{}|{}|{}",view.scale,view.fontOverride,view.outline?1:0,view.background?1:0,view.bottomMargin,view.blockGap);
+ signature+=std::format(L"#{}|{}:{}|{}|{}|{}|{}",view.scale,view.fontOverride.size(),view.fontOverride,view.outline?1:0,view.background?1:0,view.bottomMargin,view.blockGap);
signature+=std::format(L"/{}x{}/{}",rect.right,rect.bottom,view.targetLines);
signature+=std::format(L"/{}/{}/{}/{}/{}",view.preview.zoom,view.preview.centerX,view.preview.centerY,view.videoWidth,view.videoHeight);
return signature;
@@ -63,7 +65,7 @@ void updateSubtitleOverlay(HWND h,const std::vector<SubtitleLine>& lines,const S
static thread_local std::vector<std::shared_ptr<const engine::SubtitleBitmapFrame>> lastBitmaps;
if(h!=lastWindow){lastSignature.clear();lastBitmaps.clear();lastWindow=h;}
if(lines.empty()||rect.right<1||rect.bottom<1){lastSignature.clear();lastBitmaps.clear();ShowWindow(h,SW_HIDE);SetWindowTextW(h,L"");return;}
- const auto signature=signatureOf(lines,view,rect);
+ const auto signature=signatureOf(lines,view,rect)+std::format(L"/dpi{}",GetDpiForWindow(h));
if(lastSignature==signature){ShowWindow(h,SW_SHOWNOACTIVATE);return;}
const int width=rect.right,height=rect.bottom;
BITMAPINFO info{};info.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);info.bmiHeader.biWidth=width;info.bmiHeader.biHeight=-height;
@@ -104,6 +106,8 @@ void updateSubtitleOverlay(HWND h,const std::vector<SubtitleLine>& lines,const S
Line entry;
entry.path=std::make_unique<Gdiplus::GraphicsPath>();
entry.style=line.style;
+ if(line.alignOverride>=1&&line.alignOverride<=9)entry.style.alignment=line.alignOverride;
+ if(entry.style.alignment<1||entry.style.alignment>9)entry.style.alignment=2;
const double logicalSize=std::max(8.0,(line.style.size>0?line.style.size:24.0)*view.scale);
const std::wstring family=!view.fontOverride.empty()?view.fontOverride:(line.style.font.empty()?L"Microsoft YaHei UI":line.style.font);
FontFamily requested(family.c_str());
@@ -148,6 +152,10 @@ void updateSubtitleOverlay(HWND h,const std::vector<SubtitleLine>& lines,const S
const float space=std::max(1.0f,cursor-padding-gap*float(stacked?stacked-1:0));
const float scale=totalHeight>space?space/totalHeight:1;
if(scale<1)for(auto& entry:laid)if(!entry.positioned){Matrix shrink;shrink.Scale(scale,scale);entry.path->Transform(&shrink);entry.path->GetBounds(&entry.bounds);}
+ float middleHeight=0;size_t middleCount=0;
+ for(const auto& entry:laid)if(!entry.positioned&&verticalOf(entry.style.alignment)==StringAlignmentCenter){middleHeight+=entry.bounds.Height;++middleCount;}
+ if(middleCount>1)middleHeight+=gap*float(middleCount-1);
+ float topCursor=padding,middleCursor=std::max(padding,(float(height)-middleHeight)/2);
for(size_t index=laid.size();index-->0;){
auto& entry=laid[index];
const int alignment=(entry.style.alignment>=1&&entry.style.alignment<=9)?entry.style.alignment:2;
@@ -161,14 +169,15 @@ void updateSubtitleOverlay(HWND h,const std::vector<SubtitleLine>& lines,const S
x=std::clamp(x,0.0f,std::max(0.0f,float(width)-blockWidth));
}else{
const auto vertical=verticalOf(alignment);
- if(vertical==StringAlignmentNear)y=padding;
- else if(vertical==StringAlignmentCenter)y=std::max(padding,(float(height)-blockHeight)/2);
+ const float marginV=float(dip(h,std::max(0.0,entry.style.marginV)));
+ if(vertical==StringAlignmentNear){y=std::max(topCursor,padding+marginV);topCursor=y+blockHeight+gap;}
+ else if(vertical==StringAlignmentCenter){y=middleCursor;middleCursor=y+blockHeight+gap;}
+ else{y=std::min(cursor,float(height)-padding-float(dip(h,view.bottomMargin))-marginV)-blockHeight;cursor=y-gap;}
const float marginL=float(dip(h,entry.style.marginL));
const float marginR=float(dip(h,entry.style.marginR));
const float left=padding+marginL,right=float(width)-padding-marginR;
const auto horizontal=horizontalOf(alignment);
x=horizontal==StringAlignmentNear?left:horizontal==StringAlignmentFar?right-blockWidth:left+(right-left-blockWidth)/2;
- if(vertical!=StringAlignmentNear)cursor=y-gap;
}
Matrix translation;
translation.Translate(x-entry.bounds.X,y-entry.bounds.Y);
diff --git a/apps/veyra/ui/SubtitleSettingsPanel.h b/apps/veyra/ui/SubtitleSettingsPanel.h
index 2e80b723..611b7541 100644
--- a/apps/veyra/ui/SubtitleSettingsPanel.h
+++ b/apps/veyra/ui/SubtitleSettingsPanel.h
@@ -90,8 +90,8 @@ inline void showSubtitleSettings(HWND owner,SubtitleSettings settings,std::funct
RECT p{};GetWindowRect(owner,&p);
MONITORINFO monitor{sizeof(monitor)};GetMonitorInfoW(MonitorFromWindow(owner,MONITOR_DEFAULTTONEAREST),&monitor);
const int width=r.right-r.left,height=r.bottom-r.top;
- const int x=std::clamp(p.left+dip(owner,40),int(monitor.rcWork.left),std::max(int(monitor.rcWork.left),int(monitor.rcWork.right)-width));
- const int y=std::clamp(p.top+dip(owner,80),int(monitor.rcWork.top),std::max(int(monitor.rcWork.top),int(monitor.rcWork.bottom)-height));
+ const int x=std::clamp(int(p.left)+dip(owner,40),int(monitor.rcWork.left),std::max(int(monitor.rcWork.left),int(monitor.rcWork.right)-width));
+ const int y=std::clamp(int(p.top)+dip(owner,80),int(monitor.rcWork.top),std::max(int(monitor.rcWork.top),int(monitor.rcWork.bottom)-height));
subtitlePanel::window=CreateWindowExW(WS_EX_TOOLWINDOW,wc.lpszClassName,L"字幕设置",WS_CAPTION|WS_SYSMENU|WS_CLIPCHILDREN,x,y,width,height,owner,nullptr,wc.hInstance,state);
if(subtitlePanel::window)ShowWindow(subtitlePanel::window,SW_SHOW);
}
diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.md
index 54eb1676..5d3c1663 100644
--- a/docs/CURRENT_STATUS.md
+++ b/docs/CURRENT_STATUS.md
@@ -2,6 +2,8 @@
更新:2026-09-19。发布状态与开发状态分别记录,历史计划不代表当前验收。
+最新补充修复:`codex/seven-audit-20260919` 基于 `80f7dc4` 完成七项独立审查修复,涵盖压缩采集参考链/帧身份/PTS、FFmpeg EAGAIN 重送、D3D11 引用释放及字幕布局/缓存;同时修正构建依赖编码和字幕设置编译类型问题。干净构建、H.264/HEVC 软件及硬解、4K 文件、字幕像素、时序回归和主程序启动检查通过。实际采集卡队列与 GC573/GC551 未验收,详见 [七项修复报告](SEVEN_AUDIT_REPAIR_2026-09-19.md)。此前 DLSS/XeSS 调度修复保留;本轮仅本地,未打包或发布。
+
最新本地修复:`codex/fg-scheduling-repair-20260919` 从存档 `5a1931b` 修复 DLSS 暖机预算污染、CPU Present 重复计费、窗口采集期限抖动,以及 XeSS 实时呈现前的额外相位等待。构建和本机持续生成/拥堵恢复测试结果见 [补帧调度验收](FG_SCHEDULING_ACCEPTANCE_2026-09-19.md)。GC573 53fps 只新增定位诊断,尚无实卡根因与修复证明;5080 功耗、30/40 系和物理显示验收未覆盖。本轮未打包、合并 main、推送或发布。
**1.4.2 已正式发布并设为最新版**:[GitHub Release](https://github.com/Likely7/Veyra-NRVideo/releases/tag/v1.4.2),标签提交274d826。正式包、对应源码和SHA256共四资产已核对远端digest;软件短测、HDR组合与便携包七组检查通过。具体边界与发布后证据见WORKLOG。以下为历史开发记录。
diff --git a/docs/SEVEN_AUDIT_REPAIR_2026-09-19.md b/docs/SEVEN_AUDIT_REPAIR_2026-09-19.md
new file mode 100644
index 00000000..5dff06f1
--- /dev/null
+++ b/docs/SEVEN_AUDIT_REPAIR_2026-09-19.md
@@ -0,0 +1,52 @@
+# 七项独立审查修复
+
+基线 `80f7dc4`,存档 `checkpoint/pre-seven-audit-20260919`,隔离分支 `codex/seven-audit-20260919`。依据 `XESS_GC573_LOG_REPAIR_PLAN_2026-09-19.md` 的“独立审查项”,用户要求七项一起修复。上一轮 DLSS/XeSS 调度修复保留;这些缺陷不能解释所有 GC573 RGB 或 5080 功耗问题。
+
+## 实现范围
+
+1. 压缩采集队列保持容量 3。MJPEG 可独立丢旧帧;帧间压缩溢出时清除待处理包,在解码线程 flush 并等待关键帧重新建立参考链。记录丢包与恢复边界,不继续使用损坏历史。持续解码欠速仍可能等待关键帧,不能保证无停顿。
+2. 压缩 mailbox 的序号来自已解码输出计数,在同一锁内快照;不再使用仍在增长的采集回调计数。原生采集序号保持原语义。
+3. 共享 FFmpeg 解码器在 EAGAIN 时接收输出并重送同一个输入包。输出缓冲最多 16 帧;超过上限明确失败,不伪报接收成功。已接收计数只在真正成功后增加;flush/close 释放缓存。文件及诊断调用方沿用 bool 接收合同。
+4. 采集软件颜色转换保留解码 PTS、时间基及颜色信息;worker 使用实际输出 PTS 匹配有界输入元数据(最多 64 项),取得原始到达时间和 duration。B 帧包 PTS 的逆序不触发错误的解码重置。没有 PTS 或元数据无法匹配的输出明确丢弃并记录,后续输出标记断点。worker 排空已就绪输出,不将输出数量绑定为每包一帧。硬解首次输出不可导入时,软解从关键帧恢复。
+5. D3D11 Context4 的 QueryInterface/Detach 所产生的自有引用由 releaseInterop 释放。
+6. 顶部、中部、底部分别维护布局游标,中部先测整组高度再居中;显式 ASS 位置保留。支持 alignment override 和垂直 margin。
+7. 字幕缓存包含所有样式字段、精确数值、字符串长度与 DPI,避免只改粗体、边距、阴影或背景时沿用旧图。
+
+## 验收计划
+
+- 构建主程序、压缩解码回归、字幕像素回归及文件读取回归。
+- 带 B 帧的 H.264/HEVC 软件/D3D12VA 解码;批量提交强制触发 EAGAIN,核对帧数、PTS 和 flush;人为丢包后核对关键帧恢复及像素一致性。
+- 检查字幕实际像素上下界、缓存命中及粗体修改后的像素变化。
+- 保留原有文件播放与调度单测;没有实卡则不宣称 GC551/GC573 实机通过,不把像素测试称作人工观看验收。
+
+产物:`E:/项目/Veyra/{tests,logs,tmp}/seven-audit-20260919/`。复用构建 `E:/项目/Veyra/build/slider-reset-20260919/` 和依赖缓存 `E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt`。本轮不打包、不发布、不修改运行库。
+
+## 早期执行记录
+
+`scripts/build-isolated.ps1` 的 build/build2/build3 日志构建成功。生成 320x180、30fps、3 秒、GOP15/B2 的 H.264 和 HEVC 两个测试文件;实际测试日志 `h264-recovery` / `hevc-recovery` 已覆盖软件/D3D12VA、90 帧 EAGAIN 完整输出及丢包恢复像素对比。
+
+首次向 ANSI main 传中文绝对路径导致旧测试 SKIP,不能算通过,随后在测试目录传 ASCII 相对路径重跑。字幕首次测试因测试程序缺少现代 Windows manifest 未创建出 layered child,不计通过,后改为相同 renderer 的 layered popup,最终结果如下。
+
+## 最终验收
+
+干净构建 `build-utf8.log` 完成 380 个步骤;头文件触发重编译后 `build-delivery.log` 完成 14 个步骤,均退出 0。主程序及五个回归目标构建通过。以下日志位于上述本轮 logs 目录:
+
+- `h264-delivery`、`hevc-delivery`:320x180/30fps、3 秒、GOP15/B2;软件与 D3D12VA 各输出 88 帧(实时捕获未发送 EOS,尾部两帧仍在解码器中)。单独的完整文件 EAGAIN 测试各 90 帧、64 次重送,输出顺序/PTS/已接收计数和 flush 通过。丢包后从关键帧恢复,像素校验和与基准一致。D3D11VA 各三轮打开/解码/关闭及 GPU 资源导入通过。
+- `file-delivery`:3840x2160/30fps、24 帧 H.264,9 项检查通过;单线程与线程解码每帧像素/PTS 一致、EOS 数量准确、EOS 后 seek 正常。
+- `subtitle-delivery`:真实 GDI+ DIB 像素检查,上/中/下两条字幕无重叠、中部整组居中;10 项样式修改使缓存失效,未修改时命中缓存,粗体修改实际改变像素。测试截取绘制结果,不等同实屏人工观感验收。
+- `presentation_worker-clean`、`live_timing-clean`:已有呈现线程和时序回归通过,含 2X/4X/6X、29.97Hz、reset、时间戳跳变等。
+- `app-delivery`:主程序 `--smoke-empty --smoke-seconds 5` 退出 0。
+
+构建使用 `scripts/build-isolated.ps1 -Root .`,BuildDirectory、DependencyCache、TempDirectory 为前述目录,Targets 为 PowerShell 数组:`veyra,veyra_capture_compressed_tests,veyra_subtitle_overlay_tests,veyra_source_tests,veyra_presentation_worker_tests,veyra_live_timing_tests`。测试通过 `scripts/run-short-test.ps1`,解码测试上限 60 秒、主程序 30 秒;工作目录设为本轮 tests 目录,使用 ASCII 相对媒体路径。进程 PATH 加入 1.4.2 便携包和 patched FFmpeg bin,TEMP/TMP 仅进程重定向。
+
+元数据最终行为补充:没有 PTS 或元数据无法匹配的输出均明确丢弃并记录,后续输出标记断点,不编造到达时间。
+
+## 失败与追加修复
+
+4K 文件回归曾崩溃:旧 CMake MSVC `/showIncludes` 前缀乱码,头文件修改未触发 MediaFileSource 等对象重编译,形成新旧 ABI 混合。此前增量构建不作为最终证据。强制 `VSLANG=1033` 在只安装中文语言包的本机无效;最终脚本为 configure/build 统一控制台 UTF-8 编码并恢复原编码,旧目录迁移时重新配置并清理对象(ConfigureOnly 也执行清理),避免混合链接。干净编译另暴露 SubtitleSettingsPanel 的 `std::clamp` LONG/int 推导冲突,已统一类型。
+
+最终 Ninja 依赖记录包含 FFmpegVideoDecoder.h;仅触碰该头文件时间戳,dry-run 正确列出 MediaFileSource、CaptureCompressedDecoder、EngineController、VideoExportJob 等重编译,随后实际重编译并重跑交付测试。`git diff --check` 通过。初次错误目标名 `veyra_source_file_tests` 后改为实际目标 `veyra_source_tests`。
+
+## 验收边界
+
+本机 RTX5070。未接 GC551/GC573,未做真实 DirectShow 采集队列溢出和帧身份端到端测试;worker 的队列及元数据逻辑经过代码复查,解码恢复经过上述合成输入测试。未覆盖 AV1/VP9 丢包恢复、D3D11 COM 引用长期内存压力、多屏字幕视觉矩阵。未将这些修复宣称为 GC573 RGB53fps 或全部用户补帧受限的共同根因。没有独立 Reviewer;本轮为本人复查和自动回归。没有打包、合并 main、推送或发布。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 3ac7c246..bbc1e2b9 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,17 @@
# Veyra 工作记录
+## 2026-09-19 七项独立审查修复
+
+用户要求将文档中七项一起修复。存档 `checkpoint/pre-seven-audit-20260919`,基线 `80f7dc4`,隔离分支 `codex/seven-audit-20260919`,保留此前 DLSS/XeSS 调度修复。完成压缩队列参考链恢复、解码输出帧身份、EAGAIN 真正接收重送、重排时间戳、D3D11 Context4 释放、字幕顶部/中部布局和全样式缓存键。
+
+修改:FFmpegVideoDecoder、CaptureCompressedDecoder 及头文件、CaptureCardSource、SubtitleOverlay、SubtitleSettingsPanel、CMakeLists、build-isolated 脚本;增加/扩充压缩解码与字幕像素测试。完整机制、命令、失败过程与验证边界见 `docs/SEVEN_AUDIT_REPAIR_2026-09-19.md`。
+
+构建复用 `E:/项目/Veyra/build/slider-reset-20260919`;依赖 `E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt`。产物位于 `E:/项目/Veyra/{tests,logs,tmp}/seven-audit-20260919`。构建脚本使用这些显式路径和六个目标,最终 build-utf8.log 干净构建及 build-delivery.log 增量均退出0。run-short-test.ps1 单次上限30/60秒:h264-delivery、hevc-delivery、file-delivery、subtitle-delivery、presentation_worker-clean、live_timing-clean、app-delivery 全部退出0并核实非SKIP。H.264/HEVC各90帧、64次EAGAIN,D3D11VA各三轮生命周期、4K文件9项、字幕实际像素与缓存检查通过。
+
+曾发现旧MSVC依赖前缀乱码,导致共享头文件改动未重编译调用者,4K测试崩溃;不能使用早期增量包。修正构建编码、迁移时清理旧对象,修正暴露的字幕窗口LONG/int编译错误。验证Ninja依赖及触碰头文件触发编译后重跑交付测试。首次中文路径导致SKIP、测试窗口无manifest、错误目标名均已修正;保留日志追溯。
+
+本人复查,无独立Reviewer。未连接GC551/GC573,未覆盖真实采集队列溢出端到端、AV1/VP9恢复和长期COM内存压力,不能声称GC573 RGB53fps或所有补帧受限已根治。未打包、合并main、推送或发布,没有新增SDK/运行库/模型入Git。
+
## 2026-09-19 DLSS / XeSS 调度修复施工
开工存档 `5a1931b`,分支 `codex/fg-scheduling-repair-20260919`。用户明确要求同时处理 DLSS。完成暖机 FG 成本与稳态预算分离、以 GPU blit 替代 CPU Present 预算项、XeSS 实时路径取消额外源间隔相位、窗口采集固定配置帧率相位,以及 GC573 回调分项诊断。保留有界队列、真实时间戳、资源租约及必要历史 reset。
diff --git a/docs/XESS_GC573_LOG_REPAIR_PLAN_2026-09-19.md b/docs/XESS_GC573_LOG_REPAIR_PLAN_2026-09-19.md
index 15ec8de8..27159bad 100644
--- a/docs/XESS_GC573_LOG_REPAIR_PLAN_2026-09-19.md
+++ b/docs/XESS_GC573_LOG_REPAIR_PLAN_2026-09-19.md
@@ -147,6 +147,8 @@ A的11:35:30.863至11:35:34.929,`fgSkippedBeforeEval`始终为9,是累计值
此前全软件审查的压缩包队列/帧身份/EAGAIN/PTS、D3D11 context4 释放、字幕锚点重叠/缓存键遗漏,另行回归处理。它们是代码审查发现,不是三份日志全部症状的共同解释。
+后续状态:这七项已在 `codex/seven-audit-20260919` 完成代码修复及本机针对性回归,证据与未覆盖项见 [七项修复报告](SEVEN_AUDIT_REPAIR_2026-09-19.md)。真实采集卡验证仍未完成。
+
## 4. 验收与交付
- 修复前后使用同输入、同格式、同效果、同显示刷新率和驱动设置;每个稳定场景 120 秒,单次测试不超过 300 秒。过渡阶段单列,不能删掉失败窗口制造平均值。
diff --git a/include/veyra/media/FFmpegVideoDecoder.h b/include/veyra/media/FFmpegVideoDecoder.h
index 15a7941a..9ff526a6 100644
--- a/include/veyra/media/FFmpegVideoDecoder.h
+++ b/include/veyra/media/FFmpegVideoDecoder.h
@@ -4,6 +4,7 @@
// D3D12VA arrives in P3.3 as a separate configuration of the same surface.
#include <cstdint>
+#include <deque>
#include <string>
#include <unordered_map>
@@ -27,6 +28,7 @@ namespace veyra::media {
struct DecoderStats {
uint64_t framesDecoded = 0;
uint64_t framesSubmitted = 0;
+ uint64_t packetRetries = 0;
int64_t firstPts = 0;
int64_t lastPts = 0;
uint64_t ptsNonMonotonicCount = 0;
@@ -89,8 +91,8 @@ public:
int height() const;
int pixelFormat() const; // AVPixelFormat as int to keep this header light
- // Send one packet (nullptr flushes at end/seek). Returns false on a hard
- // decode error; end-of-stream is not an error.
+ // True means accepted (or an already completed nullptr drain). EAGAIN
+ // drains into a bounded output queue and retries this same packet.
bool sendPacket(const AVPacket* packet);
// Receive one decoded frame; false when more input is needed or at EOF.
@@ -100,6 +102,7 @@ public:
DecodeReceiveStatus receiveStatus() const { return receiveStatus_; }
void flushBuffers(); // seek boundary (Playbook 13.4)
+ void recoverAtKeyframe(); // compressed input loss: discard until a new key frame
const DecoderStats& stats() const { return stats_; }
// True when the decoder is producing AV_PIX_FMT_D3D12 frames.
@@ -153,6 +156,7 @@ private:
AVCodecContext* context_ = nullptr;
AVFrame* frame_ = nullptr;
+ std::deque<AVFrame*> bufferedFrames_;
DecodeReceiveStatus receiveStatus_ = DecodeReceiveStatus::NeedInput;
int frameTimeBaseNum_ = 0;
int frameTimeBaseDen_ = 0;
@@ -168,7 +172,7 @@ private:
ID3D11Device* d3d11Device_ = nullptr; // our reference (FFmpeg holds its own)
ID3D11DeviceContext* d3d11Context_ = nullptr; // borrowed from the hw device context
ID3D11Fence* d3d11Fence_ = nullptr;
- ID3D11DeviceContext4* d3d11Context4_ = nullptr; // borrowed from the hw device context
+ ID3D11DeviceContext4* d3d11Context4_ = nullptr; // owned QueryInterface reference
ID3D12Device* d3d12Device_ = nullptr; // borrowed from the caller
ID3D12Fence* d3d12Fence_ = nullptr;
uint64_t interopFenceValue_ = 0;
diff --git a/include/veyra/source/CaptureCompressedDecoder.h b/include/veyra/source/CaptureCompressedDecoder.h
index fe218363..bba9a4dc 100644
--- a/include/veyra/source/CaptureCompressedDecoder.h
+++ b/include/veyra/source/CaptureCompressedDecoder.h
@@ -38,7 +38,9 @@ public:
const uint8_t* extradata, size_t extradataBytes,
ID3D12Device* device, ID3D12CommandQueue* queue);
- // Decodes one payload. On success `*out` is a frame whose lifetime the
+ // Decodes one payload; data=nullptr, bytes=0 receives remaining output
+ // without submitting input or EOS. Drain this way before the next payload.
+ // On success `*out` is a frame whose lifetime the
// caller must not extend past the next decode():
// - hardware=true: decoder-owned D3D12 surface (AV_PIX_FMT_D3D12);
// - hardware=false: converted into `nv12Target` (owned by the caller).
@@ -50,6 +52,7 @@ public:
bool opened() const;
bool hardwareActive() const;
bool waitingForInput() const;
+ void recoverAtKeyframe();
const char* backendName() const;
const std::string& lastError() const;
uint64_t framesDecoded() const;
diff --git a/scripts/build-isolated.ps1 b/scripts/build-isolated.ps1
index 0c98d56c..d0c08034 100644
--- a/scripts/build-isolated.ps1
+++ b/scripts/build-isolated.ps1
@@ -16,16 +16,30 @@ $vswhere=Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio/Installer/v
$vs=(& $vswhere -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath | Select-Object -First 1)
if(!$vs){throw 'MSVC not found'}
$vcvars=Join-Path $vs 'VC/Auxiliary/Build/vcvars64.bat'
-$savedTemp=$env:TEMP;$savedTmp=$env:TMP
+$savedTemp=$env:TEMP;$savedTmp=$env:TMP;$savedVsLang=$env:VSLANG
+$savedCodePage=(& cmd.exe /d /c chcp) -replace '[^0-9]',''
+if(!$savedCodePage){throw 'Cannot read build console encoding'}
New-Item -ItemType Directory -Force -Path $BuildDirectory,$TempDirectory | Out-Null
try {
$env:TEMP=$TempDirectory;$env:TMP=$TempDirectory
+ # CMake and Ninja must decode the same /showIncludes bytes, including on
+ # installations that have only the Chinese MSVC language pack.
+ & cmd.exe /d /c 'chcp 65001 >nul'
+ if($LASTEXITCODE){throw 'Cannot set build console encoding'}
+ $env:VSLANG='1033'
$vcEnvironment=& cmd.exe /d /c "call `"$vcvars`" >nul && set"
if($LASTEXITCODE){throw 'vcvars failed'}
foreach($line in $vcEnvironment){if($line -match '^([^=]+)=(.*)$'){[Environment]::SetEnvironmentVariable($matches[1],$matches[2],'Process')}}
$cmake=Join-Path $vs 'Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/bin/cmake.exe'
$ninja=Join-Path $vs 'Common7/IDE/CommonExtensions/Microsoft/CMake/Ninja/ninja.exe'
$argsList=@('-S',$Root,'-B',$BuildDirectory,'-G','Ninja','-DCMAKE_BUILD_TYPE=Release',"-DCMAKE_MAKE_PROGRAM=$ninja",'-DVEYRA_ENABLE_EXPERIMENTAL_DLSSNR=ON','-DVEYRA_ENABLE_REMOTEPLAY=ON')
+ $refreshDependencies=$false
+ $rulesPath=Join-Path $BuildDirectory 'CMakeFiles/rules.ninja'
+ $encodingMarker=Join-Path $BuildDirectory 'veyra-utf8-dependencies-v1.txt'
+ if((Test-Path -LiteralPath $rulesPath) -and !(Test-Path -LiteralPath $encodingMarker)){
+ $refreshDependencies=$true;$argsList+='--fresh'
+ Write-Host 'Refreshing MSVC dependency metadata and removing old objects.'
+ }
if($DisplayVersion){$argsList+="-DVEYRA_DISPLAY_VERSION=$DisplayVersion"}
foreach($line in $cache){
if($line -match '^(VEYRA_[A-Z0-9_]+_ROOT|VEYRA_RP_CHIAKI_SOURCE_DIR|VEYRA_RP_CHIAKI_VERIFY_DIR|CMAKE_PREFIX_PATH|PROTOC|Protobuf_PROTOC_EXECUTABLE|PKG_CONFIG_EXECUTABLE):[^=]+=(.+)$'){
@@ -37,8 +51,17 @@ try {
$argsList+="-DVEYRA_NVOF_SDK_ROOT=$nvidia/Optical_Flow_SDK_5.0.7"
& $cmake @argsList
if($LASTEXITCODE){throw "Configure failed: $LASTEXITCODE"}
+ if($refreshDependencies){
+ & $cmake --build $BuildDirectory --target clean
+ if($LASTEXITCODE){throw 'Cannot clean incompatible build objects'}
+ }
+ Set-Content -LiteralPath $encodingMarker -Value 'Configure and build with console code page 65001.' -Encoding ascii
if(!$ConfigureOnly){
- & $cmake --build $BuildDirectory --parallel 8 --target @Targets
+ $buildArgs=@('--build',$BuildDirectory,'--parallel','8','--target')+@($Targets)
+ & $cmake @buildArgs
if($LASTEXITCODE){throw "Build failed: $LASTEXITCODE"}
}
-} finally {$env:TEMP=$savedTemp;$env:TMP=$savedTmp}
+} finally {
+ & cmd.exe /d /c "chcp $savedCodePage >nul"
+ $env:TEMP=$savedTemp;$env:TMP=$savedTmp;$env:VSLANG=$savedVsLang
+}
diff --git a/src/media/FFmpegVideoDecoder.cpp b/src/media/FFmpegVideoDecoder.cpp
index 2993d669..f193b4e9 100644
--- a/src/media/FFmpegVideoDecoder.cpp
+++ b/src/media/FFmpegVideoDecoder.cpp
@@ -239,7 +239,7 @@ void FFmpegVideoDecoder::releaseInterop()
d3d11Fence_->Release();
d3d11Fence_ = nullptr;
}
- d3d11Context4_ = nullptr; // borrowed from the FFmpeg device context
+ if (d3d11Context4_) { d3d11Context4_->Release(); d3d11Context4_ = nullptr; }
d3d11Context_ = nullptr; // borrowed from the FFmpeg device context
d3d12Device_ = nullptr; // borrowed from the caller
interopFenceValue_ = 0;
@@ -554,6 +554,8 @@ ID3D12Resource* FFmpegVideoDecoder::importD3D11Texture(ID3D11Texture2D* texture)
void FFmpegVideoDecoder::close()
{
+ for (auto* buffered : bufferedFrames_) av_frame_free(&buffered);
+ bufferedFrames_.clear();
receiveStatus_ = DecodeReceiveStatus::NeedInput;
if (frame_ != nullptr) {
av_frame_free(&frame_);
@@ -635,8 +637,26 @@ bool FFmpegVideoDecoder::sendPacket(const AVPacket* packet)
if (context_ == nullptr) {
return false;
}
- const int result = avcodec_send_packet(context_, packet);
- if (result < 0 && result != AVERROR(EAGAIN) && result != AVERROR_EOF) {
+ int result = avcodec_send_packet(context_, packet);
+ while (result == AVERROR(EAGAIN)) {
+ ++stats_.packetRetries;
+ if (bufferedFrames_.size() >= 16) {
+ log::error("media", "decoder: output queue full; caller must consume frames before sending more input");
+ return false;
+ }
+ AVFrame* buffered = av_frame_alloc();
+ if (!buffered) return false;
+ const int received = avcodec_receive_frame(context_, buffered);
+ if (received < 0) {
+ av_frame_free(&buffered);
+ log::error("media", std::format("decoder: send EAGAIN without receive progress code={}", received));
+ return false;
+ }
+ bufferedFrames_.push_back(buffered);
+ result = avcodec_send_packet(context_, packet);
+ }
+ if (result == AVERROR_EOF && packet == nullptr) return true;
+ if (result < 0) {
char errorText[AV_ERROR_MAX_STRING_SIZE]{};
av_strerror(result, errorText, sizeof(errorText));
log::error("media", std::format("decoder: send_packet failed code={} text={}", result, errorText));
@@ -654,7 +674,14 @@ const AVFrame* FFmpegVideoDecoder::receiveFrame()
receiveStatus_ = DecodeReceiveStatus::Error;
return nullptr;
}
- const int result = avcodec_receive_frame(context_, frame_);
+ int result = 0;
+ if (!bufferedFrames_.empty()) {
+ av_frame_unref(frame_);
+ AVFrame* buffered = bufferedFrames_.front();
+ bufferedFrames_.pop_front();
+ av_frame_move_ref(frame_, buffered);
+ av_frame_free(&buffered);
+ } else result = avcodec_receive_frame(context_, frame_);
if (result < 0) {
if (result == AVERROR(EAGAIN)) receiveStatus_ = DecodeReceiveStatus::NeedInput;
else if (result == AVERROR_EOF) receiveStatus_ = DecodeReceiveStatus::EndOfStream;
@@ -667,6 +694,7 @@ const AVFrame* FFmpegVideoDecoder::receiveFrame()
return nullptr;
}
receiveStatus_ = DecodeReceiveStatus::Frame;
+ if (frame_->flags & AV_FRAME_FLAG_KEY) context_->skip_frame = AVDISCARD_DEFAULT;
++stats_.framesDecoded;
// Frame timestamps are in the CODEC context time_base; AVFrame.time_base
// is not reliably populated by every decoder path.
@@ -781,10 +809,19 @@ const AVFrame* FFmpegVideoDecoder::receiveFrame()
void FFmpegVideoDecoder::flushBuffers()
{
+ for (auto* buffered : bufferedFrames_) av_frame_free(&buffered);
+ bufferedFrames_.clear();
receiveStatus_ = DecodeReceiveStatus::NeedInput;
if (context_ != nullptr) {
avcodec_flush_buffers(context_);
+ context_->skip_frame = AVDISCARD_DEFAULT;
}
}
+void FFmpegVideoDecoder::recoverAtKeyframe()
+{
+ flushBuffers();
+ if (context_) context_->skip_frame = AVDISCARD_NONKEY;
+}
+
} // namespace veyra::media
diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cpp
index 2cb55142..f3236d14 100644
--- a/src/source/CaptureCardSource.cpp
+++ b/src/source/CaptureCardSource.cpp
@@ -284,7 +284,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
// Decode worker: keeps the DirectShow callback cheap (payload copy only)
// and lets the decode overlap with graph work. The worker owns workerFrame
// and swaps it into the mailbox once a frame is ready.
- struct CompressedSample{std::vector<uint8_t> payload;double time=0;Clock::time_point arrival;REFERENCE_TIME start=0,end=0;bool completeTime=false,bad=false;};
+ struct CompressedSample{std::vector<uint8_t> payload;double time=0;Clock::time_point arrival;REFERENCE_TIME start=0,end=0;bool completeTime=false,bad=false,reset=false;};
std::deque<CompressedSample> compressedQueue;size_t compressedQueueLimit=3;
std::thread decodeThread;std::condition_variable decodeWake;bool decodeStop=false;
AVFrame* workerFrame=nullptr;uint64_t compressedDropped=0;double lastCallbackTime=0;
@@ -305,6 +305,9 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
// backend (software MJPEG / D3D12VA for H.264/HEVC/AV1/VP9), then hand the
// result to the mailbox. No source lock is held during decoding.
void decodeLoop(){
+ std::deque<CompressedSample> metadata;
+ bool recoveryBoundary=false;
+ bool draining=false;
for(;;){
CompressedSample sample;AVFrame* target=nullptr;
{
@@ -312,15 +315,21 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
// The worker needs both a payload and a frame it may write
// into; the pool is refilled by read() releasing the caller's
// previous frame.
- decodeWake.wait(lock,[&]{return decodeStop||(!compressedQueue.empty()&&workerFrame!=nullptr);});
+ decodeWake.wait(lock,[&]{return decodeStop||((draining||!compressedQueue.empty())&&workerFrame!=nullptr);});
if(decodeStop)return; // close() clears the queue; do not decode without a write target
- sample=std::move(compressedQueue.front());compressedQueue.pop_front();
+ if(!draining){sample=std::move(compressedQueue.front());compressedQueue.pop_front();}
target=workerFrame;workerFrame=nullptr;
}
AVFrame* decodedFrame=nullptr;bool hardware=false;
- const bool produced=compressedDecoder.decode(sample.payload.data(),sample.payload.size(),
+ if(sample.reset){compressedDecoder.recoverAtKeyframe();metadata.clear();recoveryBoundary=true;}
+ CompressedSample stamp;
+ stamp.time=sample.time;stamp.arrival=sample.arrival;stamp.start=sample.start;stamp.end=sample.end;
+ stamp.completeTime=sample.completeTime;stamp.bad=sample.bad;
+ if(!draining){metadata.push_back(stamp);if(metadata.size()>64)metadata.pop_front();}
+ const bool produced=compressedDecoder.decode(draining?nullptr:sample.payload.data(),draining?0:sample.payload.size(),
int64_t(sample.time*1e7),target,&decodedFrame,hardware);
if(!produced){
+ draining=false;
// A decoder that needs more input before it can emit a frame is
// normal for the first payload; a real error is not.
if(!compressedDecoder.waitingForInput())++compressedErrors;
@@ -328,6 +337,20 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
workerFrame=target; // no output consumed the frame
continue;
}
+ draining=true;
+ const int64_t decodedPts=decodedFrame->pts!=AV_NOPTS_VALUE?decodedFrame->pts:decodedFrame->best_effort_timestamp;
+ if(decodedPts==AV_NOPTS_VALUE){
+ log::warn("capture-decode","discarding decoded frame without a presentation timestamp");
+ recoveryBoundary=true;
+ std::lock_guard lock(mutex);workerFrame=target;++compressedErrors;++dropped;continue;
+ }
+ const auto match=std::find_if(metadata.begin(),metadata.end(),[&](const auto& item){return int64_t(item.time*1e7)==decodedPts;});
+ if(match!=metadata.end()){stamp=*match;metadata.erase(match);}
+ else{
+ log::warn("capture-decode","discarding decoded frame without matching input metadata");
+ recoveryBoundary=true;
+ std::lock_guard lock(mutex);workerFrame=target;++compressedErrors;++dropped;continue;
+ }
{
std::lock_guard lock(mutex);
if(hardware){
@@ -346,9 +369,10 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
if(!compressedFree.empty()){workerFrame=compressedFree.back();compressedFree.pop_back();}
}
pendingIsHardware=hardware;
- pending=true;pendingTime=sample.time;pendingArrival=sample.arrival;
- pendingDuration=captureDuration(sample.start,sample.end,sample.completeTime,nominalDuration100ns);
- pendingDiscontinuity=sample.bad;
+ pendingDiscontinuity=(pending&&pendingDiscontinuity)||stamp.bad||recoveryBoundary;
+ recoveryBoundary=false;
+ pending=true;pendingTime=stamp.time;pendingArrival=stamp.arrival;
+ pendingDuration=captureDuration(stamp.start,stamp.end,stamp.completeTime,nominalDuration100ns);
++compressedDecoded;
if((compressedDecoded%600)==0)log::info("capture-decode",std::format("decoded={} errors={} queueDrops={} backend={} (decode worker)",compressedDecoded,compressedErrors,compressedDropped,compressedDecoder.backendName()));
}
@@ -373,7 +397,10 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
const double previous=compressedPath?lastCallbackTime:pendingTime;
if(received){arrivalDeltaMs=std::chrono::duration<double,std::milli>(arrival-latestArrival).count();ptsDeltaMs=(time-previous)*1000;}
const bool driverBreak=sample->IsDiscontinuity()==S_OK;
- const bool clockBreak=received&&(time<=previous||time-previous>(info.averageFps>0?2.5/info.averageFps:.1));
+ // Interframe packet PTS may move backwards in decode order.
+ // Apply cadence checks to decoded output, not B-frame packets.
+ const bool clockBreak=received&&(!compressedPath||codec==CaptureCodec::Mjpeg)&&
+ (time<=previous||time-previous>(info.averageFps>0?2.5/info.averageFps:.1));
if(driverBreak||clockBreak){
++discontinuitySamples;
if(discontinuitySamples<=4||discontinuitySamples%120==0)
@@ -388,11 +415,19 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
// payload; the decode worker produces the NV12 frame.
const auto* payload=reinterpret_cast<const uint8_t*>(data);
const size_t bytes=size_t(sample->GetActualDataLength());
- if(compressedQueue.size()>=compressedQueueLimit){compressedQueue.pop_front();++compressedDropped;++dropped;}
CompressedSample entry;entry.payload.assign(payload,payload+bytes);
+ if(compressedQueue.size()>=compressedQueueLimit){
+ if(codec==CaptureCodec::Mjpeg){compressedQueue.pop_front();++compressedDropped;++dropped;entry.bad=true;}
+ else{
+ compressedDropped+=compressedQueue.size();dropped+=compressedQueue.size();
+ compressedQueue.clear();entry.reset=true;entry.bad=true;
+ log::warn("capture-decode","compressed queue overflow: discard damaged history and recover at keyframe");
+ }
+ }
entry.time=time;entry.arrival=arrival;entry.start=sampleStart;entry.end=sampleEnd;entry.completeTime=sampleTime;
- entry.bad=captureDiscontinuity(!compressedQueue.empty()||pending,pendingDiscontinuity,driverBreak,received>0,lastCallbackTime,time,info.averageFps);
- pendingDiscontinuity=entry.bad;lastCallbackTime=time;
+ entry.bad=entry.bad||driverBreak||clockBreak;
+ entry.reset=entry.reset||((driverBreak||clockBreak)&&codec!=CaptureCodec::Mjpeg);
+ lastCallbackTime=time;
compressedQueue.push_back(std::move(entry));enqueued=true;
}else{
if(!copyCaptureSample(layout,data,size_t(sample->GetActualDataLength()),*pendingFrame,verticalFlip.load())){callbackError=true;wake.notify_one();return S_OK;}
@@ -1153,7 +1188,7 @@ SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,c
if(p.dropped!=p.lastDrop)flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Drop);
if(p.pendingDiscontinuity)flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Discontinuity);
if(p.forceDiscontinuity){flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Discontinuity);p.forceDiscontinuity=false;}
- p.lastDrop=p.dropped;p.lastPts=time;++p.sequence;sequence=p.received;
+ p.lastDrop=p.dropped;p.lastPts=time;++p.sequence;sequence=p.compressedPath?p.compressedDecoded:p.received;
}
if(feedDecode)p.decodeWake.notify_one();
if(expiredHardware)av_frame_free(&expiredHardware);
diff --git a/src/source/CaptureCompressedDecoder.cpp b/src/source/CaptureCompressedDecoder.cpp
index b4bad166..5392b40d 100644
--- a/src/source/CaptureCompressedDecoder.cpp
+++ b/src/source/CaptureCompressedDecoder.cpp
@@ -118,6 +118,16 @@ struct CaptureCompressedDecoder::Impl {
++failures;
return false;
}
+ target->pts = frame.pts;
+ target->best_effort_timestamp = frame.best_effort_timestamp;
+ target->pkt_dts = frame.pkt_dts;
+ target->duration = frame.duration;
+ target->time_base = frame.time_base;
+ target->flags = frame.flags;
+ target->colorspace = frame.colorspace;
+ target->color_primaries = frame.color_primaries;
+ target->color_trc = frame.color_trc;
+ target->color_range = targetFullRange ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
return true;
}
};
@@ -185,7 +195,8 @@ bool CaptureCompressedDecoder::decode(const uint8_t* data, size_t bytes, int64_t
*out = nullptr;
hardware = false;
p.waiting = false;
- if (!p.decoder.opened() || data == nullptr || bytes == 0 || nv12Target == nullptr) {
+ const bool receiveOnly = data == nullptr && bytes == 0;
+ if (!p.decoder.opened() || (!receiveOnly && (data == nullptr || bytes == 0)) || nv12Target == nullptr) {
p.error = "decode called without an open decoder or a writable target frame";
++p.failures;
return false;
@@ -194,27 +205,29 @@ bool CaptureCompressedDecoder::decode(const uint8_t* data, size_t bytes, int64_t
// hardware decoder whose first frame cannot be imported has been replaced
// by the software decoder.
for (int attempt = 0; attempt < 2; ++attempt) {
- AVPacket* packet = av_packet_alloc();
- if (packet == nullptr) {
- p.error = "av_packet_alloc failed";
- ++p.failures;
- return false;
- }
- if (av_new_packet(packet, int(bytes)) < 0) {
+ if (!receiveOnly) {
+ AVPacket* packet = av_packet_alloc();
+ if (packet == nullptr) {
+ p.error = "av_packet_alloc failed";
+ ++p.failures;
+ return false;
+ }
+ if (av_new_packet(packet, int(bytes)) < 0) {
+ av_packet_free(&packet);
+ p.error = "av_new_packet failed";
+ ++p.failures;
+ return false;
+ }
+ std::memcpy(packet->data, data, bytes);
+ packet->pts = pts100ns;
+ packet->dts = AV_NOPTS_VALUE; // capture PTS is not decode order for B frames
+ const bool sent = p.decoder.sendPacket(packet);
av_packet_free(&packet);
- p.error = "av_new_packet failed";
- ++p.failures;
- return false;
- }
- std::memcpy(packet->data, data, bytes);
- packet->pts = pts100ns;
- packet->dts = pts100ns;
- const bool sent = p.decoder.sendPacket(packet);
- av_packet_free(&packet);
- if (!sent) {
- p.error = "decoder rejected the compressed payload";
- ++p.failures;
- return false;
+ if (!sent) {
+ p.error = "decoder rejected the compressed payload";
+ ++p.failures;
+ return false;
+ }
}
const AVFrame* frame = p.decoder.receiveFrame();
if (frame == nullptr) {
@@ -240,8 +253,10 @@ bool CaptureCompressedDecoder::decode(const uint8_t* data, size_t bytes, int64_t
return false;
}
p.hardware = false;
+ p.decoder.recoverAtKeyframe();
++p.fallbacks;
- continue; // re-send this payload on the software decoder
+ if (receiveOnly) { p.waiting=true; return false; }
+ continue; // only a new key frame can rebuild the lost reference chain
}
}
if (p.hardware) {
@@ -266,6 +281,7 @@ bool CaptureCompressedDecoder::decode(const uint8_t* data, size_t bytes, int64_t
bool CaptureCompressedDecoder::opened() const { return p_->decoder.opened(); }
bool CaptureCompressedDecoder::hardwareActive() const { return p_->hardware; }
bool CaptureCompressedDecoder::waitingForInput() const { return p_->waiting; }
+void CaptureCompressedDecoder::recoverAtKeyframe() { p_->decoder.recoverAtKeyframe(); }
const char* CaptureCompressedDecoder::backendName() const
{
if (p_->hardware) return "d3d12va";
diff --git a/tests/integration/SubtitleOverlayTests.cpp b/tests/integration/SubtitleOverlayTests.cpp
new file mode 100644
index 00000000..1d05b4bd
--- /dev/null
+++ b/tests/integration/SubtitleOverlayTests.cpp
@@ -0,0 +1,57 @@
+#include <windows.h>
+#include <vector>
+#include <iostream>
+static std::vector<unsigned long> pixels;
+static int imageWidth=0,imageHeight=0,updates=0;
+static BOOL captureLayer(HWND,HDC,POINT*,SIZE* size,HDC source,POINT*,COLORREF,BLENDFUNCTION*,DWORD){
+ DIBSECTION bitmap{};
+ GetObjectW(GetCurrentObject(source,OBJ_BITMAP),sizeof(bitmap),&bitmap);
+ imageWidth=size->cx;imageHeight=size->cy;++updates;
+ auto* data=static_cast<unsigned long*>(bitmap.dsBm.bmBits);
+ pixels.assign(data,data+size_t(imageWidth)*imageHeight);
+ return TRUE;
+}
+#define UpdateLayeredWindow captureLayer
+#include "../../apps/veyra/ui/SubtitleOverlay.cpp"
+#undef UpdateLayeredWindow
+
+int main(){
+ using namespace veyra::ui;
+ Gdiplus::GdiplusStartupInput input;ULONG_PTR token=0;
+ if(Gdiplus::GdiplusStartup(&token,&input,nullptr)!=Gdiplus::Ok)return 1;
+ HWND parent=CreateWindowExW(0,L"STATIC",L"overlay test",WS_OVERLAPPEDWINDOW,0,0,800,600,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
+ // Test executables do not carry the app's Windows 8+ manifest, which is
+ // required for layered child windows. Use the same renderer in a popup.
+ HWND registered=createSubtitleOverlay(parent);if(registered)DestroyWindow(registered);
+ HWND overlay=CreateWindowExW(WS_EX_LAYERED,L"VeyraSubtitleOverlay",L"",WS_POPUP,0,0,640,480,parent,nullptr,GetModuleHandleW(nullptr),nullptr);
+ if(!overlay)return 2;
+ int failures=0;
+ auto check=[&](bool ok,const char* name){std::cout<<(ok?"PASS ":"FAIL ")<<name<<'\n';failures+=!ok;};
+ SubtitleView view;view.outline=false;view.targetLines=0;
+ SubtitleLine red,green;red.text=L"First subtitle";green.text=L"Second subtitle";
+ red.style.size=green.style.size=28;red.style.primary=0xFFFF0000;green.style.primary=0xFF00FF00;
+ for(int alignment:{2,5,8}){
+ red.style.alignment=green.style.alignment=alignment;
+ updateSubtitleOverlay(overlay,{red,green},view);
+ int r0=480,r1=-1,g0=480,g1=-1;
+ for(int y=0;y<imageHeight;++y)for(int x=0;x<imageWidth;++x){auto c=pixels[size_t(y)*imageWidth+x];int r=(c>>16)&255,g=(c>>8)&255;
+ if(r>30&&r>2*g){r0=std::min(r0,y);r1=std::max(r1,y);}
+ if(g>30&&g>2*r){g0=std::min(g0,y);g1=std::max(g1,y);}}
+ check(r1>=r0&&g1>=g0&&(r1<g0||g1<r0),"top/middle/bottom cues do not overlap");
+ std::cout<<"alignment="<<alignment<<" extent="<<imageWidth<<'x'<<imageHeight<<" red="<<r0<<','<<r1<<" green="<<g0<<','<<g1<<'\n';
+ if(alignment==5)check(std::abs((std::min(r0,g0)+std::max(r1,g1))/2-240)<12,"middle group is centered");
+ }
+ RECT rect{0,0,640,480};
+ const auto original=signatureOf({red},view,rect);
+ auto changes=[&](auto change){auto copy=red;change(copy.style);check(signatureOf({copy},view,rect)!=original,"style mutation invalidates cache");};
+ changes([](auto& s){s.bold=true;});changes([](auto& s){s.italic=true;});
+ changes([](auto& s){s.marginL=10;});changes([](auto& s){s.marginR=10;});changes([](auto& s){s.marginV=10;});
+ changes([](auto& s){s.back=0xFF112233;});changes([](auto& s){s.background=true;});
+ changes([](auto& s){s.outlineWidth=3;});changes([](auto& s){s.shadow=3;});changes([](auto& s){s.size+=.001;});
+ updateSubtitleOverlay(overlay,{red},view);auto before=pixels;int count=updates;
+ updateSubtitleOverlay(overlay,{red},view);check(updates==count,"unchanged cues reuse cache");
+ red.style.bold=true;updateSubtitleOverlay(overlay,{red},view);
+ check(updates==count+1&&pixels!=before,"bold change repaints actual raster");
+ DestroyWindow(overlay);DestroyWindow(parent);Gdiplus::GdiplusShutdown(token);
+ return failures?1:0;
+}
diff --git a/tests/unit/CaptureCompressedDecoderTests.cpp b/tests/unit/CaptureCompressedDecoderTests.cpp
index d26291bf..4e7e3a8f 100644
--- a/tests/unit/CaptureCompressedDecoderTests.cpp
+++ b/tests/unit/CaptureCompressedDecoderTests.cpp
@@ -7,8 +7,11 @@
#include "veyra/source/CaptureCompressedDecoder.h"
#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/media/FFmpegVideoDecoder.h"
#include <iostream>
+#include <algorithm>
+#include <map>
#include <string>
#include <vector>
@@ -17,6 +20,7 @@ extern "C" {
#include <libavcodec/bsf.h>
#include <libavformat/avformat.h>
#include <libavutil/frame.h>
+#include <libavutil/adler32.h>
}
using namespace veyra;
@@ -27,6 +31,7 @@ struct ElementaryStream {
int width = 0, height = 0;
source::CaptureCodec codec = source::CaptureCodec::None;
std::vector<std::vector<uint8_t>> accessUnits;
+ std::vector<int64_t> pts;
};
bool loadAnnexB(const char* path, ElementaryStream& stream, std::string& error)
@@ -88,6 +93,7 @@ bool loadAnnexB(const char* path, ElementaryStream& stream, std::string& error)
if (packet->stream_index == videoIndex && av_bsf_send_packet(bsf, packet) >= 0) {
while (av_bsf_receive_packet(bsf, filtered) >= 0) {
stream.accessUnits.emplace_back(filtered->data, filtered->data + filtered->size);
+ stream.pts.push_back(av_rescale_q(filtered->pts,bsf->time_base_out,AVRational{1,10000000}));
av_packet_unref(filtered);
}
}
@@ -109,9 +115,11 @@ struct DecodeRun {
uint64_t failures = 0;
bool sawHardwareFrame = false;
std::string firstError;
+ std::map<int64_t,uint32_t> pixels;
+ bool recovered=false;
};
-DecodeRun decodeAll(ElementaryStream& stream, ID3D12Device* device, ID3D12CommandQueue* queue)
+DecodeRun decodeAll(ElementaryStream& stream, ID3D12Device* device, ID3D12CommandQueue* queue,bool injectLoss=false)
{
DecodeRun run;
source::CaptureCompressedDecoder decoder;
@@ -130,13 +138,25 @@ DecodeRun decodeAll(ElementaryStream& stream, ID3D12Device* device, ID3D12Comman
++run.failures;
return run;
}
- int64_t pts = 0;
+ size_t inputIndex=0;
+ auto displayPts=stream.pts;std::sort(displayPts.begin(),displayPts.end());
+ bool awaitingKey=false;
for (const auto& unit : stream.accessUnits) {
+ if(injectLoss&&inputIndex==7){decoder.recoverAtKeyframe();awaitingKey=true;}
+ if(injectLoss&&inputIndex>=7&&inputIndex<10){++inputIndex;continue;}
AVFrame* out = nullptr;
bool hardware = false;
- const bool produced = decoder.decode(unit.data(), unit.size(), pts, target, &out, hardware);
+ const bool produced = decoder.decode(unit.data(), unit.size(), stream.pts[inputIndex++], target, &out, hardware);
if (produced) {
++run.frames;
+ if(!injectLoss&&(run.frames>displayPts.size()||out->pts!=displayPts[run.frames-1])){++run.failures;run.firstError="decoded PTS was lost or assigned from current packet";}
+ if(awaitingKey){
+ if(!(out->flags&AV_FRAME_FLAG_KEY)){++run.failures;run.firstError="recovery exposed a dependent frame before keyframe";}
+ awaitingKey=false;run.recovered=true;
+ }
+ if(!hardware){uint32_t checksum=1;for(int plane=0;plane<2;++plane)for(int y=0;y<(plane?out->height/2:out->height);++y)
+ checksum=av_adler32_update(checksum,out->data[plane]+ptrdiff_t(y)*out->linesize[plane],out->width);
+ run.pixels[out->pts]=checksum;}
if (hardware) {
run.sawHardwareFrame = true;
if (out == nullptr || out->format != AV_PIX_FMT_D3D12 || out->data[0] == nullptr) {
@@ -151,12 +171,58 @@ DecodeRun decodeAll(ElementaryStream& stream, ID3D12Device* device, ID3D12Comman
if (run.firstError.empty()) run.firstError = decoder.lastError();
++run.failures;
}
- pts += 333667;
+ AVFrame* remaining=nullptr;bool remainingHardware=false;
+ if(decoder.decode(nullptr,0,0,target,&remaining,remainingHardware)||!decoder.waitingForInput()){
+ ++run.failures;run.firstError="receive-only drain returned stale output or an error";
+ }
}
av_frame_free(&target);
return run;
}
+bool packetRetryTest(const char* path,gfx::D3D12DeviceContext& device) {
+ AVFormatContext* format=nullptr;
+ if(avformat_open_input(&format,path,nullptr,nullptr)<0)return false;
+ if(avformat_find_stream_info(format,nullptr)<0){avformat_close_input(&format);return false;}
+ int index=av_find_best_stream(format,AVMEDIA_TYPE_VIDEO,-1,-1,nullptr,0);
+ if(index<0){avformat_close_input(&format);return false;}
+ auto* stream=format->streams[index];
+ media::FFmpegVideoDecoder reference,batched;
+ bool ok=reference.openSoftware(stream->codecpar,stream->time_base.num,stream->time_base.den)&&batched.openSoftware(stream->codecpar,stream->time_base.num,stream->time_base.den);
+ std::vector<int64_t> expected,actual;
+ auto drain=[](auto& decoder,auto& pts){while(auto* f=decoder.receiveFrame())pts.push_back(f->pts);};
+ AVPacket* packet=av_packet_alloc();size_t count=0;
+ while(ok&&av_read_frame(format,packet)>=0){
+ if(packet->stream_index==index){
+ ok=reference.sendPacket(packet)&&batched.sendPacket(packet);++count;
+ drain(reference,expected);
+ if(count%8==0)drain(batched,actual); // deliberately forces send EAGAIN
+ }
+ av_packet_unref(packet);
+ }
+ ok=ok&&reference.sendPacket(nullptr)&&batched.sendPacket(nullptr);
+ drain(reference,expected);drain(batched,actual);
+ ok=ok&&!expected.empty()&&expected==actual&&batched.stats().framesSubmitted==count&&batched.stats().packetRetries>0;
+ batched.flushBuffers();
+ ok=ok&&!batched.receiveFrame()&&batched.receiveStatus()==media::DecodeReceiveStatus::NeedInput;
+ std::cout<<(ok?"PASS ":"FAIL ")<<"EAGAIN resend, output order, accepted count and flush frames="<<actual.size()<<" retries="<<batched.stats().packetRetries<<'\n';
+ media::FFmpegVideoDecoder interop;
+ for(int pass=0;ok&&pass<3;++pass){
+ ok=av_seek_frame(format,index,0,AVSEEK_FLAG_BACKWARD)>=0&&interop.openD3D11VA(stream->codecpar,stream->time_base.num,stream->time_base.den,device.adapter().luid,device.device());
+ std::vector<int64_t> imported;
+ auto receive=[&]{while(auto* frame=interop.receiveFrame()){ok=ok&&interop.hardwareFrameImportable();imported.push_back(frame->pts);}};
+ while(ok&&av_read_frame(format,packet)>=0){
+ if(packet->stream_index==index){ok=interop.sendPacket(packet);receive();}
+ av_packet_unref(packet);
+ }
+ ok=ok&&interop.sendPacket(nullptr);receive();
+ ok=ok&&imported==expected;interop.close();interop.close();
+ }
+ std::cout<<(ok?"PASS ":"FAIL ")<<"D3D11VA repeated open/decode/close, import and PTS\n";
+ av_packet_free(&packet);avformat_close_input(&format);
+ return ok;
+}
+
} // namespace
int main(int argc, char** argv)
@@ -179,8 +245,10 @@ int main(int argc, char** argv)
}
int failures = 0;
+ if(!packetRetryTest(path,context))++failures;
const auto hardware = decodeAll(stream, context.device(), context.directQueue());
const auto software = decodeAll(stream, nullptr, nullptr);
+ const auto recovery = decodeAll(stream, nullptr, nullptr,true);
std::cout << "hardware frames=" << hardware.frames << " failures=" << hardware.failures
<< " sawD3D12=" << hardware.sawHardwareFrame << " error=" << hardware.firstError << '\n';
std::cout << "software frames=" << software.frames << " failures=" << software.failures
@@ -193,6 +261,8 @@ int main(int argc, char** argv)
check(hardware.failures == 0 && hardware.frames > 0, "hardware decode produces frames without errors");
check(hardware.sawHardwareFrame, "hardware backend returns importable D3D12 frames");
check(software.failures == 0 && software.frames > 0, "software decode produces frames without errors");
+ bool samePixels=true;for(const auto& [pts,pixels]:recovery.pixels){auto found=software.pixels.find(pts);samePixels=samePixels&&found!=software.pixels.end()&&found->second==pixels;}
+ check(recovery.recovered&&recovery.failures==0&&samePixels,"packet loss resumes at keyframe with reference-identical pixels and PTS");
// B-frame reordering may emit a slightly different count on the software
// path; the hardware and software backends must stay within one frame.
const uint64_t difference = hardware.frames > software.frames ? hardware.frames - software.frames : software.frames - hardware.frames;