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

test(5a): define letterbox content-loss and actual ROI diagnostics

Veyra Goal Agent0a5daef5e7dc
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 7c49d1e0..7aac312d 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1059,6 +1059,10 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionT
target_compile_features(veyra_nr_auto_pool_experiment PRIVATE cxx_std_20)
target_compile_options(veyra_nr_auto_pool_experiment PRIVATE /utf-8)
target_link_libraries(veyra_nr_auto_pool_experiment PRIVATE veyra_engine)
+ add_executable(veyra_nr_letterbox_experiment tests/perf/NrLetterboxExperiment.cpp)
+ target_compile_features(veyra_nr_letterbox_experiment PRIVATE cxx_std_20)
+ target_compile_options(veyra_nr_letterbox_experiment PRIVATE /utf-8)
+ target_link_libraries(veyra_nr_letterbox_experiment PRIVATE veyra_engine)
add_executable(veyra_nr_queue_migration_experiment tests/perf/NrQueueMigrationExperiment.cpp)
target_compile_features(veyra_nr_queue_migration_experiment PRIVATE cxx_std_20)
target_compile_options(veyra_nr_queue_migration_experiment PRIVATE /utf-8)
diff --git a/docs/PERF_5A_LETTERBOX_2026-10-05.md b/docs/PERF_5A_LETTERBOX_2026-10-05.md
new file mode 100644
index 00000000..18506b0b
--- /dev/null
+++ b/docs/PERF_5A_LETTERBOX_2026-10-05.md
@@ -0,0 +1,12 @@
+# 5a:黑边候选、画面合同与反例(2026-10-05)
+
+只做普通负载和功能/画质实验,不做压力测试。开工存档`checkpoint/perf-nr-5a-letterbox-before-20261004`,源码`54fd585`。没有真实M3电影/M4主机采集,作者生成的图像/片段必须单独标记,不冒充电影或主机验收。
+
+原方案“裁掉后直接填黑”不能原样进产品:已确认黑边后才出现的烧录字幕、台标和提示也属于用户画面。60帧确认/一秒滞回会让这类内容在发现前被抹掉;输出至少必须保留当前源在ROI外的像素。黑场和淡入不改变已确认范围,但恢复全画幅时不能沿用裁剪范围误伤新画面。
+
+先用独立诊断验证两个问题:
+
+1. 保守标准比例检测与确认/滞回,在全画幅、纯黑、淡入、窄暗边、标准黑边、后出现的字幕和比例切换上,是否会误伤;把预测区域与作者定义的实际有效内容逐帧核对。CPU参考只用于诊断,不能将全帧CPU扫描接入正常播放。
+2. 实际ROI尺寸创建的现有NR图与完整尺寸NR相比,比较完整RGBA、有效区域PSNR/SSIM、边界/字幕原图和真实GPU增强区间。ROI外保留当前源,图内指引尺寸与像素单位遵循现有合同;这是独立画质/成本实验,不宣称生产GPU裁剪已接入。
+
+若ROI尺寸改变产生不接受的边缘/时域变化,或检测无法满足原方案“不误伤”,记录反例、归档并不接默认黑边开关。只有ROI合同与正确性有证据才推进异步GPU小统计、生产资源重建、SR/光流/保护映射和UI;不能用理论25%像素减少作为提速结果。
diff --git a/scripts/perf/nr-letterbox-detection.py b/scripts/perf/nr-letterbox-detection.py
new file mode 100644
index 00000000..a1ec4cc9
--- /dev/null
+++ b/scripts/perf/nr-letterbox-detection.py
@@ -0,0 +1,62 @@
+"""CPU reference of the proposed thresholds/confirmation, diagnostic only.
+Run after GPU timing tests; authored truth exposes false crops and late text.
+"""
+from pathlib import Path
+import json,sys
+import numpy as np
+from PIL import Image
+BASE=Path('E:/项目/Veyra');TASK='perf-nr-20261004';label=sys.argv[1]
+out=BASE/'tests'/TASK/label;out.mkdir(parents=True,exist_ok=False)
+W,H=1920,1080
+# sRGB -> linear; exact authored pixels, no codec/tone-mapping ambiguity.
+table=np.arange(256,dtype=np.float64)/255
+table=np.where(table<=.04045,table/12.92,((table+.055)/1.055)**2.4)
+rects=[(0,138,1920,804),(0,132,1920,816),(0,104,1920,872),(0,22,1920,1036),(240,0,1440,1080),(150,0,1620,1080)]
+def detect(a):
+ rgb=table[a[:,:,:3]];peak=rgb.max(axis=2)
+ if float(np.mean(peak>.03))<.1:return 'dark'
+ for x,y,w,h in rects:
+ strips=[]
+ if y:strips.extend((peak[:y,:],peak[y+h:,:]))
+ if x:strips.extend((peak[:,:x],peak[:,x+w:]))
+ if all(float(s.max())<.015 and float(s.var())<.00001 for s in strips):return (x,y,w,h)
+ return None
+class Confirm:
+ def __init__(self):self.active=None;self.candidate=None;self.frames=0
+ def update(self,value):
+ if value=='dark':return self.active
+ if value!=self.candidate:self.candidate=value;self.frames=0
+ self.frames+=1
+ if self.frames>=60:self.active=value
+ return self.active
+def canvas(margins=0):
+ a=np.full((H,W,4),255,dtype=np.uint8);a[:,:,:3]=margins
+ a[138:942,:,:3]=110
+ return a
+rows=[]
+for name,a,truth,initial in [('standard239',canvas(),(0,138,W,804),False),
+ ('full-frame-dark-content-at-edges',canvas(18),(0,0,W,H),False),
+ ('black-fade-holds-confirmed-roi',np.zeros((H,W,4),dtype=np.uint8),(0,138,W,804),True),
+ ('late-burned-in-subtitle',canvas(),(0,0,W,H),True)]:
+ if name=='late-burned-in-subtitle':a[992:1014,840:960,:3]=235
+ a[:,:,3]=255
+ candidate=detect(a);state=Confirm()
+ if initial:
+ for _ in range(60):state.update((0,138,W,804))
+ frames=[state.update(candidate) for _ in range(75)]
+ false=[i for i,r in enumerate(frames) if r is not None and tuple(r)!=tuple(truth)]
+ removed=[]
+ for r in frames:
+ if r is None:removed.append(0);continue
+ x,y,w,h=r;mask=np.ones((H,W),dtype=bool);mask[y:y+h,x:x+w]=False
+ removed.append(int(np.count_nonzero(np.any(a[:,:,:3]!=0,axis=2)&mask)))
+ row={'case':name,'truth':truth,'detected':candidate,'falseCropFrames':false,
+ 'maxNonblackPixelsErasedByFillBlack':max(removed),'observations':frames,'authored':True}
+ rows.append(row);Image.fromarray(a).save(out/(name+'.png'))
+assert not rows[0]['falseCropFrames'] and not rows[2]['falseCropFrames']
+assert rows[1]['falseCropFrames'] and rows[1]['maxNonblackPixelsErasedByFillBlack']>500000
+assert len(rows[3]['falseCropFrames'])==59 and rows[3]['maxNonblackPixelsErasedByFillBlack']==2640
+(out/'results.json').write_text(json.dumps({'cases':rows,'linearThreshold':.015,'confirmationFrames':60,
+ 'scope':'CPU diagnostic reference, no normal-playback readback/scanning installed',
+ 'verdict':'Proposed fill-black and approximate-black detection have concrete content-loss counterexamples'},ensure_ascii=False,indent=2),encoding='utf-8')
+print('LETTERBOX_DETECTION_COUNTEREXAMPLES',json.dumps([{k:r[k] for k in ('case','detected','falseCropFrames','maxNonblackPixelsErasedByFillBlack')} for r in rows],ensure_ascii=False))
diff --git a/scripts/perf/nr-letterbox-native.py b/scripts/perf/nr-letterbox-native.py
new file mode 100644
index 00000000..163c5fbb
--- /dev/null
+++ b/scripts/perf/nr-letterbox-native.py
@@ -0,0 +1,54 @@
+"""Actual-size crop diagnostic, ordinary M1 pixels; no product ROI claim."""
+from pathlib import Path
+import csv,importlib.util,json,os,shutil,statistics,subprocess,sys,time
+import numpy as np
+from PIL import Image
+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='perf-nr-20261004'
+spec=importlib.util.spec_from_file_location('matrix',ROOT/'scripts/perf/nr-matrix.py');matrix=importlib.util.module_from_spec(spec);spec.loader.exec_module(matrix)
+variant,label=sys.argv[1:3];repeats=int(sys.argv[3]) if len(sys.argv)>3 else 2;assert 1<=repeats<=3
+matrix.assert_gpu_tests_idle();folder=BASE/'logs'/TASK/(label+'-summary');folder.mkdir(parents=True,exist_ok=False)
+app=matrix.stage(variant,label);exe=app/'veyra_nr_letterbox_experiment.exe';shutil.copy2(BASE/'build'/TASK/variant/exe.name,exe)
+payload={p.relative_to(app).as_posix():matrix.digest(p) for p in app.rglob('*') if p.is_file() and p.suffix.lower() in ('.exe','.dll','.qml')}
+(folder/'artifacts.json').write_text(json.dumps(payload,ensure_ascii=False,indent=2),encoding='utf-8')
+results=[];references={}
+for shape in ('239','43'):
+ for repeat in range(1,repeats+1):
+ for mode in ('none','full','crop'):
+ name=f'{label}-{shape}-{mode}-r{repeat}';out=BASE/'tests'/TASK/name;out.mkdir(parents=True,exist_ok=False)
+ tmp=BASE/'tmp'/TASK/name;tmp.mkdir(parents=True,exist_ok=False)
+ env={k:v for k,v in os.environ.items() if not k.upper().startswith(('VEYRA_','QT_QUICK_BACKEND','QSG_RHI_BACKEND'))};env.update(TEMP=str(tmp),TMP=str(tmp),VEYRA_VERBOSE_FRAME_LOGS='1')
+ matrix.assert_gpu_tests_idle();print('START',name,flush=True);start=time.monotonic()
+ with (out/'console.log').open('x',encoding='utf-8') as stream:
+ proc=subprocess.run([str(exe),str(matrix.SOURCES['M1']),str(out),mode,shape],cwd=app,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=250)
+ console=(out/'console.log').read_text(encoding='utf-8',errors='replace');log=(out/'engine.log').read_text(encoding='utf-8',errors='replace')
+ passed=proc.returncode==0 and 'LETTERBOX_RESULT pass=1 frames=40 debugErrors=0 deviceRemoved=0' in console and '[ERROR]' not in log
+ row={'name':name,'shape':shape,'mode':mode,'repeat':repeat,'passed':passed,'exitCode':proc.returncode,'wallSeconds':time.monotonic()-start,
+ 'exeSha256':matrix.digest(exe),'sourceSha256':matrix.digest(matrix.SOURCES['M1']),'sourceCommit':subprocess.check_output(['git','-C',str(ROOT),'rev-parse','HEAD']).decode().strip(),
+ 'stimulus':'Authored central crop of ordinary M1, black padding and late burned-in text. Not real letterboxed film or console capture.'}
+ results.append(row);(folder/'completed.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf-8');assert passed,row
+ with (out/'frames.csv').open(encoding='utf-8') as stream:frames=list(csv.DictReader(stream))
+ assert len(frames)==40
+ signature=[{k:r[k] for k in ('frame','pts100ns','width','height','sha256')} for r in frames]
+ if repeat==1:references[(shape,mode)]=signature
+ else:assert references[(shape,mode)]==signature,'Repeat full-frame pixel/PTS mismatch'
+ warm=[r for r in frames if int(r['frame']) in list(range(6,20))+list(range(26,40))]
+ row['gpuWarmMedianMs']={k:statistics.median(float(r[k]) for r in warm) for k in ('enhancementMs','nrMs','flowMs')}
+ if mode=='crop':
+ plain=BASE/'tests'/TASK/f'{label}-{shape}-none-r{repeat}';full=BASE/'tests'/TASK/f'{label}-{shape}-full-r{repeat}'
+ x,y,w,h=(0,138,1920,804) if shape=='239' else (240,0,1440,1080)
+ mask=np.ones((1080,1920),dtype=bool);mask[y:y+h,x:x+w]=False
+ quality=[]
+ for i in range(40):
+ a=np.asarray(Image.open(full/f'frame-{i}.png').convert('RGBA'));b=np.asarray(Image.open(out/f'frame-{i}.png').convert('RGBA'));p=np.asarray(Image.open(plain/f'frame-{i}.png').convert('RGBA'))
+ active=(a[y:y+h,x:x+w,:3].astype(np.float64)-b[y:y+h,x:x+w,:3])
+ mse=float(np.mean(active**2));quality.append({'frame':i,'activePsnrDb':float(10*np.log10(255**2/mse)) if mse else None,
+ 'activeDifferentRgbPixels':int(np.count_nonzero(np.any(active!=0,axis=2))),
+ 'activeMaxDifference':int(np.abs(active).max()),'outsideDifferentFromSourcePixels':int(np.count_nonzero(np.any(b!=p,axis=2)&mask)),
+ 'outsideDifferentFromFullNrPixels':int(np.count_nonzero(np.any(a!=b,axis=2)&mask))})
+ row['quality']=quality;assert not any(q['outsideDifferentFromSourcePixels'] for q in quality)
+ (folder/'completed.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf-8')
+ print('LETTERBOX_NATIVE_RESULT',json.dumps({k:v for k,v in row.items() if k!='quality'},ensure_ascii=False),flush=True)
+assert all(matrix.digest(app/name)==sha for name,sha in payload.items());matrix.assert_gpu_tests_idle()
+(folder/'summary.json').write_text(json.dumps({'runs':results,'fullFrameCount':len(results)*40,'repeatDifferentFrames':0,
+ 'payloadUnchanged':True,'extraGpuLoad':False,'scope':'Independent ROI diagnostic; per-frame CPU waits/readback and extra base graph excluded from production'},ensure_ascii=False,indent=2),encoding='utf-8')
+print('LETTERBOX_NATIVE_COMPLETE',len(results),flush=True)
diff --git a/tests/perf/NrLetterboxExperiment.cpp b/tests/perf/NrLetterboxExperiment.cpp
new file mode 100644
index 00000000..1da4bb4f
--- /dev/null
+++ b/tests/perf/NrLetterboxExperiment.cpp
@@ -0,0 +1,84 @@
+// Authored diagnostic stimulus, not a production crop/readback path.
+#include "veyra/engine/PreviewGpuSession.h"
+#include "veyra/engine/GraphDescription.h"
+#include "veyra/source/MediaFileSource.h"
+#include "veyra/sink/ImageExportSink.h"
+#include "veyra/diagnostics/EnhancementProcessingTime.h"
+#include "veyra/RuntimePaths.h"
+#include "veyra/FileIdentity.h"
+#include <d3d12sdklayers.h>
+#include <cstring>
+#include <fstream>
+#include <iostream>
+extern "C" {
+#include <libavutil/frame.h>
+#include <libavutil/pixfmt.h>
+}
+
+int wmain(int argc,wchar_t** argv){
+ using namespace veyra;if(argc!=5)return 2;
+ const std::wstring mode=argv[3],shape=argv[4];
+ if((mode!=L"none"&&mode!=L"full"&&mode!=L"crop")||(shape!=L"239"&&shape!=L"43"))return 2;
+ const bool crop=mode==L"crop",nr=mode!=L"none";
+ const unsigned x=shape==L"43"?240:0,y=shape==L"239"?138:0,w=1920-x*2,h=1080-y*2;
+ const HRESULT com=CoInitializeEx(nullptr,COINIT_MULTITHREADED);if(FAILED(com))return 2;
+ struct Apartment{~Apartment(){CoUninitialize();}} apartment;
+ const std::filesystem::path out=argv[2];std::filesystem::create_directories(out);Logger::instance().openFile((out/L"engine.log").wstring());
+ Microsoft::WRL::ComPtr<ID3D12Debug> layer;if(FAILED(D3D12GetDebugInterface(IID_PPV_ARGS(&layer))))return 2;layer->EnableDebugLayer();
+ engine::EnhancementSettings settings;settings.nr=nr;settings.nrTemporal=false;settings.nrPolicy=pipeline::NrSizePolicy::Native;
+ engine::StageRequest request;request.nr=nr;request.width=crop?w:1920;request.height=crop?h:1080;
+ pipeline::EnhanceGraphDesc desc;engine::describeStages(request,settings,desc);desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
+ engine::PreviewGpuSession session;if(!session.initialize()||!session.graph->initialize(desc)||!session.graph->createViews())return 2;
+ session.graph->recordGpuTimings();
+ pipeline::EnhanceGraph base(session.context,session.ring,&session.core);
+ if(crop){auto off=settings;off.nr=false;request.nr=false;request.width=1920;request.height=1080;
+ pipeline::EnhanceGraphDesc plain;engine::describeStages(request,off,plain);plain.noNgx=true;plain.noFeatures=true;
+ if(!base.initialize(plain)||!base.createViews())return 2;}
+ source::MediaFileSource source;source::SourceOpenDesc open;open.path=argv[1];open.preferHardwareDecode=false;if(!source.open(open))return 2;
+ std::ofstream frames(out/L"frames.csv");frames<<"frame,pts100ns,width,height,sha256,enhancementMs,nrMs,flowMs\n";
+ bool pass=true;unsigned done=0;
+ for(unsigned i=0;i<40&&pass;++i){
+ if(i==20)pass=source.seek({10,1});
+ pipeline::FramePacket packet;const AVFrame* input=nullptr;
+ pass=pass&&source.read(packet,&input)==source::SourceReadStatus::Frame&&input&&input->format==AV_PIX_FMT_YUV420P;
+ if(!pass)break;
+ AVFrame* canvas=av_frame_alloc();canvas->format=input->format;canvas->width=1920;canvas->height=1080;
+ pass=av_frame_get_buffer(canvas,32)>=0&&av_frame_copy_props(canvas,input)>=0;
+ if(pass)for(unsigned p=0;p<3;++p){const unsigned div=p?2:1,pw=1920/div,ph=1080/div;
+ for(unsigned row=0;row<ph;++row)std::memset(canvas->data[p]+row*canvas->linesize[p],p?128:16,pw);
+ for(unsigned row=0;row<h/div;++row)std::memcpy(canvas->data[p]+(y/div+row)*canvas->linesize[p]+x/div,
+ input->data[p]+(y/div+row)*input->linesize[p]+x/div,w/div);}
+ // Late burned-in text/OSD outside the previously confirmed black ROI.
+ if(pass&&i>=10){const unsigned tx=shape==L"239"?840:60,ty=shape==L"239"?992:420;
+ for(unsigned row=0;row<22;++row)for(unsigned col=0;col<120;++col)
+ if((col/8+row/4)%3!=0)canvas->data[0][(ty+row)*canvas->linesize[0]+tx+col]=235;}
+ AVFrame* view=pass?av_frame_clone(canvas):nullptr;
+ if(pass&&crop){view->crop_left=x;view->crop_right=x;view->crop_top=y;view->crop_bottom=y;
+ pass=av_frame_apply_cropping(view,AV_FRAME_CROP_UNALIGNED)>=0&&view->width==int(w)&&view->height==int(h);}
+ sink::RgbaImage image,baseImage;pipeline::EnhanceGraph::FrameOutputs output;
+ if(pass)pass=session.graph->process(view,packet.pts.toDouble()*1000,i==0||i==20,output,packet.sequence,&packet.colorInfo)&&session.ring.waitIdle();
+ const auto times=session.graph->takeGpuTimings();
+ std::optional<double> enhanced,nrMs,flowMs;
+ for(const auto& timing:times){enhanced=diagnostics::enhancementProcessingMs(timing);
+ nrMs=timing.gpu[size_t(diagnostics::GpuStage::Nr)].milliseconds;flowMs=timing.gpu[size_t(diagnostics::GpuStage::Flow)].milliseconds;}
+ if(pass)pass=sink::readRgba8(session.context,session.ring,session.graph->videoFrameResource(output.videoSlot),image);
+ if(pass&&crop){pipeline::EnhanceGraph::FrameOutputs plain;
+ pass=base.process(canvas,packet.pts.toDouble()*1000,i==0||i==20,plain,packet.sequence,&packet.colorInfo)&&session.ring.waitIdle()&&
+ sink::readRgba8(session.context,session.ring,base.videoFrameResource(plain.videoSlot),baseImage);
+ if(pass){for(unsigned row=0;row<h;++row)std::memcpy(baseImage.pixels.data()+((y+row)*1920+x)*4,image.pixels.data()+row*w*4,w*4);
+ image=std::move(baseImage);}}
+ av_frame_free(&view);av_frame_free(&canvas);
+ if(pass)pass=image.width==1920&&image.height==1080&&enhanced.has_value()&&
+ sink::saveImage((out/(L"frame-"+std::to_wstring(i)+L".png")).wstring(),image);
+ if(pass){frames<<i<<','<<int64_t(packet.pts.toDouble()*10000000)<<",1920,1080,"<<sha256Hex(image.pixels.data(),image.pixels.size())
+ <<','<<*enhanced<<','<<nrMs.value_or(0)<<','<<flowMs.value_or(0)<<'\n';frames.flush();++done;}
+ }
+ source.close();session.ring.drainQueue();base.shutdown();session.graph->shutdown();pass=session.core.close("letterbox-diagnostic")&&pass;
+ Microsoft::WRL::ComPtr<ID3D12InfoQueue> debug;unsigned errors=0;if(FAILED(session.context.device()->QueryInterface(IID_PPV_ARGS(&debug))))return 2;
+ for(UINT64 i=0;i<debug->GetNumStoredMessages();++i){SIZE_T n=0;debug->GetMessage(i,nullptr,&n);std::vector<unsigned char> bytes(n);
+ auto* message=reinterpret_cast<D3D12_MESSAGE*>(bytes.data());if(FAILED(debug->GetMessage(i,message,&n)))return 2;
+ if(message->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;std::cerr<<"DEBUG_ERROR "<<message->pDescription<<std::endl;}}
+ const auto removed=session.context.device()->GetDeviceRemovedReason();pass=pass&&done==40&&errors==0&&SUCCEEDED(removed);
+ debug.Reset();session.shutdown();std::cout<<"LETTERBOX_RESULT pass="<<pass<<" frames="<<done<<" debugErrors="<<errors<<" deviceRemoved="<<unsigned(removed)<<std::endl;
+ return pass?0:1;
+}