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

revert(capture): remove the negative-gain N2 direct-ingress path

Veyra Goal Agent383e1b5a69a4
diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cpp
index da4a0c90..f540f324 100644
--- a/apps/veyra/ui/AppShell.cpp
+++ b/apps/veyra/ui/AppShell.cpp
@@ -269,7 +269,7 @@ LRESULT CALLBACK interaction(HWND h,UINT m,WPARAM w,LPARAM l,UINT_PTR id,DWORD_P
if(id==VideoSurface&&m==WM_LBUTTONUP&&GetCapture()==h){ReleaseCapture();return 0;}
return DefSubclassProc(h,m,w,l);
}
-veyra::engine::PlayerOptions options(){auto o=veyra::engine::PlayerOptions::from(engine.snapshot().desired);o.captureCpuUnpack=initialOptions.captureCpuUnpack;o.captureDirectIngress=initialOptions.captureDirectIngress;return o;}
+veyra::engine::PlayerOptions options(){auto o=veyra::engine::PlayerOptions::from(engine.snapshot().desired);o.captureCpuUnpack=initialOptions.captureCpuUnpack;return o;}
// Win32 dispatch reenters during move/resize and modal dialogs. Large path
// buffers must be per-operation heap storage, never part of every WndProc frame.
@@ -790,7 +790,7 @@ int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);for(int i=1;i<a
{
// --capture-flip: diagnostics/smoke only; the interactive path uses the
// capture panel checkbox and persists captureFlipVertical with presets.
- {int flipArgc=0;auto flipArgv=CommandLineToArgvW(GetCommandLineW(),&flipArgc);for(int i=1;i<flipArgc;++i){if(!_wcsicmp(flipArgv[i],L"--capture-flip"))initialOptions.settings.captureFlipVertical=true;else if(!wcsncmp(flipArgv[i],L"--capture-buffer=",17)){const wchar_t* value=flipArgv[i]+17;if(!_wcsicmp(value,L"auto"))initialOptions.settings.captureBuffer=veyra::source::CaptureBufferMode::Auto;else if(!_wcsicmp(value,L"minimum"))initialOptions.settings.captureBuffer=veyra::source::CaptureBufferMode::Minimum;else if(!_wcsicmp(value,L"driver"))initialOptions.settings.captureBuffer=veyra::source::CaptureBufferMode::DriverDefault;}else if(!_wcsicmp(flipArgv[i],L"--capture-cpu-unpack"))initialOptions.captureCpuUnpack=true;else if(!_wcsicmp(flipArgv[i],L"--capture-direct-ingress"))initialOptions.captureDirectIngress=true;}LocalFree(flipArgv);}
+ {int flipArgc=0;auto flipArgv=CommandLineToArgvW(GetCommandLineW(),&flipArgc);for(int i=1;i<flipArgc;++i){if(!_wcsicmp(flipArgv[i],L"--capture-flip"))initialOptions.settings.captureFlipVertical=true;else if(!wcsncmp(flipArgv[i],L"--capture-buffer=",17)){const wchar_t* value=flipArgv[i]+17;if(!_wcsicmp(value,L"auto"))initialOptions.settings.captureBuffer=veyra::source::CaptureBufferMode::Auto;else if(!_wcsicmp(value,L"minimum"))initialOptions.settings.captureBuffer=veyra::source::CaptureBufferMode::Minimum;else if(!_wcsicmp(value,L"driver"))initialOptions.settings.captureBuffer=veyra::source::CaptureBufferMode::DriverDefault;}else if(!_wcsicmp(flipArgv[i],L"--capture-cpu-unpack"))initialOptions.captureCpuUnpack=true;}LocalFree(flipArgv);}
int positionalArgc=0;auto positionalArgv=CommandLineToArgvW(GetCommandLineW(),&positionalArgc);std::wstring positional;
const wchar_t* valueFlags[]={L"--export-worker",L"--smoke-view",L"--smoke-dual-export",L"--smoke-seconds",L"--export-out",L"--max-frames",L"--cancel-after-ms",L"--smoke-save",L"--fg-multiplier",L"--capture-audio",L"--video-sr",L"--bitrate-mbps",L"--subtitle-primary",L"--subtitle-secondary",L"--subtitle-offset-ms",L"--subtitle-font-size"};
for(int i=1;i<positionalArgc;++i){const std::wstring a=positionalArgv[i];
diff --git a/docs/CAPTURE_DECODE_LATENCY_PLAN_2026-09-16.md b/docs/CAPTURE_DECODE_LATENCY_PLAN_2026-09-16.md
index aeeaf7ff..b5fd3636 100644
--- a/docs/CAPTURE_DECODE_LATENCY_PLAN_2026-09-16.md
+++ b/docs/CAPTURE_DECODE_LATENCY_PLAN_2026-09-16.md
@@ -1,6 +1,7 @@
# 采集解码与延迟:最终架构实施方案(2026-09-16)
-状态:**施工中**(2026-09-16 晚:N4/N3/N1 已完成并各自取证,N2 与压缩解码链路待开工;逐项进度见
+状态:**施工中**(2026-09-16 晚:N4/N3/N1 已完成并各自取证,N2 尝试后回退——实测负收益,见 WORKLOG;
+压缩解码链路待开工;逐项进度见
WORKLOG 对应条目与本文标注)。包含两部分:①压缩格式
(MJPEG/H.264/HEVC)的解码架构;②原生格式(YUY2/NV12/RGB…)的 N1–N4 优化。目标是一条架构做到
"低延迟 + 顶级效果 + N/A/I 三家全覆盖",不分期、不并行多套过渡形态。
@@ -86,7 +87,7 @@ WORKLOG 对应条目与本文标注)。包含两部分:①压缩格式
6. **原生格式拷贝合并**:sink 直接写进图中转缓冲(省一次整帧拷贝)。
7. **清理与验收**:默认不再走 RGB32 兼容路径;跑完整门禁 + 真机对比。
-> 进度(2026-09-16):①–④ 未开工;⑤(=N4)**已完成**;⑥(=N2)未开工;⑦ 未开工。
+> 进度(2026-09-16):①–④ 未开工;⑤(=N4)**已完成**;⑥(=N2)**尝试后回退(实测负收益,见 WORKLOG)**;⑦ 未开工。
## 5. 验收指标(可量化,达不到不算完成)
@@ -130,7 +131,7 @@ WORKLOG 对应条目与本文标注)。包含两部分:①压缩格式
原生格式不走解码器,但当前在**采集回调线程里**做两件重活,且有 5 种打包格式是**逐像素 CPU
转换**(基线见 §1 微基准)。
-> **进度(2026-09-16 晚)**:N4 ✅(视频 pin 缓冲协商 + 三档设置 + requested/actual 日志;本机 UVC 卡驱动忽略建议、如实标注)/ N3 ✅(排序 + 延迟档位 + 一次性提示)/ N1 ✅(GPU 解包;4K 回调成本 RGB24 1.12ms、RGB565 0.83ms、UYVY 0.64ms,全部达标;`--capture-cpu-unpack` 可回退)/ N2 ⏳ 未开工。证据见 WORKLOG 2026-09-16 三节。
+> **进度(2026-09-16 晚)**:N4 ✅(视频 pin 缓冲协商 + 三档设置 + requested/actual 日志;本机 UVC 卡驱动忽略建议、如实标注)/ N3 ✅(排序 + 延迟档位 + 一次性提示)/ N1 ✅(GPU 解包;4K 回调成本 RGB24 1.12ms、RGB565 0.83ms、UYVY 0.64ms,全部达标;`--capture-cpu-unpack` 可回退)/ N2 ✖ 尝试后回退(直接写入图上传缓冲,功能可用但 1080p/4K 均净亏 ~0.85ms,原因见 WORKLOG;代码已整体移除)。证据见 WORKLOG 2026-09-16 各节。
### N1:逐像素转换从 CPU 挪到 GPU
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 4f5f2c24..e6f51325 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,16 +1,16 @@
# 2026-09-11 继续修复目标模式执行中
-## 2026-09-16 采集链路 N2 第一版:直接写入图上传缓冲(真机验证失败,默认关闭)
+## 2026-09-16 采集链路 N2:两次拷贝合并(直接写入图上传缓冲)——实测负收益,整体回退
-按方案 §8 N2 实现"两次拷贝合并成一次"的第一版:`EnhanceGraph::prepareIngressSlot/tryPrepareIngressSlot` 暴露映射上传缓冲(写入前检查该 slot 的 upload fence,非阻塞版供采集回调使用);`CaptureCardSource` 增加 `DirectIngressHooks`(attach/detach/releaseDirectFrame、双槽握手、inUse/latest 原子、图重建时丢弃陈旧缓冲并回退信箱);`EnhanceGraph::process` 在帧指针等于映射缓冲时跳过 CPU 拷贝;引擎在建图后 attach、process 后 release;CLI `--capture-direct-ingress` 开启(默认关)。
+按方案 §8 N2 实现并反复调试后,功能上已攻破(真机 1080p60 / 4K18:直接提交 100%、0 丢帧、1 次历史重置),但**性能净亏**,按用户指示整体回退:
-**真机验证(¥30 UVC 卡 1080p60 YUY2,10 秒)失败**:开启后 `processedFps=10.00`、`captureDropped≈465`、`mailboxOverwritten≈460`、`historyResets=101`(每帧一次重置)、`callbackToPresentReturnP95Ms=169ms`、`firstValidObserveMs=84.5ms`;两次修正(回调改用非阻塞 fence 检查、读取时校验缓冲指针是否已随图重建失效)后数值不变。默认(信箱路径)同卡复测正常:577 帧、60fps、0 丢帧、callback→Present P95 2.673ms;delivery 门禁 PASS(`logs/delivery/fa725fe8b5e844fd910600211ce35c9f/result.json`)。
+- 1080p60 YUY2:直接写入 P95 **3.536ms** / processCpu 1.494ms vs 信箱 **2.629ms** / 0.429ms(**+0.91ms**)
+- 4K18 YUY2:直接写入 P95 **4.102ms** / processCpu 1.885ms vs 信箱 **3.265ms** / 1.013ms(**+0.84ms**)
+- 原因:合并后写入目标是 D3D12 upload heap(write-combined 内存),CPU 写 WC 的成本加"跨线程写完、GPU 读取前的 flush/可见性等待",超过省掉的那次 RAM→上传缓冲 memcpy。
-**处置**:`PlayerOptions::captureDirectIngress` 默认 **false**,保留 `--capture-direct-ingress` 供继续排查;信箱路径与所有既有行为不变。**未完成(如实)**:N2 未达标,需定位直接写入路径导致引擎每帧 reset/10fps 的根因(怀疑方向:Drop 标志自激、图 parity 与源槽位错位、upload fence 覆盖范围过大),修复并重新真机验证前不得计入收益。压缩解码链路仍未开工。
+调试过程存档(避免重复踩坑):① 上传 fence 索引错位(图按 parity 记录、源按槽位写入,丢帧后错位);② `EngineController::open()` 用 `PlayerOptions::from` 重建时把诊断字段丢光;③ 直接视图帧 `buf[0]==nullptr` 导致呈现/调度停摆——挂上 `av_buffer_create` 的真实 AVBufferRef 后消失(这三条都不是最终选择它的理由)。
-**同日后续(根因修复 + 新的阻塞点)**:定位到最可能的根因——**上传 fence 索引错位**:图按自己的 parity 记录提交 fence,但直接模式下缓冲槽位由源决定,丢帧后两者错位,源会在 GPU 仍在读取该缓冲时覆盖它(表现为 GPU-ready 84ms、每帧 reset、10fps 自激)。已修:直接帧的提交 fence 同时记录到其缓冲槽位(`uploadFences_[slot]`),并加了回调侧直接提交/回退计数(每 120 帧一条日志)。重跑时又发现 **`--capture-direct-ingress` 没有真正触发 attach**(日志无 `[capture-direct]`):根因是 `options()` 从引擎快照重建 `PlayerOptions` 时丢弃了 CLI-only 字段;已修(`options()` 现在携带 `captureCpuUnpack`/`captureDirectIngress`)。截至本轮结束,**带 attach 的直接路径尚未完成真机复测**:默认(信箱)路径健康、门禁 PASS(`logs/delivery/5b494cdb690d4254a670d1d14ccfe54e/result.json`),直接路径继续默认关闭。下一步:用 `--capture-direct-ingress` 复测确认 attach→直接提交计数→4K18 A/B,再决定是否转默认。
-
-**同日第三次修正(CLI 管道修好后的实测,14:29/14:31)**:`EngineController::open()` 还会用 `PlayerOptions::from(desired_)` 重建 options——这是字段丢失的真正位置(只显式保留了 captureReplay 两字段)。已修并复测:**attach 成功**(`[capture-direct] graph direct ingress attached`),回调计数证实直接路径全程在用:`commits=479 fallbacks=1 drops=0`(每 120 帧一条)。读取侧也不再因 fence 未完成而误丢帧(新增 `ingressSlotBuffer` 无 fence 的"当前缓冲"校验,仅比对缓冲指针;回调写入前仍用带 fence 的 `tryPrepareIngressSlot`)。**但引擎仍退化**:`processed=102/565`、`displaySubmits=1`、`firstValidObserveMs=89.3ms`、每帧一次 history reset、P95 177ms——**说明卡点已不在"回调→图缓冲"的交接层,而在呈现/实时调度路径**(直接视图帧作为图输入后,呈现只提交了 1 次;信箱路径同条件 displaySubmits≈processed)。N2 继续默认关闭,下一步聚焦:直接帧与信箱帧的 `pkt`/frame 字段逐项对比(pts/arrival、frame 指针身份、view 的 buf[0]=null 对 live scheduler/presenter 的影响),定位为何呈现停摆。
+**处置**:N2 相关代码全部 `git revert`,软件内不再保留直接写入路径与 `--capture-direct-ingress` 开关;方案 §8 N2 状态改为"尝试后回退(负收益)"。N1 的 `--capture-cpu-unpack` 诊断字段管道(被回退误伤)已单独恢复。
## 2026-09-16 采集链路 N1:逐像素转换从 CPU 挪到 GPU
diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.h
index 21049cfb..98f3864d 100644
--- a/include/veyra/engine/EngineController.h
+++ b/include/veyra/engine/EngineController.h
@@ -21,10 +21,6 @@ struct PlayerOptions { bool nr=false,sr=false,fg=false,realtime=true; uint32_t f
bool captureReplayForTest=false; // file-backed live scheduler test; never enabled by UI
bool captureReplayDisableFgAdmissionForTest=false; // controlled scheduler A/B only
bool captureCpuUnpack=false; // N1 diagnostic: legacy per-pixel CPU unpack
- // N2 direct ingress is opt-in: the first implementation (callback writes
- // into the graph upload buffers) failed real-card verification (10fps /
- // 460+ drops on 2026-09-16), so the default stays on the owned mailbox.
- bool captureDirectIngress=false;
EnhancementSettings snapshot()const{auto s=settings;s.nr=nr;s.sr=sr;s.multiplier=fg?fgMultiplier:1;s.nrPolicy=realtime?(settings.nrPolicy==pipeline::NrSizePolicy::Native?pipeline::NrSizePolicy::Realtime:settings.nrPolicy):pipeline::NrSizePolicy::Native;return s;}
static PlayerOptions from(EnhancementSettings s){PlayerOptions o;o.nr=s.nr;o.sr=s.sr;o.fg=s.multiplier>1;o.fgMultiplier=std::max(2u,s.multiplier);o.realtime=s.nrPolicy!=pipeline::NrSizePolicy::Native;o.settings=s;return o;}
};
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index c22f6a47..e4a33937 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -1,6 +1,5 @@
#pragma once
#include "veyra/engine/BackendRecovery.h"
-#include <atomic>
// EnhanceGraph - the real unified processing graph (Playbook R3.2).
// Chains, per real frame:
@@ -123,21 +122,6 @@ public:
// safe after every allocation in the process has happened.
bool initialize(const EnhanceGraphDesc& desc);
bool createViews();
- // N2 direct capture ingress (single-plane rgb/yuy2/packed ingress only).
- // The producer asks for a slot's mapped upload buffer after its upload
- // fence, writes the frame and commits it; the consumer passes an AVFrame
- // view over the same buffer to process(), which then skips the CPU copy.
- // Returns false while the graph is not ready, so the caller keeps its own
- // mailbox instead of touching stale buffers.
- bool prepareIngressSlot(unsigned slot,void*& buffer,size_t& capacity,unsigned& pitch,unsigned& rowBytes);
- // Non-blocking variant: returns false while the slot's previous upload is
- // still in flight, so the capture callback can fall back to its mailbox
- // instead of blocking the DirectShow thread on a GPU fence.
- bool tryPrepareIngressSlot(unsigned slot,void*& buffer,size_t& capacity,unsigned& pitch,unsigned& rowBytes);
- // Cheap freshness probe for the consumer: current mapped buffer of a slot,
- // no fence wait (the consumer only checks that the frame it committed still
- // belongs to the live graph generation).
- bool ingressSlotBuffer(unsigned slot,void*& buffer) const;
struct FrameOutputs {
FrameBatch batch;
@@ -369,7 +353,6 @@ private:
std::weak_ptr<FrameLease> realLeases_[2],generatedLeases_[kGeneratedPoolSlots];
uint32_t nextListSlot_ = 0;
uint64_t uploadFences_[2] = {};
- std::atomic<bool> ingressDirectReady_{false};
// FFmpeg may recycle a hardware surface as soon as its AVFrame is freed.
// Retain each imported surface until our last consumer fence completes.
std::shared_ptr<AVFrame> hardwareInputFrames_[2];
diff --git a/include/veyra/source/CaptureCardSource.h b/include/veyra/source/CaptureCardSource.h
index 21187b87..d9fe8465 100644
--- a/include/veyra/source/CaptureCardSource.h
+++ b/include/veyra/source/CaptureCardSource.h
@@ -55,21 +55,6 @@ public:
// N1 diagnostic: keep the legacy per-pixel CPU unpack (BGR0/YUY2 targets)
// instead of the GPU unpack path. Applied on the next connect.
void setCpuUnpack(bool enabled);
- // N2 direct ingress: the graph provides mapped upload buffers; the
- // callback writes capture frames straight into them and the owned mailbox
- // stays as the fallback whenever prepare() returns false (graph rebuilding,
- // slot busy, stale buffer). releaseDirectFrame() is called by the consumer
- // once the frame returned by read() has been consumed.
- struct DirectIngressHooks {
- void* context=nullptr;
- bool (*prepare)(void* context,unsigned slot,void*& buffer,size_t& capacity,unsigned& pitch,unsigned& rowBytes)=nullptr;
- // Consumer-side freshness probe: current buffer of a slot, no fence wait.
- bool (*current)(void* context,unsigned slot,void*& buffer)=nullptr;
- };
- bool attachDirectIngress(const DirectIngressHooks& hooks);
- void detachDirectIngress();
- bool directIngressActive() const;
- void releaseDirectFrame();
CaptureMetrics metrics()const;
void videoPresented(double ptsMs,int64_t host100ns,int64_t arrival100ns);
void videoReset(bool resetAudio=true);
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 78348c96..698aab01 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -65,12 +65,10 @@ void EngineController::open(HWND video,const std::wstring& path,PlayerOptions op
// Diagnostics-only PlayerOptions fields never enter EnhancementSettings;
// keep them across the snapshot round-trip below.
const bool captureCpuUnpack=opts.captureCpuUnpack;
- const bool captureDirectIngress=opts.captureDirectIngress;
{std::lock_guard lock(mutex_);snapshot_={};activeFlow_.reset();previewView_={};fgMultiFrameMaxCap_=0;xessMaxInterpolatedFramesCap_=0;fsrMaxGeneratedFramesCap_=0;snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;savePath_.clear();desired_=opts.snapshot();desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_);}
opts.captureReplayForTest=captureReplay;
opts.captureReplayDisableFgAdmissionForTest=disableAdmission;
opts.captureCpuUnpack=captureCpuUnpack;
- opts.captureDirectIngress=captureDirectIngress;
post([this,video,path,opts]{paused_=false;seekSeconds_=-1;run(video,path,opts);});
}
#ifdef VEYRA_ENABLE_REMOTEPLAY
@@ -286,15 +284,6 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
auto failure=graph.failedBackend();
if(opened){
opened=presenter.open(ctx,window,graph,selected.settings.captureCompatible)&&graph.createViews();
- if(opened&&physicalCapture&&options.captureDirectIngress){
- source::CaptureCardSource::DirectIngressHooks hooks{};
- hooks.context=&graph;
- hooks.prepare=[](void* context,unsigned slot,void*& buffer,size_t& capacity,unsigned& pitch,unsigned& rowBytes){
- return static_cast<pipeline::EnhanceGraph*>(context)->tryPrepareIngressSlot(slot,buffer,capacity,pitch,rowBytes);};
- hooks.current=[](void* context,unsigned slot,void*& buffer){
- return static_cast<pipeline::EnhanceGraph*>(context)->ingressSlotBuffer(slot,buffer);};
- if(captureSource.attachDirectIngress(hooks))veyra::log::info("capture-direct","N2 direct capture ingress enabled");
- }
failure=FailedBackend::Infrastructure;
if(opened&&graph.xessEnabled()&&!presenter.xessActive()){opened=false;failure=FailedBackend::Fg;}
if(opened&&graph.fsrEnabled()&&!presenter.fsrActive()){opened=false;failure=FailedBackend::Fg;}
@@ -947,7 +936,6 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
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;}
- if(physicalCapture)captureSource.releaseDirectFrame();
previewSkipSinceProcess=false;
if(!processed){
const auto failedComponent=graph.failedBackend();
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index dd7abda9..2fe9a488 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -103,7 +103,6 @@ EnhanceGraph::~EnhanceGraph()
bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)
{
failedBackend_=engine::FailedBackend::Infrastructure;
- ingressDirectReady_.store(false);
if(!desc.protection.validate().empty())return false;
if(desc.srMotionProbe){
const auto d=desc.srMotionProbe->GetDesc();ComPtr<ID3D12Device> device;
@@ -213,7 +212,6 @@ bool EnhanceGraph::createResources()
for(unsigned i=0;i<2;++i){upRgb_[i]=makeUploadBuffer(context_.device(),rgbPitch_*srcH_);
if(!upRgb_[i]||FAILED(upRgb_[i]->Map(0,nullptr,reinterpret_cast<void**>(&mappedRgb_[i]))))return false;
}
- ingressDirectReady_.store(true);
}
srcRgba_ = makeTexture(context_.device(), srcW_, srcH_, DXGI_FORMAT_R16G16B16A16_FLOAT, true);
if(srEnabled_&&desc_.videoSrQuality&&desc_.videoSrQuality!=engine::kVideoSrFsr){videoSrInput_=makeTexture(context_.device(),srcW_,srcH_,DXGI_FORMAT_R8G8B8A8_UNORM,true);videoSrOutput_=makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R8G8B8A8_UNORM,true);if(!videoSrInput_||!videoSrOutput_)return false;}
@@ -1067,7 +1065,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
if(frame->width!=int(srcW_)||frame->height!=int(srcH_)||!frame->data[0]||std::abs(int64_t(frame->linesize[0]))<int64_t(ingressRowBytes))return false;
for(uint32_t y=0;y<srcH_;++y){
auto* dst=mappedRgb_[parity]+y*rgbPitch_;const auto* src=frame->data[0]+ptrdiff_t(y)*frame->linesize[0];
- if(packed||desc_.yuy2Input||frame->format==AV_PIX_FMT_RGBA){if(dst!=src)std::memcpy(dst,src,size_t(ingressRowBytes));}
+ if(packed||desc_.yuy2Input||frame->format==AV_PIX_FMT_RGBA)std::memcpy(dst,src,size_t(ingressRowBytes));
else for(uint32_t x=0;x<srcW_;++x){
const bool bgr=frame->format==AV_PIX_FMT_BGRA||frame->format==AV_PIX_FMT_BGR0;
dst[x*4]=src[x*4+(bgr?2:0)];dst[x*4+1]=src[x*4+1];dst[x*4+2]=src[x*4+(bgr?0:2)];
@@ -1577,14 +1575,6 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
failedBackend_=engine::FailedBackend::None;
if(runFg)fgHistorySkipped_=false;
uploadFences_[parity]=ring_.lastSignaledValue();
- // N2 direct ingress: the producer wrote straight into one of the mapped
- // buffers, so record this submission's fence under that buffer's own slot
- // too; the source waits it before overwriting the buffer (its slot and the
- // graph parity can drift apart once a frame is dropped).
- if(frame&&frame->data[0]){
- if(frame->data[0]==mappedRgb_[0])uploadFences_[0]=ring_.lastSignaledValue();
- else if(frame->data[0]==mappedRgb_[1])uploadFences_[1]=ring_.lastSignaledValue();
- }
prevPtsMs_ = ptsMs;
prevValid_ = true;
@@ -1692,29 +1682,8 @@ ID3D12Resource* EnhanceGraph::generatedFrameResource(uint32_t slot) const
// The NVOF out-fence drain must ALREADY have happened (caller), while the
// ring and fences were alive.
// ---------------------------------------------------------------------------
-bool EnhanceGraph::tryPrepareIngressSlot(unsigned slot,void*& buffer,size_t& capacity,unsigned& pitch,unsigned& rowBytes){
- buffer=nullptr;capacity=0;pitch=0;rowBytes=0;
- if(slot>1||!ingressDirectReady_.load()||!upRgb_[slot]||!mappedRgb_[slot]||!rgbPitch_||!srcW_||!srcH_)return false;
- if(uploadFences_[slot]&&context_.fenceCompletedValue()<uploadFences_[slot])return false;
- buffer=mappedRgb_[slot];capacity=size_t(rgbPitch_)*srcH_;pitch=unsigned(rgbPitch_);
- rowBytes=desc_.packedInput?packedIngressRowBytes(desc_.packedInput,srcW_):desc_.yuy2Input?srcW_*2:srcW_*4;
- return true;
-}
-bool EnhanceGraph::prepareIngressSlot(unsigned slot,void*& buffer,size_t& capacity,unsigned& pitch,unsigned& rowBytes){
- if(tryPrepareIngressSlot(slot,buffer,capacity,pitch,rowBytes))return true;
- if(slot>1||!ingressDirectReady_.load()||!upRgb_[slot]||!mappedRgb_[slot]||!rgbPitch_||!srcW_||!srcH_)return false;
- if(uploadFences_[slot]&&!context_.waitForFenceValue(uploadFences_[slot]))return false;
- return tryPrepareIngressSlot(slot,buffer,capacity,pitch,rowBytes);
-}
-bool EnhanceGraph::ingressSlotBuffer(unsigned slot,void*& buffer) const{
- buffer=nullptr;
- if(slot>1||!ingressDirectReady_.load()||!upRgb_[slot]||!mappedRgb_[slot])return false;
- buffer=mappedRgb_[slot];
- return true;
-}
void EnhanceGraph::shutdown()
{
- ingressDirectReady_.store(false);
if (!initialized_ && !nrAdapter_ && !nvof_ && !srcRgba_) return;
(void)ring_.drainQueue();(void)ring_.discardRecording();
for(auto& input:hardwareInputFrames_)input.reset();
diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cpp
index 7f337ab1..cc5d5156 100644
--- a/src/source/CaptureCardSource.cpp
+++ b/src/source/CaptureCardSource.cpp
@@ -148,19 +148,6 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
unsigned bufferMode=0;
// N1 diagnostic: legacy per-pixel CPU unpack instead of GPU unpack.
bool cpuUnpack=false;
- // N2 direct ingress state. The callback writes into the graph's mapped
- // upload buffers; the owned mailbox remains the fallback.
- DirectIngressHooks direct{};
- std::atomic<bool> directActive{false};
- std::atomic<bool> directInUse[2]{};
- std::atomic<int> directLatest{-1};
- unsigned directNext=0; // callback thread only
- AVFrame* directView[2]{};
- void* directCommitted[2]{};
- double directTime=0;Clock::time_point directArrival{};pipeline::Rational directDuration;bool directPending=false;
- int directSlot=-1; // consumer slot handed out by read()
- uint64_t directDrops=0;
- uint64_t directCommits=0,directFallbacks=0;
// Manual capture flip; read by the DirectShow callback thread.
std::atomic<bool> verticalFlip{false};
std::unique_ptr<WasapiAudioInput> wasapi;
@@ -179,49 +166,18 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
std::lock_guard lock(mutex);
if(!valid||!pendingFrame){callbackError=true;}
else {
- // N2: write straight into the graph's mapped upload buffer when
- // one is offered; otherwise keep the owned mailbox (first frame,
- // graph rebuild, or both slots busy).
- AVFrame* target=pendingFrame;unsigned directSlot=0;bool useDirect=false;
- if(directActive.load()&&direct.prepare){
- directSlot=directNext;
- void* buffer=nullptr;size_t capacity=0;unsigned pitch=0,rowBytes=0;
- bool ready=direct.prepare(direct.context,directSlot,buffer,capacity,pitch,rowBytes)&&buffer&&capacity>=layout.sampleBytes&&rowBytes>=layout.rowBytes;
- if(ready&&directInUse[directSlot].load()){
- const unsigned other=directSlot^1;
- ready=!directInUse[other].load()&&direct.prepare(direct.context,other,buffer,capacity,pitch,rowBytes)&&buffer&&capacity>=layout.sampleBytes&&rowBytes>=layout.rowBytes;
- if(ready)directSlot=other;
- }
- if(ready){
- useDirect=true;target=directView[directSlot];
- target->format=layout.format;target->width=int(layout.width);target->height=int(layout.height);
- target->data[0]=static_cast<uint8_t*>(buffer);target->linesize[0]=int(pitch);
- directCommitted[directSlot]=buffer;
- }
- }
- if(useDirect)++directCommits;else if(directActive.load())++directFallbacks;
- // Copy directly into the destination; read() hands the buffer
- // out under this lock, so the frame consumed by the GPU is not
- // overwritten while it is in use.
- if(!copyCaptureSample(layout,data,size_t(sample->GetActualDataLength()),*target,verticalFlip.load())){callbackError=true;wake.notify_one();return S_OK;}
- if(useDirect){
- if(pending){pending=false;++dropped;} // discard a stale mailbox frame
- directNext=directSlot^1;
- const int previous=directLatest.exchange(int(directSlot));
- if(previous>=0)++dropped; // unconsumed direct frame overwritten
- directTime=time;directArrival=arrival;
- }else if(pending)++dropped;
+ // Copy directly into our bounded mailbox; read() swaps frames
+ // under this lock, so the frame consumed by the GPU is untouched.
+ if(!copyCaptureSample(layout,data,size_t(sample->GetActualDataLength()),*pendingFrame,verticalFlip.load())){callbackError=true;wake.notify_one();return S_OK;}
+ if(pending)++dropped;
// Inspect consecutive callbacks, not consecutive mailbox reads.
// Preserve a driver/clock break when its sample is overwritten.
- pendingDiscontinuity=captureDiscontinuity(pending||directPending,pendingDiscontinuity,
+ pendingDiscontinuity=captureDiscontinuity(pending,pendingDiscontinuity,
sample->IsDiscontinuity()==S_OK,received>0,pendingTime,time,info.averageFps);
- if(useDirect)directPending=true;else pending=true;
- pendingTime=time;pendingArrival=arrival;
+ pending=true;pendingTime=time;pendingArrival=arrival;
pendingDuration=captureDuration(sampleStart,sampleEnd,sampleTime,nominalDuration100ns);
- if(useDirect)directDuration=pendingDuration;
if(!received)firstArrival=arrival;
++received;latestArrival=arrival;
- if(directActive.load()&&(received%120)==0)log::info("capture-direct",std::format("commits={} fallbacks={} drops={} (direct ingress counters)",directCommits,directFallbacks,directDrops));
}
}
wake.notify_one();return S_OK;
@@ -308,29 +264,6 @@ void CaptureCardSource::setCpuUnpack(bool enabled){
p.cpuUnpack=enabled;
log::warn("capture-unpack",std::format("legacy CPU per-pixel unpack={} (diagnostic; takes effect on the next connect)",enabled?1:0));
}
-bool CaptureCardSource::attachDirectIngress(const DirectIngressHooks& hooks){
- auto& p=*p_;
- if(!hooks.prepare||!hooks.current)return false;
- std::lock_guard lock(p.mutex);
- if(!p.configured||p.layout.planes!=1)return false;
- for(auto*& view:p.directView){if(!view)view=av_frame_alloc();if(!view)return false;}
- p.direct=hooks;p.directNext=0;p.directLatest.store(-1);p.directInUse[0].store(false);p.directInUse[1].store(false);
- p.directSlot=-1;p.directPending=false;p.directCommitted[0]=p.directCommitted[1]=nullptr;
- p.directActive.store(true);
- log::info("capture-direct",std::format("graph direct ingress attached format={} rowBytes={} (owned mailbox retained as fallback)",int(p.layout.format),p.layout.rowBytes));
- return true;
-}
-void CaptureCardSource::detachDirectIngress(){
- auto& p=*p_;std::lock_guard lock(p.mutex);
- if(!p.directActive.exchange(false))return;
- p.direct={};p.directLatest.store(-1);p.directInUse[0].store(false);p.directInUse[1].store(false);p.directSlot=-1;p.directPending=false;
- log::info("capture-direct","graph direct ingress detached");
-}
-bool CaptureCardSource::directIngressActive()const{return p_->directActive.load();}
-void CaptureCardSource::releaseDirectFrame(){
- auto& p=*p_;std::lock_guard lock(p.mutex);
- if(p.directSlot>=0){p.directInUse[unsigned(p.directSlot)].store(false);p.directSlot=-1;}
-}
bool CaptureCardSource::setAudioGain(float gain){
if(p_->wasapi){p_->wasapi->setGain(gain);return p_->wasapi->snapshot().available;}
auto& p=*p_;if(p.audioSession){p.audioSession->setGain(gain);return p.audioSession->snapshot().available;}if(!p.graph||!p.audioFilter)return false;
@@ -754,33 +687,13 @@ SourceReadStatus CaptureCardSource::read(pipeline::FramePacket& packet,const AVF
SourceReadStatus CaptureCardSource::tryRead(pipeline::FramePacket& packet,const AVFrame** frame){return readWithWait(packet,frame,0);}
SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,const AVFrame** frame,unsigned milliseconds){auto& p=*p_;*frame=nullptr;if(!p.info.opened)return SourceReadStatus::Error;
long code=0;LONG_PTR a=0,b=0;while(p.events&&p.events->GetEvent(&code,&a,&b,0)==S_OK){if(code==EC_DEVICE_LOST||code==EC_ERRORABORT)log::warn("capture-reconnect",std::format("DirectShow event={} detail=0x{:X}",code,uint64_t(a)));p.events->FreeEventParams(code,a,b);if(code==EC_DEVICE_LOST||code==EC_ERRORABORT)return SourceReadStatus::Error;}
- double time=0;uint32_t flags=0;uint64_t sequence=0;pipeline::Rational duration;AVFrame* outFrame=nullptr;
+ double time=0;uint32_t flags=0;uint64_t sequence=0;pipeline::Rational duration;
{
- std::unique_lock lock(p.mutex);if(milliseconds)p.wake.wait_for(lock,std::chrono::milliseconds(milliseconds),[&]{return p.pending||p.directLatest.load()>=0||p.callbackError;});
+ std::unique_lock lock(p.mutex);if(milliseconds)p.wake.wait_for(lock,std::chrono::milliseconds(milliseconds),[&]{return p.pending||p.callbackError;});
if(p.callbackError)return SourceReadStatus::Error;
- if(p.directActive.load()&&p.directLatest.load()>=0){
- const int slot=p.directLatest.exchange(-1);
- if(slot>=0){
- const unsigned s=unsigned(slot);
- void* buffer=nullptr;size_t capacity=0;unsigned pitch=0,rowBytes=0;
- if(p.direct.current&&p.direct.current(p.direct.context,s,buffer)&&buffer==p.directCommitted[s]){
- p.directInUse[s].store(true);p.directSlot=int(s);p.directPending=false;
- outFrame=p.directView[s];time=p.directTime;p.readArrival=p.directArrival;duration=p.directDuration;
- }else{
- // The graph rebuilt between commit and read: the bytes live
- // in a retired buffer, so drop the frame instead of reading
- // stale memory. The mailbox path below stays available.
- ++p.directDrops;++p.dropped;
- if(p.directInUse[s].load())p.directInUse[s].store(false);
- }
- }
- }
- if(!outFrame){
- if(!p.pending)return Impl::Clock::now()-p.lastFrame>std::chrono::seconds(3)?SourceReadStatus::Error:SourceReadStatus::Waiting;
- std::swap(p.frame,p.pendingFrame);p.pending=false;time=p.pendingTime;p.readArrival=p.pendingArrival;
- duration=p.pendingDuration;
- outFrame=p.frame;
- }
+ if(!p.pending)return Impl::Clock::now()-p.lastFrame>std::chrono::seconds(3)?SourceReadStatus::Error:SourceReadStatus::Waiting;
+ std::swap(p.frame,p.pendingFrame);p.pending=false;time=p.pendingTime;p.readArrival=p.pendingArrival;
+ duration=p.pendingDuration;
p.readAgeMs=std::chrono::duration<double,std::milli>(Impl::Clock::now()-p.readArrival).count();
if(!p.sequence)flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Open);
if(p.dropped!=p.lastDrop)flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Drop);
@@ -788,10 +701,10 @@ SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,c
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;
}
- outFrame->pts=static_cast<int64_t>(time*10000000);outFrame->duration=duration.isUnknown()?0:duration.to100ns();outFrame->time_base={1,10000000};packet={};packet.pts={outFrame->pts,10000000};packet.duration=duration;packet.colorInfo=p.info.color;packet.sourceKind=pipeline::SourceKind::CaptureCard;packet.sequence=sequence;packet.flags=flags;packet.sourceEpoch=1;
+ p.frame->pts=static_cast<int64_t>(time*10000000);p.frame->duration=duration.isUnknown()?0:duration.to100ns();p.frame->time_base={1,10000000};packet={};packet.pts={p.frame->pts,10000000};packet.duration=duration;packet.colorInfo=p.info.color;packet.sourceKind=pipeline::SourceKind::CaptureCard;packet.sequence=sequence;packet.flags=flags;packet.sourceEpoch=1;
packet.sequence+=receivedOffset_;packet.sourceEpoch=epoch_;
packet.arrivalHost100ns=std::chrono::duration_cast<std::chrono::nanoseconds>(p.readArrival.time_since_epoch()).count()/100;
- *frame=outFrame;p.lastFrame=Impl::Clock::now();return SourceReadStatus::Frame;
+ *frame=p.frame;p.lastFrame=Impl::Clock::now();return SourceReadStatus::Frame;
}
void CaptureCardSource::close()noexcept{
auto& p=*p_;if(p.control){const HRESULT hr=p.control->Stop();if(FAILED(hr))log::error("capture-close",std::format("Stop failed hr=0x{:08X}; releasing graph",uint32_t(hr)));}if(p.grab){const HRESULT hr=p.grab->SetCallback(nullptr,0);if(FAILED(hr))log::error("capture-close",std::format("detach callback hr=0x{:08X}",uint32_t(hr)));}
@@ -799,8 +712,7 @@ void CaptureCardSource::close()noexcept{
if(p.audioSession)p.audioSession->stop();p.audioError.clear();
if(p.audioPassthrough)p.audioPassthrough->close();
p.events.Reset();p.control.Reset();p.grab.Reset();p.nullFilter.Reset();p.grabFilter.Reset();p.audioSink.Reset();p.audioFilter.Reset();p.config.Reset();p.device.Reset();p.builder.Reset();p.graph.Reset();p.referenceClock.Reset();p.audioSession.reset();p.audioPassthrough.reset();
- av_frame_free(&p.frame);av_frame_free(&p.pendingFrame);for(auto*& view:p.directView)av_frame_free(&view);
- p.directActive.store(false);p.direct={};p.directLatest.store(-1);p.info={};
+ av_frame_free(&p.frame);av_frame_free(&p.pendingFrame);p.info={};
p.sequence=p.received=p.dropped=p.lastDrop=0;p.pending=p.callbackError=p.configured=p.forceDiscontinuity=false;p.lastPts=p.readAgeMs=0;
}
}