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(export,media): CFR whole-slot gap fill with honest hold frames + D3D11VA HEVC decode path (IMAX MKV), plus the headless export probe

Veyra Goal Agentb3052cc293b9
diff --git a/CMakeLists.txt b/CMakeLists.txt
index d33c5bb9..a695aff4 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -416,7 +416,9 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
# (Playbook 5.3: never let third-party headers block the build).
target_compile_options(veyra_media PRIVATE /WX-)
target_compile_features(veyra_media PUBLIC cxx_std_20)
- target_link_libraries(veyra_media PUBLIC veyra_base veyra_gfx)
+ # d3d11: the HEVC hardware path decodes on a private D3D11VA device and shares
+ # the surfaces with the D3D12 graph as NT handles.
+ target_link_libraries(veyra_media PUBLIC veyra_base veyra_gfx d3d11)
target_include_directories(veyra_media PUBLIC ${FFMPEG_INCLUDE_DIRS})
target_link_directories(veyra_media PUBLIC ${FFMPEG_LIBRARY_DIRS})
target_link_libraries(veyra_media PUBLIC ${FFMPEG_LIBRARIES})
@@ -741,6 +743,12 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_compile_features(veyra_hw_import_image_tests PRIVATE cxx_std_20)
target_compile_definitions(veyra_hw_import_image_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
target_link_libraries(veyra_hw_import_image_tests PRIVATE veyra_engine)
+ # Headless export harness: verifies the frame-timestamp policy (tail snap,
+ # dropped-sample gap fill, hard refusal) without the GUI.
+ add_executable(veyra_export_probe tools/export_probe/main.cpp)
+ target_compile_features(veyra_export_probe PRIVATE cxx_std_20)
+ target_compile_definitions(veyra_export_probe PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+ target_link_libraries(veyra_export_probe PRIVATE veyra_engine)
target_compile_features(veyra_hdr_color_tests PRIVATE cxx_std_20)
target_compile_definitions(veyra_hdr_color_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
target_link_libraries(veyra_hdr_color_tests PRIVATE veyra_engine)
diff --git a/docs/DIAG_HEVC_D3D12VA_AND_EXPORT_CFR_2026-09-17.md b/docs/DIAG_HEVC_D3D12VA_AND_EXPORT_CFR_2026-09-17.md
index a5718809..612457d1 100644
--- a/docs/DIAG_HEVC_D3D12VA_AND_EXPORT_CFR_2026-09-17.md
+++ b/docs/DIAG_HEVC_D3D12VA_AND_EXPORT_CFR_2026-09-17.md
@@ -193,3 +193,101 @@ ffmpeg -hide_banner -loglevel verbose -hwaccel d3d11va -i IMAX.mkv -frames:v 60
# Veyra 本体(任意 HEVC 文件都会复现)
Veyra.exe <any_hevc.mkv> --smoke-seconds 6
```
+
+## 8. 修复实施:HEVC 改走 D3D11VA(2026-09-17 当天完成)
+
+用户决定:**HEVC 一律接 D3D11VA,不再用 D3D12VA 碰运气。**
+
+### 8.1 实现
+
+| 文件 | 改动 |
+|---|---|
+| `include/veyra/media/FFmpegVideoDecoder.h` / `src/media/FFmpegVideoDecoder.cpp` | 新增 `openD3D11VA()`(同适配器私有 D3D11 设备 + 共享纹理环 + D3D11→D3D12 fence)、`HardwareSurfaceView`、`receiveFrame()` 里逐帧发布共享面;`hardwareFrameImportable()` 支持 D3D11 面 |
+| `include/veyra/pipeline/FramePacket.h` | 新增 `HardwareSurfaceInput`(纹理 / 子资源 / 等待 fence / 纹理尺寸),随帧包传递 |
+| `include/veyra/pipeline/EnhanceGraph.h` / `src/pipeline/EnhanceGraph.cpp` | `process()` 增加硬件面参数;ingress 支持 `AV_PIX_FMT_D3D11`,与 D3D12VA 共用同一段 SRV/等待逻辑 |
+| `include/veyra/source/IFrameSource.h` / `src/source/MediaFileSource.cpp` | `SourceOpenDesc.d3d12AdapterLuid`、`SourceInfo.videoDecodePath`;**HEVC → D3D11VA**,其余编码仍走 D3D12VA,失败再软解 |
+| `include/veyra/gfx/D3D12DeviceContext.h` / `src/gfx/D3D12DeviceContext.cpp` | `AdapterInfo.luid`(D3D11 设备需要同适配器) |
+| `src/engine/EngineController.cpp` / `src/engine/VideoExportJob.cpp` 等 | 传 adapter LUID 与 `&packet.hardwareSurface` |
+| `tests/integration/HardwareImportImageTests.cpp` | 支持两种硬件路径,打印真实解码路径与共享面信息 |
+| `CMakeLists.txt` | `veyra_media` 链接 `d3d11` |
+
+### 8.2 为什么是"拷贝进自己的共享纹理"而不是直接共享解码面
+
+实测(本机 RTX 5070 / 616.56):
+
+1. 给 FFmpeg 的解码池加 `SHARED_NTHANDLE` → `[AVHWFramesContext] Could not create the texture (80070057)`,
+ 即驱动拒绝在 **DXVA 解码输出纹理**上开共享。
+2. 自己新建一张 NV12 纹理,只加 `SHARED_NTHANDLE` → 同样 `0x80070057`。
+3. 换成 `D3D11_RESOURCE_MISC_SHARED | D3D11_RESOURCE_MISC_SHARED_NTHANDLE`(NT 句柄共享的标准组合)
+ → 创建成功,D3D12 `OpenSharedHandle` 成功。
+
+所以最终结构:FFmpeg 用标准(非共享)解码池 → 每帧把解码切片 **GPU 拷贝**进我们自己的共享纹理环(8 槽,
+保留解码对齐尺寸)→ D3D11 fence 加信号 → 图在 D3D12 队列上 `Wait` 一次再采样。全程零回读、零 CPU 等待。
+图入口本来就按**绝对 texel 索引**差分采样,所以对齐留白(HEVC 128 对齐)天然不会被读进来。
+
+槽位复用安全性:应用每 `read()` 一帧才提交一次 D3D12 工作,而 6 个命令槽会强制"第 N 帧提交前,第 N-6 帧
+的 GPU 工作已完成";8 槽 > 6+1,因此一个槽在 8 帧后被重写时,它上一次的读取已经完成。同一槽内的两次拷贝
+之间还有 D3D11 侧 fence 等待兜底。
+
+### 8.3 验证(`veyra_hw_import_image_tests`,硬解 vs 软解逐像素全图对比)
+
+| 输入 | 解码路径 | 解码面 | 结果 |
+|---|---|---|---|
+| 1280x720 HEVC(本机 NVENC) | `d3d11va` | 1280x768(对齐) | `FULL_IMAGE_PASS=1 worst=0` |
+| 3840x2160 HEVC(本机 NVENC) | `d3d11va` | 3840x2176(对齐) | `FULL_IMAGE_PASS=1 worst=0` |
+| **IMAX 3840x2024 HEVC(用户文件)** | `d3d11va` | 3840x2048(对齐) | `FULL_IMAGE_PASS=1 worst=0` |
+| 1080x1920 H.264(回归) | `d3d12va`(未变) | 1080x1920 | `FULL_IMAGE_PASS=1 worst=0` |
+
+`worst=0` = 4 帧全图平均绝对误差为 0,说明共享/拷贝/裁剪链路与软解完全一致,没有颜色或几何失真;
+测试内附带的 `hardwareImportFixtures`(1/3 切片纹理阵列)同样通过。
+
+### 8.4 未验证(不许当作已通过)
+
+- **没有跑 Veyra 本体 smoke**:构建目录里的 `veyra.exe` 被另一个正在运行的实例占用。
+ 全目标编译(`cmake --build <dir> -- -k 0`)结果:**105/105 个其他目标全部编译+链接通过**,唯一失败的是
+ `veyra.exe` 的链接(`LNK1104: 无法打开文件"veyra.exe"`,纯文件锁)。因此"打开 IMAX 文件、播放 30 秒"
+ 这一条留给用户顺手验收。
+- 10-bit HEVC(P010)未测;AMD/Intel 适配器未测;低延迟(采集)路径未测。
+- 8 槽复用的推理依赖"应用 6 命令槽 + 每次 read 提交一帧"这一当前架构,改环大小或改调度需重新评估。
+
+## 9. 导出修复:整槽缺口补帧(同日晚,用户拍板"把导出修复一下")
+
+### 9.1 策略
+
+- **只有"正好缺整数个网格槽位"才补**:`CfrTimeline::missingSlots()` 要求该帧时间戳落在网格上
+ (残差 ≤ 半个容器 tick),且相对当前索引前移 1..2 槽。落在网格外(真 VFR 抖动)或跳幅超过 2 槽的源,
+ **照旧硬失败**,输出不落地。
+- 缺口用**上一帧真实画面重复填充**(`multiplier` 个输出帧,与正常一格的输出格数一致),**不伪造插值**:
+ DLSS-G 无法用"同一帧"做插值,硬插会编造运动。补帧计入 `hold`,并单独统计 `gapFillEvents/gapFilledSlots`。
+- 补完立刻 `CfrTimeline::resync()` 重锚相位,后续帧继续严格校验;预检的 120 帧抽样
+ (`CfrTimeline::select()`)也认同样的整槽缺口,否则文件会在进循环前就被拒。
+- 结束语会写清楚:`(源文件缺帧 N 处/M 帧,已按恒定帧率复制上一帧补齐)`;日志另有一行
+ `[export-timeline] gap filled … (previous frame repeated; no interpolation invented)`。
+
+### 9.2 验证
+
+素材:`testsrc2` 30fps / 6.000s / 180 帧 CFR,用 `select` 精确抠掉样点(保留时间轴):
+`exp_hole1.mp4`(缺第 60 帧,179 帧,时间戳 1.9333→2.0333)与 `exp_hole3.mp4`(缺 60/61/62,177 帧)。
+
+| 用例 | 命令 | 结果 |
+|---|---|---|
+| 单元策略 | `veyra_repair_contract_tests` | **197 checks / 0 failures**(新增 6 项:缺口识别、网格外抖动拒绝、>2 槽拒绝、resync 后重对齐) |
+| 缺 1 帧导出 | `veyra_export_probe exp_hole1.mp4 out_hole1.mp4` | **exit 0**;`gap filled source=60 … missingSlots=1`;`source=179 hold=1 output=180 gapFillEvents=1`;`export-verify decoded=180 expected=180 passed=true` |
+| 缺 3 帧导出 | `veyra_export_probe exp_hole3.mp4 out_hole3.mp4` | **exit 1**,`CFR rejected source=preflight`,**不生成输出文件**(边界未被放宽) |
+| 无缺口回归 | `veyra_export_probe exp_src.mp4 out_clean.mp4` | exit 0,`gapFillEvents=0 hold=0 output=180`,verify 通过 |
+| **应用本体无界面导出** | `Veyra.exe exp_hole1.mp4 --export-out … --max-frames 80` | **exitCode=0**,输出存在,`[app] export result=true`,verify `decoded=81 expected=81` |
+| 补的是不是"上一帧" | 输出第 60 帧 vs 源各帧 PSNR | 源第 59 帧(洞前最后一张)**43.64 dB**,源第 60 帧(洞后第一张)20.47 dB,源第 57 帧 22.20 dB → 确为重复上一帧,不是插值/编造 |
+
+### 9.3 改动文件
+
+`include/veyra/engine/CfrTimeline.h`(`missingSlots()` / `resync()` / `select()` 缺口容忍)、
+`src/engine/VideoExportJob.cpp`(补帧 + 重锚 + 计数 + 收尾文案)、
+`tests/unit/RepairContractTests.cpp`(策略用例)、
+`tools/export_probe/main.cpp` + `CMakeLists.txt`(无界面导出验证台)。
+
+### 9.4 边界(如实记录)
+
+- 只补 1..2 槽;3 槽以上或网格外偏差仍然拒绝——**没有把 VFR 源悄悄当 CFR 导出**。
+- 缺口处是"冻结上一帧",缺口后第一帧的 DLSSG 插值仍取自(洞前, 洞后)两帧;那一处运动速度会比真实
+ 时间轴略快,属于源素材本身丢帧的固有代价,不额外伪造。
+- 补帧数计入 `hold`(导出摘要里的"重复帧"),未新增 `ExportCounts` 字段以免动 UI 契约。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 9ae48b7d..4b51cf2a 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -101,8 +101,23 @@ veyra.exe capture:0:0:0 --smoke-seconds 120 --color-grade=1.0 # 链路开(+1
- 1080x1920 H.264 → 仍 `path=d3d12va`,`worst=0`,无回归。
- 测试内 `hardwareImportFixtures`(1/3 切片阵列)同样通过。
-**未验证**:Veyra 本体 smoke(构建目录 `veyra.exe` 被另一个运行中的实例占用,编译全过、只差最后链接)、
-10-bit P010、AMD/Intel、采集低延迟路径。**本轮未提交、未发布、未替换便携包。**
+**未验证**:GUI 里打开 IMAX 文件的播放 smoke(`veyra.exe` 已链接成功、应用级无界面导出已实测,但没跑
+窗口播放);10-bit P010、AMD/Intel、采集低延迟路径。**本轮未提交、未发布、未替换便携包。**
+
+#### 再后续:导出整槽缺口补帧(用户拍板"把导出修复一下")
+
+- 策略:`CfrTimeline::missingSlots()` 只认"落在网格上、前移 1..2 槽"的缺口(残差 ≤ 半个容器 tick),
+ 补帧用**上一帧真实画面重复** `multiplier` 次,**不伪造插值**;补完 `resync()` 重锚相位;预检
+ `select()` 的 120 帧抽样同样容忍整槽缺口(否则文件在进循环前就被拒)。网格外抖动或 >2 槽照旧硬失败。
+- 改动:`include/veyra/engine/CfrTimeline.h`、`src/engine/VideoExportJob.cpp`、
+ `tests/unit/RepairContractTests.cpp`、新增 `tools/export_probe`(无界面导出验证台)+ `CMakeLists.txt`。
+- 验证:单元 **197 checks / 0 failures**;`exp_hole1.mp4`(缺 1 帧)导出 **exit 0**,
+ `gap filled source=60 missingSlots=1`、`source=179 hold=1 output=180 gapFillEvents=1`、
+ `export-verify decoded=180 expected=180 passed=true`;`exp_hole3.mp4`(缺 3 帧)仍 **exit 1 + 无输出**;
+ 无缺口素材 `gapFillEvents=0` 正常;**应用本体无界面导出**(`Veyra.exe … --export-out … --max-frames 80`)
+ `exitCode=0`、`export result=true`;补帧正确性用 PSNR 证明:输出第 60 帧 vs 源第 59 帧 **43.64 dB**
+ (vs 洞后第一帧 20.47 dB),确为重复上一帧,不是插值。
+- 全目标编译 `-k 0` → **21/21 全部链接成功(含 veyra.exe)**。仍未提交、未发布。
用户报两件事:`IMAX.Laser.Pre.Show.New.2160P.DDP5.1.Atmos-ZhiLuan.mkv` 打不开;另一台机器上
连续两次导出跑到一半中止(`C:\Users\123\Desktop\导出失败\`)。
diff --git a/include/veyra/engine/CfrTimeline.h b/include/veyra/engine/CfrTimeline.h
index 6cf832b8..c152fb5a 100644
--- a/include/veyra/engine/CfrTimeline.h
+++ b/include/veyra/engine/CfrTimeline.h
@@ -32,6 +32,35 @@ public:
const double interval = double(den_) / num_;
return std::abs(pts - expected(index)) <= 1.5 * interval + quantum_;
}
+ // Recovery for containers that are missing whole samples (a recording that
+ // dropped a frame but kept its timeline): a source frame landing exactly on
+ // a later grid slot is a hole the exporter can fill by repeating the
+ // previous frame, instead of aborting a mostly-fine multi-hour export.
+ // Returns the number of missing slots, or 0 when this is not a clean
+ // whole-slot gap (exactly on grid, ahead by 1..maxSlots slots).
+ uint64_t missingSlots(uint64_t index, double pts, double maxSlots = 2.0) const {
+ if(!valid() || !std::isfinite(pts) || quantum_ <= 0 || maxSlots < 1.0 || !std::isfinite(maxSlots)) return 0;
+ const double interval = double(den_) / num_;
+ const double slot = (pts - origin_) / interval;
+ const double nearest = std::round(slot);
+ // The frame must sit on the grid to the container's own tick accuracy;
+ // anything else is real VFR and stays refused.
+ if(std::abs(slot - nearest) * interval > quantum_ * 0.5 + 1e-9) return 0;
+ const double missing = nearest - double(index);
+ if(missing < 1.0 || missing > maxSlots + 1e-9) return 0;
+ return uint64_t(std::llround(missing));
+ }
+ // Re-aligns the grid after a filled gap. Only call with the same (index,
+ // pts) that missingSlots() accepted: the stream is grid-aligned again from
+ // this frame on, so the phase window restarts here.
+ void resync(uint64_t index, double pts) {
+ if(!valid() || !std::isfinite(pts)) return;
+ origin_ = pts - double(index) * double(den_) / num_;
+ low_ = -quantum_ / 2;
+ high_ = quantum_ / 2;
+ previous_ = pts;
+ havePrevious_ = true;
+ }
bool accepts(uint64_t index, double pts) {
if(!valid() || !std::isfinite(pts) || (havePrevious_ && pts<=previous_))return false;
const double error=pts-expected(index);
@@ -43,7 +72,19 @@ public:
}
static std::pair<int,int> select(int nominalNum,int nominalDen,double quantum,std::span<const double> samples) {
if(samples.empty())return {0,0};
- auto fits=[&](int n,int d){CfrTimeline t(n,d,quantum,samples.front());for(size_t i=0;i<samples.size();++i)if(!t.accepts(i,samples[i]))return false;return t.valid();};
+ // Whole-slot holes (a dropped sample in the middle of the scan window)
+ // are tolerated the same way the export loop fills them; irregular
+ // timing still disqualifies the rate.
+ auto fits=[&](int n,int d){
+ CfrTimeline t(n,d,quantum,samples.front());uint64_t index=0;
+ for(size_t i=0;i<samples.size();++i){
+ if(t.accepts(index,samples[i])){++index;continue;}
+ if(t.missingSlots(index,samples[i])==0)return false;
+ t.resync(index,samples[i]);
+ ++index;
+ }
+ return t.valid();
+ };
// Prefer a declared standard rate when consistent. Otherwise choose a
// simple, timestamp-consistent standard candidate, then the declaration.
// Quantized short clips cannot prove a unique exact original rate.
diff --git a/include/veyra/media/FFmpegVideoDecoder.h b/include/veyra/media/FFmpegVideoDecoder.h
index d0c76112..15a7941a 100644
--- a/include/veyra/media/FFmpegVideoDecoder.h
+++ b/include/veyra/media/FFmpegVideoDecoder.h
@@ -13,6 +13,7 @@ struct AVFrame;
struct AVPacket;
struct AVBufferRef;
struct ID3D11Device;
+struct ID3D11DeviceContext;
struct ID3D11DeviceContext4;
struct ID3D11Fence;
struct ID3D11Texture2D;
@@ -113,6 +114,12 @@ public:
&& hwAccelKind_ == HardwareDecodeKind::D3D11VA;
}
bool hardwareActive() const { return hwAccelActive_ && context_ != nullptr; }
+ // Decode path actually in use, for telemetry/UI labels: "d3d12va",
+ // "d3d11va" or "software". Do not label a session with a path it is not on.
+ const char* decodePathName() const {
+ if (!hwAccelActive_) { return "software"; }
+ return hwAccelKind_ == HardwareDecodeKind::D3D11VA ? "d3d11va" : "d3d12va";
+ }
// Latest decoded surface for the D3D11VA path; only valid after
// receiveFrame() returned a frame and receiveStatus() == Frame.
const HardwareSurfaceView& hardwareSurface() const { return hardwareSurface_; }
@@ -126,7 +133,21 @@ public:
private:
enum class HardwareDecodeKind { None, D3D12VA, D3D11VA };
+ // Decoded slices are copied into these D3D11 textures, which are shared to
+ // D3D12 as NT handles. The ring is oversized for the app's six command
+ // slots, so a slot is only rewritten well after the graph finished reading
+ // it (see the comment in receiveFrame()).
+ static constexpr uint32_t kInteropSlotCount = 8;
+ struct InteropSlot {
+ ID3D11Texture2D* texture = nullptr;
+ ID3D12Resource* resource = nullptr;
+ uint32_t width = 0;
+ uint32_t height = 0;
+ uint64_t lastFenceValue = 0;
+ };
+
ID3D12Resource* importD3D11Texture(ID3D11Texture2D* texture);
+ bool createInteropSlots(const void* sourceDesc);
bool createInteropFence(ID3D12Device* d3d12Device);
void releaseInterop();
@@ -145,11 +166,15 @@ private:
// the extra device reference, the fence pair and the opened texture views.
AVBufferRef* d3d11DeviceRef_ = nullptr;
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
ID3D12Device* d3d12Device_ = nullptr; // borrowed from the caller
ID3D12Fence* d3d12Fence_ = nullptr;
uint64_t interopFenceValue_ = 0;
+ uint64_t interopFrameIndex_ = 0;
+ uint32_t interopSlotIndex_ = 0;
+ InteropSlot interopSlots_[kInteropSlotCount];
HardwareSurfaceView hardwareSurface_{};
struct D3D11TextureImport { ID3D12Resource* resource = nullptr; bool logged = false; };
// One decoder pool is a single texture array, so this map stays tiny; the
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index 9f00734a..060fb409 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -55,6 +55,8 @@ class NvOfSession;
namespace veyra::pipeline {
struct ColorDescription;
+// Decoded-surface view for the D3D11VA ingress (defined in FramePacket.h).
+struct HardwareSurfaceInput;
// One generated-frame texture per (parity, subframe): 2 parities x 5 generated
// frames = 6X multi-frame generation. Sized once, reused for every FG backend.
@@ -159,7 +161,10 @@ public:
// temporal epoch (open/seek/...): NVOF/FG history is not consumed.
// Returns false on hard failure (run verdict must FAIL).
using FgAdmission=std::function<bool(const FrameBatch&)>;
- bool process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId = 0, const ColorDescription* color = nullptr, bool retainReferences = true, const FgAdmission& admitFg = {});
+ // `hardwareSurface` carries the decoded texture for paths whose surface
+ // does not travel inside the AVFrame (D3D11VA). It must be provided exactly
+ // when frame->format == AV_PIX_FMT_D3D11 and is unused otherwise.
+ bool process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId = 0, const ColorDescription* color = nullptr, const HardwareSurfaceInput* hardwareSurface = nullptr, bool retainReferences = true, const FgAdmission& admitFg = {});
bool nextFrameSlotAvailable()const {
const unsigned slot=unsigned(realFrameIndex_%2);
if(!realLeases_[slot].expired())return false;
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 48193570..15228617 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -199,10 +199,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// capability check and records its fallback.
od.preferHardwareDecode=true;
od.d3d12Device=ctx.device();od.d3d12Queue=ctx.directQueue();
+ od.d3d12AdapterLuid=ctx.adapter().luid;
// Diagnostic uses the production graph/presenter to validate
// D3D12VA imports without needing a paired PS5 or credentials.
if(!isCapture&&GetEnvironmentVariableW(L"VEYRA_TEST_FILE_HW_DECODE",nullptr,0)){
- od.preferHardwareDecode=true;od.d3d12Device=ctx.device();od.d3d12Queue=ctx.directQueue();
+ od.preferHardwareDecode=true;od.d3d12Device=ctx.device();od.d3d12Queue=ctx.directQueue();od.d3d12AdapterLuid=ctx.adapter().luid;
}
// Audio ingress policy has to be in place before the capture
// graph negotiates its media type, otherwise the first connect
@@ -778,7 +779,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(cachedFrame){
pipeline::EnhanceGraph::FrameOutputs refreshed;
const double refreshPtsMs=cachedPacket.pts.toDouble()*1000.0;
- if(graph.process(cachedFrame,refreshPtsMs,true,refreshed,cachedPacket.sequence,&cachedPacket.colorInfo,false)){
+ if(graph.process(cachedFrame,refreshPtsMs,true,refreshed,cachedPacket.sequence,&cachedPacket.colorInfo,&cachedPacket.hardwareSurface,false)){
out=refreshed;
hasOutput=true;
{std::lock_guard lock(mutex_);++snapshot_.pausedFrameRefreshes;}
@@ -981,7 +982,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// settings/history or inventing GPU execution timestamps.
wchar_t testWork[16]{};
if(!isImage&&GetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",testWork,16))std::this_thread::sleep_for(std::chrono::milliseconds(std::clamp(_wtoi(testWork),0,150)));
- bool processed=false;{processWaitBase=ring.cpuWaitCount();processWaitMsBase=ring.cpuWaitMilliseconds();processSubmitBase=ring.submitCount();processed=!injectedReject&&graph.process(frame,pts,historyReset,out,pkt.sequence,&pkt.colorInfo,comparisonMode_!=0,admitFg);processSlotWaitMs=ring.cpuWaitMilliseconds()-processWaitMsBase;}
+ bool processed=false;{processWaitBase=ring.cpuWaitCount();processWaitMsBase=ring.cpuWaitMilliseconds();processSubmitBase=ring.submitCount();processed=!injectedReject&&graph.process(frame,pts,historyReset,out,pkt.sequence,&pkt.colorInfo,&pkt.hardwareSurface,comparisonMode_!=0,admitFg);processSlotWaitMs=ring.cpuWaitMilliseconds()-processWaitMsBase;}
previewSkipSinceProcess=false;
if(!processed){
const auto failedComponent=graph.failedBackend();
@@ -1009,7 +1010,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(transaction){
ring.drainQueue();out={};presenter.close();graph.shutdown();options=PlayerOptions::from(previous);
gd=previousDesc;
- if(graph.initialize(gd)&&presenter.open(ctx,window,graph,options.settings.captureCompatible)&&graph.createViews()&&graph.process(frame,pts,true,out,pkt.sequence,&pkt.colorInfo,comparisonMode_!=0)){
+ if(graph.initialize(gd)&&presenter.open(ctx,window,graph,options.settings.captureCompatible)&&graph.createViews()&&graph.process(frame,pts,true,out,pkt.sequence,&pkt.colorInfo,&pkt.hardwareSurface,comparisonMode_!=0)){
finishReset(diagnostics::ResetOutcome::RolledBack);
std::lock_guard lock(mutex_);desired_.rejectVideoRequest(requested,previous);snapshot_.desired=desired_;snapshot_.rejectedRevision=requested.revision;snapshot_.applying=desired_!=previous;snapshot_.status=L"参数执行失败,已整套回滚";transaction=false;
}else{status(L"参数回滚失败,已停止",true);break;}
diff --git a/src/engine/TiledImageProcessor.cpp b/src/engine/TiledImageProcessor.cpp
index cbf64507..ca3e49fd 100644
--- a/src/engine/TiledImageProcessor.cpp
+++ b/src/engine/TiledImageProcessor.cpp
@@ -65,7 +65,7 @@ bool TiledImageProcessor::process(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotR
tileSettings.revision=desc.settingsRevision;if(!graph.applySettings(tileSettings))return false;
pipeline::EnhanceGraph::FrameOutputs out;sink::RgbaImage tile;
// Every tile is a new spatial image, never a temporal neighbour.
- if(!graph.process(frame.get(),0,true,out,uint64_t(stats.tiles)+1,nullptr,false)||
+ if(!graph.process(frame.get(),0,true,out,uint64_t(stats.tiles)+1,nullptr,nullptr,false)||
!sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),tile))return false;
if(tile.width!=tileW||tile.height!=tileH)return false;
out={};
diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cpp
index 436a6806..0905b03c 100644
--- a/src/engine/VideoExportJob.cpp
+++ b/src/engine/VideoExportJob.cpp
@@ -43,7 +43,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
std::unique_ptr<sink::VideoEncoder> encoder;
AVFormatContext *mux=nullptr,*audioInput=nullptr;AVStream* videoStream=nullptr;AVStream* audioStream=nullptr;AVPacket* audioPacket=av_packet_alloc();
int audioIndex=-1;bool audioPending=false,audioEof=false,ok=false,headerWritten=false;int64_t written=0;double audioEndSeconds=0,videoOriginSeconds=0;
- uint64_t tailSnapped=0;
+ uint64_t tailSnapped=0,gapFilledSlots=0,gapFillEvents=0;
std::wstring encoderName;
std::wstring failureReason;
auto failAv=[&](const wchar_t* stage,int code){
@@ -206,12 +206,32 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
if(timeline.tailAccepts(sourceCount,pts,estimatedFrames)){
++tailSnapped;
veyra::log::warn("export-timeline",std::format("tail snap source={} pts={} expected={} deviationMs={:.3f} estimatedFrames={} outputIndex={}",sourceCount,pts,expectedPts,deviationMs,estimatedFrames,outputIndex));
+ } else if(const uint64_t missing=timeline.missingSlots(sourceCount,pts);missing>0&&lastReal){
+ // The source is missing whole samples here (a dropped frame
+ // that kept the timeline). Repeat the previous real frame for
+ // every missing slot so the exported grid stays continuous,
+ // then re-align the validator. No interpolation is invented
+ // for the hole and this is reported to the user, never silent.
+ const uint32_t multiplier=options.fg?options.fgMultiplier:1u;
+ veyra::log::warn("export-timeline",std::format(
+ "gap filled source={} pts={} expected={} deviationMs={:.3f} missingSlots={} outputIndex={} multiplier={} (previous frame repeated; no interpolation invented)",
+ sourceCount,pts,expectedPts,deviationMs,missing,outputIndex,multiplier));
+ ++gapFillEvents;gapFilledSlots+=missing;
+ bool fillOk=true;
+ for(uint64_t slotIndex=0;slotIndex<missing&&fillOk;++slotIndex){
+ for(uint32_t j=0;j<multiplier;++j){
+ if(!encoder->encode(lastReal->slot,false,outputIndex++)){fillOk=false;break;}
+ ++holdCount;
+ }
+ }
+ if(!fillOk){if(failureReason.empty())failureReason=L"缺口补帧编码失败,请查看编码器诊断";error=true;break;}
+ timeline.resync(sourceCount,pts);
} else {
progress(0,std::format(L"源文件第 {} 帧时间戳偏移 {:.1f} 毫秒,无法按恒定帧率无损对齐;已停止写入并保留 partial",sourceCount,deviationMs));
veyra::log::error("export-timeline",std::format("CFR rejected source={} pts={} expected={} deviationMs={:.3f} estimatedFrames={} outputIndex={}",sourceCount,pts,expectedPts,deviationMs,estimatedFrames,outputIndex));error=true;break;
}
}
- pipeline::EnhanceGraph::FrameOutputs out;if(!graph.process(frame,packet.pts.toDouble()*1000,sourceCount==0||pipeline::breaksHistory(packet.flags),out,packet.sequence,&packet.colorInfo,false)){error=true;break;}
+ pipeline::EnhanceGraph::FrameOutputs out;if(!graph.process(frame,packet.pts.toDouble()*1000,sourceCount==0||pipeline::breaksHistory(packet.flags),out,packet.sequence,&packet.colorInfo,&packet.hardwareSurface,false)){error=true;break;}
const auto readyStart=std::chrono::steady_clock::now();
while(!cancel&&!graph.resolveGeneration(out)){
if(std::chrono::steady_clock::now()-readyStart>std::chrono::seconds(2)){error=true;break;}
@@ -236,7 +256,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
if(error||cancel)break;
if(options.fg&&lastReal)for(uint32_t j=1;j<options.fgMultiplier;++j){if(!encoder->encode(lastReal->slot,false,outputIndex++)){error=true;break;}++holdCount;}
if(error)break;
- veyra::log::info("export-counts",std::format("source={} generated={} hold={} output={} multiplier={} tailSnapped={} backend={} encoder={} bitrateMbps={} note={} (CFR holds are not DLSSG)",sourceCount,generatedCount,holdCount,outputIndex,options.fg?options.fgMultiplier:1,tailSnapped,frameGenerationBackendName(options.settings.frameGenerationBackend),std::string(sink::encoderBackendName(encoder->backend())),options.settings.exportBitrateMbps,utf8(fgNote)));
+ veyra::log::info("export-counts",std::format("source={} generated={} hold={} output={} multiplier={} tailSnapped={} gapFillEvents={} gapFilledSlots={} backend={} encoder={} bitrateMbps={} note={} (CFR holds are not DLSSG)",sourceCount,generatedCount,holdCount,outputIndex,options.fg?options.fgMultiplier:1,tailSnapped,gapFillEvents,gapFilledSlots,frameGenerationBackendName(options.settings.frameGenerationBackend),std::string(sink::encoderBackendName(encoder->backend())),options.settings.exportBitrateMbps,utf8(fgNote)));
progress(.99,L"正在收尾:等待编码器输出剩余帧");
if(!encoder->finish()){if(failureReason.empty())failureReason=L"编码器收尾失败,请查看编码器诊断";break;}
if(!writeAudioUntil(audioEndSeconds))break;
@@ -286,6 +306,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
if(ok){
std::wstring done=encoderName.empty()?L"视频导出完成,逐帧完整性验证通过":std::format(L"视频导出完成({}),逐帧完整性验证通过",encoderName);
if(tailSnapped>0)done+=std::format(L"(尾部 {} 帧时间戳已按恒定帧率对齐)",tailSnapped);
+ if(gapFilledSlots>0)done+=std::format(L"(源文件缺帧 {} 处/{} 帧,已按恒定帧率复制上一帧补齐)",gapFillEvents,gapFilledSlots);
progress(1,fgNote.empty()?done:fgNote+L";"+done);
}
else {
diff --git a/src/media/FFmpegVideoDecoder.cpp b/src/media/FFmpegVideoDecoder.cpp
index 10db74b5..2993d669 100644
--- a/src/media/FFmpegVideoDecoder.cpp
+++ b/src/media/FFmpegVideoDecoder.cpp
@@ -208,6 +208,350 @@ bool FFmpegVideoDecoder::openD3D12VA(const AVCodecParameters* codecParameters,
return true;
}
+void FFmpegVideoDecoder::releaseInterop()
+{
+ for (auto& entry : d3d11Imports_) {
+ if (entry.second.resource != nullptr) {
+ entry.second.resource->Release();
+ }
+ }
+ d3d11Imports_.clear();
+ for (auto& slot : interopSlots_) {
+ if (slot.resource != nullptr) {
+ slot.resource->Release();
+ slot.resource = nullptr;
+ }
+ if (slot.texture != nullptr) {
+ slot.texture->Release();
+ slot.texture = nullptr;
+ }
+ slot.lastFenceValue = 0;
+ slot.width = slot.height = 0;
+ }
+ interopFrameIndex_ = 0;
+ interopSlotIndex_ = 0;
+ hardwareSurface_ = HardwareSurfaceView{};
+ if (d3d12Fence_ != nullptr) {
+ d3d12Fence_->Release();
+ d3d12Fence_ = nullptr;
+ }
+ if (d3d11Fence_ != nullptr) {
+ d3d11Fence_->Release();
+ d3d11Fence_ = nullptr;
+ }
+ d3d11Context4_ = nullptr; // borrowed from the FFmpeg device context
+ d3d11Context_ = nullptr; // borrowed from the FFmpeg device context
+ d3d12Device_ = nullptr; // borrowed from the caller
+ interopFenceValue_ = 0;
+ if (d3d11DeviceRef_ != nullptr) {
+ // Releases the FFmpeg device context (and its reference on our device).
+ av_buffer_unref(&d3d11DeviceRef_);
+ }
+ if (d3d11Device_ != nullptr) {
+ d3d11Device_->Release();
+ d3d11Device_ = nullptr;
+ }
+}
+
+bool FFmpegVideoDecoder::createInteropFence(ID3D12Device* d3d12Device)
+{
+ if (d3d11DeviceRef_ == nullptr || d3d11Device_ == nullptr || d3d12Device == nullptr) {
+ return false;
+ }
+ auto* hwDevice = reinterpret_cast<AVHWDeviceContext*>(d3d11DeviceRef_->data);
+ auto* hwctx = reinterpret_cast<AVD3D11VADeviceContext*>(hwDevice->hwctx);
+ if (hwctx->device_context == nullptr) {
+ log::error("media", "decoder: d3d11va device context missing; cannot create the interop fence");
+ return false;
+ }
+ d3d12Device_ = d3d12Device;
+
+ ComPtr<ID3D11Device5> device5;
+ HRESULT hr = d3d11Device_->QueryInterface(IID_PPV_ARGS(&device5));
+ if (FAILED(hr) || !device5) {
+ log::error("media", std::format("decoder: ID3D11Device5 unavailable hr={} (Windows 10 1703+ required for shared fences)", hrText(hr)));
+ return false;
+ }
+ ComPtr<ID3D11Fence> fence11;
+ hr = device5->CreateFence(0, D3D11_FENCE_FLAG_SHARED, IID_PPV_ARGS(&fence11));
+ if (FAILED(hr) || !fence11) {
+ log::error("media", std::format("decoder: ID3D11Device5::CreateFence(shared) failed hr={}", hrText(hr)));
+ return false;
+ }
+ HANDLE shared = nullptr;
+ hr = fence11->CreateSharedHandle(nullptr, GENERIC_ALL, nullptr, &shared);
+ if (FAILED(hr) || shared == nullptr) {
+ log::error("media", std::format("decoder: ID3D11Fence::CreateSharedHandle failed hr={}", hrText(hr)));
+ return false;
+ }
+ ComPtr<ID3D12Fence> fence12;
+ const HRESULT openHr = d3d12Device->OpenSharedHandle(shared, IID_PPV_ARGS(&fence12));
+ CloseHandle(shared);
+ if (FAILED(openHr) || !fence12) {
+ log::error("media", std::format("decoder: D3D12 OpenSharedHandle(fence) failed hr={}", hrText(openHr)));
+ return false;
+ }
+ ComPtr<ID3D11DeviceContext4> context4;
+ hr = hwctx->device_context->QueryInterface(IID_PPV_ARGS(&context4));
+ if (FAILED(hr) || !context4) {
+ log::error("media", std::format("decoder: ID3D11DeviceContext4 unavailable hr={}", hrText(hr)));
+ return false;
+ }
+ d3d11Context_ = hwctx->device_context; // borrowed, FFmpeg owns it
+ d3d11Fence_ = fence11.Detach();
+ d3d12Fence_ = fence12.Detach();
+ d3d11Context4_ = context4.Detach();
+ log::info("media", "decoder: d3d11va interop fence ready (D3D11 signal -> D3D12 queue wait, no CPU wait)");
+ return true;
+}
+
+bool FFmpegVideoDecoder::createInteropSlots(const void* sourceDescVoid)
+{
+ if (sourceDescVoid == nullptr || d3d11Device_ == nullptr || d3d12Device_ == nullptr) {
+ return false;
+ }
+ const auto& sourceDesc = *static_cast<const D3D11_TEXTURE2D_DESC*>(sourceDescVoid);
+ for (auto& slot : interopSlots_) {
+ D3D11_TEXTURE2D_DESC desc{};
+ desc.Width = sourceDesc.Width;
+ desc.Height = sourceDesc.Height;
+ desc.MipLevels = 1;
+ desc.ArraySize = 1;
+ desc.Format = sourceDesc.Format;
+ desc.SampleDesc = { 1, 0 };
+ desc.Usage = D3D11_USAGE_DEFAULT;
+ desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
+ // NT-handle sharing requires the legacy SHARED flag as well; the
+ // keyed mutex is not used because ordering is done with the fence pair.
+ desc.MiscFlags = D3D11_RESOURCE_MISC_SHARED | D3D11_RESOURCE_MISC_SHARED_NTHANDLE;
+ const HRESULT createHr = d3d11Device_->CreateTexture2D(&desc, nullptr, &slot.texture);
+ if (FAILED(createHr) || slot.texture == nullptr) {
+ log::error("media", std::format("decoder: shared copy texture {}x{} format={} failed hr={}",
+ desc.Width, desc.Height, static_cast<int>(desc.Format), hrText(createHr)));
+ return false;
+ }
+ ComPtr<IDXGIResource1> dxgiResource;
+ HRESULT hr = slot.texture->QueryInterface(IID_PPV_ARGS(&dxgiResource));
+ HANDLE shared = nullptr;
+ if (SUCCEEDED(hr) && dxgiResource) {
+ hr = dxgiResource->CreateSharedHandle(nullptr, DXGI_SHARED_RESOURCE_READ, nullptr, &shared);
+ }
+ if (FAILED(hr) || shared == nullptr) {
+ log::error("media", std::format("decoder: shared copy texture handle failed hr={}", hrText(hr)));
+ return false;
+ }
+ ComPtr<ID3D12Resource> resource;
+ const HRESULT openHr = d3d12Device_->OpenSharedHandle(shared, IID_PPV_ARGS(&resource));
+ CloseHandle(shared);
+ if (FAILED(openHr) || !resource) {
+ log::error("media", std::format("decoder: D3D12 open of the shared copy texture failed hr={}", hrText(openHr)));
+ return false;
+ }
+ slot.resource = resource.Detach();
+ slot.width = desc.Width;
+ slot.height = desc.Height;
+ }
+ log::info("media", std::format("decoder: d3d11va interop ring ready slots={} surface={}x{} format={}",
+ kInteropSlotCount, sourceDesc.Width, sourceDesc.Height, static_cast<int>(sourceDesc.Format)));
+ return true;
+}
+
+bool FFmpegVideoDecoder::openD3D11VA(const AVCodecParameters* codecParameters,
+ int streamTimeBaseNum, int streamTimeBaseDen,
+ uint64_t adapterLuid, ID3D12Device* d3d12Device, bool lowLatency)
+{
+ receiveStatus_ = DecodeReceiveStatus::NeedInput;
+ if (context_ != nullptr) {
+ close();
+ }
+ if (codecParameters == nullptr || d3d12Device == nullptr) {
+ return false;
+ }
+ frameTimeBaseNum_ = streamTimeBaseNum;
+ frameTimeBaseDen_ = streamTimeBaseDen;
+
+ const AVCodec* codec = avcodec_find_decoder(codecParameters->codec_id);
+ if (codec == nullptr) {
+ log::error("media", "decoder: no decoder for d3d11va codec");
+ return false;
+ }
+
+ // The D3D11 device has to live on the same adapter as the Veyra D3D12
+ // device, otherwise the decoded surfaces cannot be opened by D3D12.
+ const LUID luid{ static_cast<DWORD>(adapterLuid & 0xFFFFFFFFull),
+ static_cast<LONG>(adapterLuid >> 32) };
+ ComPtr<IDXGIFactory4> factory;
+ HRESULT hr = CreateDXGIFactory1(IID_PPV_ARGS(&factory));
+ ComPtr<IDXGIAdapter1> adapter;
+ if (SUCCEEDED(hr) && factory) {
+ hr = factory->EnumAdapterByLuid(luid, IID_PPV_ARGS(&adapter));
+ }
+ if (FAILED(hr) || !adapter) {
+ log::error("media", std::format("decoder: cannot resolve the D3D12 adapter LUID 0x{:X}:0x{:X} for D3D11VA hr={}",
+ uint32_t(adapterLuid >> 32), uint32_t(adapterLuid & 0xFFFFFFFFull), hrText(hr)));
+ return false;
+ }
+
+ // D3D11_CREATE_DEVICE_VIDEO_SUPPORT is the documented flag for decode
+ // devices; some adapters refuse it, so retry without it before giving up.
+ const D3D_FEATURE_LEVEL levels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0,
+ D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0 };
+ D3D_FEATURE_LEVEL featureLevel{};
+ ComPtr<ID3D11DeviceContext> immediate;
+ hr = D3D11CreateDevice(adapter.Get(), D3D_DRIVER_TYPE_UNKNOWN, nullptr,
+ D3D11_CREATE_DEVICE_VIDEO_SUPPORT, levels, UINT(sizeof(levels)/sizeof(levels[0])), D3D11_SDK_VERSION,
+ &d3d11Device_, &featureLevel, &immediate);
+ if (FAILED(hr)) {
+ log::warn("media", std::format("decoder: D3D11CreateDevice(video support) failed hr={}; retrying without the flag", hrText(hr)));
+ hr = D3D11CreateDevice(adapter.Get(), D3D_DRIVER_TYPE_UNKNOWN, nullptr,
+ 0, levels, UINT(sizeof(levels)/sizeof(levels[0])), D3D11_SDK_VERSION,
+ &d3d11Device_, &featureLevel, &immediate);
+ }
+ if (FAILED(hr) || d3d11Device_ == nullptr) {
+ log::error("media", std::format("decoder: D3D11CreateDevice failed hr={}", hrText(hr)));
+ d3d11Device_ = nullptr;
+ return false;
+ }
+ d3d11Device_->AddRef(); // FFmpeg's device context owns one reference
+ log::info("media", std::format("decoder: d3d11va device created featureLevel=0x{:X} luid=0x{:X}",
+ static_cast<unsigned>(featureLevel), adapterLuid));
+
+ AVBufferRef* deviceRef = av_hwdevice_ctx_alloc(AV_HWDEVICE_TYPE_D3D11VA);
+ if (deviceRef == nullptr) {
+ log::error("media", "decoder: av_hwdevice_ctx_alloc(D3D11VA) failed");
+ d3d11Device_->Release();
+ d3d11Device_ = nullptr;
+ return false;
+ }
+ {
+ auto* hwDevice = reinterpret_cast<AVHWDeviceContext*>(deviceRef->data);
+ auto* hwctx = reinterpret_cast<AVD3D11VADeviceContext*>(hwDevice->hwctx);
+ hwctx->device = d3d11Device_;
+ // The decoder pool itself is left exactly as FFmpeg builds it: the
+ // NVIDIA driver rejects SHARED_NTHANDLE on DXVA decoder output textures
+ // (CreateTexture2D -> E_INVALIDARG, 0x80070057 on RTX 5070/616.56).
+ // Decoded slices are copied into our own shared textures instead; see
+ // receiveFrame().
+ if (av_hwdevice_ctx_init(deviceRef) < 0) {
+ log::error("media", "decoder: av_hwdevice_ctx_init(D3D11VA) failed");
+ av_buffer_unref(&deviceRef);
+ d3d11Device_->Release();
+ d3d11Device_ = nullptr;
+ return false;
+ }
+ }
+ log::info("media", "decoder: d3d11va hw device context initialized");
+ d3d11DeviceRef_ = deviceRef;
+
+ context_ = avcodec_alloc_context3(codec);
+ if (context_ == nullptr) {
+ releaseInterop();
+ return false;
+ }
+ if (avcodec_parameters_to_context(context_, codecParameters) < 0) {
+ log::error("media", "decoder: avcodec_parameters_to_context failed (d3d11va)");
+ avcodec_free_context(&context_);
+ releaseInterop();
+ return false;
+ }
+ context_->thread_count = 1;
+ if (lowLatency) {
+ context_->flags |= AV_CODEC_FLAG_LOW_DELAY;
+ }
+ // FFmpeg's D3D11VA frame parameters pick P010 only when the software format
+ // is already declared; without this a 10-bit stream would be handed NV12
+ // surfaces. Set the same value ff_get_format would have chosen.
+ if (context_->sw_pix_fmt == AV_PIX_FMT_NONE) {
+ const bool tenBit = codecParameters->format == AV_PIX_FMT_YUV420P10
+ || codecParameters->format == AV_PIX_FMT_YUV420P12
+ || codecParameters->bits_per_raw_sample > 8;
+ context_->sw_pix_fmt = tenBit ? AV_PIX_FMT_YUV420P10 : AV_PIX_FMT_YUV420P;
+ }
+
+ context_->get_format = SelectD3D11Format;
+ context_->hw_device_ctx = av_buffer_ref(d3d11DeviceRef_);
+
+ if (avcodec_open2(context_, codec, nullptr) < 0) {
+ log::error("media", "decoder: avcodec_open2 failed for d3d11va");
+ avcodec_free_context(&context_);
+ releaseInterop();
+ return false;
+ }
+ // The hardware frames context is created lazily by the decoder on the first
+ // frame (ff_get_format), so the pooled surface is validated there instead of
+ // here; see the D3D11VA branch of receiveFrame().
+ frame_ = av_frame_alloc();
+ if (frame_ == nullptr) {
+ avcodec_free_context(&context_);
+ releaseInterop();
+ return false;
+ }
+
+ stats_ = DecoderStats{};
+ hwAccelActive_ = true;
+ hwAccelKind_ = HardwareDecodeKind::D3D11VA;
+ gpuQueueWaitCount_ = 0;
+ if (!createInteropFence(d3d12Device)) {
+ close();
+ return false;
+ }
+ log::info("media", std::format("decoder: d3d11va decoder opened codec={} {}x{} lowLatency={} (private device, shared surfaces)",
+ codec->name, context_->width, context_->height, lowLatency));
+ return true;
+}
+
+ID3D12Resource* FFmpegVideoDecoder::importD3D11Texture(ID3D11Texture2D* texture)
+{
+ if (texture == nullptr || d3d12Device_ == nullptr) {
+ return nullptr;
+ }
+ const auto cached = d3d11Imports_.find(texture);
+ if (cached != d3d11Imports_.end()) {
+ return cached->second.resource;
+ }
+ if (d3d11Imports_.size() >= 32) {
+ // A decoder pool is a single array texture, so this only happens when a
+ // driver rebuilds pools repeatedly; drop the views and re-open lazily.
+ for (auto& entry : d3d11Imports_) {
+ if (entry.second.resource != nullptr) {
+ entry.second.resource->Release();
+ }
+ }
+ d3d11Imports_.clear();
+ }
+
+ ComPtr<IDXGIResource1> dxgiResource;
+ HRESULT hr = texture->QueryInterface(IID_PPV_ARGS(&dxgiResource));
+ if (FAILED(hr) || !dxgiResource) {
+ log::error("media", std::format("decoder: decoded texture has no IDXGIResource1 hr={}", hrText(hr)));
+ return nullptr;
+ }
+ HANDLE shared = nullptr;
+ hr = dxgiResource->CreateSharedHandle(nullptr, DXGI_SHARED_RESOURCE_READ, nullptr, &shared);
+ if (FAILED(hr) || shared == nullptr) {
+ log::error("media", std::format("decoder: CreateSharedHandle(decoded texture) failed hr={}", hrText(hr)));
+ return nullptr;
+ }
+ ComPtr<ID3D12Resource> resource;
+ const HRESULT openHr = d3d12Device_->OpenSharedHandle(shared, IID_PPV_ARGS(&resource));
+ CloseHandle(shared);
+ if (FAILED(openHr) || !resource) {
+ log::error("media", std::format("decoder: D3D12 OpenSharedHandle(decoded texture) failed hr={}", hrText(openHr)));
+ return nullptr;
+ }
+ D3D11_TEXTURE2D_DESC desc{};
+ texture->GetDesc(&desc);
+ const auto d3d12Desc = resource->GetDesc();
+ log::info("media", std::format(
+ "decoder: imported d3d11va surface {}x{} array={} format={} -> d3d12 format={} arraySize={}",
+ desc.Width, desc.Height, desc.ArraySize, static_cast<int>(desc.Format),
+ static_cast<int>(d3d12Desc.Format), d3d12Desc.DepthOrArraySize));
+
+ ID3D12Resource* raw = resource.Detach();
+ d3d11Imports_.emplace(texture, D3D11TextureImport{ raw, true });
+ return raw;
+}
+
void FFmpegVideoDecoder::close()
{
receiveStatus_ = DecodeReceiveStatus::NeedInput;
@@ -226,7 +570,33 @@ void FFmpegVideoDecoder::close()
bool FFmpegVideoDecoder::hardwareFrameImportable() const
{
- if (!hardwareActive() || frame_ == nullptr || frame_->format != AV_PIX_FMT_D3D12) {
+ if (!hardwareActive() || frame_ == nullptr) {
+ return false;
+ }
+ if (hwAccelKind_ == HardwareDecodeKind::D3D11VA) {
+ if (frame_->format != AV_PIX_FMT_D3D11 || hardwareSurface_.texture == nullptr) {
+ return false;
+ }
+ auto* decoded = reinterpret_cast<ID3D11Texture2D*>(frame_->data[0]);
+ if (decoded == nullptr) {
+ return false;
+ }
+ D3D11_TEXTURE2D_DESC desc{};
+ decoded->GetDesc(&desc);
+ if (desc.MipLevels != 1 || desc.SampleDesc.Count != 1 || desc.ArraySize == 0) {
+ return false;
+ }
+ if (desc.Format != DXGI_FORMAT_NV12 && desc.Format != DXGI_FORMAT_P010) {
+ return false;
+ }
+ // The shared copy keeps the decoder's aligned extent (128 px for HEVC),
+ // which legitimately exceeds the visible size: the ingress samples by
+ // texel index and never reads the pad.
+ return context_ != nullptr
+ && hardwareSurface_.textureWidth >= static_cast<uint32_t>(context_->width)
+ && hardwareSurface_.textureHeight >= static_cast<uint32_t>(context_->height);
+ }
+ if (frame_->format != AV_PIX_FMT_D3D12) {
return false;
}
auto* d3dFrame = reinterpret_cast<AVD3D12VAFrame*>(frame_->data[0]);
@@ -327,6 +697,73 @@ const AVFrame* FFmpegVideoDecoder::receiveFrame()
// issues queue->Wait before touching the texture.
++gpuQueueWaitCount_;
}
+ } else if (hwAccelKind_ == HardwareDecodeKind::D3D11VA && frame_->format == AV_PIX_FMT_D3D11) {
+ // The decoded slice is copied into our own shared texture (the driver
+ // refuses NT-handle sharing on DXVA decoder output textures), then the
+ // D3D11 fence is signalled so the graph can enqueue one GPU-side wait.
+ // Nothing here waits on the CPU.
+ hardwareSurface_ = HardwareSurfaceView{};
+ auto* decoded = reinterpret_cast<ID3D11Texture2D*>(frame_->data[0]);
+ if (decoded == nullptr) {
+ log::error("media", "decoder: d3d11va frame without a texture");
+ return frame_;
+ }
+ D3D11_TEXTURE2D_DESC desc{};
+ decoded->GetDesc(&desc);
+ if (stats_.framesDecoded == 1) {
+ log::info("media", std::format(
+ "decoder: d3d11va decoded surface {}x{} visible={}x{} array={} slice={} format={} bind=0x{:X} misc=0x{:X}",
+ desc.Width, desc.Height, frame_->width, frame_->height, desc.ArraySize,
+ static_cast<uint32_t>(reinterpret_cast<intptr_t>(frame_->data[1])),
+ static_cast<int>(desc.Format), desc.BindFlags, desc.MiscFlags));
+ if (!createInteropSlots(&desc)) {
+ log::error("media", "decoder: d3d11va interop ring creation failed");
+ return frame_;
+ }
+ }
+ if (d3d11Context_ == nullptr || d3d11Context4_ == nullptr || d3d11Fence_ == nullptr || d3d12Fence_ == nullptr) {
+ log::error("media", "decoder: d3d11va interop state missing; frame cannot be ordered");
+ return frame_;
+ }
+ // Ring reuse is safe by construction: the app submits one frame per
+ // read() and its six command slots force the GPU to finish frame N-6
+ // before frame N is submitted, so a slot rewritten eight frames later
+ // can no longer be in flight on the D3D12 queue. The previous copy into
+ // this slot is also ordered by a GPU-side fence wait on the D3D11 side.
+ interopSlotIndex_ = static_cast<uint32_t>(interopFrameIndex_ % kInteropSlotCount);
+ auto& slot = interopSlots_[interopSlotIndex_];
+ ++interopFrameIndex_;
+ if (slot.texture == nullptr) {
+ log::error("media", "decoder: d3d11va interop slot missing");
+ return frame_;
+ }
+ if (slot.lastFenceValue != 0) {
+ d3d11Context4_->Wait(d3d11Fence_, slot.lastFenceValue);
+ }
+ const UINT slice = static_cast<UINT>(reinterpret_cast<intptr_t>(frame_->data[1]));
+ d3d11Context_->CopySubresourceRegion(slot.texture, 0, 0, 0, 0, decoded, slice, nullptr);
+ ++interopFenceValue_;
+ const HRESULT hr = d3d11Context4_->Signal(d3d11Fence_, interopFenceValue_);
+ if (SUCCEEDED(hr)) {
+ d3d11Context4_->Flush();
+ slot.lastFenceValue = interopFenceValue_;
+ hardwareSurface_.waitFence = d3d12Fence_;
+ hardwareSurface_.waitValue = interopFenceValue_;
+ ++gpuQueueWaitCount_;
+ } else {
+ log::error("media", std::format("decoder: d3d11va fence signal failed hr={}", hrText(hr)));
+ }
+ hardwareSurface_.texture = slot.resource;
+ hardwareSurface_.subresourceIndex = 0;
+ hardwareSurface_.textureWidth = slot.width;
+ hardwareSurface_.textureHeight = slot.height;
+ if (stats_.framesDecoded <= 3) {
+ log::info("media", std::format("decoder: d3d11va copy slot={} fence={} sourceSlice={} extent={}x{}",
+ interopSlotIndex_, hardwareSurface_.waitValue, slice, slot.width, slot.height));
+ }
+ if (hardwareSurface_.texture == nullptr) {
+ log::error("media", "decoder: d3d11va surface import failed");
+ }
}
if (stats_.framesDecoded <= 3) {
log::info("media", std::format("decoder: frame#{} stamp={} tb={}/{} -> ptsUs={} format={}",
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index 76e6d05d..4d9b8459 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -1242,7 +1242,7 @@ bool EnhanceGraph::createViews()
// ---------------------------------------------------------------------------
// process: the per-frame chain (verbatim from the probe lambda).
// ---------------------------------------------------------------------------
-bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId, const ColorDescription* color, bool retainReferences, const FgAdmission& admitFg)
+bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId, const ColorDescription* color, const HardwareSurfaceInput* hardwareSurface, bool retainReferences, const FgAdmission& admitFg)
{
failedBackend_=engine::FailedBackend::Infrastructure;
out = FrameOutputs{};
@@ -1307,7 +1307,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
uint32_t slot = 0;
if (uploadFences_[parity] && !context_.waitForFenceValue(uploadFences_[parity])) return false;
hardwareInputFrames_[parity].reset();
- if(frame->format==AV_PIX_FMT_D3D12){
+ if(frame->format==AV_PIX_FMT_D3D12||frame->format==AV_PIX_FMT_D3D11){
auto* retained=av_frame_clone(frame);
if(!retained)return false;
hardwareInputFrames_[parity]=std::shared_ptr<AVFrame>(retained,[](AVFrame* value){av_frame_free(&value);});
@@ -1372,17 +1372,37 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
src.PlacedFootprint.Footprint={DXGI_FORMAT_R8G8B8A8_UNORM,packed?packedIngressTexels(desc_.packedInput,srcW_):desc_.yuy2Input?srcW_/2:srcW_,srcH_,1,UINT(rgbPitch_)};
list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);
tracker_.transition(list,rgbTex_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
- } else if (frame->format == AV_PIX_FMT_D3D12) {
- auto* d3dFrame = reinterpret_cast<AVD3D12VAFrame*>(frame->data[0]);
- if (d3dFrame == nullptr || d3dFrame->texture == nullptr) {
- veyra::log::error("graph", "null d3d12va frame");
- return false;
+ } else if (frame->format == AV_PIX_FMT_D3D12 || frame->format == AV_PIX_FMT_D3D11) {
+ // Two hardware sources feed the same import: D3D12VA hands the surface
+ // over inside the AVFrame, D3D11VA through the packet (NT-handle shared
+ // texture + D3D11 fence). Both become one NV12/P010 D3D12 texture plus
+ // one GPU-side wait; the shader samples by texel index inside the
+ // visible extent, so decoder allocation padding is never read.
+ ID3D12Fence* waitFence = nullptr;
+ uint64_t waitValue = 0;
+ UINT nv12Slice = 0;
+ if (frame->format == AV_PIX_FMT_D3D12) {
+ auto* d3dFrame = reinterpret_cast<AVD3D12VAFrame*>(frame->data[0]);
+ if (d3dFrame == nullptr || d3dFrame->texture == nullptr) {
+ veyra::log::error("graph", "null d3d12va frame");
+ return false;
+ }
+ nv12Texture = d3dFrame->texture;
+ nv12Slice = static_cast<UINT>(d3dFrame->subresource_index);
+ waitFence = d3dFrame->sync_ctx.fence;
+ waitValue = d3dFrame->sync_ctx.fence_value;
+ } else {
+ if (hardwareSurface == nullptr || !hardwareSurface->present()) {
+ veyra::log::error("graph", "d3d11va frame has no hardware surface view");
+ return false;
+ }
+ nv12Texture = hardwareSurface->texture;
+ nv12Slice = hardwareSurface->subresourceIndex;
+ waitFence = hardwareSurface->waitFence;
+ waitValue = hardwareSurface->waitValue;
}
- nv12Texture = d3dFrame->texture;
- const UINT nv12Slice = static_cast<UINT>(d3dFrame->subresource_index);
- if (d3dFrame->sync_ctx.fence != nullptr) {
- if (FAILED(context_.directQueue()->Wait(
- d3dFrame->sync_ctx.fence, d3dFrame->sync_ctx.fence_value))) {
+ if (waitFence != nullptr) {
+ if (FAILED(context_.directQueue()->Wait(waitFence, waitValue))) {
veyra::log::error("graph", "nv12 fence wait");
return false;
}
diff --git a/src/source/MediaFileSource.cpp b/src/source/MediaFileSource.cpp
index ef937311..27fa1169 100644
--- a/src/source/MediaFileSource.cpp
+++ b/src/source/MediaFileSource.cpp
@@ -54,6 +54,7 @@ bool MediaFileSource::fallbackToSoftware(std::string_view reason)
return false;
}
info_.hardwareDecodeActive = false;
+ info_.videoDecodePath = "software";
info_.containerName = demuxer_.formatName();
info_.videoPixelFormatName = params->format >= 0 && av_get_pix_fmt_name(static_cast<AVPixelFormat>(params->format))
? av_get_pix_fmt_name(static_cast<AVPixelFormat>(params->format)) : "unknown";
@@ -140,14 +141,31 @@ bool MediaFileSource::open(const SourceOpenDesc& desc)
bool decoderOpen = false;
if (desc.preferHardwareDecode && desc.d3d12Device != nullptr && desc.d3d12Queue != nullptr) {
- decoderOpen = decoder_.openD3D12VA(params, demuxer_.videoTimeBaseNum(),
- demuxer_.videoTimeBaseDen(),
- static_cast<ID3D12Device*>(desc.d3d12Device),
- static_cast<ID3D12CommandQueue*>(desc.d3d12Queue));
- if (decoderOpen) {
- veyra::log::info("source-file", "D3D12VA decode active (shared device)");
+ // HEVC uses D3D11VA on purpose. On some drivers (RTX 5070 + 616.56) the
+ // first HEVC picture of the D3D12VA decoder faults the driver and the
+ // SHARED D3D12 device is removed, which took the whole session down
+ // instead of falling back (docs/DIAG_HEVC_D3D12VA_AND_EXPORT_CFR_2026-09-17.md).
+ // The D3D11VA path decodes on its own device and shares the surfaces as
+ // NT handles, so a failure there can only cost a software fallback.
+ if (params->codec_id == AV_CODEC_ID_HEVC) {
+ decoderOpen = decoder_.openD3D11VA(params, demuxer_.videoTimeBaseNum(),
+ demuxer_.videoTimeBaseDen(), desc.d3d12AdapterLuid,
+ static_cast<ID3D12Device*>(desc.d3d12Device));
+ if (decoderOpen) {
+ veyra::log::info("source-file", "D3D11VA decode active (NT-handle surfaces shared to the D3D12 graph)");
+ } else {
+ veyra::log::warn("source-file", "D3D11VA open failed; falling back to software decode (explicit)");
+ }
} else {
- veyra::log::warn("source-file", "D3D12VA open failed; falling back to software decode (explicit)");
+ decoderOpen = decoder_.openD3D12VA(params, demuxer_.videoTimeBaseNum(),
+ demuxer_.videoTimeBaseDen(),
+ static_cast<ID3D12Device*>(desc.d3d12Device),
+ static_cast<ID3D12CommandQueue*>(desc.d3d12Queue));
+ if (decoderOpen) {
+ veyra::log::info("source-file", "D3D12VA decode active (shared device)");
+ } else {
+ veyra::log::warn("source-file", "D3D12VA open failed; falling back to software decode (explicit)");
+ }
}
}
if (!decoderOpen) {
@@ -176,6 +194,7 @@ bool MediaFileSource::open(const SourceOpenDesc& desc)
info_.nominalRateDen = demuxer_.nominalRateDen();
info_.timestampQuantum = demuxer_.videoTimeBaseDen() > 0 ? double(demuxer_.videoTimeBaseNum()) / demuxer_.videoTimeBaseDen() : 0;
info_.hardwareDecodeActive = decoder_.hardwareActive();
+ info_.videoDecodePath = decoder_.decodePathName();
info_.containerName = demuxer_.formatName();
info_.videoCodecName = avcodec_get_name(params->codec_id);
info_.videoPixelFormatName = params->format >= 0 && av_get_pix_fmt_name(static_cast<AVPixelFormat>(params->format))
@@ -366,6 +385,20 @@ SourceReadStatus MediaFileSource::read(pipeline::FramePacket& out, const AVFrame
// The canonical linear working texture is produced by the graph's
// ingress conversion; the source hands over the decoded frame view.
out.color.resource = nullptr;
+ // Hardware surfaces that do not travel inside the AVFrame (D3D11VA) are
+ // published per frame; every other path clears the field so the ingress
+ // never sees a stale texture from an earlier frame.
+ if (decoder_.usingD3D11Frames()) {
+ const auto& view = decoder_.hardwareSurface();
+ out.hardwareSurface.texture = view.texture;
+ out.hardwareSurface.subresourceIndex = view.subresourceIndex;
+ out.hardwareSurface.waitFence = view.waitFence;
+ out.hardwareSurface.waitValue = view.waitValue;
+ out.hardwareSurface.textureWidth = view.textureWidth;
+ out.hardwareSurface.textureHeight = view.textureHeight;
+ } else {
+ out.hardwareSurface = pipeline::HardwareSurfaceInput{};
+ }
++framesRead_;
if (decodedFrame != nullptr) { *decodedFrame = frame; }
diff --git a/tests/integration/FgAdmissionTests.cpp b/tests/integration/FgAdmissionTests.cpp
index 397657a8..33d2a02d 100644
--- a/tests/integration/FgAdmissionTests.cpp
+++ b/tests/integration/FgAdmissionTests.cpp
@@ -37,7 +37,7 @@ int wmain(int argc,wchar_t** argv){
pipeline::EnhanceGraph::FrameOutputs out;
const bool reject=(i>=8&&i<12)||(i>=24&&i<28);
auto admission=[&](const auto&){return engine::admitLiveFg(reject?2000000:900000,1000000,0,std::nullopt,0);};
- ok=graph.process(frame,packet.pts.toDouble()*1000,i==0,out,packet.sequence,&packet.colorInfo,false,admission);
+ ok=graph.process(frame,packet.pts.toDouble()*1000,i==0,out,packet.sequence,&packet.colorInfo,nullptr,false,admission);
const auto start=std::chrono::steady_clock::now();
while(ok&&!graph.resolveGeneration(out)){
if(std::chrono::steady_clock::now()-start>std::chrono::seconds(2)){ok=false;break;}wait.slice(.2);
diff --git a/tests/integration/HardwareImportImageTests.cpp b/tests/integration/HardwareImportImageTests.cpp
index b4eee051..dee4222a 100644
--- a/tests/integration/HardwareImportImageTests.cpp
+++ b/tests/integration/HardwareImportImageTests.cpp
@@ -20,18 +20,23 @@ int wmain(int argc,wchar_t** argv){
if(!ctx.initialize({},st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,st))return 3;
std::vector<sink::RgbaImage> reference;double worst=0;
for(bool hardware:{false,true}){
- source::MediaFileSource source;source::SourceOpenDesc sd;sd.path=argv[1];sd.preferHardwareDecode=hardware;sd.d3d12Device=ctx.device();sd.d3d12Queue=ctx.directQueue();
+ source::MediaFileSource source;source::SourceOpenDesc sd;sd.path=argv[1];sd.preferHardwareDecode=hardware;sd.d3d12Device=ctx.device();sd.d3d12Queue=ctx.directQueue();sd.d3d12AdapterLuid=ctx.adapter().luid;
if(!source.open(sd))return 4;
pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc gd;
gd.sourceWidth=gd.workWidth=source.info().width;gd.sourceHeight=gd.workHeight=source.info().height;gd.enableNr=false;gd.enableSr=false;gd.enableFg=false;
if(!graph.initialize(gd)||!graph.createViews())return 5;
+ std::cout<<"DECODE_PATH hardware="<<hardware<<" path="<<source.info().videoDecodePath<<" visible="<<source.info().width<<"x"<<source.info().height<<std::endl;
for(unsigned i=0;i<4;++i){
pipeline::FramePacket packet;const AVFrame* frame=nullptr;source::SourceReadStatus result;
do{result=source.read(packet,&frame);}while(result==source::SourceReadStatus::Waiting);
- if(result!=source::SourceReadStatus::Frame||(frame->format==AV_PIX_FMT_D3D12)!=hardware)return 6;
- if(hardware){auto* native=reinterpret_cast<AVD3D12VAFrame*>(frame->data[0]);auto d=native->texture->GetDesc();std::cout<<"GPU_IMPORT frame="<<i<<" visible="<<frame->width<<"x"<<frame->height<<" resource="<<d.Width<<"x"<<d.Height<<" array="<<d.DepthOrArraySize<<" slice="<<native->subresource_index<<" format="<<d.Format<<std::endl;}
+ // Hardware decode is D3D12VA for most codecs and D3D11VA (NT-handle shared)
+ // for HEVC; both must hand the ingress an importable NV12/P010 surface.
+ const bool hwFrame=frame->format==AV_PIX_FMT_D3D12||frame->format==AV_PIX_FMT_D3D11;
+ if(result!=source::SourceReadStatus::Frame||hwFrame!=hardware)return 6;
+ if(hardware&&frame->format==AV_PIX_FMT_D3D12){auto* native=reinterpret_cast<AVD3D12VAFrame*>(frame->data[0]);auto d=native->texture->GetDesc();std::cout<<"GPU_IMPORT d3d12va frame="<<i<<" visible="<<frame->width<<"x"<<frame->height<<" resource="<<d.Width<<"x"<<d.Height<<" array="<<d.DepthOrArraySize<<" slice="<<native->subresource_index<<" format="<<d.Format<<std::endl;}
+ else if(hardware){if(!packet.hardwareSurface.present())return 6;std::cout<<"GPU_IMPORT d3d11va frame="<<i<<" visible="<<frame->width<<"x"<<frame->height<<" resource="<<packet.hardwareSurface.textureWidth<<"x"<<packet.hardwareSurface.textureHeight<<" slice="<<packet.hardwareSurface.subresourceIndex<<" fence="<<(packet.hardwareSurface.waitFence!=nullptr)<<" value="<<packet.hardwareSurface.waitValue<<std::endl;}
pipeline::EnhanceGraph::FrameOutputs out;
- if(!graph.process(frame,i*1000.0/30,i==0,out,i+1,&packet.colorInfo))return 7;
+ if(!graph.process(frame,i*1000.0/30,i==0,out,i+1,&packet.colorInfo,&packet.hardwareSurface))return 7;
sink::RgbaImage image;if(!sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),image))return 8;
if(i==0&&!sink::saveImage(std::wstring(argv[2])+(hardware?L"-hardware.png":L"-software.png"),image))return 9;
if(!hardware)reference.push_back(std::move(image));
diff --git a/tests/integration/PreviewGeometryTests.cpp b/tests/integration/PreviewGeometryTests.cpp
index 47b11322..afd400ba 100644
--- a/tests/integration/PreviewGeometryTests.cpp
+++ b/tests/integration/PreviewGeometryTests.cpp
@@ -40,7 +40,7 @@ int wmain(int argc,wchar_t** argv){
if(ok)ok=test("reset",{},0,{{160,10,0,0,0},{280,80,0,255,0}});
if(ok){
for(int y=0;y<32;++y)for(int x=0;x<64;++x){auto* p=f->data[0]+y*f->linesize[0]+x*4;p[0]=0;p[1]=0;p[2]=255;p[3]=255;}
- pipeline::EnhanceGraph::FrameOutputs current;ok=graph.process(f,33.333,false,current,2,nullptr,false);
+ pipeline::EnhanceGraph::FrameOutputs current;ok=graph.process(f,33.333,false,current,2,nullptr,nullptr,false);
if(ok){out=std::move(current);ok=test("invalid-reference",{},1,{{40,80,0,0,255},{280,160,0,0,255}});}
}
ring.drainQueue();out={};presenter.close();graph.shutdown();av_frame_free(&f);ring.shutdown();ctx.shutdown();DestroyWindow(window);CoUninitialize();return ok?0:1;
diff --git a/tests/unit/RepairContractTests.cpp b/tests/unit/RepairContractTests.cpp
index b29cc133..cb239de8 100644
--- a/tests/unit/RepairContractTests.cpp
+++ b/tests/unit/RepairContractTests.cpp
@@ -423,6 +423,25 @@ int main(){
check(!tail.tailAccepts(51247,854.133,60000)&&!tail.tailAccepts(100,std::round(100*1000.0/60)/1000+.1,60000),"tail snap never covers a mid-stream gap");
check(!tail.tailAccepts(51247,854.9,51249)&&!tail.tailAccepts(51247,854.133,0),"tail snap rejects larger deviations and unknown streams");
}
+ {
+ // User report 2026-09-17: an 11 minute CFR mp4 where ONE sample was
+ // dropped (frame 10467 carries the timestamp of slot 10468) aborted the
+ // export at 51%. A whole-slot hole is now filled with the previous frame
+ // and the validator re-aligns; off-grid jitter and bigger jumps still fail.
+ engine::CfrTimeline holes(30,1,1.0/90000,0);
+ bool seated=true;for(uint64_t i=0;i<10467;++i)seated &= holes.accepts(i,double(i)/30.0);
+ check(seated&&!holes.accepts(10467,10468/30.0),"a dropped mid-stream sample still breaks the strict phase test");
+ check(holes.missingSlots(10467,10468/30.0)==1,"whole-slot hole is detected as one missing sample");
+ check(holes.missingSlots(10467,10467/30.0)==0&&holes.missingSlots(10467,10467/30.0+0.0002)==0
+ &&holes.missingSlots(10467,10470/30.0)==0,"on-grid frames, off-grid jitter and oversized jumps are not fillable holes");
+ check(holes.missingSlots(10467,10468/30.0,1.0)==1&&holes.missingSlots(10467,10469/30.0,1.0)==0,"fill limit bounds how much damage is repaired");
+ holes.resync(10467,10468/30.0);
+ // resync consumes frame 10467 itself (the exporter keeps processing it),
+ // so the grid is verified from the next source frame onwards.
+ bool realigned=true;for(uint64_t i=10468;i<10468+120;++i)realigned &= holes.accepts(i,double(i+1)/30.0);
+ check(realigned,"gap resync re-aligns the grid for the rest of the stream");
+ check(holes.missingSlots(10587,10588.0/30.0)==0,"post-resync frames sit on the new grid instead of reporting another hole");
+ }
{
// Subtitle engine: external SRT/ASS/WebVTT parsing, style mapping and
// indexed lookup (the renderer and the embedded-track extraction share
diff --git a/tools/export_probe/main.cpp b/tools/export_probe/main.cpp
new file mode 100644
index 00000000..f87820ce
--- /dev/null
+++ b/tools/export_probe/main.cpp
@@ -0,0 +1,48 @@
+// Headless export probe: runs the production export path (VideoExportJob) on
+// one file so frame-timestamp policy can be verified without the GUI. It is a
+// diagnostic harness, not a second implementation: features stay disabled so
+// the run only exercises decode -> ingress -> encode -> mux -> verify.
+//
+// veyra_export_probe <input> <output> [--hevc] [--max-frames N]
+//
+// Exit codes: 0 completed, 1 export refused/failed, 2 bad arguments.
+#include "veyra/engine/VideoExportJob.h"
+
+#include <atomic>
+#include <cstdio>
+#include <cstdlib>
+#include <string>
+
+int wmain(int argc, wchar_t** argv)
+{
+ if (argc < 3) {
+ std::fwprintf(stderr, L"usage: veyra_export_probe <input> <output> [--hevc] [--max-frames N]\n");
+ return 2;
+ }
+ const std::wstring input = argv[1];
+ const std::wstring output = argv[2];
+ bool hevc = false;
+ unsigned maxFrames = 0;
+ for (int i = 3; i < argc; ++i) {
+ const std::wstring arg = argv[i];
+ if (arg == L"--hevc") {
+ hevc = true;
+ } else if (arg == L"--max-frames" && i + 1 < argc) {
+ maxFrames = unsigned(std::wcstoul(argv[++i], nullptr, 10));
+ } else {
+ std::fwprintf(stderr, L"unknown argument: %ls\n", arg.c_str());
+ return 2;
+ }
+ }
+
+ veyra::engine::PlayerOptions options; // nr/sr/fg all off: decode -> encode only
+ std::atomic<bool> cancel{false};
+ const bool ok = veyra::engine::exportVideo(input, output, options, hevc, cancel,
+ [](double progress, const std::wstring& message) {
+ std::wprintf(L"[%5.1f%%] %ls\n", progress * 100.0, message.c_str());
+ std::fflush(stdout);
+ },
+ maxFrames);
+ std::wprintf(L"export result=%ls\n", ok ? L"ok" : L"failed");
+ return ok ? 0 : 1;
+}