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

feat(capture): N2 direct-ingress prototype (opt-in; real-card verification failed, default off)

Veyra Goal Agent1b4ca8143f0e
diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cpp
index acbad247..8632fddb 100644
--- a/apps/veyra/ui/AppShell.cpp
+++ b/apps/veyra/ui/AppShell.cpp
@@ -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;}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;else if(!_wcsicmp(flipArgv[i],L"--capture-direct-ingress"))initialOptions.captureDirectIngress=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/WORKLOG.md b/docs/WORKLOG.md
index 35f61d6e..f385053b 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,13 @@
# 2026-09-11 继续修复目标模式执行中
+## 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` 开启(默认关)。
+
+**真机验证(¥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`)。
+
+**处置**:`PlayerOptions::captureDirectIngress` 默认 **false**,保留 `--capture-direct-ingress` 供继续排查;信箱路径与所有既有行为不变。**未完成(如实)**:N2 未达标,需定位直接写入路径导致引擎每帧 reset/10fps 的根因(怀疑方向:Drop 标志自激、图 parity 与源槽位错位、upload fence 覆盖范围过大),修复并重新真机验证前不得计入收益。压缩解码链路仍未开工。
+
## 2026-09-16 采集链路 N1:逐像素转换从 CPU 挪到 GPU
- 采集侧:`captureMediaLayout` 对 UYVY/YVYU/BGR24/RGB555/RGB565 保留驱动真实 packing(UYVY422/YVYU422/BGR24/RGB555LE/RGB565LE);`copyCaptureSample` 改为按行原样拷贝(保留 DIB 方向契约、手动翻转与 YUV 色度行跟随);新增 `captureLegacyCpuLayout` + `--capture-cpu-unpack` 诊断开关,旧 BGR0/YUY2 逐像素转换仍可回退。
diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.h
index 98f3864d..21049cfb 100644
--- a/include/veyra/engine/EngineController.h
+++ b/include/veyra/engine/EngineController.h
@@ -21,6 +21,10 @@ 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 e4a33937..37eeae62 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -1,5 +1,6 @@
#pragma once
#include "veyra/engine/BackendRecovery.h"
+#include <atomic>
// EnhanceGraph - the real unified processing graph (Playbook R3.2).
// Chains, per real frame:
@@ -122,6 +123,17 @@ 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);
struct FrameOutputs {
FrameBatch batch;
@@ -353,6 +365,7 @@ 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 d9fe8465..d301520f 100644
--- a/include/veyra/source/CaptureCardSource.h
+++ b/include/veyra/source/CaptureCardSource.h
@@ -55,6 +55,19 @@ 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;
+ };
+ 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 a3e89c31..a4190fb5 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -280,6 +280,13 @@ 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);};
+ 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;}
@@ -932,6 +939,7 @@ 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 2fe9a488..c2ac791d 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -103,6 +103,7 @@ 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;
@@ -212,6 +213,7 @@ 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;}
@@ -1065,7 +1067,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)std::memcpy(dst,src,size_t(ingressRowBytes));
+ if(packed||desc_.yuy2Input||frame->format==AV_PIX_FMT_RGBA){if(dst!=src)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)];
@@ -1682,8 +1684,23 @@ 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);
+}
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 cc5d5156..c1b51cec 100644
--- a/src/source/CaptureCardSource.cpp
+++ b/src/source/CaptureCardSource.cpp
@@ -148,6 +148,18 @@ 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;
// Manual capture flip; read by the DirectShow callback thread.
std::atomic<bool> verticalFlip{false};
std::unique_ptr<WasapiAudioInput> wasapi;
@@ -166,16 +178,45 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
std::lock_guard lock(mutex);
if(!valid||!pendingFrame){callbackError=true;}
else {
- // 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;
+ // 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;
+ }
+ }
+ // 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;
// Inspect consecutive callbacks, not consecutive mailbox reads.
// Preserve a driver/clock break when its sample is overwritten.
- pendingDiscontinuity=captureDiscontinuity(pending,pendingDiscontinuity,
+ pendingDiscontinuity=captureDiscontinuity(pending||directPending,pendingDiscontinuity,
sample->IsDiscontinuity()==S_OK,received>0,pendingTime,time,info.averageFps);
- pending=true;pendingTime=time;pendingArrival=arrival;
+ if(useDirect)directPending=true;else pending=true;
+ pendingTime=time;pendingArrival=arrival;
pendingDuration=captureDuration(sampleStart,sampleEnd,sampleTime,nominalDuration100ns);
+ if(useDirect)directDuration=pendingDuration;
if(!received)firstArrival=arrival;
++received;latestArrival=arrival;
}
@@ -264,6 +305,29 @@ 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)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;
@@ -687,13 +751,33 @@ 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;
+ double time=0;uint32_t flags=0;uint64_t sequence=0;pipeline::Rational duration;AVFrame* outFrame=nullptr;
{
- std::unique_lock lock(p.mutex);if(milliseconds)p.wake.wait_for(lock,std::chrono::milliseconds(milliseconds),[&]{return p.pending||p.callbackError;});
+ 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;});
if(p.callbackError)return SourceReadStatus::Error;
- 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;
+ 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.prepare&&p.direct.prepare(p.direct.context,s,buffer,capacity,pitch,rowBytes)&&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;
+ }
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);
@@ -701,10 +785,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;
}
- 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;
+ 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;
packet.sequence+=receivedOffset_;packet.sourceEpoch=epoch_;
packet.arrivalHost100ns=std::chrono::duration_cast<std::chrono::nanoseconds>(p.readArrival.time_since_epoch()).count()/100;
- *frame=p.frame;p.lastFrame=Impl::Clock::now();return SourceReadStatus::Frame;
+ *frame=outFrame;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)));}
@@ -712,7 +796,8 @@ 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);p.info={};
+ 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={};
p.sequence=p.received=p.dropped=p.lastDrop=0;p.pending=p.callbackError=p.configured=p.forceDiscontinuity=false;p.lastPts=p.readAgeMs=0;
}
}