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

Correct color metadata and capture timing with GPU preview checks

Veyra Goal Agent0dee6c11142a
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 9f26921c..d215f83a 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -422,6 +422,11 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_include_directories(veyra_image_dimension_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})
target_compile_definitions(veyra_image_dimension_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")
target_link_libraries(veyra_image_dimension_tests PRIVATE veyra_engine)
+ add_executable(veyra_preview_geometry_tests tests/integration/PreviewGeometryTests.cpp)
+ target_compile_features(veyra_preview_geometry_tests PRIVATE cxx_std_20)
+ target_include_directories(veyra_preview_geometry_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})
+ target_compile_definitions(veyra_preview_geometry_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+ target_link_libraries(veyra_preview_geometry_tests PRIVATE veyra_engine)
target_compile_features(veyra_repair_parameter_tests PRIVATE cxx_std_20)
target_include_directories(veyra_repair_parameter_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})
target_compile_definitions(veyra_repair_parameter_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")
diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cpp
index b23b0fac..ff86538b 100644
--- a/apps/veyra/ui/AppShell.cpp
+++ b/apps/veyra/ui/AppShell.cpp
@@ -60,7 +60,7 @@ void pointerActivity(){if(!full)return;pointerTick=GetTickCount64();if(!fullCont
std::wstring currentFile,autoInput;bool paused=false,dragging=false,closing=false;int smokeSeconds=0;ULONGLONG startTick=0;int resultCode=0;
std::wstring exportOutput;unsigned exportFrames=0;unsigned cancelAfterMs=0;bool exportHevc=false;veyra::engine::PlayerOptions initialOptions;
std::vector<veyra::engine::SubtitleCue> subtitles;HWND subtitleLabel=nullptr;
-HFONT font=nullptr,emptyFont=nullptr;bool smokeZoom=false;int zoomStep=0;veyra::engine::PlayerSnapshot zoomBefore;bool smokeRollback=false,smokeRollbackFlow=false,smokeUi=false;int uiStep=0;bool smokeSettings=false;int settingsStep=0;bool smokeControls=false;int smokeStep=0;std::wstring smokeSave;
+HFONT font=nullptr,emptyFont=nullptr;bool smokeZoom=false,smokeHover=false;ULONGLONG hoverPostedTick=0;int zoomStep=0;veyra::engine::PlayerSnapshot zoomBefore;bool smokeRollback=false,smokeRollbackFlow=false,smokeUi=false;int uiStep=0;bool smokeSettings=false;int settingsStep=0;bool smokeControls=false;int smokeStep=0;std::wstring smokeSave;
void openFile(const std::wstring&);
void layout();
void updateComparison(){engine.comparison(holdOriginal?1:compareMode,referenceBase,compareSplit);}
@@ -292,7 +292,8 @@ if(smokeStep==4&&elapsed>5200&&GetEnvironmentVariableW(L"VEYRA_TEST_LARGE_IMAGE_
}auto s=engine.snapshot();const auto subtitleText=uiState.subtitles&&!(showDiagnostics&&uiState.mode==veyra::ui::Mode::Professional&&!full)?veyra::engine::subtitleAt(subtitles,s.position):L"";veyra::ui::updateSubtitleOverlay(subtitleLabel,subtitleText,subtitlePixels);
auto text=s.capture?std::format(L"{}\r\n输入 {:.1f} / 已处理 {:.1f}fps | 回调至Present返回p95 {:.1f}ms(非总延迟)| 丢弃 {} | 有效生成 {}",s.status,s.captureFps,s.fps,s.captureAgeP95Ms,s.captureDropped,s.generated):std::format(L"{}\r\n{:.1f} / {:.1f}秒 已处理 {:.1f}fps 提交迟到 {:+.1f}ms 源帧 {} / 有效生成 {}",s.status,s.position,s.duration,s.fps,s.lateMs,s.frames,s.generated);
if(smokeZoom&&startTick&&s.frames>0){const auto elapsed=GetTickCount64()-startTick;
- if(zoomStep==0&&elapsed>1300){if(uiState.mode==veyra::ui::Mode::Daily)switchMode();zoomBefore=s;RECT r{};GetWindowRect(video,&r);SendMessageW(video,WM_MOUSEWHEEL,MAKEWPARAM(0,WHEEL_DELTA*3),MAKELPARAM(r.left+(r.right-r.left)*7/10,r.top+(r.bottom-r.top)/2));zoomStep=std::abs(engine.previewView().zoom-1.728f)<.001f?1:-1;}
+ if(zoomStep==0&&elapsed>1300){if(uiState.mode==veyra::ui::Mode::Daily)switchMode();zoomBefore=s;RECT r{};GetWindowRect(video,&r);const LPARAM point=MAKELPARAM(r.left+(r.right-r.left)*7/10,r.top+(r.bottom-r.top)/2);if(smokeHover){SetFocus(GetDlgItem(hwnd,ModeSwitch));PostMessageW(hwnd,WM_MOUSEWHEEL,MAKEWPARAM(0,WHEEL_DELTA*3),point);hoverPostedTick=GetTickCount64();zoomStep=4;}else{SendMessageW(video,WM_MOUSEWHEEL,MAKEWPARAM(0,WHEEL_DELTA*3),point);zoomStep=std::abs(engine.previewView().zoom-1.728f)<.001f?1:-1;}}
+ if(zoomStep==4&&GetTickCount64()-hoverPostedTick>150){zoomStep=std::abs(engine.previewView().zoom-1.728f)<.001f?1:-1;veyra::log::info("preview-hover-test",std::format("root-message routed={} focusIsButton={}",zoomStep==1,GetFocus()==GetDlgItem(hwnd,ModeSwitch)));}
if(zoomStep==1&&elapsed>3000){const bool same=s.sessionId==zoomBefore.sessionId&&s.applied.revision==zoomBefore.applied.revision&&s.metrics.resolution.output==zoomBefore.metrics.resolution.output&&(!s.image||s.nrEvaluated==zoomBefore.nrEvaluated);SendMessageW(video,WM_MBUTTONDOWN,MK_MBUTTON,MAKELPARAM(100,100));SendMessageW(video,WM_MOUSEMOVE,MK_MBUTTON,MAKELPARAM(130,110));SendMessageW(video,WM_MBUTTONUP,0,MAKELPARAM(130,110));zoomStep=same?2:-1;}
if(zoomStep==2&&elapsed>6200){SendMessageW(video,WM_RBUTTONUP,0,0);bool reset=engine.previewView()==veyra::engine::PreviewView{};switchMode();RECT r{};GetWindowRect(video,&r);SendMessageW(video,WM_MOUSEWHEEL,MAKEWPARAM(0,WHEEL_DELTA),MAKELPARAM(r.left+10,r.top+10));bool daily=engine.previewView()==veyra::engine::PreviewView{};switchMode();zoomStep=reset&&daily?3:-1;veyra::log::info("preview-test",std::format("pass={} unchangedSession={} unchangedRevision={} source={}x{} NR={} presentation-only zoom/pan/reset/daily",zoomStep==3,s.sessionId==zoomBefore.sessionId,s.applied.revision==zoomBefore.applied.revision,s.metrics.resolution.output.width,s.metrics.resolution.output.height,s.nrEvaluated));}
}
@@ -357,7 +358,7 @@ CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED);
std::filesystem::create_directories(std::filesystem::path(VEYRA_PROJECT_ROOT)/"logs");wchar_t logOverride[32768]{};GetEnvironmentVariableW(L"VEYRA_LOG_FILE",logOverride,32768);veyra::Logger::instance().openFile(logOverride[0]?std::wstring(logOverride):(std::filesystem::path(VEYRA_PROJECT_ROOT)/"logs/veyra-app.log").wstring());
initialOptions=veyra::engine::PlayerOptions::from(veyra::ui::defaultSettings());
-int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);for(int i=1;i<argc;++i){const std::wstring arg=argv[i];if(arg==L"--export-worker"&&i+1<argc)workerMapping=reinterpret_cast<HANDLE>(_wcstoui64(argv[++i],nullptr,10));else if(arg==L"--smoke-view"&&i+1<argc)smokeView=argv[++i];else if(arg==L"--smoke-repair-ui")smokeRepair=true;else if(arg==L"--smoke-repair-ui-reject")smokeRepair=smokeRepairReject=true;else if(arg==L"--smoke-zoom")smokeZoom=true;else if(arg==L"--smoke-empty")smokeEmpty=true;else if(arg==L"--smoke-dual")smokeDual=true;else if(arg==L"--smoke-dual-pause"){smokeDual=smokeDualPause=true;}else if(arg==L"--smoke-master-reject")smokeMaster=smokeMasterReject=true;else if(arg==L"--smoke-master")smokeMaster=true;else if(arg==L"--smoke-audio")smokeAudio=true;else if(arg==L"--smoke-job-cancel")smokeJobCancel=true;else if(arg==L"--smoke-job-exit")smokeJobExit=true;else if(arg==L"--smoke-job")smokeJob=true;else if(arg==L"--smoke-dual-export"&&i+1<argc)smokeDualOutput=argv[++i];else if(arg==L"--smoke-seconds"&&i+1<argc)smokeSeconds=std::clamp(_wtoi(argv[++i]),1,240);else if(arg==L"--export-out"&&i+1<argc)exportOutput=argv[++i];else if(arg==L"--max-frames"&&i+1<argc)exportFrames=std::max(1,_wtoi(argv[++i]));else if(arg==L"--cancel-after-ms"&&i+1<argc)cancelAfterMs=std::clamp(_wtoi(argv[++i]),1,240000);else if(arg==L"--hevc")exportHevc=true;else if(arg==L"--smoke-rollback-flow"){smokeRollback=true;smokeRollbackFlow=true;}else if(arg==L"--smoke-rollback")smokeRollback=true;else if(arg==L"--smoke-ui")smokeUi=true;else if(arg==L"--no-fg")initialOptions.fg=false;else if(arg==L"--smoke-settings")smokeSettings=true;else if(arg==L"--smoke-controls")smokeControls=true;else if(arg==L"--smoke-save"&&i+1<argc)smokeSave=argv[++i];else if(arg==L"--native")initialOptions.realtime=false;else if(arg==L"--realtime")initialOptions.realtime=true;else if(arg==L"--fg")initialOptions.fg=true;else if(arg==L"--fg-multiplier"&&i+1<argc){initialOptions.fgMultiplier=std::clamp(_wtoi(argv[++i]),2,4);initialOptions.fg=true;}else if(arg==L"--sr")initialOptions.sr=true;else if(arg==L"--no-nr")initialOptions.nr=false;else if(arg==L"--nr")initialOptions.nr=true;else if(arg==L"--no-sr")initialOptions.sr=false;else autoInput=arg;}LocalFree(argv);
+int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);for(int i=1;i<argc;++i){const std::wstring arg=argv[i];if(arg==L"--export-worker"&&i+1<argc)workerMapping=reinterpret_cast<HANDLE>(_wcstoui64(argv[++i],nullptr,10));else if(arg==L"--smoke-view"&&i+1<argc)smokeView=argv[++i];else if(arg==L"--smoke-repair-ui")smokeRepair=true;else if(arg==L"--smoke-repair-ui-reject")smokeRepair=smokeRepairReject=true;else if(arg==L"--smoke-hover")smokeZoom=smokeHover=true;else if(arg==L"--smoke-zoom")smokeZoom=true;else if(arg==L"--smoke-empty")smokeEmpty=true;else if(arg==L"--smoke-dual")smokeDual=true;else if(arg==L"--smoke-dual-pause"){smokeDual=smokeDualPause=true;}else if(arg==L"--smoke-master-reject")smokeMaster=smokeMasterReject=true;else if(arg==L"--smoke-master")smokeMaster=true;else if(arg==L"--smoke-audio")smokeAudio=true;else if(arg==L"--smoke-job-cancel")smokeJobCancel=true;else if(arg==L"--smoke-job-exit")smokeJobExit=true;else if(arg==L"--smoke-job")smokeJob=true;else if(arg==L"--smoke-dual-export"&&i+1<argc)smokeDualOutput=argv[++i];else if(arg==L"--smoke-seconds"&&i+1<argc)smokeSeconds=std::clamp(_wtoi(argv[++i]),1,240);else if(arg==L"--export-out"&&i+1<argc)exportOutput=argv[++i];else if(arg==L"--max-frames"&&i+1<argc)exportFrames=std::max(1,_wtoi(argv[++i]));else if(arg==L"--cancel-after-ms"&&i+1<argc)cancelAfterMs=std::clamp(_wtoi(argv[++i]),1,240000);else if(arg==L"--hevc")exportHevc=true;else if(arg==L"--smoke-rollback-flow"){smokeRollback=true;smokeRollbackFlow=true;}else if(arg==L"--smoke-rollback")smokeRollback=true;else if(arg==L"--smoke-ui")smokeUi=true;else if(arg==L"--no-fg")initialOptions.fg=false;else if(arg==L"--smoke-settings")smokeSettings=true;else if(arg==L"--smoke-controls")smokeControls=true;else if(arg==L"--smoke-save"&&i+1<argc)smokeSave=argv[++i];else if(arg==L"--native")initialOptions.realtime=false;else if(arg==L"--realtime")initialOptions.realtime=true;else if(arg==L"--fg")initialOptions.fg=true;else if(arg==L"--fg-multiplier"&&i+1<argc){initialOptions.fgMultiplier=std::clamp(_wtoi(argv[++i]),2,4);initialOptions.fg=true;}else if(arg==L"--sr")initialOptions.sr=true;else if(arg==L"--no-nr")initialOptions.nr=false;else if(arg==L"--nr")initialOptions.nr=true;else if(arg==L"--no-sr")initialOptions.sr=false;else autoInput=arg;}LocalFree(argv);
if(workerMapping){const int code=veyra::engine::runExportWorker(workerMapping);CoUninitialize();return code;}
if(smokeSeconds<=0&&exportOutput.empty()){uiPreferences=preferences.load();initialOptions=veyra::engine::PlayerOptions::from(preferences.startup(initialOptions.snapshot()));engine.setVolume(uiPreferences.volume,uiPreferences.muted);uiState.subtitles=uiPreferences.subtitles;subtitlePixels=uiPreferences.subtitleSize;}
engine.requestSettings(initialOptions.snapshot());
diff --git a/docs/REVIEW_COLOR_TIMING_2026-09-08.md b/docs/REVIEW_COLOR_TIMING_2026-09-08.md
new file mode 100644
index 00000000..b3eab34f
--- /dev/null
+++ b/docs/REVIEW_COLOR_TIMING_2026-09-08.md
@@ -0,0 +1,7 @@
+# Cycles 56–61 independent review — 2026-09-08
+
+Reviewer: review_color_timing, new context, read-only. Verdict: scoped PASS; no concrete P0/P1/P2. Tracked fingerprint unchanged: 8c191fc1d8c7ff5fe76e4bf997f68e959d911cba.
+
+Independent preflight 71/71; phase7 logs/delivery/31051b6db0a745188a5cdfa94a7567de/result.json, 41.143 seconds, exit 0, app SHA256 CDD4A16CC66A462A907EFA9EB82C10D22AA58A7B057BAEFDFAF4FB0EC055DC4F. Image matrix image-d302d302d1c844509c11575ed8183faa, 9.461 seconds: nine actual NR Evaluates for 2561×2561, NR-off intersections exact, GPU colors 142/130/189 and red 254,0,0. Actual RTX Feature18 Create 0x1, non-null handle, SEH 0. Preview geometry and timing 14/14 passed in logs/optimization-goal-20260908/review-color-c8f5847affc54ff3b5c3590f431966ed. Hover evidence inspected, not independently rerun.
+
+No normal playback/export readback introduced. Capture duration mailbox synchronization and color metadata precedence reviewed. This is not full Goal approval. Natural-image tile context/seams, direct RGB capture, Q4–Q7, physical capture acceptance, long stability and distribution remain open.
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index d2039a88..efef3457 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1116,3 +1116,21 @@ Build scripts/build.ps1 -Root . -Preset x64-release exit0 (build-save-recovery-f
Read-only Q3 diagnosis: CaptureCardSource packet duration is still default known0; downstream clamp selects83333 ticks incorrectly. Source colorInfo defaults BT709/SD601 but graph reads unresolved AVFrame fields and uses different transfer/matrix defaults. Capture RGB32 also leaves transfer/matrix unspecified and alpha is not guaranteed meaningful. Next Q3 must resolve once, carry actual sample/nominal duration, and retain explicit fallback logging; no Q3 code changes yet.
Independent recheck PASS for implemented Q1a/Q1b/Q2 and cycle55 save recovery; see docs/REVIEW_IMAGES_PREVIEW_2026-09-08.md. Current Phase7/Goal remains in_progress. Prepare local checkpoint only; next close remaining input/preview evidence, then Q3–Q7.
+
+## 2026-09-08 cycles56–61: input/preview evidence, duration and color
+
+Prior turn progress checkpoint3b2806b; clean startup and preflight passed, no STOP. Phase7 optimization remains active.
+
+Two-dimensional2561x2561 image tests:3x3 tiles,NRoff maxError0 including intersections;NRon9 real Evaluates. Final combined image matrix image-97a039da3acf457b91046ba4e93831e1 exit0,9.532s. Earlier image4a730...9.300s before color changes. This verifies coverage/execution; natural-image neural seam/context equivalence still not asserted.
+
+Actual VideoPresenter GPU framebuffer geometry: preview-pixels-96eb8b4f9f9b44668dcfb3cb7a935ede,exit0,<1s/25s watchdog. Fit/zoom/pan/reference/reset pixel assertions passed; fit.png/zoom.png viewed. readPresentedFrameForTest is explicit diagnostics only and has no production callers. Normal playback/video export do not read pixels back. Root-window queued hover/focus test --smoke-hover: hover-0579d93ffdf14b3db425da4da6dfc553 exit0,9s,actual WindowFromPoint route with focus on ModeSwitch button;zoom/pan/reset/session/revision pass. Initial hover-fe036...failed because smoke checked in same timer before posted message could run;log shows actual route immediately afterwards. Fixed smoke's150ms post-message wait, not product logic.
+
+Actual H264 YUV444 video import: video-dimensions-4790082c088444288795325b778e400a,257x513 and1280x2561 each6frames,NR6/NVOF5,app exit0,6s smoke/25s watchdog. Old even and2160-height import guards no longer block these inputs. Does not promise unlimited model/codec dimensions or extend export codec contract.
+
+Q3 duration: CaptureTiming derives duration from complete IMediaSample GetTime;missing stop uses negotiated nominal;unknown stays unknown. FramePacket default duration is unknown. Scheduler rejects zero/invalid duration as measured interval and uses explicit nominal fallback;clamps before integer conversion. Unit14 checks pass:30/60fps,knownzero,missing/invalidsample,huge duration. Initial build-duration.log failed Windows max macro;parenthesized numeric_limits(max) fixed. No physical capture test in this run.
+
+Q3 color: shared ColorMetadata resolver combines declared AVFrame fields with source fallback (per-frame explicit wins,assumed values adapt to decoded format),SD601/HD709,YUV709/RGBsRGB defaults with assumed logs. Source metadata and graph swscale/shader share it;player and video export pass packet colors. Captured RGB32 source reports same resolved metadata. Explicit BT2020 conversion rejected instead of misinterpreted as709;HDR policy unchanged. GPU YUV neutral128 gives142(BT709),130(sRGB),189(linear);SD601red254,0,0 within golden tolerance. File parser defaults now use resolver. Capture RGB still traverses NV12 and remains a Q3 optimization task.
+
+Commands: scripts/build.ps1 -Root . -Preset x64-release exit0 (build-color-capture.log); veyra_live_timing_tests.exe14 PASS (duration-unit.log); run-image-tests.ps1 (275s bound) and explicit25s-bounded PreviewGeometry/app tests. Latest phase7 via scripts/loop-gate.ps1 -Gate phase7 exit0; logs/delivery/f3fbdc84e9c54e718e03a94066df28bc/result.json41.453s appCDD4A16CC66A462A907EFA9EB82C10D22AA58A7B057BAEFDFAF4FB0EC055DC4F. Earlier duration gate e2fee...41.489s was previous app9A5C... . Latest small metadata-format changes covered by gate; GPU color goldens precede those small changes and await independent rerun. No new export integrity checks, publish, runtime change or shutdown. Independent review pending; Q4–Q7 open.
+
+Independent scoped review PASS: docs/REVIEW_COLOR_TIMING_2026-09-08.md; actual GPU tests and phase7 rerun. Q3 direct RGB capture and Q4-Q7 remain.
diff --git a/include/veyra/engine/LivePresentationTiming.h b/include/veyra/engine/LivePresentationTiming.h
index 3ae58906..3a6272bd 100644
--- a/include/veyra/engine/LivePresentationTiming.h
+++ b/include/veyra/engine/LivePresentationTiming.h
@@ -1,8 +1,14 @@
#pragma once
#include <algorithm>
#include <cmath>
+#include "veyra/pipeline/FramePacket.h"
namespace veyra::engine {
+inline int64_t liveSourceInterval100ns(pipeline::Rational duration,double nominalFps){
+ if(!duration.isUnknown()&&duration.den>0&&duration.num>0)return int64_t(std::clamp(static_cast<long double>(duration.num)*10000000.L/duration.den,83333.L,1000000.L)+.5L);
+ if(std::isfinite(nominalFps)&&nominalFps>=10&&nominalFps<=120)return int64_t(std::llround(10000000.0/nominalFps));
+ return 200000; // documented last-resort 50 Hz estimate, never a measured duration
+}
// Live capture never waits on an absolute source PTS. Once B is available,
// display generated(A,B), then B up to half an input interval later. Anchor
// each pair to current host time, not to the first (possibly stale) sample.
diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.h
index 80f03b13..4bf669f0 100644
--- a/include/veyra/engine/VideoPresenter.h
+++ b/include/veyra/engine/VideoPresenter.h
@@ -6,12 +6,15 @@
#include <chrono>
namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }
namespace veyra::pipeline { class EnhanceGraph; }
+namespace veyra::sink { struct RgbaImage; }
namespace veyra::engine {
class VideoPresenter {
public:
bool open(gfx::D3D12DeviceContext&, HWND, pipeline::EnhanceGraph&);
bool present(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,pipeline::EnhanceGraph&,unsigned slot,bool generated,int comparison=0,bool baseReference=false,float split=.5f,pipeline::FrameIdentity identity={},PreviewView view={});
void close();
+ // Explicit integration-test capture only; never called by playback/export.
+ bool readPresentedFrameForTest(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,sink::RgbaImage&);
uint64_t submittedCount() const {return sink_.presentCount();}
diagnostics::GpuSample blitTiming(ID3D12Fence* f){gpuTimer_.collect(f);return gpuTimer_.last().gpu[size_t(diagnostics::GpuStage::Blit)];}
private:
@@ -20,6 +23,7 @@ private:
pipeline::GraphicsPass pass_;
Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> rtvs_;
unsigned inc_=0;
+ unsigned lastBuffer_=0;bool hasPresented_=false;
HWND window_=nullptr;
std::chrono::steady_clock::time_point lastResize_{};
void refresh(ID3D12Device*);
diff --git a/include/veyra/pipeline/ColorMetadata.h b/include/veyra/pipeline/ColorMetadata.h
new file mode 100644
index 00000000..4a83da5b
--- /dev/null
+++ b/include/veyra/pipeline/ColorMetadata.h
@@ -0,0 +1,45 @@
+#pragma once
+#include "veyra/pipeline/FramePacket.h"
+extern "C" {
+#include <libavutil/frame.h>
+#include <libavutil/pixfmt.h>
+#include <libavutil/pixdesc.h>
+}
+namespace veyra::pipeline {
+inline ColorDescription resolveFrameColor(const AVFrame& frame,ColorDescription c={}){
+ switch(frame.format){
+ case AV_PIX_FMT_NV12:c.pixelFormat=SourcePixelFormat::NV12;break;
+ case AV_PIX_FMT_P010:c.pixelFormat=SourcePixelFormat::P010;break;
+ case AV_PIX_FMT_YUV420P:case AV_PIX_FMT_YUVJ420P:c.pixelFormat=SourcePixelFormat::Yuv420P;break;
+ case AV_PIX_FMT_YUYV422:c.pixelFormat=SourcePixelFormat::Yuy2;break;
+ case AV_PIX_FMT_BGRA:case AV_PIX_FMT_BGR0:c.pixelFormat=SourcePixelFormat::Bgra8;break;
+ default:break;
+ }
+ const auto* format=av_pix_fmt_desc_get(AVPixelFormat(frame.format));
+ const bool rgb=format&&(format->flags&AV_PIX_FMT_FLAG_RGB)!=0;
+ switch(frame.color_range){
+ case AVCOL_RANGE_JPEG:c.range=ColorRange::Full;c.rangeAssumed=false;break;
+ case AVCOL_RANGE_MPEG:c.range=ColorRange::Limited;c.rangeAssumed=false;break;
+ default:break;
+ }
+ switch(frame.colorspace){
+ case AVCOL_SPC_BT470BG:case AVCOL_SPC_SMPTE170M:c.matrix=YuvMatrix::BT601;c.matrixAssumed=false;break;
+ case AVCOL_SPC_BT709:c.matrix=YuvMatrix::BT709;c.matrixAssumed=false;break;
+ case AVCOL_SPC_BT2020_NCL:c.matrix=YuvMatrix::BT2020NCL;c.matrixAssumed=false;break;
+ case AVCOL_SPC_BT2020_CL:c.matrix=YuvMatrix::BT2020CL;c.matrixAssumed=false;break;
+ default:break;
+ }
+ switch(frame.color_trc){
+ case AVCOL_TRC_BT709:case AVCOL_TRC_SMPTE170M:c.transfer=TransferFunction::BT709;c.transferAssumed=false;break;
+ case AVCOL_TRC_IEC61966_2_1:c.transfer=TransferFunction::SRGB;c.transferAssumed=false;break;
+ case AVCOL_TRC_LINEAR:c.transfer=TransferFunction::Linear;c.transferAssumed=false;break;
+ case AVCOL_TRC_BT2020_10:case AVCOL_TRC_BT2020_12:c.transfer=TransferFunction::BT2020_10;c.transferAssumed=false;break;
+ default:break;
+ }
+ if(c.range==ColorRange::Unknown||c.rangeAssumed){c.range=(rgb||frame.format==AV_PIX_FMT_YUVJ420P||frame.format==AV_PIX_FMT_YUVJ422P||frame.format==AV_PIX_FMT_YUVJ444P)?ColorRange::Full:ColorRange::Limited;c.rangeAssumed=true;}
+ if(c.matrix==YuvMatrix::Unknown||c.matrixAssumed){c.matrix=rgb||frame.height>=700?YuvMatrix::BT709:YuvMatrix::BT601;c.matrixAssumed=true;}
+ if(c.transfer==TransferFunction::Unknown||c.transferAssumed){c.transfer=rgb?TransferFunction::SRGB:TransferFunction::BT709;c.transferAssumed=true;}
+ return c;
+}
+inline uint32_t transferCode(TransferFunction t){return t==TransferFunction::Linear?0u:t==TransferFunction::BT709?2u:1u;}
+}
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index 92d5b633..c0ff916f 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -48,6 +48,7 @@ class NvOfSession;
}
namespace veyra::pipeline {
+struct ColorDescription;
struct EnhanceGraphDesc {
uint32_t sourceWidth = 0;
@@ -107,7 +108,7 @@ public:
// does not own the demuxer). `reset` marks the first frame of a new
// temporal epoch (open/seek/...): NVOF/FG history is not consumed.
// Returns false on hard failure (run verdict must FAIL).
- bool process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId = 0);
+ bool process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId = 0, const ColorDescription* color = nullptr);
// Nonblocking. The scheduler polls at a GPU-ready/deadline boundary; no
// full image readback and no waits inside the graph's individual passes.
bool resolveGeneration(FrameOutputs& out);
diff --git a/include/veyra/pipeline/FramePacket.h b/include/veyra/pipeline/FramePacket.h
index 3cd42035..bbe2e3cd 100644
--- a/include/veyra/pipeline/FramePacket.h
+++ b/include/veyra/pipeline/FramePacket.h
@@ -150,7 +150,7 @@ struct GpuTextureHandle {
struct FramePacket {
uint64_t sequence = 0; // monotonic per source (0 reserved as invalid)
Rational pts;
- Rational duration;
+ Rational duration=Rational::unknown();
SourceKind sourceKind = SourceKind::Unknown;
FrameFlags flags = 0;
ColorDescription colorInfo;
diff --git a/include/veyra/source/CaptureTiming.h b/include/veyra/source/CaptureTiming.h
new file mode 100644
index 00000000..c66f0724
--- /dev/null
+++ b/include/veyra/source/CaptureTiming.h
@@ -0,0 +1,12 @@
+#pragma once
+#include "veyra/pipeline/FramePacket.h"
+#include <limits>
+namespace veyra::source {
+inline pipeline::Rational captureDuration(int64_t start,int64_t end,bool completeSampleTime,int64_t nominal100ns){
+ if(completeSampleTime&&end>start){
+ const auto delta=uint64_t(end)-uint64_t(start);
+ if(delta<=uint64_t((std::numeric_limits<int64_t>::max)()))return {int64_t(delta),10000000};
+ }
+ return nominal100ns>0?pipeline::Rational{nominal100ns,10000000}:pipeline::Rational::unknown();
+}
+}
diff --git a/loop/EVIDENCE.md b/loop/EVIDENCE.md
index 2d4f41c6..8aa9d009 100644
--- a/loop/EVIDENCE.md
+++ b/loop/EVIDENCE.md
@@ -442,3 +442,21 @@ Build scripts/build.ps1 -Root . -Preset x64-release exit0 (build-save-recovery-f
Read-only Q3 diagnosis: CaptureCardSource packet duration is still default known0; downstream clamp selects83333 ticks incorrectly. Source colorInfo defaults BT709/SD601 but graph reads unresolved AVFrame fields and uses different transfer/matrix defaults. Capture RGB32 also leaves transfer/matrix unspecified and alpha is not guaranteed meaningful. Next Q3 must resolve once, carry actual sample/nominal duration, and retain explicit fallback logging; no Q3 code changes yet.
Independent recheck PASS for implemented Q1a/Q1b/Q2 and cycle55 save recovery; see docs/REVIEW_IMAGES_PREVIEW_2026-09-08.md. Current Phase7/Goal remains in_progress. Prepare local checkpoint only; next close remaining input/preview evidence, then Q3–Q7.
+
+## 2026-09-08 cycles56–61: input/preview evidence, duration and color
+
+Prior turn progress checkpoint3b2806b; clean startup and preflight passed, no STOP. Phase7 optimization remains active.
+
+Two-dimensional2561x2561 image tests:3x3 tiles,NRoff maxError0 including intersections;NRon9 real Evaluates. Final combined image matrix image-97a039da3acf457b91046ba4e93831e1 exit0,9.532s. Earlier image4a730...9.300s before color changes. This verifies coverage/execution; natural-image neural seam/context equivalence still not asserted.
+
+Actual VideoPresenter GPU framebuffer geometry: preview-pixels-96eb8b4f9f9b44668dcfb3cb7a935ede,exit0,<1s/25s watchdog. Fit/zoom/pan/reference/reset pixel assertions passed; fit.png/zoom.png viewed. readPresentedFrameForTest is explicit diagnostics only and has no production callers. Normal playback/video export do not read pixels back. Root-window queued hover/focus test --smoke-hover: hover-0579d93ffdf14b3db425da4da6dfc553 exit0,9s,actual WindowFromPoint route with focus on ModeSwitch button;zoom/pan/reset/session/revision pass. Initial hover-fe036...failed because smoke checked in same timer before posted message could run;log shows actual route immediately afterwards. Fixed smoke's150ms post-message wait, not product logic.
+
+Actual H264 YUV444 video import: video-dimensions-4790082c088444288795325b778e400a,257x513 and1280x2561 each6frames,NR6/NVOF5,app exit0,6s smoke/25s watchdog. Old even and2160-height import guards no longer block these inputs. Does not promise unlimited model/codec dimensions or extend export codec contract.
+
+Q3 duration: CaptureTiming derives duration from complete IMediaSample GetTime;missing stop uses negotiated nominal;unknown stays unknown. FramePacket default duration is unknown. Scheduler rejects zero/invalid duration as measured interval and uses explicit nominal fallback;clamps before integer conversion. Unit14 checks pass:30/60fps,knownzero,missing/invalidsample,huge duration. Initial build-duration.log failed Windows max macro;parenthesized numeric_limits(max) fixed. No physical capture test in this run.
+
+Q3 color: shared ColorMetadata resolver combines declared AVFrame fields with source fallback (per-frame explicit wins,assumed values adapt to decoded format),SD601/HD709,YUV709/RGBsRGB defaults with assumed logs. Source metadata and graph swscale/shader share it;player and video export pass packet colors. Captured RGB32 source reports same resolved metadata. Explicit BT2020 conversion rejected instead of misinterpreted as709;HDR policy unchanged. GPU YUV neutral128 gives142(BT709),130(sRGB),189(linear);SD601red254,0,0 within golden tolerance. File parser defaults now use resolver. Capture RGB still traverses NV12 and remains a Q3 optimization task.
+
+Commands: scripts/build.ps1 -Root . -Preset x64-release exit0 (build-color-capture.log); veyra_live_timing_tests.exe14 PASS (duration-unit.log); run-image-tests.ps1 (275s bound) and explicit25s-bounded PreviewGeometry/app tests. Latest phase7 via scripts/loop-gate.ps1 -Gate phase7 exit0; logs/delivery/f3fbdc84e9c54e718e03a94066df28bc/result.json41.453s appCDD4A16CC66A462A907EFA9EB82C10D22AA58A7B057BAEFDFAF4FB0EC055DC4F. Earlier duration gate e2fee...41.489s was previous app9A5C... . Latest small metadata-format changes covered by gate; GPU color goldens precede those small changes and await independent rerun. No new export integrity checks, publish, runtime change or shutdown. Independent review pending; Q4–Q7 open.
+
+Cycles56-61 independent review_color_timing PASS: docs/REVIEW_COLOR_TIMING_2026-09-08.md. Full Goal still open.
diff --git a/loop/JOURNAL.md b/loop/JOURNAL.md
index a49e5c9b..27b137af 100644
--- a/loop/JOURNAL.md
+++ b/loop/JOURNAL.md
@@ -1398,3 +1398,39 @@ Build scripts/build.ps1 -Root . -Preset x64-release exit0 (build-save-recovery-f
Read-only Q3 diagnosis: CaptureCardSource packet duration is still default known0; downstream clamp selects83333 ticks incorrectly. Source colorInfo defaults BT709/SD601 but graph reads unresolved AVFrame fields and uses different transfer/matrix defaults. Capture RGB32 also leaves transfer/matrix unspecified and alpha is not guaranteed meaningful. Next Q3 must resolve once, carry actual sample/nominal duration, and retain explicit fallback logging; no Q3 code changes yet.
Independent recheck PASS for implemented Q1a/Q1b/Q2 and cycle55 save recovery; see docs/REVIEW_IMAGES_PREVIEW_2026-09-08.md. Current Phase7/Goal remains in_progress. Prepare local checkpoint only; next close remaining input/preview evidence, then Q3–Q7.
+
+## Cycle 56 — two-dimensional image tile intersections
+Previous turn progress: implemented and reviewed Q1b/Q2, checkpoint3b2806b. Clean worktree and no STOP. Extend existing GPU/product tests to2561x2561 (3x3 tiles), including opaque/composited pixels, cancellation and real NR. This tests two-dimensional coverage/overlap arithmetic, not subjective seam equivalence.
+
+## Cycle 57 — actual GPU preview geometry
+Cycle56 matrix image-4a730aad58a64550b0944fb9ad1cd3ea9.300s passed:2561 square3x3 tiles exact NRoff,real NR9 evaluations. Add diagnostic-only last presented backbuffer read for a hidden-window test of actual VideoPresenter: fit black bars, zoom, pan, comparison and identity reset. No runtime readback unless explicitly called by integration test.
+
+## Cycle 58 — real Win32 hover/focus routing
+GPU output geometry passed preview-pixels-96eb8b4f9f9b44668dcfb3cb7a935ede; inspected fit/zoom PNGs. Add smoke variant posting wheel to root message queue while focus is ModeSwitch button and hit point lies over video; run interactive app normally for OS WindowFromPoint routing (not direct video SendMessage). Test no source/settings reset.
+
+## Cycle 59 — Q3 capture duration correctness
+Cycles57/58 close GPU geometry and actual root-queue hover/button-focus evidence; initial hover-fe036... test checked before queued delivery (log proves later route); corrected wait150ms then hover0579...exit0. Capture packet leaves default known0 duration, causing8.333ms clamp. Carry actual sample duration with nominal fallback, default absent packet duration to unknown, and use explicit positive fallback in scheduler. Physical device remains user acceptance.
+
+## Cycle 60 — actual odd/portrait video import
+Duration unit tests14 checks and phase7 pass. Verify source dimensions beyond old2160-height/even guard with real H264 YUV444 clips257x513 and1280x2561, NR on and FG off; each invocation bounded25s. This checks actual decoder/graph support, not a promise of unlimited encoder/model dimensions.
+
+## Cycle 61 — one color metadata resolver
+Actual H264 odd257x513 and portrait1280x2561 imports passed6 NR/5 NVOF each. Unify AVFrame+source fallback resolution and use it for both source packet and graph conversion; preserve declared transfer, make missing YUV709/RGBsRGB explicit, use same range/matrix for swscale and shader. No duplicate color conversion; reject explicitly unsupported2020 matrix instead of treating it as709.
+
+## 2026-09-08 cycles56–61: input/preview evidence, duration and color
+
+Prior turn progress checkpoint3b2806b; clean startup and preflight passed, no STOP. Phase7 optimization remains active.
+
+Two-dimensional2561x2561 image tests:3x3 tiles,NRoff maxError0 including intersections;NRon9 real Evaluates. Final combined image matrix image-97a039da3acf457b91046ba4e93831e1 exit0,9.532s. Earlier image4a730...9.300s before color changes. This verifies coverage/execution; natural-image neural seam/context equivalence still not asserted.
+
+Actual VideoPresenter GPU framebuffer geometry: preview-pixels-96eb8b4f9f9b44668dcfb3cb7a935ede,exit0,<1s/25s watchdog. Fit/zoom/pan/reference/reset pixel assertions passed; fit.png/zoom.png viewed. readPresentedFrameForTest is explicit diagnostics only and has no production callers. Normal playback/video export do not read pixels back. Root-window queued hover/focus test --smoke-hover: hover-0579d93ffdf14b3db425da4da6dfc553 exit0,9s,actual WindowFromPoint route with focus on ModeSwitch button;zoom/pan/reset/session/revision pass. Initial hover-fe036...failed because smoke checked in same timer before posted message could run;log shows actual route immediately afterwards. Fixed smoke's150ms post-message wait, not product logic.
+
+Actual H264 YUV444 video import: video-dimensions-4790082c088444288795325b778e400a,257x513 and1280x2561 each6frames,NR6/NVOF5,app exit0,6s smoke/25s watchdog. Old even and2160-height import guards no longer block these inputs. Does not promise unlimited model/codec dimensions or extend export codec contract.
+
+Q3 duration: CaptureTiming derives duration from complete IMediaSample GetTime;missing stop uses negotiated nominal;unknown stays unknown. FramePacket default duration is unknown. Scheduler rejects zero/invalid duration as measured interval and uses explicit nominal fallback;clamps before integer conversion. Unit14 checks pass:30/60fps,knownzero,missing/invalidsample,huge duration. Initial build-duration.log failed Windows max macro;parenthesized numeric_limits(max) fixed. No physical capture test in this run.
+
+Q3 color: shared ColorMetadata resolver combines declared AVFrame fields with source fallback (per-frame explicit wins,assumed values adapt to decoded format),SD601/HD709,YUV709/RGBsRGB defaults with assumed logs. Source metadata and graph swscale/shader share it;player and video export pass packet colors. Captured RGB32 source reports same resolved metadata. Explicit BT2020 conversion rejected instead of misinterpreted as709;HDR policy unchanged. GPU YUV neutral128 gives142(BT709),130(sRGB),189(linear);SD601red254,0,0 within golden tolerance. File parser defaults now use resolver. Capture RGB still traverses NV12 and remains a Q3 optimization task.
+
+Commands: scripts/build.ps1 -Root . -Preset x64-release exit0 (build-color-capture.log); veyra_live_timing_tests.exe14 PASS (duration-unit.log); run-image-tests.ps1 (275s bound) and explicit25s-bounded PreviewGeometry/app tests. Latest phase7 via scripts/loop-gate.ps1 -Gate phase7 exit0; logs/delivery/f3fbdc84e9c54e718e03a94066df28bc/result.json41.453s appCDD4A16CC66A462A907EFA9EB82C10D22AA58A7B057BAEFDFAF4FB0EC055DC4F. Earlier duration gate e2fee...41.489s was previous app9A5C... . Latest small metadata-format changes covered by gate; GPU color goldens precede those small changes and await independent rerun. No new export integrity checks, publish, runtime change or shutdown. Independent review pending; Q4–Q7 open.
+
+Cycles56-61 review finished: scoped PASS, no project writes by reviewer; checkpoint before next atomic RGB capture change.
diff --git a/loop/STATE.json b/loop/STATE.json
index 9fd382d0..4e9cb0c5 100644
--- a/loop/STATE.json
+++ b/loop/STATE.json
@@ -76,19 +76,19 @@
}
],
"cycle": {
- "completed": 55,
+ "completed": 61,
"maximum": 120,
"sameFailureAttempts": 0,
"maximumSameFailureAttempts": 3,
"noProgressCycles": 0,
"maximumNoProgressCycles": 5
},
- "currentTask": "Q1a/Q1b/Q2 implemented scope independently reviewed PASS; remaining visual/video-boundary evidence open",
+ "currentTask": "Cycles56-61 independently reviewed PASS; proceed to direct RGB capture",
"lastGate": {
"name": "phase7",
"status": "passed",
"exitCode": 0,
- "evidence": "logs/delivery/04815e94852a435a83840eaa45ba0ac1/result.json41.246s final app5E7BC723..."
+ "evidence": "logs/delivery/f3fbdc84e9c54e718e03a94066df28bc/result.json41.453s appCDD4A16..."
},
"lastFailureFingerprint": "",
"failureLedger": [
@@ -107,8 +107,8 @@
"Current USB2 1080p50 physical throughput passed; user perceived latency/audio/actual FG display cadence still need confirmation.",
"Public proprietary runtime distribution rights unresolved; local delivery only."
],
- "nextAction": "Close Q1/Q2 remaining 2D tile/visual-hover/video capability evidence, then Q3 duration/color and Q4-Q7 quality work.",
- "updatedAt": "2026-09-08T09:04:53.6024326Z",
+ "nextAction": "Implement and verify direct RGB capture with opaque BGR0 and shared scene/cadence analysis; then Q4-Q7.",
+ "updatedAt": "2026-09-08T09:32:12.0342288Z",
"deliveryPlan": "docs/ACTIVE_DELIVERY_PLAN.md",
"captureAcceptance": "throughput_short_test_passed_user_latency_audio_pending",
"testInvocationLimitSeconds": 300,
@@ -121,7 +121,9 @@
"Static NR test image-c17dd1e5813b494e9d25344ebd0c93e1 4.4185s exit0; 97x9001 and 257x513 actual NR Create/Evaluate; FG capability/create absent and enable rejected",
"Q1b/Q2 candidate app0409DACD...; final image-55da6...6.400s, zoom-large-nr-0b7a...10s, phase7 bb35fca...41.140s; review pending",
"Cycle55 saved failure/retry recovered: save-recovery-15610...; image988453...6.515s includes multi-band PNG/JPEG; phase7 04815...41.246s",
- "docs/REVIEW_IMAGES_PREVIEW_2026-09-08.md: independent scoped PASS; final phase7 3e2dd555...41.144s; save retry and image matrix independently verified"
+ "docs/REVIEW_IMAGES_PREVIEW_2026-09-08.md: independent scoped PASS; final phase7 3e2dd555...41.144s; save retry and image matrix independently verified",
+ "Cycles56-61:2Dtile,actualGPUpreview,rootqueuehover,odd/tallH264,14 timing checks,4 GPU color goldens; review pending",
+ "docs/REVIEW_COLOR_TIMING_2026-09-08.md: scoped independent PASS; phase7 31051b6d 41.143s, image GPU matrix and timing14 passed"
],
"reviewBaseCommit": "6f0ebaa687e3966d989bf138c86b6882380f20fb",
"localDelivery": "capture_fix_candidate_needs_review",
@@ -259,8 +261,8 @@
"testInvocationLimitSeconds": 300,
"productModified": true,
"consecutiveBlockedGoalTurns": 0,
- "previousGoalTurnClassification": "progress: static FG isolation, long native NR evidence",
- "currentGoalTurnClassification": "progress: >16384 tiled images in app with full-size save, professional viewport zoom, current gates passed",
+ "previousGoalTurnClassification": "progress: checkpoint3b2806b reviewed image/preview and save recovery",
+ "currentGoalTurnClassification": "progress: input/preview evidence, actual odd/tall video, capture duration and shared color correction",
"controlSynchronizationAuthorization": "2026-09-08 user: 确认,给你全部权限; applies to previously proposed exact two-hash synchronization"
}
}
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index e1144d54..beb36170 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -158,11 +158,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
const auto processStart=Clock::now();
const bool injectedReject=transaction&&!options.nr&&GetEnvironmentVariableW(L"VEYRA_TEST_REJECT_NR_DISABLE",nullptr,0)>0;
if(injectedReject)veyra::log::error("settings-test","test-only reject NR-disable transaction before graph process; no driver failure");
- if(injectedReject||!graph.process(frame,pts,reset||pipeline::breaksHistory(pkt.flags),out,pkt.sequence)){
+ if(injectedReject||!graph.process(frame,pts,reset||pipeline::breaksHistory(pkt.flags),out,pkt.sequence,&pkt.colorInfo)){
if(transaction){
ring.drainQueue();out={};presenter.close();graph.shutdown();options=PlayerOptions::from(previous);
gd=previousDesc;
- if(graph.initialize(gd)&&presenter.open(ctx,window,graph)&&graph.createViews()&&graph.process(frame,pts,true,out,pkt.sequence)){
+ if(graph.initialize(gd)&&presenter.open(ctx,window,graph)&&graph.createViews()&&graph.process(frame,pts,true,out,pkt.sequence,&pkt.colorInfo)){
std::lock_guard lock(mutex_);if(desired_.revision==requested.revision)desired_=previous;snapshot_.desired=desired_;snapshot_.rejectedRevision=requested.revision;snapshot_.applying=desired_.revision!=previous.revision;snapshot_.status=L"参数执行失败,已整套回滚";transaction=false;
}else{status(L"参数回滚失败,已停止",true);break;}
}else{status(L"增强执行失败;请查看日志",true);break;}
@@ -172,7 +172,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
reset=false;hasOutput=true;
const auto processDone=Clock::now();processTimes.add(elapsedMs(processStart));
if(isCapture&&!liveTimeline.anchored(out.batch.identity.epoch)){
- const auto duration100ns=pkt.duration.isUnknown()?200000:std::clamp<int64_t>(pkt.duration.to100ns(),83333,1000000);
+ const auto duration100ns=liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps);
+ veyra::log::info("capture-timeline",std::format("interval100ns={} packetDurationKnown={} packetDurationPositive={} nominalFps={} FG={}",duration100ns,!pkt.duration.isUnknown(),pkt.duration.num>0,activeSource->info().averageFps,options.fg));
liveTimeline.reset(out.batch.identity.epoch,out.batch.b100ns,std::chrono::duration_cast<std::chrono::nanoseconds>(processStart.time_since_epoch()).count()/100,options.fg?duration100ns:0);
}
if(!audioStarted&&!isImage&&!isCapture&&frames==0){if(audioPipe.open(path)&&audio.start()){audioPipe.startThread(&audio);audioStarted=true;{std::lock_guard lock(mutex_);snapshot_.audioAvailable=true;}}anchor=Clock::now();anchorMs=pts;}
diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cpp
index 96ee49ae..96036d61 100644
--- a/src/engine/VideoExportJob.cpp
+++ b/src/engine/VideoExportJob.cpp
@@ -79,7 +79,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
progress(0,L"此文件时间戳不均匀,当前CFR导出不支持;已保留partial,未改写音画时间轴");
veyra::log::error("export-timeline",std::format("CFR rejected source={} pts={} expected={}",sourceCount,packet.pts.toDouble(),expectedPts));error=true;break;
}
- pipeline::EnhanceGraph::FrameOutputs out;if(!graph.process(frame,packet.pts.toDouble()*1000,sourceCount==0||pipeline::breaksHistory(packet.flags),out,packet.sequence)){error=true;break;}
+ pipeline::EnhanceGraph::FrameOutputs out;if(!graph.process(frame,packet.pts.toDouble()*1000,sourceCount==0||pipeline::breaksHistory(packet.flags),out,packet.sequence,&packet.colorInfo)){error=true;break;}
const auto readyStart=std::chrono::steady_clock::now();
while(!cancel&&!graph.resolveGeneration(out)){
if(std::chrono::steady_clock::now()-readyStart>std::chrono::seconds(2)){error=true;break;}
diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cpp
index bf3b1479..da0c9690 100644
--- a/src/engine/VideoPresenter.cpp
+++ b/src/engine/VideoPresenter.cpp
@@ -2,6 +2,7 @@
#include "veyra/pipeline/EnhanceGraph.h"
#include "veyra/gfx/D3D12DeviceContext.h"
#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/sink/ImageExportSink.h"
namespace veyra::engine {
bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::EnhanceGraph& graph) {
gpuTimer_.initialize(ctx.device(),ctx.directQueue());window_=window;RECT rc{};GetClientRect(window,&rc);
@@ -55,7 +56,12 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
}
for(auto& b:barriers)std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(2,barriers);
gpuTimer_.mark(list,diagnostics::GpuStage::Blit,true);gpuTimer_.resolve(list);
- if(!ring.submitAndSignal(commandSlot))return false;gpuTimer_.submitted(ring.lastSignaledValue());return sink_.present(st);
+ if(!ring.submitAndSignal(commandSlot))return false;gpuTimer_.submitted(ring.lastSignaledValue());lastBuffer_=sink_.swapChain()->GetCurrentBackBufferIndex();hasPresented_=true;return sink_.present(st);
}
-void VideoPresenter::close(){gpuTimer_.close();rtvs_.Reset();pass_={};sink_.shutdown();}
+bool VideoPresenter::readPresentedFrameForTest(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,sink::RgbaImage& image){
+ if(!hasPresented_||!sink_.swapChain()||!ring.drainQueue())return false;
+ Microsoft::WRL::ComPtr<ID3D12Resource> buffer;
+ return SUCCEEDED(sink_.swapChain()->GetBuffer(lastBuffer_,IID_PPV_ARGS(&buffer)))&&sink::readRgba8(ctx,ring,buffer.Get(),image);
+}
+void VideoPresenter::close(){hasPresented_=false;gpuTimer_.close();rtvs_.Reset();pass_={};sink_.shutdown();}
}
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index a5d00f4d..9706e203 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -1,3 +1,4 @@
+#include "veyra/pipeline/ColorMetadata.h"
// EnhanceGraph implementation - the real GPU chain migrated from
// tools/player_probe main.cpp (R3.2). Ordering constraints preserved from the
// injected-layer era evidence: committed resources and NGX/NVOF objects are
@@ -608,7 +609,7 @@ bool EnhanceGraph::createViews()
// ---------------------------------------------------------------------------
// process: the per-frame chain (verbatim from the probe lambda).
// ---------------------------------------------------------------------------
-bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId)
+bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId, const ColorDescription* color)
{
out = FrameOutputs{};
out.ptsMs = ptsMs;
@@ -617,6 +618,9 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
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="E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E";diagnostic.flowApplied=std::to_string(actualFlowPerf());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;
+ const auto resolved=resolveFrameColor(*frame,color?*color:ColorDescription{});
+ if(resolved.matrix==YuvMatrix::BT2020NCL||resolved.matrix==YuvMatrix::BT2020CL||resolved.transfer==TransferFunction::BT2020_10){veyra::log::error("graph","BT.2020 input is not supported by the BT.601/709 SDR conversion");return false;}
+ if(reset||!realFrameIndex_)veyra::log::info("color",std::format("range={} assumed={} matrix={} assumed={} transfer={} assumed={}",int(resolved.range),resolved.rangeAssumed,int(resolved.matrix),resolved.matrixAssumed,int(resolved.transfer),resolved.transferAssumed));
if (frame->color_trc == AVCOL_TRC_SMPTE2084 || frame->color_trc == AVCOL_TRC_ARIB_STD_B67) {
veyra::log::error("graph", "HDR input is unsupported by the V1 SDR pipeline"); return false;
}
@@ -729,9 +733,9 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
frame->width, frame->height, AV_PIX_FMT_NV12, SWS_POINT,
nullptr, nullptr, nullptr);
if (nv12Ctx_ == nullptr) { veyra::log::error("graph", "sws"); return false; }
- const int colorSpace=(frame->colorspace==AVCOL_SPC_BT470BG||frame->colorspace==AVCOL_SPC_SMPTE170M)?SWS_CS_ITU601:SWS_CS_ITU709;
+ const int colorSpace=resolved.matrix==YuvMatrix::BT601?SWS_CS_ITU601:SWS_CS_ITU709;
const int* coefficients=sws_getCoefficients(colorSpace);
- const int full=frame->color_range==AVCOL_RANGE_JPEG?1:0;
+ const int full=resolved.range==ColorRange::Full?1:0;
if(sws_setColorspaceDetails(nv12Ctx_,coefficients,full,coefficients,full,0,1<<16,1<<16)<0)return false;
// Planar 8-bit YUV already exposes CPU luma for cadence analysis.
// Convert directly into the fenced upload slot instead of writing and
@@ -777,13 +781,13 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
// 2. YUV -> RGBA16F.
tracker_.transition(list, srcRgba_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
if(desc_.rgbInput){
- const float c[8]={uintBits(srcW_),uintBits(srcH_),uintBits(frame->color_trc==AVCOL_TRC_LINEAR?0u:(frame->color_trc==AVCOL_TRC_BT709?2u:1u)),0,0,0,0,0};
+ const float c[8]={uintBits(srcW_),uintBits(srcH_),uintBits(transferCode(resolved.transfer)),0,0,0,0,0};
rgbPass_.bind(list,c,gpuHandleOf(rgbPass_,0).ptr,gpuHandleOf(rgbPass_,1).ptr);
list->Dispatch((srcW_+15)/16,(srcH_+15)/16,1);
}else{
- const float constants[8] = { frame->color_range == AVCOL_RANGE_JPEG ? 0.0f : 1.0f,
- (frame->colorspace == AVCOL_SPC_BT470BG || frame->colorspace == AVCOL_SPC_SMPTE170M) ? 0.0f : 1.0f,
- (frame->color_trc == AVCOL_TRC_BT709 || frame->color_trc == AVCOL_TRC_SMPTE170M) ? 2.0f : 1.0f, 0.0f,
+ const float constants[8] = { resolved.range==ColorRange::Full?0.0f:1.0f,
+ resolved.matrix==YuvMatrix::BT601?0.0f:1.0f,
+ float(transferCode(resolved.transfer)), 0.0f,
uintBits(srcW_), uintBits(srcH_), 0.0f, 0.0f };
yuvPass_.bind(list, constants, gpuHandleOf(yuvPass_, 0).ptr, gpuHandleOf(yuvPass_, 2).ptr);
list->Dispatch((srcW_ + 15) / 16, (srcH_ + 15) / 16, 1);
diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cpp
index a9203dd9..b4563b9b 100644
--- a/src/source/CaptureCardSource.cpp
+++ b/src/source/CaptureCardSource.cpp
@@ -1,4 +1,6 @@
#include "veyra/source/CaptureCardSource.h"
+#include "veyra/source/CaptureTiming.h"
+#include "veyra/pipeline/ColorMetadata.h"
#include "veyra/Log.h"
#include <windows.h>
#include <dshow.h>
@@ -35,6 +37,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
// reference. Holding the producer's sole RGB32 sample starves its allocator.
AVFrame* frame=nullptr;AVFrame* pendingFrame=nullptr;bool pending=false,callbackError=false,configured=false;
double pendingTime=0,lastPts=0,readAgeMs=0;bool pendingDiscontinuity=false;
+ int64_t nominalDuration100ns=0;pipeline::Rational pendingDuration=pipeline::Rational::unknown();
uint64_t received=0,dropped=0,lastDrop=0,sequence=0;
Clock::time_point pendingArrival{},readArrival{},firstArrival{},latestArrival{};
ComPtr<IGraphBuilder> graph;ComPtr<ICaptureGraphBuilder2> builder;ComPtr<IBaseFilter> device,grabFilter,nullFilter,audioFilter;ComPtr<IAMStreamConfig> config;ComPtr<ISampleGrabber> grab;ComPtr<IMediaControl> control;ComPtr<IMediaEvent> events;
@@ -44,6 +47,8 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
ULONG STDMETHODCALLTYPE AddRef()override{return ++refs;}ULONG STDMETHODCALLTYPE Release()override{return --refs;}
HRESULT STDMETHODCALLTYPE SampleCB(double time,IMediaSample* sample)override{
const auto arrival=Clock::now();BYTE* data=nullptr;
+ REFERENCE_TIME sampleStart=0,sampleEnd=0;
+ const bool sampleTime=sample&&sample->GetTime(&sampleStart,&sampleEnd)==S_OK;
const bool valid=sample&&std::isfinite(time)&&SUCCEEDED(sample->GetPointer(&data))&&data&&
sample->GetActualDataLength()>=LONG(size_t(stride)*info.height);
{
@@ -57,6 +62,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
data+size_t(bottomUp?info.height-1-y:y)*stride,stride);
if(pending)++dropped;
pending=true;pendingTime=time;pendingArrival=arrival;
+ pendingDuration=captureDuration(sampleStart,sampleEnd,sampleTime,nominalDuration100ns);
pendingDiscontinuity=sample->IsDiscontinuity()==S_OK;
if(!received)firstArrival=arrival;
++received;latestArrival=arrival;
@@ -90,6 +96,7 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAu
if(connected.formattype!=FORMAT_VideoInfo||connected.cbFormat<sizeof(VIDEOINFOHEADER)){freeType(&connected,false);return false;}auto vi=*reinterpret_cast<VIDEOINFOHEADER*>(connected.pbFormat);freeType(&connected,false);
if(vi.bmiHeader.biWidth<=0||vi.bmiHeader.biWidth>3840||abs(vi.bmiHeader.biHeight)>2160||vi.bmiHeader.biBitCount!=32)return false;
p.info={};p.info.kind=pipeline::SourceKind::CaptureCard;p.info.width=vi.bmiHeader.biWidth;p.info.height=abs(vi.bmiHeader.biHeight);p.info.averageFps=vi.AvgTimePerFrame>0?1e7/vi.AvgTimePerFrame:0;p.info.duration=pipeline::Rational::unknown();p.bottomUp=vi.bmiHeader.biHeight>0;p.stride=p.info.width*4;
+ p.nominalDuration100ns=vi.AvgTimePerFrame;
if(audio>=0){if(!bind(unsigned(audio),true,p.audioFilter)||FAILED(p.graph->AddFilter(p.audioFilter.Get(),L"Capture audio"))||FAILED(p.builder->RenderStream(&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Audio,p.audioFilter.Get(),nullptr,nullptr)))return false;}
if(FAILED(p.graph.As(&p.control))||FAILED(p.graph.As(&p.events))||FAILED(p.grab->SetBufferSamples(FALSE))||FAILED(p.grab->SetCallback(&p,0)))return false;
for(auto** f:{&p.frame,&p.pendingFrame}){
@@ -97,7 +104,7 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAu
(*f)->format=AV_PIX_FMT_BGRA;(*f)->width=p.info.width;(*f)->height=p.info.height;(*f)->color_range=AVCOL_RANGE_JPEG;
if(av_frame_get_buffer(*f,32)<0)return false;
}
- p.configured=true;
+ p.info.color=pipeline::resolveFrameColor(*p.frame);p.configured=true;
// Log the upstream type after DirectShow has finished negotiation. The
// RGB32 output's nominal FPS alone is not proof of actual callback cadence.
AM_MEDIA_TYPE* actual=nullptr;const auto formatHr=p.config->GetFormat(&actual);
@@ -118,12 +125,13 @@ CaptureMetrics CaptureCardSource::metrics()const{
}
SourceReadStatus CaptureCardSource::read(pipeline::FramePacket& packet,const AVFrame** frame){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){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;
+ double time=0;uint32_t flags=0;uint64_t sequence=0;pipeline::Rational duration;
{
std::unique_lock lock(p.mutex);p.wake.wait_for(lock,std::chrono::milliseconds(30),[&]{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;
+ duration=p.pendingDuration;
p.readAgeMs=std::chrono::duration<double,std::milli>(Impl::Clock::now()-p.readArrival).count();
if(!p.sequence)flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Open);
if(p.dropped!=p.lastDrop)flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Drop);
@@ -131,7 +139,7 @@ SourceReadStatus CaptureCardSource::read(pipeline::FramePacket& packet,const AVF
if(p.pendingDiscontinuity||(p.sequence&&(time<=p.lastPts||time-p.lastPts>maxGap)))flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Discontinuity);
p.lastDrop=p.dropped;p.lastPts=time;sequence=++p.sequence;
}
- p.frame->pts=static_cast<int64_t>(time*10000000);packet={};packet.pts={p.frame->pts,10000000};packet.sourceKind=pipeline::SourceKind::CaptureCard;packet.sequence=sequence;packet.flags=flags;packet.sourceEpoch=1;*frame=p.frame;p.lastFrame=Impl::Clock::now();return SourceReadStatus::Frame;
+ 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;*frame=p.frame;p.lastFrame=Impl::Clock::now();return SourceReadStatus::Frame;
}
void CaptureCardSource::close()noexcept{
auto& p=*p_;if(p.control)p.control->Stop();if(p.grab)p.grab->SetCallback(nullptr,0);
diff --git a/src/source/MediaFileSource.cpp b/src/source/MediaFileSource.cpp
index 29143c51..25dd1bef 100644
--- a/src/source/MediaFileSource.cpp
+++ b/src/source/MediaFileSource.cpp
@@ -1,4 +1,5 @@
#include "veyra/source/MediaFileSource.h"
+#include "veyra/pipeline/ColorMetadata.h"
#include <climits>
#include <cmath>
@@ -68,26 +69,12 @@ pipeline::ColorDescription MediaFileSource::parseColor(const AVCodecParameters*
default: cd.primaries = pipeline::ColorPrimaries::Unknown; break;
}
- // Documented, logged defaults when the container is silent (Playbook 9):
- // SD -> BT.601, HD SDR -> BT.709; flagged assumed so the UI can show it.
- if (cd.matrix == pipeline::YuvMatrix::Unknown) {
- const bool hd = info_.height >= 700;
- cd.matrix = hd ? pipeline::YuvMatrix::BT709 : pipeline::YuvMatrix::BT601;
- cd.matrixAssumed = true;
- }
- if (cd.range == pipeline::ColorRange::Unknown) {
- cd.range = pipeline::ColorRange::Limited;
- cd.rangeAssumed = true;
- }
- if (cd.transfer == pipeline::TransferFunction::Unknown) {
- cd.transfer = pipeline::TransferFunction::BT709;
- cd.transferAssumed = true;
- }
if (cd.primaries == pipeline::ColorPrimaries::Unknown) {
cd.primaries = pipeline::ColorPrimaries::BT709;
cd.primariesAssumed = true;
}
- return cd;
+ AVFrame metadata{};metadata.format=params->format;metadata.height=info_.height;metadata.color_range=params->color_range;metadata.colorspace=params->color_space;metadata.color_trc=params->color_trc;
+ return pipeline::resolveFrameColor(metadata,cd);
}
bool MediaFileSource::open(const SourceOpenDesc& desc)
@@ -207,7 +194,7 @@ SourceReadStatus MediaFileSource::read(pipeline::FramePacket& out, const AVFrame
out.duration = pipeline::Rational::unknown();
}
out.sourceKind = pipeline::SourceKind::File;
- out.colorInfo = info_.color;
+ out.colorInfo = pipeline::resolveFrameColor(*frame,info_.color);
out.sourceEpoch = epoch_;
uint32_t flags = 0;
diff --git a/tests/integration/ImageDimensionTests.cpp b/tests/integration/ImageDimensionTests.cpp
index 14bfefaf..680fcebc 100644
--- a/tests/integration/ImageDimensionTests.cpp
+++ b/tests/integration/ImageDimensionTests.cpp
@@ -4,6 +4,7 @@
#include "veyra/sink/ImageExportSink.h"
#include "veyra/engine/EnhancementSettings.h"
#include "veyra/engine/TiledImageProcessor.h"
+#include "veyra/pipeline/ColorMetadata.h"
#include <filesystem>
#include <iostream>
#include <cmath>
@@ -80,6 +81,26 @@ bool codecBands(const std::filesystem::path& directory){
}
std::cout<<"IMAGE_CODEC_BANDS pass="<<ok<<std::endl;return ok;
}
+bool colorFallback(){
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status st;gfx::DeviceContextDesc device;
+ if(!ctx.initialize(device,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,st))return false;
+ pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc gd;gd.sourceWidth=gd.sourceHeight=gd.workWidth=gd.workHeight=64;gd.stillImage=gd.noFeatures=true;gd.enableNr=gd.enableFg=false;
+ if(!graph.initialize(gd)||!graph.createViews())return false;
+ AVFrame* f=av_frame_alloc();f->format=AV_PIX_FMT_YUV420P;f->width=f->height=64;
+ if(av_frame_get_buffer(f,32)<0){av_frame_free(&f);return false;}
+ bool ok=true;uint64_t sequence=0;
+ auto test=[&](int y,int u,int v,AVColorTransferCharacteristic trc,int expectedR,int expectedG,int expectedB){
+ f->color_trc=trc;f->color_range=AVCOL_RANGE_UNSPECIFIED;f->colorspace=AVCOL_SPC_UNSPECIFIED;
+ for(int row=0;row<64;++row)memset(f->data[0]+row*f->linesize[0],y,64);
+ for(int row=0;row<32;++row){memset(f->data[1]+row*f->linesize[1],u,32);memset(f->data[2]+row*f->linesize[2],v,32);}
+ auto metadata=pipeline::resolveFrameColor(*f);pipeline::EnhanceGraph::FrameOutputs out;sink::RgbaImage result;
+ bool pass=graph.process(f,0,true,out,++sequence,&metadata)&&sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),result);
+ if(pass){auto* p=result.pixels.data()+(32*64+32)*4;pass=std::abs(int(p[0])-expectedR)<=2&&std::abs(int(p[1])-expectedG)<=2&&std::abs(int(p[2])-expectedB)<=2;std::cout<<"COLOR_PIXEL transfer="<<trc<<" rgb="<<int(p[0])<<','<<int(p[1])<<','<<int(p[2])<<" pass="<<pass<<std::endl;}
+ out={};return pass;
+ };
+ ok=test(128,128,128,AVCOL_TRC_UNSPECIFIED,142,142,142)&&test(128,128,128,AVCOL_TRC_IEC61966_2_1,130,130,130)&&test(128,128,128,AVCOL_TRC_LINEAR,189,189,189)&&test(81,90,240,AVCOL_TRC_UNSPECIFIED,255,0,0);
+ ring.drainQueue();graph.shutdown();av_frame_free(&f);ring.shutdown();ctx.shutdown();return ok;
+}
int wmain(int argc,wchar_t** argv){
if(argc!=2)return 2;CoInitializeEx(nullptr,COINIT_MULTITHREADED);std::filesystem::path directory(argv[1]);std::filesystem::create_directories(directory);
bool ok=true;for(auto e:{pipeline::Extent{1,1},{257,513},{97,9001},{4097,257},{257,4097}}){if(!run(e.width,e.height,false,directory)){ok=false;break;}}
@@ -88,6 +109,9 @@ int wmain(int argc,wchar_t** argv){
if(ok)ok=tiled(17001,17,false,directory);
if(ok)ok=tiled(17,17001,false,directory);
if(ok)ok=tiled(97,17001,true,directory);
+ if(ok)ok=tiled(2561,2561,false,directory);
+ if(ok)ok=tiled(2561,2561,true,directory);
if(ok)ok=codecBands(directory);
+ if(ok)ok=colorFallback();
CoUninitialize();return ok?0:1;
}
diff --git a/tests/integration/PreviewGeometryTests.cpp b/tests/integration/PreviewGeometryTests.cpp
new file mode 100644
index 00000000..8e695695
--- /dev/null
+++ b/tests/integration/PreviewGeometryTests.cpp
@@ -0,0 +1,41 @@
+#include "veyra/engine/VideoPresenter.h"
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/sink/ImageExportSink.h"
+#include <filesystem>
+#include <iostream>
+extern "C" {
+#include <libavutil/frame.h>
+#include <libavutil/pixfmt.h>
+}
+using namespace veyra;
+int wmain(int argc,wchar_t** argv){
+ if(argc!=2)return 2;CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ const auto dir=std::filesystem::path(argv[1]);std::filesystem::create_directories(dir);
+ HWND window=CreateWindowExW(0,L"STATIC",L"Preview geometry test",WS_POPUP,0,0,320,240,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
+ if(!window)return 1;
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status st;gfx::DeviceContextDesc device;
+ if(!ctx.initialize(device,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,st))return 1;
+ pipeline::EnhanceGraph graph(ctx,ring);engine::VideoPresenter presenter;
+ pipeline::EnhanceGraphDesc desc;desc.sourceWidth=desc.workWidth=64;desc.sourceHeight=desc.workHeight=32;desc.rgbInput=desc.stillImage=desc.noFeatures=true;desc.enableNr=desc.enableFg=false;
+ bool ok=graph.initialize(desc)&&presenter.open(ctx,window,graph)&&graph.createViews();
+ AVFrame* f=av_frame_alloc();f->format=AV_PIX_FMT_RGBA;f->width=64;f->height=32;f->color_trc=AVCOL_TRC_IEC61966_2_1;
+ ok=ok&&av_frame_get_buffer(f,32)>=0;
+ if(ok)for(int y=0;y<32;++y)for(int x=0;x<64;++x){auto* p=f->data[0]+y*f->linesize[0]+x*4;bool right=x>=32,bottom=y>=16;p[0]=!right||bottom?255:0;p[1]=right?255:0;p[2]=bottom?255:0;p[3]=255;}
+ pipeline::EnhanceGraph::FrameOutputs out;ok=ok&&graph.process(f,0,true,out,1);
+ struct Sample {int x,y,r,g,b;};
+ auto test=[&](const char* name,engine::PreviewView view,int comparison,std::initializer_list<Sample> samples){
+ sink::RgbaImage image;bool pass=presenter.present(ctx,ring,graph,out.videoSlot,false,comparison,false,.5f,{},view)&&presenter.readPresentedFrameForTest(ctx,ring,image);
+ pass=pass&&image.width==320&&image.height==240;
+ if(pass)for(auto s:samples){auto* p=image.pixels.data()+(s.y*image.width+s.x)*4;pass=pass&&std::abs(int(p[0])-s.r)<=2&&std::abs(int(p[1])-s.g)<=2&&std::abs(int(p[2])-s.b)<=2;}
+ if(pass)pass=sink::saveImage((dir/(std::string(name)+".png")).wstring(),image);
+ std::cout<<"PREVIEW_GEOMETRY "<<name<<" pass="<<pass<<std::endl;return pass;
+ };
+ if(ok)ok=test("fit",{},0,{{160,10,0,0,0},{40,80,255,0,0},{280,80,0,255,0},{40,160,255,0,255},{280,160,255,255,255}});
+ if(ok)ok=test("zoom",{2,.5f,.5f},0,{{40,10,255,0,0},{280,10,0,255,0},{40,230,255,0,255}});
+ if(ok)ok=test("pan",{2,.25f,.5f},0,{{280,60,255,0,0},{280,200,255,0,255}});
+ if(ok)ok=test("reference",{2,.5f,.5f},1,{{40,10,255,0,0},{280,10,0,255,0}});
+ if(ok)ok=test("reset",{},0,{{160,10,0,0,0},{280,80,0,255,0}});
+ ring.drainQueue();out={};presenter.close();graph.shutdown();av_frame_free(&f);ring.shutdown();ctx.shutdown();DestroyWindow(window);CoUninitialize();return ok?0:1;
+}
diff --git a/tests/unit/LivePresentationTimingTests.cpp b/tests/unit/LivePresentationTimingTests.cpp
index 54b52a4e..b61f0e51 100644
--- a/tests/unit/LivePresentationTimingTests.cpp
+++ b/tests/unit/LivePresentationTimingTests.cpp
@@ -1,4 +1,5 @@
#include "veyra/engine/LivePresentationTiming.h"
+#include "veyra/source/CaptureTiming.h"
#include <cmath>
#include <limits>
#include <cstdio>
@@ -6,6 +7,14 @@ int main(){
using veyra::engine::livePairHoldMs;
int failed=0;
auto check=[&](bool ok,const char* label){printf("%s %s\n",ok?"PASS":"FAIL",label);if(!ok)++failed;};
+ using veyra::source::captureDuration;using veyra::engine::liveSourceInterval100ns;
+ check(veyra::pipeline::FramePacket{}.duration.isUnknown(),"unset packet duration is unknown, not known zero");
+ check(captureDuration(100,166767,true,333333).to100ns()==166667,"sample duration wins over nominal");
+ check(captureDuration(100,100,false,333333).to100ns()==333333,"missing sample stop uses nominal30fps");
+ check(captureDuration(100,90,true,0).isUnknown(),"invalid sample and absent nominal stay unknown");
+ check(liveSourceInterval100ns({0,1},60)==166667,"known zero cannot turn60fps into120fps");
+ check(liveSourceInterval100ns(captureDuration(0,0,false,333333),60)==333333,"30fps packet retained by scheduler");
+ check(liveSourceInterval100ns({INT64_MAX,1},60)==1000000,"huge duration clamps before integer conversion");
check(livePairHoldMs(false,1822.09,22.64)==0,"no-FG never waits on stale source PTS");
check(livePairHoldMs(false,1e12,0)==0,"no-FG absolute PTS cannot add latency");
check(livePairHoldMs(true,100,90)==10,"50fps FG pair half interval");