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): D3D12VA/software backend for compressed capture payloads (MPEG chain stage 3)
Veyra Goal Agent705e9071da3d
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 04637d74..d30567f2 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -465,6 +465,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformsrc/source/NativeCaptureSink.cppsrc/source/MediaFileSource.cppsrc/source/CaptureCardSource.cpp+ src/source/CaptureCompressedDecoder.cppsrc/source/WasapiAudioInput.cpp)veyra_apply_warnings(veyra_sources)@@ -475,7 +476,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformUNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)target_include_directories(veyra_sources PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)target_link_libraries(veyra_sources PUBLIC veyra_pipeline veyra_media veyra_base)- target_link_libraries(veyra_sources PRIVATE ${FFMPEG_LIBRARIES} strmiids ole32 oleaut32)+ target_link_libraries(veyra_sources PRIVATE ${FFMPEG_LIBRARIES} strmiids ole32 oleaut32 d3d12 dxgi)if(VEYRA_ENABLE_REMOTEPLAY)set(VEYRA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}")@@ -584,6 +585,11 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_link_libraries(veyra_fg_admission_tests PRIVATE veyra_engine)target_compile_features(veyra_capture_color_tests PRIVATE cxx_std_20)target_link_libraries(veyra_capture_color_tests PRIVATE veyra_sources)+ add_executable(veyra_capture_compressed_tests tests/unit/CaptureCompressedDecoderTests.cpp)+ target_compile_features(veyra_capture_compressed_tests PRIVATE cxx_std_20)+ target_compile_definitions(veyra_capture_compressed_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)+ target_include_directories(veyra_capture_compressed_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})+ target_link_libraries(veyra_capture_compressed_tests PRIVATE veyra_sources veyra_gfx ${FFMPEG_LIBRARIES})add_executable(veyra_yuy2_color_tests tests/integration/Yuy2ColorTests.cpp)target_compile_features(veyra_yuy2_color_tests PRIVATE cxx_std_20)target_link_libraries(veyra_yuy2_color_tests PRIVATE veyra_engine)diff --git a/include/veyra/media/FFmpegVideoDecoder.h b/include/veyra/media/FFmpegVideoDecoder.hindex 8b2ad211..7bfb69fd 100644--- a/include/veyra/media/FFmpegVideoDecoder.h+++ b/include/veyra/media/FFmpegVideoDecoder.h@@ -40,7 +40,8 @@ public:// Den` is the DEMUXER stream time base: decoder frame PTS pass through in// that base when the codec context itself carries none.bool openSoftware(const AVCodecParameters* codecParameters,- int streamTimeBaseNum = 0, int streamTimeBaseDen = 0, unsigned softwareThreads = 1);+ int streamTimeBaseNum = 0, int streamTimeBaseDen = 0, unsigned softwareThreads = 1,+ bool lowLatency = false);// D3D12VA hardware decode on the SHARED Veyra device (Playbook 13.2):// creates an AV_HWDEVICE_TYPE_D3D12VA context wrapping `device`/`queue`,@@ -48,7 +49,7 @@ public:// records GPU queue waits on each frame's sync fence.bool openD3D12VA(const AVCodecParameters* codecParameters,int streamTimeBaseNum, int streamTimeBaseDen,- ID3D12Device* device, ID3D12CommandQueue* queue);+ ID3D12Device* device, ID3D12CommandQueue* queue, bool lowLatency = false);void close();bool opened() const { return context_ != nullptr; }diff --git a/include/veyra/source/CaptureCompressedDecoder.h b/include/veyra/source/CaptureCompressedDecoder.hnew file mode 100644index 00000000..fe218363--- /dev/null+++ b/include/veyra/source/CaptureCompressedDecoder.h@@ -0,0 +1,65 @@+#pragma once++// Compressed capture payload decoder (MPEG chain stage 3). Owns the FFmpeg+// decoder that turns the direct-connect capture payloads (MJPEG / H.264 /+// HEVC / AV1 / VP9) into frames the capture ingress understands. It is used+// from the single capture decode worker thread and is not thread safe.++#include <cstddef>+#include <cstdint>+#include <memory>+#include <string>++#include "veyra/source/CaptureCodec.h"++struct AVFrame;+struct ID3D12Device;+struct ID3D12CommandQueue;++namespace veyra::source {++class CaptureCompressedDecoder {+public:+ CaptureCompressedDecoder();+ ~CaptureCompressedDecoder();++ CaptureCompressedDecoder(const CaptureCompressedDecoder&) = delete;+ CaptureCompressedDecoder& operator=(const CaptureCompressedDecoder&) = delete;++ // Backend order: MJPEG always decodes in software (drivers disagree on+ // 4:2:0 vs 4:2:2 and there is no 4:2:2 hardware path); everything else+ // tries D3D12VA on the shared Veyra device first. A hardware decoder whose+ // first frame cannot be imported by the graph is closed and replaced by+ // the software decoder, which converts into `nv12Target` instead.+ //+ // `extradata` (SPS/PPS from MPEG2VIDEOINFO) may be empty; the bitstream's+ // in-band parameter sets are then required.+ bool open(CaptureCodec codec, unsigned width, unsigned height,+ const uint8_t* extradata, size_t extradataBytes,+ ID3D12Device* device, ID3D12CommandQueue* queue);++ // Decodes one payload. On success `*out` is a frame whose lifetime the+ // caller must not extend past the next decode():+ // - hardware=true: decoder-owned D3D12 surface (AV_PIX_FMT_D3D12);+ // - hardware=false: converted into `nv12Target` (owned by the caller).+ // Returns false when the payload produced no frame (pending input) or the+ // decoder reported an error; see lastError()/waitingForInput().+ bool decode(const uint8_t* data, size_t bytes, int64_t pts100ns,+ AVFrame* nv12Target, AVFrame** out, bool& hardware);++ bool opened() const;+ bool hardwareActive() const;+ bool waitingForInput() const;+ const char* backendName() const;+ const std::string& lastError() const;+ uint64_t framesDecoded() const;+ uint64_t decodeFailures() const;+ uint64_t hardwareFallbacks() const;+ void close();++private:+ struct Impl;+ std::unique_ptr<Impl> p_;+};++} // namespace veyra::sourcediff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex 698aab01..127421a1 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -187,12 +187,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s{std::lock_guard lock(mutex_);desired_.multiplier=1;snapshot_.image=true;snapshot_.desired=desired_;}}else{source::SourceOpenDesc od;od.path=path;- // Files use the same shared D3D12 device as the graph. The- // source performs a capability check and falls back to- // software before returning its first frame; capture/PS5- // retain their own decode contracts.- od.preferHardwareDecode=!isCapture;- if(od.preferHardwareDecode){od.d3d12Device=ctx.device();od.d3d12Queue=ctx.directQueue();}+ // Files use the same shared D3D12 device as the graph. Capture+ // uses it for the compressed-payload decoder (H.264/HEVC/AV1/+ // VP9 through D3D12VA; MJPEG stays on the software path inside+ // CaptureCompressedDecoder). Each source performs its own+ // capability check and records its fallback.+ od.preferHardwareDecode=true;+ od.d3d12Device=ctx.device();od.d3d12Queue=ctx.directQueue();// 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)){diff --git a/src/media/FFmpegVideoDecoder.cpp b/src/media/FFmpegVideoDecoder.cppindex 41a735b6..aaba0f18 100644--- a/src/media/FFmpegVideoDecoder.cpp+++ b/src/media/FFmpegVideoDecoder.cpp@@ -37,7 +37,7 @@ FFmpegVideoDecoder::~FFmpegVideoDecoder()}bool FFmpegVideoDecoder::openSoftware(const AVCodecParameters* codecParameters,- int streamTimeBaseNum, int streamTimeBaseDen, unsigned softwareThreads)+ int streamTimeBaseNum, int streamTimeBaseDen, unsigned softwareThreads, bool lowLatency){receiveStatus_ = DecodeReceiveStatus::NeedInput;if (context_ != nullptr) {@@ -82,6 +82,14 @@ bool FFmpegVideoDecoder::openSoftware(const AVCodecParameters* codecParameters,// queue and no capture lookahead are introduced.context_->thread_count = int(std::clamp(softwareThreads,1u,4u));context_->thread_type = FF_THREAD_FRAME | FF_THREAD_SLICE;+ if (lowLatency) {+ // Live capture: never trade latency for throughput. Frame threading+ // buffers whole frames before returning any output, so slice-only+ // execution plus the codec's low-delay flag keeps every decoded frame+ // available as soon as it is complete.+ context_->thread_type = FF_THREAD_SLICE;+ context_->flags |= AV_CODEC_FLAG_LOW_DELAY;+ }if (avcodec_open2(context_, codec, nullptr) < 0) {log::error("media", "decoder: avcodec_open2 failed");avcodec_free_context(&context_);@@ -95,14 +103,14 @@ bool FFmpegVideoDecoder::openSoftware(const AVCodecParameters* codecParameters,}stats_ = DecoderStats{};- log::info("media", std::format("decoder: software decoder opened codec={} {}x{} pixFmt={} threads={} activeThreadType={}",- codec->name, context_->width, context_->height, static_cast<int>(context_->pix_fmt),context_->thread_count,context_->active_thread_type));+ log::info("media", std::format("decoder: software decoder opened codec={} {}x{} pixFmt={} threads={} activeThreadType={} lowLatency={}",+ codec->name, context_->width, context_->height, static_cast<int>(context_->pix_fmt),context_->thread_count,context_->active_thread_type,lowLatency));return true;}bool FFmpegVideoDecoder::openD3D12VA(const AVCodecParameters* codecParameters,int streamTimeBaseNum, int streamTimeBaseDen,- ID3D12Device* device, ID3D12CommandQueue* queue)+ ID3D12Device* device, ID3D12CommandQueue* queue, bool lowLatency){receiveStatus_ = DecodeReceiveStatus::NeedInput;if (context_ != nullptr) {@@ -151,6 +159,10 @@ bool FFmpegVideoDecoder::openD3D12VA(const AVCodecParameters* codecParameters,context_->thread_count = 1;context_->get_format = SelectD3D12Format;context_->hw_device_ctx = av_buffer_ref(hwDeviceRef);+ if (lowLatency) {+ // Live capture must not wait for the decoder's reorder window.+ context_->flags |= AV_CODEC_FLAG_LOW_DELAY;+ }av_buffer_unref(&hwDeviceRef); // codec ctx holds its own reference nowif (avcodec_open2(context_, codec, nullptr) < 0) {@@ -167,8 +179,8 @@ bool FFmpegVideoDecoder::openD3D12VA(const AVCodecParameters* codecParameters,stats_ = DecoderStats{};hwAccelActive_ = true;gpuQueueWaitCount_ = 0;- log::info("media", std::format("decoder: d3d12va decoder opened codec={} {}x{} (shared Veyra device)",- codec->name, context_->width, context_->height));+ log::info("media", std::format("decoder: d3d12va decoder opened codec={} {}x{} lowLatency={} (shared Veyra device)",+ codec->name, context_->width, context_->height, lowLatency));return true;}diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cppindex 1f25c2ab..a0e55c44 100644--- a/src/source/CaptureCardSource.cpp+++ b/src/source/CaptureCardSource.cpp@@ -6,6 +6,7 @@#include "veyra/source/CaptureBuffer.h"#include "veyra/source/CaptureFormatRank.h"#include "veyra/source/CaptureCodec.h"+#include "veyra/source/CaptureCompressedDecoder.h"#include "veyra/pipeline/ColorMetadata.h"#include "veyra/Log.h"#include "veyra/sink/AudioFormat.h"@@ -16,11 +17,12 @@#include <dvdmedia.h>#include <ks.h>#include <ksmedia.h>+#include <d3d12.h>#include <wrl/client.h>extern "C" {#include <libavcodec/avcodec.h>-#include <libswscale/swscale.h>}+#include <vector>#include <algorithm>#include <deque>#include <thread>@@ -47,6 +49,81 @@ struct __declspec(uuid("6B652FFF-11FE-4FCE-92AD-0266B5D7C78F")) ISampleGrabber:Iconst CLSID SampleGrabberClass={0xc1f400a0,0x3f08,0x11d3,{0x9f,0x0b,0x00,0x60,0x08,0x03,0x9e,0x37}};const CLSID NullRendererClass={0xc1f400a4,0x3f08,0x11d3,{0x9f,0x0b,0x00,0x60,0x08,0x03,0x9e,0x37}};void freeType(AM_MEDIA_TYPE* t,bool pointer=true){if(!t)return;CoTaskMemFree(t->pbFormat);if(t->pUnk)t->pUnk->Release();if(pointer)CoTaskMemFree(t);}+// MPEG2VIDEOINFO carries the codec's sequence header (SPS/PPS) for compressed+// capture formats. Drivers are inconsistent: some store Annex-B with start+// codes, some store 4-byte length-prefixed NAL units, some an+// AVCDecoderConfigurationRecord / HEVCDecoderConfigurationRecord. Normalize+// everything to the Annex-B form the FFmpeg decoders consume. An empty result+// means the caller relies on the bitstream's in-band parameter sets, and a+// decoder that still cannot start falls back to the RGB32 compatibility path.+std::vector<uint8_t> captureCompressedExtradata(const AM_MEDIA_TYPE& type,CaptureCodec codec){+ std::vector<uint8_t> result;+ if(codec==CaptureCodec::None||codec==CaptureCodec::Mjpeg)return result;+ if(type.formattype!=FORMAT_MPEG2Video||!type.pbFormat||type.cbFormat<sizeof(MPEG2VIDEOINFO))return result;+ const auto& info=*reinterpret_cast<const MPEG2VIDEOINFO*>(type.pbFormat);+ const size_t bytes=size_t(info.cbSequenceHeader);+ if(bytes<4||bytes>256*1024)return result;+ if(offsetof(MPEG2VIDEOINFO,dwSequenceHeader)+bytes>size_t(type.cbFormat))return result;+ const uint8_t* data=reinterpret_cast<const uint8_t*>(info.dwSequenceHeader);+ const auto appendNal=[&result](const uint8_t* nal,size_t length){+ result.insert(result.end(),{0,0,0,1});+ result.insert(result.end(),nal,nal+length);+ };+ // Already Annex-B (start code with 3 or 4 bytes).+ if(data[0]==0&&data[1]==0&&(data[2]==1||(data[2]==0&&data[3]==1))){result.assign(data,data+bytes);return result;}+ // AVCDecoderConfigurationRecord: version 1, SPS/PPS length-prefixed lists.+ if(codec==CaptureCodec::H264&&data[0]==1&&bytes>=7){+ size_t offset=5;+ const unsigned spsCount=data[offset++]&0x1f;+ for(unsigned i=0;i<spsCount;++i){+ if(offset+2>bytes)return {};+ const size_t length=(size_t(data[offset])<<8)|data[offset+1];offset+=2;+ if(!length||offset+length>bytes)return {};+ appendNal(data+offset,length);offset+=length;+ }+ if(offset>=bytes)return {};+ const unsigned ppsCount=data[offset++];+ for(unsigned i=0;i<ppsCount;++i){+ if(offset+2>bytes)return {};+ const size_t length=(size_t(data[offset])<<8)|data[offset+1];offset+=2;+ if(!length||offset+length>bytes)return {};+ appendNal(data+offset,length);offset+=length;+ }+ return result;+ }+ // HEVCDecoderConfigurationRecord: version 1, array of NAL units.+ if(codec==CaptureCodec::Hevc&&data[0]==1&&bytes>=23){+ const unsigned arrayCount=data[22];+ size_t offset=23;+ for(unsigned i=0;i<arrayCount;++i){+ if(offset+3>bytes)return {};+ const unsigned nalType=data[offset]&0x3f;++offset;+ const unsigned count=(unsigned(data[offset])<<8)|data[offset+1];offset+=2;+ for(unsigned j=0;j<count;++j){+ if(offset+2>bytes)return {};+ const size_t length=(size_t(data[offset])<<8)|data[offset+1];offset+=2;+ if(!length||offset+length>bytes)return {};+ // Keep VPS(32)/SPS(33)/PPS(34) only; other arrays are optional.+ if(nalType==32||nalType==33||nalType==34)appendNal(data+offset,length);+ offset+=length;+ }+ }+ return result;+ }+ // Consecutive 4-byte length-prefixed NAL units.+ std::vector<uint8_t> converted;+ size_t offset=0;+ while(offset+4<=bytes){+ const size_t length=(size_t(data[offset])<<24)|(size_t(data[offset+1])<<16)|(size_t(data[offset+2])<<8)|size_t(data[offset+3]);+ offset+=4;+ if(!length||offset+length>bytes)return {};+ converted.insert(converted.end(),{0,0,0,1});+ converted.insert(converted.end(),data+offset,data+offset+length);+ offset+=length;+ }+ if(offset!=bytes||converted.empty())return {};+ return converted;+}std::wstring propertyString(IMoniker* moniker,LPCOLESTR property){if(!moniker)return {};ComPtr<IPropertyBag> bag;VARIANT value;VariantInit(&value);std::wstring result;@@ -159,8 +236,12 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {// Decoding happens on the DirectShow callback thread for now (one decoder);// a bounded parallel decode queue is a later refinement.bool compressedPath=false;CaptureCodec codec=CaptureCodec::None;- AVCodecContext* decoder=nullptr;SwsContext* sws=nullptr;AVFrame* decoded=nullptr;+ CaptureCompressedDecoder compressedDecoder;+ ID3D12Device* decodeDevice=nullptr;ID3D12CommandQueue* decodeQueue=nullptr;uint64_t compressedDecoded=0,compressedErrors=0;+ // D3D12VA frames are decoder-owned surfaces, so they travel through their+ // own mailbox slot instead of the preallocated NV12 buffer.+ AVFrame* pendingHardware=nullptr;AVFrame* hardwareRead=nullptr;bool pendingIsHardware=false;// Decode worker: keeps the DirectShow callback cheap (payload copy only)// and lets the decode overlap with graph work. The worker owns workerFrame// and swaps it into the mailbox once a frame is ready.@@ -176,8 +257,9 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {SourceInfo info;CaptureMediaLayout layout;Clock::time_point lastFrame;HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** pp)override{if(!pp)return E_POINTER;*pp=nullptr;if(id==IID_IUnknown||id==__uuidof(ISampleGrabberCB)){*pp=static_cast<ISampleGrabberCB*>(this);AddRef();return S_OK;}return E_NOINTERFACE;}ULONG STDMETHODCALLTYPE AddRef()override{return ++refs;}ULONG STDMETHODCALLTYPE Release()override{return --refs;}- // Decode worker loop: pop a compressed payload, decode it into the worker- // frame (no source lock held), then swap it into the mailbox.+ // Decode worker loop: pop a compressed payload, decode it with our own+ // backend (software MJPEG / D3D12VA for H.264/HEVC/AV1/VP9), then hand the+ // result to the mailbox. No source lock is held during decoding.void decodeLoop(){for(;;){CompressedSample sample;@@ -187,37 +269,33 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {if(decodeStop&&compressedQueue.empty())return;sample=std::move(compressedQueue.front());compressedQueue.pop_front();}- AVPacket* packet=av_packet_alloc();if(!packet){++compressedErrors;continue;}- if(av_new_packet(packet,int(sample.payload.size()))<0){av_packet_free(&packet);++compressedErrors;continue;}- std::memcpy(packet->data,sample.payload.data(),sample.payload.size());- const int send=avcodec_send_packet(decoder,packet);av_packet_free(&packet);- if(send<0){++compressedErrors;continue;}- if(avcodec_receive_frame(decoder,decoded)<0){++compressedErrors;continue;}- // MJPEG decodes to the deprecated full-range YUVJ formats; map them- // to standard formats and pin the range explicitly instead of- // letting swscale guess (and spam a warning every frame).- AVPixelFormat srcFormat=AVPixelFormat(decoded->format);- if(srcFormat==AV_PIX_FMT_YUVJ422P)srcFormat=AV_PIX_FMT_YUV422P;- else if(srcFormat==AV_PIX_FMT_YUVJ420P)srcFormat=AV_PIX_FMT_YUV420P;- else if(srcFormat==AV_PIX_FMT_YUVJ444P)srcFormat=AV_PIX_FMT_YUV444P;- sws=sws_getCachedContext(sws,decoded->width,decoded->height,srcFormat,- int(layout.width),int(layout.height),AV_PIX_FMT_NV12,SWS_BILINEAR,nullptr,nullptr,nullptr);- if(!sws){av_frame_unref(decoded);++compressedErrors;continue;}- const int* coefficients=sws_getCoefficients(decoded->colorspace==AVCOL_SPC_BT709?SWS_CS_ITU709:SWS_CS_ITU601);- sws_setColorspaceDetails(sws,coefficients,1,coefficients,1,0,1<<16,1<<16);- uint8_t* dst[4]={workerFrame->data[0],workerFrame->data[1],nullptr,nullptr};- const int dstStride[4]={workerFrame->linesize[0],workerFrame->linesize[1],0,0};- sws_scale(sws,decoded->data,decoded->linesize,0,decoded->height,dst,dstStride);- av_frame_unref(decoded);- ++compressedDecoded;+ AVFrame* decodedFrame=nullptr;bool hardware=false;+ const bool produced=compressedDecoder.decode(sample.payload.data(),sample.payload.size(),+ int64_t(sample.time*1e7),workerFrame,&decodedFrame,hardware);+ if(!produced){+ // A decoder that needs more input before it can emit a frame is+ // normal for the first payload; a real error is not.+ if(!compressedDecoder.waitingForInput())++compressedErrors;+ continue;+ }{std::lock_guard lock(mutex);- if(pending)++dropped; // mailbox semantics: newest wins- std::swap(pendingFrame,workerFrame);+ if(hardware){+ AVFrame* cloned=av_frame_clone(decodedFrame);+ if(!cloned){++compressedErrors;continue;}+ if(pending)++dropped; // mailbox semantics: newest wins+ if(pendingHardware)av_frame_free(&pendingHardware);+ pendingHardware=cloned;+ }else{+ if(pending)++dropped;+ std::swap(pendingFrame,workerFrame);+ }+ pendingIsHardware=hardware;pending=true;pendingTime=sample.time;pendingArrival=sample.arrival;pendingDuration=captureDuration(sample.start,sample.end,sample.completeTime,nominalDuration100ns);pendingDiscontinuity=sample.bad;- if((compressedDecoded%600)==0)log::info("capture-decode",std::format("decoded={} errors={} queueDrops={} (decode worker)",compressedDecoded,compressedErrors,compressedDropped));+ ++compressedDecoded;+ if((compressedDecoded%600)==0)log::info("capture-decode",std::format("decoded={} errors={} queueDrops={} backend={} (decode worker)",compressedDecoded,compressedErrors,compressedDropped,compressedDecoder.backendName()));}wake.notify_one();}@@ -235,8 +313,8 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {else {// Copy directly into our bounded mailbox; read() swaps frames// under this lock, so the frame consumed by the GPU is untouched.- // Compressed MJPEG payloads are decoded into the same NV12- // mailbox frame instead of being expanded by the system graph.+ // Compressed payloads are decoded by our own backend instead of+ // being expanded by the system graph's decoder/color converter.if(compressedPath){// MPEG chain: the callback only copies the compressed// payload; the decode worker produces the NV12 frame.@@ -400,20 +478,11 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAuconst bool direct=nativeSupported&&!desc.legacyCaptureRgbForDiagnostic;const CaptureCodec codec=captureCodecOf(native->subtype);unsigned compressedWidth=0,compressedHeight=0;int64_t compressedDuration=0;- bool compressedPath=false;- if(!direct&&!nativeSupported&&codec==CaptureCodec::Mjpeg&&!desc.legacyCaptureRgbForDiagnostic){- // MPEG chain stage 2: MJPEG bypasses the system decoder stack entirely;- // our own decoder turns each payload into an NV12 mailbox frame. Any- // failure below falls back to the RGB32 compatibility path.- const AVCodec* avcodec=avcodec_find_decoder(AV_CODEC_ID_MJPEG);- p.decoder=avcodec?avcodec_alloc_context3(avcodec):nullptr;- p.decoded=av_frame_alloc();- if(p.decoder&&p.decoded&&avcodec_open2(p.decoder,avcodec,nullptr)>=0){compressedPath=true;p.compressedPath=true;p.codec=codec;}- else{- if(p.decoded)av_frame_free(&p.decoded);if(p.decoder)avcodec_free_context(&p.decoder);- log::warn("capture-decode","MJPEG decoder unavailable; keeping the RGB32 compatibility path");- }- }+ // MPEG chain: every compressed subtype (MJPEG/H.264/HEVC/AV1/VP9) now+ // bypasses the system decoder stack; our own backend decodes it. Any+ // failure below falls back to the RGB32 compatibility path.+ const bool compressedPath=!direct&&!nativeSupported&&codec!=CaptureCodec::None&&!desc.legacyCaptureRgbForDiagnostic;+ if(compressedPath){p.compressedPath=true;p.codec=codec;}AM_MEDIA_TYPE connected{};if(compressedPath){ComPtr<IPin> input,output;@@ -428,6 +497,18 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAuelse if(connected.formattype==FORMAT_VideoInfo&&connected.cbFormat>=sizeof(VIDEOINFOHEADER)){const auto& v=*reinterpret_cast<const VIDEOINFOHEADER*>(connected.pbFormat);compressedWidth=unsigned(v.bmiHeader.biWidth);compressedHeight=unsigned(std::abs(int64_t(v.bmiHeader.biHeight)));compressedDuration=int64_t(v.AvgTimePerFrame);}if(!compressedWidth||!compressedHeight||compressedWidth%2||compressedHeight%2){log::warn("capture-decode","compressed dimensions unusable; falling back to the RGB32 compatibility path");hr=VFW_E_INVALIDMEDIATYPE;}}+ if(SUCCEEDED(hr)){+ const auto extradata=captureCompressedExtradata(*native,codec);+ if(!p.compressedDecoder.open(codec,compressedWidth,compressedHeight,extradata.data(),extradata.size(),+ static_cast<ID3D12Device*>(desc.d3d12Device),static_cast<ID3D12CommandQueue*>(desc.d3d12Queue))){+ log::warn("capture-decode",std::format("no usable decoder for codec={}; falling back to the RGB32 compatibility path",captureCodecKey(codec)));+ hr=VFW_E_INVALIDMEDIATYPE;+ }else{+ // Keep the shared device/queue alive for the decode worker.+ if(desc.d3d12Device){p.decodeDevice=static_cast<ID3D12Device*>(desc.d3d12Device);p.decodeDevice->AddRef();}+ if(desc.d3d12Queue){p.decodeQueue=static_cast<ID3D12CommandQueue*>(desc.d3d12Queue);p.decodeQueue->AddRef();}+ }+ }log::info("capture-decode",std::format("compressed ConnectDirect codec={} subtype=0x{:08X} size={}x{} hr=0x{:08X}",captureCodecKey(codec),native->subtype.Data1,compressedWidth,compressedHeight,uint32_t(hr)));if(FAILED(hr)){log::warn("capture-decode","compressed direct connect failed; retrying the RGB32 compatibility path");SourceOpenDesc retry=desc;retry.legacyCaptureRgbForDiagnostic=true;return configure(retry);}}else if(direct){@@ -475,9 +556,16 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAup.layout.duration=compressedDuration;AVFrame probe{};probe.format=AV_PIX_FMT_NV12;probe.width=int(p.layout.width);probe.height=int(p.layout.height);p.layout.color=pipeline::resolveFrameColor(probe);- p.layout.color.range=pipeline::ColorRange::Full;- p.layout.color.transfer=pipeline::TransferFunction::SRGB;- p.layout.color.preserveSdrCodeValues=true;+ if(codec==CaptureCodec::Mjpeg){+ // JPEG planes are full-range by definition and our MJPEG software+ // decoder emits full-range NV12 (the pre-MPEG colour contract).+ p.layout.color.range=pipeline::ColorRange::Full;+ p.layout.color.transfer=pipeline::TransferFunction::SRGB;+ p.layout.color.preserveSdrCodeValues=true;+ }+ // Compressed video keeps the standard limited-range NV12 contract as+ // its declared fallback; the bitstream's own VUI metadata overrides it+ // per frame through resolveFrameColor().p.layout.color.rangeAssumed=p.layout.color.matrixAssumed=p.layout.color.transferAssumed=true;layoutValid=true;}else{@@ -527,7 +615,7 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAup.workerFrame->format=AV_PIX_FMT_NV12;p.workerFrame->width=int(p.layout.width);p.workerFrame->height=int(p.layout.height);if(av_frame_get_buffer(p.workerFrame,32)<0)return false;p.decodeStop=false;p.decodeThread=std::thread([&p]{p.decodeLoop();});- log::info("capture-decode",std::format("decode worker started queue={} (single decode thread; the parallel pool is a later refinement)",p.compressedQueueLimit));+ log::info("capture-decode",std::format("decode worker started queue={} backend={} (single decode thread; the parallel pool is a later refinement)",p.compressedQueueLimit,p.compressedDecoder.backendName()));}p.configured=true;reconnectDesc_=desc;reconnectInfo_=p.info;reconnectFormat_.clear();@@ -827,12 +915,20 @@ SourceReadStatus CaptureCardSource::read(pipeline::FramePacket& packet,const AVFSourceReadStatus 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* delivered=nullptr;AVFrame* expiredHardware=nullptr;{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.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;+ if(p.pendingIsHardware){+ // D3D12VA surfaces cannot be copied into the preallocated NV12+ // buffer; the read slot owns the cloned frame and the previous one+ // is released after the lock is dropped.+ expiredHardware=p.hardwareRead;p.hardwareRead=p.pendingHardware;p.pendingHardware=nullptr;delivered=p.hardwareRead;+ }else{+ std::swap(p.frame,p.pendingFrame);delivered=p.frame;+ }+ 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);@@ -841,10 +937,20 @@ SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,cif(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;+ if(expiredHardware)av_frame_free(&expiredHardware);+ if(delivered==nullptr)return SourceReadStatus::Error;+ auto colorInfo=p.info.color;+ if(p.compressedPath){+ // Compressed video carries its own VUI metadata; the negotiated layout+ // stays the declared fallback. D3D12VA surfaces report NV12 by+ // contract (the capture ingress contract is 8-bit for this path).+ colorInfo=pipeline::resolveFrameColor(*delivered,p.layout.color);+ if(delivered->format==AV_PIX_FMT_D3D12&&colorInfo.pixelFormat==pipeline::SourcePixelFormat::Unknown)colorInfo.pixelFormat=pipeline::SourcePixelFormat::NV12;+ }+ delivered->pts=static_cast<int64_t>(time*10000000);delivered->duration=duration.isUnknown()?0:duration.to100ns();delivered->time_base={1,10000000};packet={};packet.pts={delivered->pts,10000000};packet.duration=duration;packet.colorInfo=colorInfo;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=delivered;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)));}@@ -855,8 +961,10 @@ void CaptureCardSource::close()noexcept{if(p.decodeThread.joinable()){{std::lock_guard lock(p.mutex);p.decodeStop=true;p.compressedQueue.clear();}p.decodeWake.notify_all();p.decodeThread.join();}if(p.workerFrame)av_frame_free(&p.workerFrame);av_frame_free(&p.frame);av_frame_free(&p.pendingFrame);- if(p.decoded)av_frame_free(&p.decoded);if(p.decoder)avcodec_free_context(&p.decoder);if(p.sws)sws_freeContext(p.sws);- p.sws=nullptr;p.compressedPath=false;p.codec=CaptureCodec::None;p.compressedDecoded=p.compressedErrors=0;+ 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;}+ p.pendingIsHardware=false;p.compressedPath=false;p.codec=CaptureCodec::None;p.compressedDecoded=p.compressedErrors=0;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;}diff --git a/src/source/CaptureCompressedDecoder.cpp b/src/source/CaptureCompressedDecoder.cppnew file mode 100644index 00000000..b4bad166--- /dev/null+++ b/src/source/CaptureCompressedDecoder.cpp@@ -0,0 +1,281 @@+#include "veyra/source/CaptureCompressedDecoder.h"++extern "C" {+#include <libavcodec/avcodec.h>+#include <libavutil/avutil.h>+#include <libavutil/pixdesc.h>+#include <libswscale/swscale.h>+}++#include <cstring>+#include <format>++#include "veyra/Log.h"+#include "veyra/media/FFmpegVideoDecoder.h"++namespace veyra::source {++namespace {++AVCodecID captureAvCodecId(CaptureCodec codec)+{+ switch (codec) {+ case CaptureCodec::Mjpeg: return AV_CODEC_ID_MJPEG;+ case CaptureCodec::H264: return AV_CODEC_ID_H264;+ case CaptureCodec::Hevc: return AV_CODEC_ID_HEVC;+ case CaptureCodec::Av1: return AV_CODEC_ID_AV1;+ case CaptureCodec::Vp9: return AV_CODEC_ID_VP9;+ case CaptureCodec::None: break;+ }+ return AV_CODEC_ID_NONE;+}++// swscale colour coefficients for the bitstream's declared matrix; the same+// coefficients are used for both sides so no hidden matrix conversion is+// introduced, only the range change.+int swsColorspaceOf(AVColorSpace space, unsigned height)+{+ switch (space) {+ case AVCOL_SPC_BT709: return SWS_CS_ITU709;+ case AVCOL_SPC_BT470BG:+ case AVCOL_SPC_SMPTE170M: return SWS_CS_ITU601;+ case AVCOL_SPC_BT2020_NCL:+ case AVCOL_SPC_BT2020_CL: return SWS_CS_BT2020;+ default: break;+ }+ return height > 576 ? SWS_CS_ITU709 : SWS_CS_ITU601;+}++} // namespace++struct CaptureCompressedDecoder::Impl {+ CaptureCodec codec = CaptureCodec::None;+ unsigned width = 0, height = 0;+ media::FFmpegVideoDecoder decoder;+ AVCodecParameters* parameters = nullptr;+ SwsContext* sws = nullptr;+ bool hardwareRequested = false;+ bool hardware = false;+ bool hardwareChecked = false;+ bool waiting = false;+ bool depthWarningLogged = false;+ std::string error;+ uint64_t frames = 0, failures = 0, fallbacks = 0;++ ~Impl() { close(); }++ void close()+ {+ if (sws) { sws_freeContext(sws); sws = nullptr; }+ if (parameters) { avcodec_parameters_free(¶meters); parameters = nullptr; }+ decoder.close();+ codec = CaptureCodec::None;+ width = height = 0;+ hardwareRequested = hardware = hardwareChecked = waiting = false;+ depthWarningLogged = false;+ frames = failures = fallbacks = 0;+ error.clear();+ }++ bool openSoftwareDecoder()+ {+ if (parameters == nullptr) return false;+ return decoder.openSoftware(parameters, 1, 10000000, 1, true);+ }++ bool convertToNv12(const AVFrame& frame, AVFrame* target)+ {+ AVPixelFormat sourceFormat = AVPixelFormat(frame.format);+ if (sourceFormat == AV_PIX_FMT_YUVJ422P) sourceFormat = AV_PIX_FMT_YUV422P;+ else if (sourceFormat == AV_PIX_FMT_YUVJ420P) sourceFormat = AV_PIX_FMT_YUV420P;+ else if (sourceFormat == AV_PIX_FMT_YUVJ444P) sourceFormat = AV_PIX_FMT_YUV444P;+ if (const auto* description = av_pix_fmt_desc_get(sourceFormat)) {+ if (description->comp[0].depth > 8 && !depthWarningLogged) {+ depthWarningLogged = true;+ log::warn("capture-decode", std::format(+ "codec={} bitstream is {}-bit; converting to 8-bit NV12 because the capture ingress contract is 8-bit SDR (a P010/HDR capture contract is not implemented)",+ captureCodecKey(codec), description->comp[0].depth));+ }+ }+ sws = sws_getCachedContext(sws, frame.width, frame.height, sourceFormat,+ int(width), int(height), AV_PIX_FMT_NV12, SWS_BILINEAR, nullptr, nullptr, nullptr);+ if (sws == nullptr) {+ error = "swscale context creation failed";+ ++failures;+ return false;+ }+ const int* coefficients = sws_getCoefficients(swsColorspaceOf(frame.colorspace, unsigned(frame.height)));+ // MJPEG samples are full-range JPEG planes and the declared ingress+ // contract for that path is full-range NV12. Compressed video keeps+ // the bitstream's own range and lands on the standard limited NV12.+ const int sourceFullRange = (codec == CaptureCodec::Mjpeg || frame.color_range == AVCOL_RANGE_JPEG) ? 1 : 0;+ const int targetFullRange = codec == CaptureCodec::Mjpeg ? 1 : 0;+ sws_setColorspaceDetails(sws, coefficients, sourceFullRange, coefficients, targetFullRange, 0, 1 << 16, 1 << 16);+ uint8_t* destination[4] = { target->data[0], target->data[1], nullptr, nullptr };+ const int destinationStride[4] = { target->linesize[0], target->linesize[1], 0, 0 };+ if (sws_scale(sws, frame.data, frame.linesize, 0, frame.height, destination, destinationStride) != frame.height) {+ error = "swscale conversion failed";+ ++failures;+ return false;+ }+ return true;+ }+};++CaptureCompressedDecoder::CaptureCompressedDecoder() : p_(std::make_unique<Impl>()) {}+CaptureCompressedDecoder::~CaptureCompressedDecoder() = default;++bool CaptureCompressedDecoder::open(CaptureCodec codec, unsigned width, unsigned height,+ const uint8_t* extradata, size_t extradataBytes, ID3D12Device* device, ID3D12CommandQueue* queue)+{+ auto& p = *p_;+ p.close();+ if (codec == CaptureCodec::None || !width || !height) return false;+ p.codec = codec;+ p.width = width;+ p.height = height;+ p.parameters = avcodec_parameters_alloc();+ if (p.parameters == nullptr) {+ p.error = "avcodec_parameters_alloc failed";+ return false;+ }+ p.parameters->codec_type = AVMEDIA_TYPE_VIDEO;+ p.parameters->codec_id = captureAvCodecId(codec);+ p.parameters->width = int(width);+ p.parameters->height = int(height);+ if (extradata != nullptr && extradataBytes != 0) {+ p.parameters->extradata = static_cast<uint8_t*>(av_mallocz(extradataBytes + AV_INPUT_BUFFER_PADDING_SIZE));+ if (p.parameters->extradata == nullptr) {+ p.error = "extradata allocation failed";+ p.close();+ return false;+ }+ std::memcpy(p.parameters->extradata, extradata, extradataBytes);+ p.parameters->extradata_size = int(extradataBytes);+ }+ // MJPEG stays software: UVC drivers disagree about 4:2:0 vs 4:2:2 and the+ // hardware path only exists for 4:2:0 on one vendor. Everything else gets+ // the D3D12VA session on the shared Veyra device, with the software+ // decoder as the recorded fallback.+ if (codec != CaptureCodec::Mjpeg && device != nullptr && queue != nullptr) {+ p.hardwareRequested = true;+ if (p.decoder.openD3D12VA(p.parameters, 1, 10000000, device, queue, true)) {+ p.hardware = true;+ } else {+ log::warn("capture-decode", std::format(+ "D3D12VA open failed codec={}; falling back to the software decoder", captureCodecKey(codec)));+ }+ }+ if (!p.hardware && !p.openSoftwareDecoder()) {+ p.error = std::format("no usable decoder for codec={}", captureCodecKey(codec));+ log::error("capture-decode", p.error);+ p.close();+ return false;+ }+ log::info("capture-decode", std::format(+ "compressed decoder opened codec={} {}x{} backend={} extradataBytes={}",+ captureCodecKey(codec), width, height, backendName(), extradataBytes));+ return true;+}++bool CaptureCompressedDecoder::decode(const uint8_t* data, size_t bytes, int64_t pts100ns,+ AVFrame* nv12Target, AVFrame** out, bool& hardware)+{+ auto& p = *p_;+ *out = nullptr;+ hardware = false;+ p.waiting = false;+ if (!p.decoder.opened() || data == nullptr || bytes == 0 || nv12Target == nullptr) {+ p.error = "decode called without an open decoder or a writable target frame";+ ++p.failures;+ return false;+ }+ // Two attempts at most: the second one re-sends the same payload after a+ // hardware decoder whose first frame cannot be imported has been replaced+ // by the software decoder.+ for (int attempt = 0; attempt < 2; ++attempt) {+ AVPacket* packet = av_packet_alloc();+ if (packet == nullptr) {+ p.error = "av_packet_alloc failed";+ ++p.failures;+ return false;+ }+ if (av_new_packet(packet, int(bytes)) < 0) {+ av_packet_free(&packet);+ p.error = "av_new_packet failed";+ ++p.failures;+ return false;+ }+ std::memcpy(packet->data, data, bytes);+ packet->pts = pts100ns;+ packet->dts = pts100ns;+ const bool sent = p.decoder.sendPacket(packet);+ av_packet_free(&packet);+ if (!sent) {+ p.error = "decoder rejected the compressed payload";+ ++p.failures;+ return false;+ }+ const AVFrame* frame = p.decoder.receiveFrame();+ if (frame == nullptr) {+ if (p.decoder.receiveStatus() == media::DecodeReceiveStatus::Error) {+ p.error = "decoder receive failed";+ ++p.failures;+ } else {+ p.error.clear();+ p.waiting = true;+ }+ return false;+ }+ if (p.hardware && !p.hardwareChecked) {+ p.hardwareChecked = true;+ if (!p.decoder.hardwareFrameImportable()) {+ log::warn("capture-decode", std::format(+ "codec={} hardware frame is not an importable NV12/P010 surface; switching to the software decoder",+ captureCodecKey(p.codec)));+ p.decoder.close();+ if (!p.openSoftwareDecoder()) {+ p.error = "software fallback after an unimportable hardware frame failed";+ ++p.failures;+ return false;+ }+ p.hardware = false;+ ++p.fallbacks;+ continue; // re-send this payload on the software decoder+ }+ }+ if (p.hardware) {+ *out = const_cast<AVFrame*>(frame);+ hardware = true;+ ++p.frames;+ p.error.clear();+ return true;+ }+ if (!p.convertToNv12(*frame, nv12Target)) return false;+ *out = nv12Target;+ hardware = false;+ ++p.frames;+ p.error.clear();+ return true;+ }+ p.error = "hardware-to-software fallback did not converge";+ ++p.failures;+ return false;+}++bool CaptureCompressedDecoder::opened() const { return p_->decoder.opened(); }+bool CaptureCompressedDecoder::hardwareActive() const { return p_->hardware; }+bool CaptureCompressedDecoder::waitingForInput() const { return p_->waiting; }+const char* CaptureCompressedDecoder::backendName() const+{+ if (p_->hardware) return "d3d12va";+ if (p_->hardwareRequested) return "software(after d3d12va)";+ return p_->decoder.opened() ? "software" : "none";+}+const std::string& CaptureCompressedDecoder::lastError() const { return p_->error; }+uint64_t CaptureCompressedDecoder::framesDecoded() const { return p_->frames; }+uint64_t CaptureCompressedDecoder::decodeFailures() const { return p_->failures; }+uint64_t CaptureCompressedDecoder::hardwareFallbacks() const { return p_->fallbacks; }+void CaptureCompressedDecoder::close() { p_->close(); }++} // namespace veyra::sourcediff --git a/tests/unit/CaptureCompressedDecoderTests.cpp b/tests/unit/CaptureCompressedDecoderTests.cppnew file mode 100644index 00000000..d26291bf--- /dev/null+++ b/tests/unit/CaptureCompressedDecoderTests.cpp@@ -0,0 +1,202 @@+// MPEG chain stage 3: the compressed-payload decoder must drive real H.264+// elementary streams through both backends (D3D12VA and software) and produce+// frames the capture ingress can consume. The physical capture card on this+// machine has no H.264/HEVC format, so the payloads are the Annex-B form of a+// local H.264 clip; the decoder under test is the exact one the capture worker+// uses, driven packet by packet like a live stream.++#include "veyra/source/CaptureCompressedDecoder.h"+#include "veyra/gfx/D3D12DeviceContext.h"++#include <iostream>+#include <string>+#include <vector>++extern "C" {+#include <libavcodec/avcodec.h>+#include <libavcodec/bsf.h>+#include <libavformat/avformat.h>+#include <libavutil/frame.h>+}++using namespace veyra;++namespace {++struct ElementaryStream {+ int width = 0, height = 0;+ source::CaptureCodec codec = source::CaptureCodec::None;+ std::vector<std::vector<uint8_t>> accessUnits;+};++bool loadAnnexB(const char* path, ElementaryStream& stream, std::string& error)+{+ AVFormatContext* format = nullptr;+ if (avformat_open_input(&format, path, nullptr, nullptr) < 0) {+ error = std::string("cannot open ") + path;+ return false;+ }+ if (avformat_find_stream_info(format, nullptr) < 0) {+ avformat_close_input(&format);+ error = "find_stream_info failed";+ return false;+ }+ const int videoIndex = av_find_best_stream(format, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);+ if (videoIndex < 0) {+ avformat_close_input(&format);+ error = "no video stream";+ return false;+ }+ AVCodecParameters* parameters = format->streams[videoIndex]->codecpar;+ const char* filterName = nullptr;+ if (parameters->codec_id == AV_CODEC_ID_H264) {+ stream.codec = source::CaptureCodec::H264;+ filterName = "h264_mp4toannexb";+ } else if (parameters->codec_id == AV_CODEC_ID_HEVC) {+ stream.codec = source::CaptureCodec::Hevc;+ filterName = "hevc_mp4toannexb";+ } else {+ avformat_close_input(&format);+ error = "test input is not H.264/HEVC";+ return false;+ }+ stream.width = parameters->width;+ stream.height = parameters->height;+ const AVBitStreamFilter* filter = av_bsf_get_by_name(filterName);+ AVBSFContext* bsf = nullptr;+ if (filter == nullptr || av_bsf_alloc(filter, &bsf) < 0) {+ avformat_close_input(&format);+ error = "bitstream filter unavailable";+ return false;+ }+ if (avcodec_parameters_copy(bsf->par_in, parameters) < 0) {+ av_bsf_free(&bsf);+ avformat_close_input(&format);+ error = "parameter copy failed";+ return false;+ }+ bsf->time_base_in = format->streams[videoIndex]->time_base;+ if (av_bsf_init(bsf) < 0) {+ av_bsf_free(&bsf);+ avformat_close_input(&format);+ error = "bitstream filter init failed";+ return false;+ }+ AVPacket* packet = av_packet_alloc();+ AVPacket* filtered = av_packet_alloc();+ while (packet != nullptr && filtered != nullptr && av_read_frame(format, packet) >= 0) {+ if (packet->stream_index == videoIndex && av_bsf_send_packet(bsf, packet) >= 0) {+ while (av_bsf_receive_packet(bsf, filtered) >= 0) {+ stream.accessUnits.emplace_back(filtered->data, filtered->data + filtered->size);+ av_packet_unref(filtered);+ }+ }+ av_packet_unref(packet);+ }+ av_packet_free(&packet);+ av_packet_free(&filtered);+ av_bsf_free(&bsf);+ avformat_close_input(&format);+ if (stream.accessUnits.empty()) {+ error = "no access units extracted";+ return false;+ }+ return true;+}++struct DecodeRun {+ uint64_t frames = 0;+ uint64_t failures = 0;+ bool sawHardwareFrame = false;+ std::string firstError;+};++DecodeRun decodeAll(ElementaryStream& stream, ID3D12Device* device, ID3D12CommandQueue* queue)+{+ DecodeRun run;+ source::CaptureCompressedDecoder decoder;+ if (!decoder.open(stream.codec, unsigned(stream.width), unsigned(stream.height), nullptr, 0, device, queue)) {+ run.firstError = decoder.lastError().empty() ? "decoder open failed" : decoder.lastError();+ ++run.failures;+ return run;+ }+ AVFrame* target = av_frame_alloc();+ target->format = AV_PIX_FMT_NV12;+ target->width = stream.width;+ target->height = stream.height;+ if (av_frame_get_buffer(target, 32) < 0) {+ av_frame_free(&target);+ run.firstError = "target allocation failed";+ ++run.failures;+ return run;+ }+ int64_t pts = 0;+ for (const auto& unit : stream.accessUnits) {+ AVFrame* out = nullptr;+ bool hardware = false;+ const bool produced = decoder.decode(unit.data(), unit.size(), pts, target, &out, hardware);+ if (produced) {+ ++run.frames;+ if (hardware) {+ run.sawHardwareFrame = true;+ if (out == nullptr || out->format != AV_PIX_FMT_D3D12 || out->data[0] == nullptr) {+ run.firstError = "hardware frame is not a D3D12 surface";+ ++run.failures;+ }+ } else if (out == nullptr || out != target) {+ run.firstError = "software frame did not land in the target";+ ++run.failures;+ }+ } else if (!decoder.waitingForInput()) {+ if (run.firstError.empty()) run.firstError = decoder.lastError();+ ++run.failures;+ }+ pts += 333667;+ }+ av_frame_free(&target);+ return run;+}++} // namespace++int main(int argc, char** argv)+{+ const char* path = argc > 1 ? argv[1] : "loop/local/fixed_clips/test_h264_1080p.mp4";+ ElementaryStream stream;+ std::string error;+ if (!loadAnnexB(path, stream, error)) {+ std::cout << "SKIP " << error << " (path=" << path << ")\n";+ return 0; // missing corpus is not a product failure; the gate reports it+ }+ std::cout << "loaded accessUnits=" << stream.accessUnits.size() << " " << stream.width << "x" << stream.height << '\n';++ gfx::D3D12DeviceContext context;+ gfx::DeviceContextDesc desc;+ Status status;+ if (!context.initialize(desc, status)) {+ std::cout << "SKIP no D3D12 device available\n";+ return 0;+ }++ int failures = 0;+ const auto hardware = decodeAll(stream, context.device(), context.directQueue());+ const auto software = decodeAll(stream, nullptr, nullptr);+ std::cout << "hardware frames=" << hardware.frames << " failures=" << hardware.failures+ << " sawD3D12=" << hardware.sawHardwareFrame << " error=" << hardware.firstError << '\n';+ std::cout << "software frames=" << software.frames << " failures=" << software.failures+ << " error=" << software.firstError << '\n';++ const auto check = [&failures](bool pass, const char* name) {+ std::cout << (pass ? "PASS " : "FAIL ") << name << '\n';+ if (!pass) ++failures;+ };+ check(hardware.failures == 0 && hardware.frames > 0, "hardware decode produces frames without errors");+ check(hardware.sawHardwareFrame, "hardware backend returns importable D3D12 frames");+ check(software.failures == 0 && software.frames > 0, "software decode produces frames without errors");+ // B-frame reordering may emit a slightly different count on the software+ // path; the hardware and software backends must stay within one frame.+ const uint64_t difference = hardware.frames > software.frames ? hardware.frames - software.frames : software.frames - hardware.frames;+ check(difference <= 1, "hardware and software frame counts agree");+ std::cout << (failures == 0 ? "ALL PASS" : "FAILURES") << " " << failures << '\n';+ return failures == 0 ? 0 : 1;+}