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: batch 7 - capture copy outside mailbox lock, owner wake on capture event, mid-stream software fallback, audio resampler rebuild, per-frame buffer reuse

Veyra Goal Agent6d019dc4f696
diff --git a/include/veyra/engine/DeadlineWait.h b/include/veyra/engine/DeadlineWait.h
index aca13061..113a858e 100644
--- a/include/veyra/engine/DeadlineWait.h
+++ b/include/veyra/engine/DeadlineWait.h
@@ -13,12 +13,22 @@ public:
~DeadlineWait(){if(timer_)CloseHandle(timer_);}
DeadlineWait(const DeadlineWait&)=delete;
DeadlineWait& operator=(const DeadlineWait&)=delete;
- void slice(double milliseconds=1){
- if(!timer_){Sleep(1);return;}
+ // Waits for the timer or, when supplied, an external event (capture
+ // sample arrival). Returns true when the event fired first.
+ bool slice(double milliseconds=1,HANDLE wakeEvent=nullptr){
+ if(!timer_){Sleep(1);return false;}
LARGE_INTEGER due;due.QuadPart=-std::max<LONGLONG>(1,static_cast<LONGLONG>(std::clamp(milliseconds,0.05,2.0)*10000));
- if(!SetWaitableTimer(timer_,&due,0,nullptr,nullptr,FALSE)){log::error("scheduler","SetWaitableTimer error="+std::to_string(GetLastError()));return;}
+ if(!SetWaitableTimer(timer_,&due,0,nullptr,nullptr,FALSE)){log::error("scheduler","SetWaitableTimer error="+std::to_string(GetLastError()));return false;}
+ if(wakeEvent){
+ HANDLE handles[2]={wakeEvent,timer_};
+ const auto result=WaitForMultipleObjects(2,handles,FALSE,10);
+ if(result==WAIT_OBJECT_0)return true;
+ if(result!=WAIT_OBJECT_0+1)log::warn("scheduler","wait result="+std::to_string(result));
+ return false;
+ }
const auto result=WaitForSingleObject(timer_,10);
if(result!=WAIT_OBJECT_0)log::warn("scheduler","wait timer result="+std::to_string(result));
+ return false;
}
private:HANDLE timer_=nullptr;
};
diff --git a/include/veyra/gfx/CommandSlotRing.h b/include/veyra/gfx/CommandSlotRing.h
index 273536b9..96fd3c3d 100644
--- a/include/veyra/gfx/CommandSlotRing.h
+++ b/include/veyra/gfx/CommandSlotRing.h
@@ -109,7 +109,8 @@ private:
ComPtr<ID3D12Resource> timingReadback_;
uint64_t timestampFrequency_ = 0, cpuWaitCount_ = 0, submitCount_ = 0;
double cpuWaitMilliseconds_ = 0;
- std::vector<double> gpuCommandTimesMs_;
+ std::vector<double> gpuCommandTimesMs_; // 16384-entry ring once full (sweep E6)
+ size_t gpuCommandTimesCursor_=0;
};
} // namespace veyra::gfx
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index aaed562b..2672db28 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -19,6 +19,7 @@
// warm-up evaluate runs before views exist; static views are created last.
#include <cstdint>
#include "veyra/pipeline/ResetCoordinator.h"
+#include "veyra/diagnostics/DiagnosticEvent.h"
#include <functional>
#include <memory>
#include <string>
@@ -451,6 +452,12 @@ private:
std::shared_ptr<AVFrame> hardwareInputFrames_[2];
core::SceneCadenceAnalyzer scene_;
std::vector<uint8_t> previousLuma_;
+ // Reused per-frame scratch (sweep A4/A5): diagnostic context and the
+ // 64x36 luma sample / 256-bin histogram used by scene/cadence analysis.
+ diagnostics::DiagnosticEvent frameDiagnostic_;
+ uint32_t diagnosticFlowPerf_=~0u;
+ std::vector<uint8_t> lumaSample_;
+ std::vector<double> lumaHistogram_=std::vector<double>(256,0.0);
double prevPtsMs_ = -1.0;
bool prevValid_ = false;
bool fgHistorySkipped_ = false;
diff --git a/include/veyra/source/CaptureCardSource.h b/include/veyra/source/CaptureCardSource.h
index 3e6f2985..74ff6856 100644
--- a/include/veyra/source/CaptureCardSource.h
+++ b/include/veyra/source/CaptureCardSource.h
@@ -65,6 +65,10 @@ public:
const std::wstring& errorMessage()const{return error_;}
SourceReadStatus read(pipeline::FramePacket&,const AVFrame**)override;
SourceReadStatus tryRead(pipeline::FramePacket&,const AVFrame**);
+ // Auto-reset event signalled after each delivered sample; lets the graph
+ // owner wait on "frame or deadline" instead of a fixed 1 ms timer slice.
+ // Null until configure(); the handle stays valid until close().
+ HANDLE frameEvent()const;
bool seek(const pipeline::Rational&)override{return false;}
void close()noexcept override;
private:
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index de7cb9ce..c6ec5041 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -671,7 +671,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
};
auto drainLivePresentation=[&]{cadence.reset();if(liveScheduler){++presentationDrains;liveScheduler->cancel();pollCompletions();pendingCompletions.clear();}pairLatency.reset();};
auto advanceLive=[&]{applyPresentation();if(liveScheduler){pollCompletions();if(stop_||(paused_&&!seekPreviewPending)||seekSeconds_>=0){liveScheduler->cancel();cadence.reset();}else liveScheduler->advance(host100ns());}};
- auto waitLive=[&]{const auto due=liveScheduler?liveScheduler->wakeAt():0;deadlineWait.slice(due>host100ns()?std::min(1.0,double(due-host100ns())/10000):1.0);};
+ auto waitLive=[&]{const auto due=liveScheduler?liveScheduler->wakeAt():0;deadlineWait.slice(due>host100ns()?std::min(1.0,double(due-host100ns())/10000):1.0,physicalCapture?captureSource.frameEvent():nullptr);};
uint64_t metricsRevision=options.settings.revision,metricsEpoch=0,metricsWindowEpoch=0,statsSourceBase=0;
uint64_t slotWaitBase=ring.cpuWaitCount(),submitBase=ring.submitCount();double slotWaitMsBase=ring.cpuWaitMilliseconds();
std::shared_ptr<FrameCompletionRates> completionRates;
diff --git a/src/gfx/CommandSlotRing.cpp b/src/gfx/CommandSlotRing.cpp
index a5feb038..4467adb8 100644
--- a/src/gfx/CommandSlotRing.cpp
+++ b/src/gfx/CommandSlotRing.cpp
@@ -136,7 +136,7 @@ ID3D12GraphicsCommandList* CommandSlotRing::acquire(uint32_t slot, Status& statu
uint64_t* data=nullptr;D3D12_RANGE range{slot*2*sizeof(uint64_t),(slot*2+2)*sizeof(uint64_t)};
if(SUCCEEDED(timingReadback_->Map(0,&range,reinterpret_cast<void**>(&data)))) {
const uint64_t begin=data[slot*2],end=data[slot*2+1];
- if(end>=begin&&gpuCommandTimesMs_.size()<16384){const double ms=double(end-begin)*1000.0/timestampFrequency_;gpuCommandTimesMs_.push_back(ms);if(!target.label.empty()&&veyra::log::verboseFrameLogs())veyra::log::info("gpu-profile",std::format("{} {:.4f} ms",target.label,ms));}
+ if(end>=begin){const double ms=double(end-begin)*1000.0/timestampFrequency_;if(gpuCommandTimesMs_.size()<16384)gpuCommandTimesMs_.push_back(ms);else gpuCommandTimesMs_[gpuCommandTimesCursor_++%16384]=ms;if(!target.label.empty()&&veyra::log::verboseFrameLogs())veyra::log::info("gpu-profile",std::format("{} {:.4f} ms",target.label,ms));}
D3D12_RANGE empty{0,0};timingReadback_->Unmap(0,&empty);
}target.timed=false;target.label.clear();
}
diff --git a/src/media/FFmpegVideoDecoder.cpp b/src/media/FFmpegVideoDecoder.cpp
index f193b4e9..80f5ef4c 100644
--- a/src/media/FFmpegVideoDecoder.cpp
+++ b/src/media/FFmpegVideoDecoder.cpp
@@ -640,7 +640,9 @@ bool FFmpegVideoDecoder::sendPacket(const AVPacket* packet)
int result = avcodec_send_packet(context_, packet);
while (result == AVERROR(EAGAIN)) {
++stats_.packetRetries;
- if (bufferedFrames_.size() >= 16) {
+ // Bound: each buffered frame pins a decoder pool surface on the
+ // hardware paths (pool ~20); keep well below it (sweep 2026-09-22 C9).
+ if (bufferedFrames_.size() >= (hardwareActive() ? 8u : 16u)) {
log::error("media", "decoder: output queue full; caller must consume frames before sending more input");
return false;
}
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index 2362904e..3413e494 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -1264,8 +1264,16 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
out = FrameOutputs{};
out.ptsMs = ptsMs;
if(!sourceFrameId)sourceFrameId=realFrameIndex_+1;
- diagnostics::DiagnosticEvent diagnostic;diagnostic.stage="frame";diagnostic.identity={epoch_+uint64_t(reset),desc_.settingsRevision,sourceFrameId};diagnostic.batch=realFrameIndex_+1;
- diagnostic.resolution.source={srcW_,srcH_};diagnostic.resolution.base={workW_,workH_};diagnostic.resolution.nr={nrW_,nrH_};diagnostic.resolution.flow={nvofW_,nvofH_};diagnostic.resolution.fg=diagnostic.resolution.output={workW_,workH_};diagnostic.runtimeHash="unverified-user-replaceable";diagnostic.flowApplied=std::to_string(actualFlowPerf());diagnostic.fallbackReason=mvecSource_;Logger::diagnosticContext(diagnostic);
+ // The per-frame diagnostic context is only consumed when a warning or
+ // error is logged; reuse one member event and refresh the cheap fields
+ // (the string members are set once per graph, sweep 2026-09-22 A4).
+ diagnostics::DiagnosticEvent& diagnostic=frameDiagnostic_;
+ if(diagnostic.stage.empty()){diagnostic.stage="frame";diagnostic.runtimeHash="unverified-user-replaceable";}
+ diagnostic.identity={epoch_+uint64_t(reset),desc_.settingsRevision,sourceFrameId};diagnostic.batch=realFrameIndex_+1;
+ diagnostic.resolution.source={srcW_,srcH_};diagnostic.resolution.base={workW_,workH_};diagnostic.resolution.nr={nrW_,nrH_};diagnostic.resolution.flow={nvofW_,nvofH_};diagnostic.resolution.fg=diagnostic.resolution.output={workW_,workH_};
+ if(diagnosticFlowPerf_!=actualFlowPerf()){diagnosticFlowPerf_=actualFlowPerf();diagnostic.flowApplied=std::to_string(diagnosticFlowPerf_);}
+ if(diagnostic.fallbackReason!=mvecSource_)diagnostic.fallbackReason=mvecSource_;
+ Logger::diagnosticContext(diagnostic);
static const bool graphOff = GetEnvironmentVariableW(L"VEYRA_GRAPH_OFF", nullptr, 0) != 0;
if (!frame || !initialized_ || !std::isfinite(ptsMs)) return false;
// Reject before CPU plane access, swscale, or command-slot acquisition.
@@ -1347,8 +1355,8 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
gpuTimer_.frame({epoch_,desc_.settingsRevision,realFrameIndex_+1},context_.fence());gpuTimer_.mark(list,GpuStage::Color);
// Both CPU source layouts feed the same bounded scene/cadence history.
- auto analyzeLuma = [&](std::vector<uint8_t> sample) {
- std::vector<double> hist(256,0);double sad=0;
+ auto analyzeLuma = [&](std::vector<uint8_t>& sample) {
+ auto& hist=lumaHistogram_;std::fill(hist.begin(),hist.end(),0.0);double sad=0;
for(auto v:sample)hist[v]+=1.0/sample.size();
if(previousLuma_.size()==sample.size())for(size_t i=0;i<sample.size();++i)sad+=std::abs(int(sample[i])-int(previousLuma_[i]))/(255.0*sample.size());
cadence_.observe(ptsMs,sad,previousLuma_.size()==sample.size());
@@ -1362,7 +1370,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
veyra::log::info("scene",std::format("history boundary frame={} ptsMs={} cutCandidate={} cadenceBreak={} sad={} histogramDistance={}",
realFrameIndex_,ptsMs,analysis.isSceneCut,analysis.isCadenceBreak,analysis.sadScore,analysis.histogramDistance));
}
- previousLuma_=std::move(sample);
+ std::swap(previousLuma_,sample);
};
if(gpuRgb){
@@ -1390,7 +1398,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
}
}
if(!desc_.stillImage){
- std::vector<uint8_t> sample;sample.reserve(64*36);
+ auto& sample=lumaSample_;sample.clear();sample.reserve(64*36);
const bool bgr=frame->format==AV_PIX_FMT_BGRA||frame->format==AV_PIX_FMT_BGR0;
for(unsigned y=0;y<36;++y)for(unsigned x=0;x<64;++x){
const unsigned sx=x*srcW_/64,sy=y*srcH_/36;
@@ -1398,7 +1406,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
else{const auto* p=frame->data[0]+ptrdiff_t(sy)*frame->linesize[0]+sx*(desc_.yuy2Input?2:4);
sample.push_back(desc_.yuy2Input?p[0]:uint8_t((54*unsigned(p[bgr?2:0])+183*unsigned(p[1])+19*unsigned(p[bgr?0:2])+128)>>8));}
}
- analyzeLuma(std::move(sample));
+ analyzeLuma(sample);
}
tracker_.transition(list,rgbTex_.Get(),D3D12_RESOURCE_STATE_COPY_DEST);
D3D12_TEXTURE_COPY_LOCATION dst{},src{};dst.pResource=rgbTex_.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
@@ -1521,10 +1529,10 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
// of P010/P016 retains the existing 8-bit scene/cadence proxy exactly.
const auto* sampleLuma=directUpload?frame->data[0]:planes[0];
const auto samplePitch=directUpload?ptrdiff_t(frame->linesize[0]):ptrdiff_t(lumaPitch_);
- std::vector<uint8_t> sample;sample.reserve(64*36);
+ auto& sample=lumaSample_;sample.clear();sample.reserve(64*36);
for(unsigned y=0;y<36;++y)for(unsigned x=0;x<64;++x)
sample.push_back(sampleLuma[ptrdiff_t(y*srcH_/36)*samplePitch+(x*srcW_/64)*sampleBytes+(sampleBytes-1)]);
- analyzeLuma(std::move(sample));
+ analyzeLuma(sample);
if(!directUpload){for (uint32_t y = 0; y < srcH_; ++y)
std::memcpy(mappedLuma_[parity] + y * lumaPitch_, planes[0] + y * lumaPitch_, srcW_*(desc_.wideYuvInput()?2:1));
for (uint32_t y = 0; y < (srcH_+1) / 2; ++y)
diff --git a/src/sink/WasapiAudioSink.cpp b/src/sink/WasapiAudioSink.cpp
index c6d23494..0b51edc6 100644
--- a/src/sink/WasapiAudioSink.cpp
+++ b/src/sink/WasapiAudioSink.cpp
@@ -161,11 +161,17 @@ void AudioPipeline::pushDecoded(const AVFrame* frame)
const bool layoutMatches=layout.nb_channels==int(pcmFormat_.channels)&&
((layout.order==AV_CHANNEL_ORDER_NATIVE&&layout.u.mask==pcmFormat_.mask)||
(layout.order==AV_CHANNEL_ORDER_UNSPEC&&layout.nb_channels<=2));
- if(!layoutMatches||frame->sample_rate<=0||
- (swr_&&(frame->sample_rate!=swrInputRate_||frame->format!=swrInputFormat_))){
- log::error("audio-format","Decoded audio layout/rate/format changed; reopen source required");
+ if(!layoutMatches||frame->sample_rate<=0){
+ log::error("audio-format","Decoded audio channel layout changed; reopen source required");
stopFlag_=true;return;
}
+ if(swr_&&(frame->sample_rate!=swrInputRate_||frame->format!=swrInputFormat_)){
+ // Sample rate / sample format changes (common at chapter or ad
+ // boundaries) rebuild the resampler instead of going silent
+ // (sweep 2026-09-22 C7). The output layout is unchanged.
+ log::info("audio-format",std::format("decoded audio rate/format changed {}Hz/{} -> {}Hz/{}; rebuilding resampler",swrInputRate_,int(swrInputFormat_),frame->sample_rate,frame->format));
+ swr_free(&swr_);swr_=nullptr;
+ }
// Convert to 48 kHz float in converted_, preserving the speaker layout.
if (swr_ == nullptr) {
AVChannelLayout outLayout{};av_channel_layout_from_mask(&outLayout,pcmFormat_.mask);
diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cpp
index d0487a30..2d765295 100644
--- a/src/source/CaptureCardSource.cpp
+++ b/src/source/CaptureCardSource.cpp
@@ -228,6 +228,14 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
// One pending frame plus one reader-owned frame, never an IMediaSample
// reference. Holding the producer's sole RGB32 sample starves its allocator.
AVFrame* frame=nullptr;AVFrame* pendingFrame=nullptr;bool pending=false,callbackError=false,configured=false;
+ // Native path only: the callback copies the driver sample into
+ // stagingFrame WITHOUT holding the mailbox lock (a 4K NV12 copy is
+ // 1-3 ms and used to block tryRead for its whole duration, sweep
+ // 2026-09-22 C3), then publishes it by pointer swap.
+ AVFrame* stagingFrame=nullptr;bool stagingBusy=false;
+ // Owner wake event for tryRead callers that prefer an event over a timer
+ // (capture latency review item 2).
+ HANDLE frameEvent=nullptr;
double pendingTime=0,lastPts=0,readAgeMs=0;bool pendingDiscontinuity=false,forceDiscontinuity=false;
int64_t nominalDuration100ns=0;pipeline::Rational pendingDuration=pipeline::Rational::unknown();
uint64_t received=0,dropped=0,lastDrop=0,sequence=0;
@@ -394,13 +402,19 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
const bool valid=sample&&std::isfinite(time)&&SUCCEEDED(sample->GetPointer(&data))&&data&&
(compressedPath?sample->GetActualDataLength()>0:sample->GetActualDataLength()>=LONG(layout.sampleBytes));
bool enqueued=false;uint64_t timingSequence=0;int64_t copied100ns=0;double lockWaitMs=0,arrivalDeltaMs=0,ptsDeltaMs=0;
+ // Native path: claim the staging frame, copy outside the lock.
+ AVFrame* staged=nullptr;bool stagedOk=false;
+ if(valid&&!compressedPath){
+ {std::lock_guard lock(mutex);if(stagingFrame&&!stagingBusy){stagingBusy=true;staged=stagingFrame;}}
+ if(staged)stagedOk=copyCaptureSample(layout,data,size_t(sample->GetActualDataLength()),*staged,verticalFlip.load());
+ }
{
std::lock_guard lock(mutex);
lockWaitMs=std::chrono::duration<double,std::milli>(Clock::now()-arrival).count();
// The compressed path decodes in its own worker and keeps its own
// frame pool, so the preallocated NV12 mailbox is legitimately
// empty between reads; only the native path requires it here.
- if(!valid||(!compressedPath&&!pendingFrame)){callbackError=true;}
+ if(!valid||(!compressedPath&&!pendingFrame)){callbackError=true;if(staged)stagingBusy=false;}
else {
const double previous=compressedPath?lastCallbackTime:pendingTime;
if(received){arrivalDeltaMs=std::chrono::duration<double,std::milli>(arrival-latestArrival).count();ptsDeltaMs=(time-previous)*1000;}
@@ -445,7 +459,17 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
lastCallbackTime=time;
compressedQueue.push_back(std::move(entry));enqueued=true;
}else{
- if(!copyCaptureSample(layout,data,size_t(sample->GetActualDataLength()),*pendingFrame,verticalFlip.load())){callbackError=true;wake.notify_one();return S_OK;}
+ if(staged){
+ stagingBusy=false;
+ if(!stagedOk){callbackError=true;wake.notify_one();return S_OK;}
+ // Publish: the copied frame becomes pendingFrame; the
+ // previous pendingFrame is the next staging target.
+ std::swap(stagingFrame,pendingFrame);
+ }else{
+ // Staging frame unavailable (should not happen once
+ // configured); keep the locked copy as a safe fallback.
+ 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.
@@ -462,6 +486,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
}
}
if(enqueued)decodeWake.notify_one();
+ if(frameEvent)SetEvent(frameEvent);
if(timingSequence&&(timingSequence%120==0||lockWaitMs>5))log::info("capture-callback",std::format("source={} entryToLockMs={:.3f} entryToCopiedMs={:.3f} bytes={} compressed={} arrivalDeltaMs={:.3f} ptsDeltaMs={:.3f} sampleDurationMs={:.3f} (callback cost, not display latency)",timingSequence,lockWaitMs,(copied100ns-std::chrono::duration_cast<std::chrono::nanoseconds>(arrival.time_since_epoch()).count()/100)/10000.0,sample->GetActualDataLength(),compressedPath,arrivalDeltaMs,ptsDeltaMs,sampleTime?double(sampleEnd-sampleStart)/10000:-1));
if(log::verboseFrameLogs()&&timingSequence)log::info("capture-ingress-sample",std::format("source={} arrival={} copied={} compressed={}",timingSequence,std::chrono::duration_cast<std::chrono::nanoseconds>(arrival.time_since_epoch()).count()/100,copied100ns,compressedPath));
wake.notify_one();return S_OK;
@@ -469,7 +494,8 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
HRESULT STDMETHODCALLTYPE BufferCB(double,BYTE*,long)override{return E_NOTIMPL;}
};
CaptureCardSource::CaptureCardSource():p_(std::make_unique<Impl>()){}
-CaptureCardSource::~CaptureCardSource(){close();}
+HANDLE CaptureCardSource::frameEvent()const{return p_->frameEvent;}
+CaptureCardSource::~CaptureCardSource(){close();if(p_->frameEvent){CloseHandle(p_->frameEvent);p_->frameEvent=nullptr;}}
std::vector<CaptureDevice> CaptureCardSource::deviceDetails(bool audio){
std::vector<CaptureDevice> result;
for(auto& moniker:monikers(audio)){
@@ -790,11 +816,13 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.cle
}
if(FAILED(p.graph.As(&p.control))||FAILED(p.graph.As(&p.events)))return false;
if(p.grab&&(FAILED(p.grab->SetBufferSamples(FALSE))||FAILED(p.grab->SetCallback(&p,0))))return false;
- for(auto** f:{&p.frame,&p.pendingFrame}){
+ for(auto** f:{&p.frame,&p.pendingFrame,&p.stagingFrame}){
*f=av_frame_alloc();if(!*f)return false;
(*f)->format=p.layout.format;(*f)->width=p.info.width;(*f)->height=p.info.height;
if(av_frame_get_buffer(*f,32)<0)return false;
}
+ p.stagingBusy=false;
+ if(!p.frameEvent)p.frameEvent=CreateEventW(nullptr,FALSE,FALSE,nullptr);
if(compressedPath){
// Write targets: the frame the worker is filling plus one spare handed
// out by read(). Frames are never reused while the caller still owns
@@ -1262,7 +1290,7 @@ void CaptureCardSource::close()noexcept{
if(p.workerFrame)av_frame_free(&p.workerFrame);
for(auto*& frame:p.compressedFree)if(frame)av_frame_free(&frame);
p.compressedFree.clear();
- av_frame_free(&p.frame);av_frame_free(&p.pendingFrame);
+ av_frame_free(&p.frame);av_frame_free(&p.pendingFrame);av_frame_free(&p.stagingFrame);p.stagingBusy=false;
if(p.pendingHardware)av_frame_free(&p.pendingHardware);if(p.hardwareRead)av_frame_free(&p.hardwareRead);
p.compressedDecoder.close();
if(p.decodeDevice){p.decodeDevice->Release();p.decodeDevice=nullptr;}if(p.decodeQueue){p.decodeQueue->Release();p.decodeQueue=nullptr;}
diff --git a/src/source/MediaFileSource.cpp b/src/source/MediaFileSource.cpp
index 6edfbc0e..ffcc68bb 100644
--- a/src/source/MediaFileSource.cpp
+++ b/src/source/MediaFileSource.cpp
@@ -49,11 +49,16 @@ MediaFileSource::~MediaFileSource()
bool MediaFileSource::fallbackToSoftware(std::string_view reason)
{
- if (!decoder_.hardwareActive() || framesRead_ != 0 || path_.empty()) {
+ if (!decoder_.hardwareActive() || path_.empty()) {
return false;
}
+ // Mid-stream failures (driver/pool errors after frames were delivered)
+ // reopen in software and seek back to the last delivered PTS; the caller
+ // sees a Discontinuity flag so temporal history resets (sweep B5).
+ const bool midStream = framesRead_ != 0;
+ const int64_t resumeUs = lastPtsUs_;
veyra::log::warn("source-file", std::format(
- "D3D12VA first-frame fallback to software reason={} path=redacted", reason));
+ "D3D12VA {} fallback to software reason={} path=redacted resumeUs={}", midStream ? "mid-stream" : "first-frame", reason, resumeUs));
decoder_.close();
demuxer_.close();
if (!demuxer_.open(path_)) {
@@ -67,6 +72,15 @@ bool MediaFileSource::fallbackToSoftware(std::string_view reason)
return false;
}
info_.hardwareDecodeActive = false;
+ if (midStream && resumeUs != INT64_MIN) {
+ if (!demuxer_.seekToUs(std::max<int64_t>(0, resumeUs))) veyra::log::warn("source-file", "software fallback could not seek back; continuing from stream start");
+ decoder_.flushBuffers();
+ // The engine treats Seek as a hard history reset; frames before the
+ // resume point are dropped by the caller's discardBefore logic.
+ pendingSeekFlag_ = true;
+ lastPtsUs_ = INT64_MIN;
+ ++epoch_;
+ }
info_.videoDecodePath = "software";
info_.containerName = demuxer_.formatName();
info_.videoPixelFormatName = params->format >= 0 && av_get_pix_fmt_name(static_cast<AVPixelFormat>(params->format))
diff --git a/src/source/NativeCaptureSink.cpp b/src/source/NativeCaptureSink.cpp
index bf239346..e45219b4 100644
--- a/src/source/NativeCaptureSink.cpp
+++ b/src/source/NativeCaptureSink.cpp
@@ -133,6 +133,10 @@ public:
if(!p)return E_POINTER;std::lock_guard lock(mutex_);
*p={compressed_?4:3,compressed_?LONG(512*1024):audio_?audioBlockBytes(*reinterpret_cast<const WAVEFORMATEX*>(desired_.pbFormat)):LONG(layout_.sampleBytes),1,0};return S_OK;
}
+ // Receive holds the pin mutex across the callback (DirectShow requires
+ // Stop()/GetState() to observe a quiescent pin). The callback itself now
+ // copies outside the source mailbox lock (CaptureCardSource C3), so the
+ // remaining hold covers only validation and pointer publication.
HRESULT STDMETHODCALLTYPE Receive(IMediaSample* sample)override{
if(!sample)return E_POINTER;std::lock_guard lock(mutex_);if(flushing_)return S_FALSE;if(state_==State_Stopped)return VFW_E_WRONG_STATE;
// A device mode change needs full source/graph recreation, never a